Repository navigation
Expand file tree
/
Copy pathcmd_migrate.py
More file actions
567 lines (513 loc) · 22.3 KB
/
Copy pathcmd_migrate.py
File metadata and controls
567 lines (513 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/env python
"""
Migrate Python Lib files from CPython, preserving explicit local adaptations.
Usage:
python scripts/update_lib migrate cpython/Lib/test/test_foo.py
python scripts/update_lib migrate cpython/Lib/test/test_foo.py --patches remaining.json
python scripts/update_lib migrate cpython/Lib/example.py --new-file-adaptations new.json
Remaining metadata names the exact repository-relative target and its existing
decorator patches. An optional "doctests" object selects existing guarded inputs
by exact source text, mapping each to a single-line reason. Guarded doctests need
this explicit selection; an empty object retires all their guards. Canonical
expected output is never copied from the old file. Optional "blocks" lists
[canonical, local] source pairs to preserve exact existing changes.
Both fragments must match uniquely; no module-specific defaults are inferred.
Non-marker adaptations require reviewed blocks on each migration, for example
{"target": "Lib/example.py", "patches": {}, "blocks": [["old = 1", "old = 2"]]}.
Use a host Python that parses the source version (Python 3.15 for 3.15 syntax),
as required by the existing marker extraction and application steps.
For a new destination only, --new-file-adaptations accepts exactly "target",
"source_sha256" (the raw canonical file hash), and "blocks". Each canonical
fragment must occur uniquely, and fragments must not overlap. Only top-level
imports and existing binding values may change; all class/function bodies are
preserved. These adaptations still require review: preserving their AST does
not prove behavioral equivalence. Existing destinations are never overwritten.
Ordinary migration will:
1. Extract patches from Lib/test/test_foo.py (if exists)
2. Apply them to cpython/Lib/test/test_foo.py
3. Write result to Lib/test/test_foo.py
"""
import argparse
import ast
import collections
import hashlib
import json
import pathlib
import shutil
import sys
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent))
from update_lib.file_utils import parse_lib_path
def migrate_new_file(src_path: pathlib.Path, document: dict) -> None:
"""Introduce reviewed import/binding adaptations into a new canonical file.
This opt-in path never overwrites an existing destination or changes the
preservation rules of ordinary migrations. Metadata pins the raw source
hash and exact target; all fragments are validated before any write.
Import and binding values still require review: AST preservation alone does
not establish behavioral equivalence of the adapted module.
"""
if not isinstance(document, dict) or set(document) != {
"target",
"source_sha256",
"blocks",
}:
raise ValueError(
"New-file adaptations require target, source_sha256 and blocks"
)
target_name = document["target"]
if not isinstance(target_name, str) or "\\" in target_name:
raise ValueError("Expected a repository-relative Lib Python file")
relative = pathlib.Path(target_name)
if (
relative.is_absolute()
or ".." in relative.parts
or relative.parts[:1] != ("Lib",)
or relative.suffix != ".py"
or relative.as_posix() != target_name
or relative != parse_lib_path(src_path)
):
raise ValueError("New-file adaptation target does not match canonical Lib path")
repository = pathlib.Path(__file__).resolve().parents[2]
target = repository / relative
if any(
(repository / parent).is_symlink() for parent in (relative, *relative.parents)
):
raise ValueError("New-file destination must not contain symlinks")
if target.exists():
raise ValueError("New-file adaptation destination already exists")
if not src_path.is_file() or src_path.is_symlink():
raise ValueError("New-file source must be a regular canonical file")
raw = src_path.read_bytes()
if hashlib.sha256(raw).hexdigest() != document["source_sha256"]:
raise ValueError("New-file canonical source hash mismatch")
canonical = raw.decode("utf-8")
blocks = document["blocks"]
if (
not isinstance(blocks, list)
or not blocks
or any(
not isinstance(pair, list)
or len(pair) != 2
or any(not isinstance(text, str) or not text.strip() for text in pair)
for pair in blocks
)
):
raise ValueError("New-file blocks must be nonempty canonical/local pairs")
edits = []
for old, new in blocks:
start = canonical.find(old)
if start < 0 or canonical.find(old, start + 1) >= 0:
raise ValueError("Missing or ambiguous new-file canonical fragment")
edits.append((start, start + len(old), new))
edits.sort()
if any(left[1] > right[0] for left, right in zip(edits, edits[1:])):
raise ValueError("Overlapping new-file adaptation fragments")
adapted = canonical
for start, end, new in reversed(edits):
adapted = adapted[:start] + new + adapted[end:]
def protected_structure(text):
tree = ast.parse(text)
protected = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
continue
if isinstance(node, (ast.Assign, ast.AnnAssign)):
# Only the value of an existing top-level binding may change.
# Assignment targets, their order and annotations are retained.
node.value = ast.Constant(value=None)
protected.append(ast.dump(node, include_attributes=False))
return protected
try:
if protected_structure(canonical) != protected_structure(adapted):
raise ValueError(
"New-file adaptations may change only imports and bindings"
)
except SyntaxError as error:
raise ValueError("Invalid Python in new-file adaptation") from error
target.parent.mkdir(parents=True, exist_ok=True)
try:
with target.open("xb") as output:
output.write(adapted.encode("utf-8"))
except FileExistsError as error:
raise ValueError("New-file adaptation destination already exists") from error
def _preserve_block(old, new, canonical, local):
"""Preserve an explicit existing fragment; do not infer module adaptations."""
if old.count(local) != 1 or new.count(canonical) != 1:
raise ValueError("Changed or ambiguous preservation block")
return new.replace(canonical, local, 1)
def patch_single_content(
src_path: pathlib.Path,
lib_path: pathlib.Path,
patches_document: dict | None = None,
) -> str:
"""
Patch content without writing to disk.
Args:
src_path: Source file path (e.g., cpython/Lib/test/foo.py)
lib_path: Lib path to extract patches from (e.g., Lib/test/foo.py)
Returns:
The patched content.
"""
from update_lib import apply_patches, extract_patches
from update_lib.patch_spec import apply_doctest_metadata, extract_doctest_guards
# Extract patches from existing file (if exists)
if lib_path.exists():
old_content = lib_path.read_text(encoding="utf-8")
patches = extract_patches(old_content)
else:
patches = {}
repository = pathlib.Path(__file__).resolve().parents[2]
try:
relative_path = lib_path.resolve().relative_to(repository)
except ValueError:
# Explicit output paths outside this repository are not its Lib.
relative_path = pathlib.Path("__external_output__")
if patches_document is not None:
from update_lib.patch_spec import select_remaining_patches
patches = select_remaining_patches(
patches,
patches_document,
relative_path,
old_content=old_content if lib_path.exists() else None,
)
blocks = patches_document.get("blocks", []) if patches_document else []
if not isinstance(blocks, list) or any(
not isinstance(pair, list)
or len(pair) != 2
or any(not isinstance(text, str) or not text.strip() for text in pair)
for pair in blocks
):
raise ValueError("Blocks must be canonical/local source pairs")
if blocks and not lib_path.exists():
raise ValueError("Blocks require an existing local file")
# Apply patches to source content
src_content = src_path.read_text(encoding="utf-8")
if lib_path.exists():
if any(src_content.count(canonical) != 1 for canonical, _ in blocks):
raise ValueError("Changed or ambiguous canonical preservation block")
for canonical, local in blocks:
src_content = _preserve_block(old_content, src_content, canonical, local)
guards = extract_doctest_guards(old_content)
selection = patches_document.get("doctests") if patches_document else None
if guards and selection is None:
raise ValueError(
"Existing doctest guards require explicit doctests metadata"
)
if selection is not None:
src_content = apply_doctest_metadata(old_content, src_content, selection)
if not src_content and not patches:
return src_content
try:
result = apply_patches(src_content, patches)
except SyntaxError as error:
if blocks:
raise ValueError("Preserved blocks produced invalid Python") from error
raise
return result
def patch_file(
src_path: pathlib.Path,
lib_path: pathlib.Path | None = None,
verbose: bool = True,
patches_document: dict | None = None,
) -> None:
"""
Patch a single file from source to lib.
Args:
src_path: Source file path (e.g., cpython/Lib/test/foo.py)
lib_path: Target lib path. If None, derived from src_path.
verbose: Print progress messages
"""
if lib_path is None:
lib_path = parse_lib_path(src_path)
if lib_path.exists():
if verbose:
print(f"Patching: {src_path} -> {lib_path}")
content = patch_single_content(src_path, lib_path, patches_document)
else:
if verbose:
print(f"Copying: {src_path} -> {lib_path}")
if patches_document is not None:
raise ValueError("Marker override requires an existing target")
content = src_path.read_text(encoding="utf-8")
lib_path.parent.mkdir(parents=True, exist_ok=True)
lib_path.write_text(content, encoding="utf-8")
def patch_directory(
src_dir: pathlib.Path,
lib_dir: pathlib.Path | None = None,
verbose: bool = True,
) -> None:
"""
Patch all files in a directory from source to lib.
Args:
src_dir: Source directory path (e.g., cpython/Lib/test/test_foo/)
lib_dir: Target lib directory. If None, derived from src_dir.
verbose: Print progress messages
"""
if lib_dir is None:
lib_dir = parse_lib_path(src_dir)
src_files = sorted(
f
for f in src_dir.glob("**/*")
if f.is_file() and "__pycache__" not in f.relative_to(src_dir).parts[:-1]
)
for src_file in src_files:
rel_path = src_file.relative_to(src_dir)
lib_file = lib_dir / rel_path
if src_file.suffix == ".py":
if lib_file.exists():
if verbose:
print(f"Patching: {src_file} -> {lib_file}")
content = patch_single_content(src_file, lib_file)
else:
if verbose:
print(f"Copying: {src_file} -> {lib_file}")
content = src_file.read_text(encoding="utf-8")
lib_file.parent.mkdir(parents=True, exist_ok=True)
lib_file.write_text(content, encoding="utf-8")
else:
if verbose:
print(f"Copying: {src_file} -> {lib_file}")
lib_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_file, lib_file)
def retire_legacy_paths(src_dir: pathlib.Path, mapping: dict) -> None:
"""Retire explicit upstream-absent files after checking their replacements.
Flat legacy maps use repository-relative Lib paths and name an already
canonical replacement, or null for an upstream removal. They never rewrite
replacements or recursively prune directories.
"""
from update_lib.file_utils import get_cpython_dir
canonical = get_cpython_dir(src_dir).resolve()
local = pathlib.Path.cwd().resolve()
if not (canonical / "Lib").is_dir() or not src_dir.is_dir():
raise ValueError("Canonical Lib or migration source directory does not exist")
def lib_file(root, name):
path = pathlib.Path(name)
if path.is_absolute() or ".." in path.parts or path.parts[:1] != ("Lib",):
raise ValueError(f"Expected a repository-relative Lib file: {name}")
result = root / path
if result.is_symlink() or not result.resolve().is_relative_to(root / "Lib"):
raise ValueError(f"Lib file escapes its source tree: {name}")
return result
legacy_files = []
for old, new in mapping.items():
legacy = lib_file(local, old)
upstream_old = lib_file(canonical, old)
if upstream_old.exists() or not legacy.is_file():
raise ValueError(f"Not an existing upstream-absent file: {old}")
if new is not None:
replacement = lib_file(local, new)
upstream_new = lib_file(canonical, new)
if (
not upstream_new.is_file()
or not replacement.is_file()
or replacement.read_bytes() != upstream_new.read_bytes()
):
raise ValueError(f"Replacement is not canonical: {new}")
legacy_files.append(legacy)
# Check the whole map before retiring any file.
for legacy in legacy_files:
legacy.unlink()
def migrate_package(
src_dir: pathlib.Path, lib_dir: pathlib.Path, mapping_path: pathlib.Path
) -> None:
"""Validate the complete migration before writing or removing legacy files.
The JSON map names legacy files beside lib_dir, mapping every marked class
to its canonical file relative to src_dir. Empty maps retire unmarked files.
No test modules are imported or executed.
"""
from update_lib.patch_spec import (
_iter_class_methods,
_iter_module_classes,
apply_patches,
build_patch_dict,
extract_doctest_guards,
iter_patches,
)
mapping = json.loads(mapping_path.read_text(encoding="utf-8"))
if not isinstance(mapping, dict) or not mapping:
raise ValueError("Legacy mapping must be a nonempty object")
if all(value is None or isinstance(value, str) for value in mapping.values()):
retire_legacy_paths(src_dir, mapping)
return
if lib_dir.exists():
raise ValueError(f"Destination already exists: {lib_dir}")
if (
src_dir.resolve() == lib_dir.resolve()
or src_dir.resolve() in lib_dir.resolve().parents
):
raise ValueError("Source and destination overlap")
source_files = sorted(
p
for p in src_dir.rglob("*")
if p.is_file() and "__pycache__" not in p.relative_to(src_dir).parts[:-1]
)
if not (src_dir / "__init__.py").is_file():
raise ValueError("Source must be a Python package")
if any(
p.is_symlink() or src_dir.resolve() not in p.resolve().parents
for p in source_files
):
raise ValueError("Source files must remain inside the canonical package")
contents = {p.relative_to(src_dir): p.read_bytes() for p in source_files}
entries = collections.defaultdict(list)
owners = {}
legacy_files = []
for name, class_map in mapping.items():
if pathlib.Path(name).name != name or not name.endswith(".py"):
raise ValueError(f"Legacy file must be a sibling .py file: {name}")
if not isinstance(class_map, dict):
raise ValueError(f"Class map must be an object: {name}")
legacy = lib_dir.parent / name
if legacy.is_symlink() or legacy.resolve().parent != lib_dir.parent.resolve():
raise ValueError(f"Legacy file escapes destination parent: {name}")
if (
legacy.resolve() == lib_dir.resolve()
or src_dir.resolve() in legacy.resolve().parents
):
raise ValueError(f"Legacy file overlaps canonical package: {name}")
legacy_files.append(legacy)
legacy_content = legacy.read_text(encoding="utf-8")
if extract_doctest_guards(legacy_content):
raise ValueError("Legacy package migration cannot select doctest guards")
patches = list(iter_patches(legacy_content))
legacy_classes = collections.defaultdict(list)
for cls in _iter_module_classes(ast.parse(legacy_content)):
legacy_classes[cls.name].append(cls)
if set(class_map) != {p.parent_class for p in patches}:
raise ValueError(f"Missing or unused class mapping: {name}")
for entry in patches:
source_classes = legacy_classes[entry.parent_class]
if len(source_classes) != 1:
raise ValueError(f"Ambiguous legacy class: {entry.parent_class}")
if (
entry.test_name != "__self__"
and sum(
method.name == entry.test_name
for method in _iter_class_methods(source_classes[0])
)
!= 1
):
raise ValueError(
f"Ambiguous legacy method: {entry.parent_class}.{entry.test_name}"
)
target = pathlib.Path(class_map[entry.parent_class])
if target.is_absolute() or ".." in target.parts or target not in contents:
raise ValueError(f"Invalid canonical destination: {target}")
if target.suffix != ".py":
raise ValueError(f"Marker destination is not Python: {target}")
tree = ast.parse(contents[target].decode("utf-8"))
classes = collections.defaultdict(list)
for cls in _iter_module_classes(tree):
classes[cls.name].append(cls)
def has_method(class_name, seen):
if class_name in seen:
return False
seen = seen | {class_name}
nodes = classes.get(class_name, [])
if len(nodes) != 1:
raise ValueError(f"Missing or ambiguous class: {class_name}")
cls = nodes[0]
methods = [
m for m in _iter_class_methods(cls) if m.name == entry.test_name
]
if len(methods) > 1:
raise ValueError(
f"Ambiguous method: {class_name}.{entry.test_name}"
)
if methods or entry.test_name == "__self__":
return True
return any(
has_method(base.id, seen)
for base in cls.bases
if isinstance(base, ast.Name) and base.id in classes
)
if not has_method(entry.parent_class, set()):
raise ValueError(
f"Missing method: {entry.parent_class}.{entry.test_name}"
)
owner_key = (target, entry.parent_class, entry.test_name)
if owner_key in owners and owners[owner_key] != legacy:
raise ValueError(
f"Duplicate mapped marker: {entry.parent_class}.{entry.test_name}"
)
owners[owner_key] = legacy
entries[target].append(entry)
# Render and validate everything before changing the destination.
for target, patches in entries.items():
contents[target] = apply_patches(
contents[target].decode("utf-8"), build_patch_dict(iter(patches))
).encode("utf-8")
for target, data in contents.items():
if target.suffix == ".py":
text = data.decode("utf-8")
ast.parse(text)
if collections.Counter(iter_patches(text)) != collections.Counter(
entries[target]
):
raise ValueError(f"Marker roundtrip mismatch: {target}")
for target, data in contents.items():
destination = lib_dir / target
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(data)
for legacy in legacy_files:
legacy.unlink()
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"path",
type=pathlib.Path,
help="Source path containing /Lib/ (file or directory)",
)
parser.add_argument(
"--legacy-map",
type=pathlib.Path,
help="Legacy class mapping, or exact Lib path to canonical replacement/null map",
)
parser.add_argument(
"--patches",
type=pathlib.Path,
help="Single-file target, remaining decorator patches, and optional doctests JSON",
)
parser.add_argument(
"--new-file-adaptations",
type=pathlib.Path,
help="Opt-in exact source hash and import/binding blocks for a new Lib file",
)
args = parser.parse_args(argv)
try:
if args.new_file_adaptations is not None:
if (
args.path.is_dir()
or args.legacy_map is not None
or args.patches is not None
):
raise ValueError("--new-file-adaptations requires a single new file")
migrate_new_file(
args.path,
json.loads(args.new_file_adaptations.read_text(encoding="utf-8")),
)
return 0
if args.patches is not None and (
args.path.is_dir() or args.legacy_map is not None
):
raise ValueError("--patches requires a single file without --legacy-map")
document = (
json.loads(args.patches.read_text()) if args.patches is not None else None
)
if args.legacy_map is not None:
migrate_package(args.path, parse_lib_path(args.path), args.legacy_map)
elif args.path.is_dir():
patch_directory(args.path)
else:
patch_file(args.path, patches_document=document)
return 0
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
except FileNotFoundError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())