Skip to content

Commit 29c80a6

Browse files
committed
Consolidate structural canonical test insertion with the existing updater
Keep the existing add-after implementation, dependency policy, local-import acknowledgments and receipt unchanged. Add the distinct insert-before mode through a separate helper and mutually exclusive CLI dispatch. Preserve shared replacement coverage and both mode-specific suites without duplicates. All 39 synthetic tooling tests passed under an isolated bounded host Python gate. Normal affected hooks passed; no actual Lib change, RustPython runtime, canonical test or fixture execution is included. Assisted-by: OpenAI Codex:model version unavailable
1 parent f0c4d6d commit 29c80a6

4 files changed

Lines changed: 478 additions & 4 deletions

File tree

‎scripts/update_lib/__main__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
python scripts/update_lib patches --from Lib/test/foo.py --to cpython/Lib/test/foo.py
1010
python scripts/update_lib auto-mark Lib/test/test_foo.py
1111
python scripts/update_lib copy-test SOURCE DESTINATION --test ClassName.method_name --source-sha256 HASH --destination-sha256 HASH
12+
python scripts/update_lib copy-test SOURCE DESTINATION --test ClassName.new_method --insert-before ClassName.anchor --source-sha256 HASH --destination-sha256 HASH
1213
"""
1314

1415
import argparse

‎scripts/update_lib/cmd_copy_test.py‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,14 @@ def main(argv: list[str] | None = None) -> int:
9898
parser.add_argument("source", type=Path)
9999
parser.add_argument("destination", type=Path)
100100
parser.add_argument("--test", required=True, help="Exact ClassName.method_name")
101-
parser.add_argument(
101+
insertion = parser.add_mutually_exclusive_group()
102+
insertion.add_argument(
102103
"--add-after", help="Append an absent method after this exact ClassName.anchor"
103104
)
105+
insertion.add_argument(
106+
"--insert-before",
107+
help="Insert an absent method before an unchanged anchor; structural checks only",
108+
)
104109
parser.add_argument(
105110
"--allow-local-import",
106111
action="append",
@@ -141,9 +146,19 @@ def main(argv: list[str] | None = None) -> int:
141146
else:
142147
if args.allow_local_import:
143148
raise ValueError("Local import acknowledgment requires --add-after")
144-
result_text = copy_test(
145-
source.decode("utf-8"), destination.decode("utf-8"), args.test
146-
)
149+
if args.insert_before:
150+
from update_lib.copy_test_insertion import insert_test
151+
152+
result_text = insert_test(
153+
source.decode("utf-8"),
154+
destination.decode("utf-8"),
155+
args.test,
156+
args.insert_before,
157+
)
158+
else:
159+
result_text = copy_test(
160+
source.decode("utf-8"), destination.decode("utf-8"), args.test
161+
)
147162
result = result_text.encode("utf-8")
148163
# Recheck the destination immediately before writing so stale invocations
149164
# fail instead of overwriting an intervening edit.
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
"""Insert an absent canonical method before an unchanged class anchor."""
2+
3+
import ast
4+
5+
from update_lib.cmd_copy_test import _definition
6+
7+
8+
def _class_scope_nodes(cls):
9+
"""Visit class bindings, not bindings inside nested lexical scopes.
10+
11+
Definition names and header expressions still belong to the surrounding
12+
scope. Inspect annotations conservatively too, even when evaluation is
13+
deferred; do not inspect nested bodies or type-parameter scopes.
14+
"""
15+
16+
def visit(node):
17+
yield node
18+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
19+
children = [node.args, *node.decorator_list]
20+
if node.returns is not None:
21+
children.append(node.returns)
22+
elif isinstance(node, ast.Lambda):
23+
children = [node.args]
24+
elif isinstance(node, ast.ClassDef):
25+
children = [*node.bases, *node.keywords, *node.decorator_list]
26+
elif isinstance(
27+
node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
28+
):
29+
# Only the outermost iterable is evaluated outside the implicit
30+
# comprehension scope. Its iteration targets are not class bindings.
31+
children = [node.generators[0].iter]
32+
else:
33+
children = ast.iter_child_nodes(node)
34+
for child in children:
35+
yield from visit(child)
36+
37+
for node in cls.body:
38+
yield from visit(node)
39+
40+
41+
def insert_test(source: str, destination: str, qualified_name: str, before: str) -> str:
42+
"""Insert an absent direct method before an unchanged canonical anchor.
43+
44+
This intentionally excludes guarded classes/methods and non-LF inputs.
45+
It copies no imports or helpers: callers must review those dependencies.
46+
"""
47+
if any("\r" in text or not text.endswith("\n") for text in (source, destination)):
48+
raise ValueError("Insertion requires LF input with a final newline")
49+
method, guards, start, end = _definition(source, qualified_name)
50+
anchor, anchor_guards, anchor_start, anchor_end = _definition(source, before)
51+
dst_anchor, dst_guards, dst_start, dst_end = _definition(destination, before)
52+
class_name, name = qualified_name.split(".")
53+
if before.split(".")[0] != class_name:
54+
raise ValueError("Insertion anchor must be in the same class")
55+
if guards or anchor_guards or dst_guards:
56+
raise ValueError("Insertion does not support guarded definitions")
57+
src_tree, dst_tree = ast.parse(source), ast.parse(destination)
58+
src_class = next(
59+
node
60+
for node in src_tree.body
61+
if isinstance(node, ast.ClassDef) and node.name == class_name
62+
)
63+
dst_class = next(
64+
node
65+
for node in dst_tree.body
66+
if isinstance(node, ast.ClassDef) and node.name == class_name
67+
)
68+
if any(
69+
isinstance(node, (ast.Global, ast.Nonlocal))
70+
for cls in (src_class, dst_class)
71+
for node in _class_scope_nodes(cls)
72+
):
73+
raise ValueError("Insertion does not support scope declarations in classes")
74+
# Nodes come from separate parses; compare their unique source locations.
75+
members = {node.lineno: index for index, node in enumerate(src_class.body)}
76+
if members.get(anchor.lineno) != members.get(method.lineno, -2) + 1:
77+
raise ValueError("Source test must immediately precede its direct anchor")
78+
if not any(node.lineno == dst_anchor.lineno for node in dst_class.body):
79+
raise ValueError("Destination anchor must be a direct class member")
80+
for node in _class_scope_nodes(dst_class):
81+
if (
82+
(
83+
isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
84+
and node.name == name
85+
)
86+
or (
87+
isinstance(node, ast.Name)
88+
and isinstance(node.ctx, ast.Store)
89+
and node.id == name
90+
)
91+
or (
92+
isinstance(node, ast.alias)
93+
and (node.asname or node.name.split(".")[0]) == name
94+
)
95+
or (
96+
isinstance(node, (ast.MatchAs, ast.MatchStar, ast.ExceptHandler))
97+
and node.name == name
98+
)
99+
or (isinstance(node, ast.MatchMapping) and node.rest == name)
100+
):
101+
raise ValueError("Insertion test name already exists in destination class")
102+
103+
# AST line numbers count LF, not Unicode separators embedded in strings.
104+
def lines(text):
105+
return [line + "\n" for line in text.split("\n")[:-1]]
106+
107+
src_lines, dst_lines = lines(source), lines(destination)
108+
109+
def header(cls, lines):
110+
first = min([cls.lineno, *(node.lineno for node in cls.decorator_list)]) - 1
111+
child = cls.body[0]
112+
child_start = (
113+
min(
114+
[
115+
child.lineno,
116+
*(node.lineno for node in getattr(child, "decorator_list", [])),
117+
]
118+
)
119+
- 1
120+
)
121+
return lines[first:child_start]
122+
123+
if header(src_class, src_lines) != header(dst_class, dst_lines):
124+
raise ValueError("Insertion class headers differ")
125+
if src_lines[anchor_start:anchor_end] != dst_lines[dst_start:dst_end]:
126+
raise ValueError("Insertion anchor text differs")
127+
if (
128+
method.col_offset != anchor.col_offset
129+
or method.col_offset != dst_anchor.col_offset
130+
):
131+
raise ValueError("Insertion indentation differs")
132+
# Do not split or silently omit comments attached to either definition.
133+
previous = [node.end_lineno for node in src_class.body if node.end_lineno <= start]
134+
previous_end = max(previous, default=src_class.lineno)
135+
dst_previous = [
136+
node.end_lineno for node in dst_class.body if node.end_lineno <= dst_start
137+
]
138+
dst_previous_end = max(dst_previous, default=dst_class.lineno)
139+
for gap in (
140+
src_lines[previous_end:start],
141+
src_lines[end:anchor_start],
142+
dst_lines[dst_previous_end:dst_start],
143+
):
144+
if any(line.strip() for line in gap):
145+
raise ValueError("Insertion requires blank definition boundaries")
146+
block = src_lines[start:anchor_start]
147+
result = "".join(dst_lines[:dst_start] + block + dst_lines[dst_start:])
148+
_, _, result_start, result_end = _definition(result, qualified_name)
149+
if lines(result)[result_start:result_end] != src_lines[start:end]:
150+
raise ValueError("Inserted definition is not byte-identical to the source")
151+
return result

0 commit comments

Comments
 (0)