lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/upgrade.py ADDED
@@ -0,0 +1,706 @@
1
+ # lean-pkg doctor --upgrade-from -- what changed for a package author between two lean-pkg versions
2
+ """`lean-pkg doctor --upgrade-from OLD [--to NEW] [--source DIR] [--json]`.
3
+
4
+ A package author about to move from one lean-pkg to another (or between two commits that carry the same
5
+ version string) wants one machine-readable answer to "what changed for me": formats, derived keys,
6
+ commands and flags, the Python floor, and the behaviour rules a receipt is now judged by. The design is in
7
+ docs/design/upgrade-preflight.md. Two halves:
8
+
9
+ * **Mechanical** (the surface): read from the two source trees' git objects, never by running their code.
10
+ pyproject.toml (version, requires-python, dependencies, console scripts); the golden CLI contract
11
+ (tests/golden/help/*.txt: the command paths and their options; tests/golden/json-keys.json: each
12
+ command's --json key set); module-level constants found by parsing the source with `ast` (format
13
+ markers such as `"comparator-receipt/2"`, the registry version, formalization's SCHEMA_VERSION and
14
+ DERIVED_PATHS, the on-disk key lists PACKAGE_FIELDS / RECEIPT_FIELDS / COMPARATOR_FIELDS / ...,
15
+ command_tree's alias tables); and the blob ids of the packaged data files (schemas, templates,
16
+ scripts, site profiles).
17
+ * **Curated** (behaviour): docs/upgrades/<version>.yaml (schema `lean-pkg-upgrade-record/1`) at the
18
+ NEW tree, one entry per change a surface diff cannot show (a receipt that used to pass and is now
19
+ refused). An entry applies when its PR's squash commit (subject ending `(#N)`) lies in OLD..NEW, so a
20
+ commit-to-commit comparison inside one version gets exactly the entries merged in between.
21
+ Merged PRs in the range that no record names are listed under `uncurated` (the record may be
22
+ incomplete; read their CHANGELOG entries).
23
+
24
+ Read-only: never the registry, no network, writes nothing.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import ast
29
+ import json
30
+ import pathlib
31
+ import re
32
+ import tomllib
33
+
34
+ import yaml
35
+
36
+ from . import cli
37
+ from . import core
38
+
39
+ SCHEMA = "lean-pkg-upgrade/1"
40
+ RECORD_SCHEMA = "lean-pkg-upgrade-record/1"
41
+ RECORD_DIR = "docs/upgrades"
42
+ SRC = "src/lean_pkg"
43
+ HELP_DIR = "tests/golden/help"
44
+ JSON_KEYS = "tests/golden/json-keys.json"
45
+ DATA_DIRS = ("schemas", "templates", "scripts", "site_profiles")
46
+ FORMAT_RE = re.compile(r"^([a-z][a-z0-9-]*)/(\d+)$")
47
+ # Named constants whose value is a version or a key list of an on-disk format (module, name). A `core`
48
+ # constant is read from cli.py in a tree that has no core.py yet (before the core split, #317): _const.
49
+ NAMED = {
50
+ "registry_version": ("core", "REGISTRY_VERSION"),
51
+ "registry_versions_read": ("core", "SUPPORTED_REGISTRY_VERSIONS"),
52
+ "event_line_version": ("core", "EVENT_LINE_VERSION"),
53
+ "formalization_yaml_version": ("formalization", "SCHEMA_VERSION"),
54
+ }
55
+ KEY_LISTS = { # format label -> (module, constant in lower case: an upper-case COMPARATOR_* literal reads as an
56
+ # environment variable to the suite's env scan); a tuple of tuples counts by its first items
57
+ "registry package": ("core", "package_fields"),
58
+ "registry lease": ("core", "lease_fields"),
59
+ "lower-tier receipt": ("core", "receipt_fields"),
60
+ "comparator receipt": ("core", "comparator_fields"),
61
+ "comparator receipt config": ("core", "comparator_config_fields"),
62
+ "comparator receipt digests": ("core", "comparator_toolchain_digests"),
63
+ "formalization.yaml derived": ("formalization", "derived_paths"),
64
+ }
65
+ RECORD_KINDS = ("behavior", "format", "command", "requirement")
66
+ RECORD_KEYS = {"pr", "id", "kind", "area", "summary", "action", "breaking", "changelog", "split"}
67
+
68
+
69
+ class Unknown:
70
+ """A value the restricted evaluator does not compute (a call result, an f-string, arithmetic)."""
71
+
72
+ def __repr__(self) -> str:
73
+ return "<unknown>"
74
+
75
+
76
+ UNKNOWN = Unknown()
77
+
78
+
79
+ # --------------------------------------------------------------------------
80
+ # reading a tree from git objects
81
+
82
+
83
+ class Tree:
84
+ def __init__(self, repo: pathlib.Path, rev: str):
85
+ self.repo, self.rev = repo, rev
86
+ self.commit = resolve(repo, rev)
87
+ self._ls: list[str] | None = None
88
+
89
+ def read(self, rel: str) -> str | None:
90
+ p = core.git(self.repo, "show", f"{self.commit}:{rel}")
91
+ return p.stdout if p.returncode == 0 else None
92
+
93
+ def files(self) -> list[str]:
94
+ if self._ls is None:
95
+ p = core.git(self.repo, "ls-tree", "-r", "--name-only", self.commit)
96
+ self._ls = p.stdout.splitlines() if p.returncode == 0 else []
97
+ return self._ls
98
+
99
+ def blobs(self, prefix: str) -> dict[str, str]:
100
+ p = core.git(self.repo, "ls-tree", "-r", self.commit, "--", prefix)
101
+ out = {}
102
+ for line in p.stdout.splitlines():
103
+ meta, _, path = line.partition("\t")
104
+ parts = meta.split()
105
+ if len(parts) == 3 and parts[1] == "blob" and "__pycache__" not in path:
106
+ out[path[len(SRC) + 1:]] = parts[2]
107
+ return out
108
+
109
+
110
+ def resolve(repo: pathlib.Path, rev: str) -> str:
111
+ """A lean-pkg version (0.9.0 / v0.9.0: its tag, else the `release: 0.9.0` commit) or any git revision."""
112
+ candidates = [rev]
113
+ m = re.fullmatch(r"v?(\d+\.\d+\.\d+(?:[-.+][0-9A-Za-z.]+)?)", rev)
114
+ if m:
115
+ candidates = [f"v{m.group(1)}", rev]
116
+ for c in candidates:
117
+ p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{c}^{{commit}}")
118
+ if p.returncode == 0 and p.stdout.strip():
119
+ return p.stdout.strip()
120
+ if m:
121
+ p = core.git(repo, "log", "--all", "--format=%H", "--fixed-strings", f"--grep=release: {m.group(1)}")
122
+ for h in p.stdout.split():
123
+ subj = core.git(repo, "log", "-1", "--format=%s", h).stdout.strip()
124
+ if subj == f"release: {m.group(1)}":
125
+ return h
126
+ raise core.Fail(f"{rev!r} is neither a lean-pkg version (tag v{rev.lstrip('v')} or a `release:` commit) nor a "
127
+ f"commit in {repo}")
128
+
129
+
130
+ # --------------------------------------------------------------------------
131
+ # the restricted evaluator (never executes the source)
132
+
133
+
134
+ def literal(node):
135
+ if isinstance(node, ast.Constant):
136
+ return node.value
137
+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
138
+ return tuple(literal(e) for e in node.elts)
139
+ if isinstance(node, ast.Dict):
140
+ return {literal(k): literal(v) for k, v in zip(node.keys, node.values, strict=False) if k is not None}
141
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
142
+ return {"__call__": node.func.id, "args": tuple(literal(a) for a in node.args),
143
+ **{k.arg: literal(k.value) for k in node.keywords if k.arg}}
144
+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
145
+ return UNKNOWN
146
+ return UNKNOWN
147
+
148
+
149
+ def module_constants(source: str | None) -> dict:
150
+ """Module-level NAME = <literal> assignments (the last one wins), values evaluated by `literal`."""
151
+ if not source:
152
+ return {}
153
+ try:
154
+ tree = ast.parse(source)
155
+ except SyntaxError:
156
+ return {}
157
+ out = {}
158
+ for node in tree.body:
159
+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
160
+ out[node.targets[0].id] = literal(node.value)
161
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:
162
+ out[node.target.id] = literal(node.value)
163
+ return out
164
+
165
+
166
+ def _jsonable(v):
167
+ if isinstance(v, Unknown):
168
+ return None
169
+ if isinstance(v, tuple):
170
+ return [_jsonable(x) for x in v]
171
+ if isinstance(v, dict):
172
+ return {str(k): _jsonable(x) for k, x in v.items()}
173
+ return v
174
+
175
+
176
+ def _key_names(v) -> list[str] | None:
177
+ """Key names of a key-list constant: strings as they are, key paths (DERIVED_PATHS) dotted, and
178
+ (name, tier, meaning) rows (PACKAGE_FIELDS) by their first item."""
179
+ if not isinstance(v, tuple):
180
+ return None
181
+ if v and _is_path_list(v):
182
+ return [".".join(i) for i in v]
183
+ return [i if isinstance(i, str) else i[0] for i in v
184
+ if isinstance(i, str) or (isinstance(i, tuple) and i and isinstance(i[0], str))]
185
+
186
+
187
+ def _is_path_list(v) -> bool:
188
+ """DERIVED_PATHS-like: a tuple of tuples of identifiers (key paths), not (name, tier, meaning) rows."""
189
+ return all(isinstance(i, tuple) and all(isinstance(x, str) and re.fullmatch(r"[a-z_]+", x) for x in i)
190
+ for i in v)
191
+
192
+
193
+ # --------------------------------------------------------------------------
194
+ # the surface of one tree
195
+
196
+
197
+ def help_surface(tree: Tree) -> dict[str, list[str]] | None:
198
+ """{command path: sorted options} from the help goldens ("" is the bare `lean-pkg`)."""
199
+ names = [f for f in tree.files() if f.startswith(HELP_DIR + "/") and f.endswith(".txt")]
200
+ if not names:
201
+ return None
202
+ out = {}
203
+ for f in names:
204
+ stem = f[len(HELP_DIR) + 1:-4]
205
+ if stem == "lean-pkg":
206
+ path = ""
207
+ elif stem.startswith("lean-pkg."):
208
+ path = stem[len("lean-pkg."):].replace(".", " ")
209
+ else:
210
+ path = stem # another executable (comparator-receipt, lean-exercise, ...)
211
+ text = tree.read(f) or ""
212
+ opts = set()
213
+ for line in text.splitlines():
214
+ # argparse lists an option at exactly two spaces; a wrapped help or command-list line that happens to
215
+ # begin with a `--flag` mention (`--contracts-only`), `--format=...`) sits deeper and is no option
216
+ m = re.match(r"^ {2}(?:-\w, )?(--[a-z0-9][a-z0-9-]*)", line)
217
+ if m:
218
+ opts.add(m.group(1))
219
+ out[path] = sorted(opts)
220
+ return out
221
+
222
+
223
+ def alias_surface(consts: dict) -> dict:
224
+ cmds, flags, implied = [], [], []
225
+ for a in consts.get("COMMAND_ALIASES") or ():
226
+ if isinstance(a, dict) and len(a.get("args", ())) == 2:
227
+ old, new = a["args"]
228
+ cmds.append(f"{' '.join(old)} -> {' '.join(new)}")
229
+ for a in (consts.get("FLAG_ALIASES") or ()) + (consts.get("PROGRAM_FLAG_ALIASES") or ()):
230
+ if isinstance(a, dict) and len(a.get("args", ())) == 3:
231
+ cmd, old, new = a["args"]
232
+ flags.append(f"{' '.join(cmd)} {old} -> {new}")
233
+ iv = consts.get("IMPLIED_VERBS")
234
+ if isinstance(iv, dict):
235
+ for noun, v in iv.items():
236
+ if isinstance(v, dict) and v.get("args"):
237
+ verbs = v["args"][1] if len(v["args"]) > 1 else ()
238
+ implied.append(f"{noun} NAME -> {noun} {v['args'][0]} NAME (verbs: {', '.join(verbs)})")
239
+ return {"commands": sorted(cmds), "flags": sorted(flags), "implied_verbs": sorted(implied)}
240
+
241
+
242
+ def alias_map(consts: dict) -> dict:
243
+ """The alias tables as lookups: {old words: new words}, {noun: implied verb}, {command: {old: new flag}}."""
244
+ cmds, implied, flags = {}, {}, {}
245
+ for a in consts.get("COMMAND_ALIASES") or ():
246
+ if isinstance(a, dict) and len(a.get("args", ())) == 2:
247
+ cmds[" ".join(a["args"][0])] = " ".join(a["args"][1])
248
+ iv = consts.get("IMPLIED_VERBS")
249
+ for noun, v in (iv.items() if isinstance(iv, dict) else ()):
250
+ if isinstance(v, dict) and v.get("args") and isinstance(v["args"][0], str):
251
+ implied[noun] = v["args"][0]
252
+ for a in consts.get("FLAG_ALIASES") or ():
253
+ if isinstance(a, dict) and len(a.get("args", ())) == 3:
254
+ cmd, old, new = a["args"]
255
+ flags.setdefault(" ".join(cmd), {})[old] = new
256
+ modes: dict[str, dict[str, str]] = {}
257
+ for a in consts.get("MODE_ALIASES") or (): # ModeAlias(command, flag, new command, ...): a split mode
258
+ if isinstance(a, dict) and len(a.get("args", ())) >= 3:
259
+ cmd, flag, new = a["args"][:3]
260
+ if isinstance(cmd, tuple) and isinstance(new, tuple) and isinstance(flag, str):
261
+ modes.setdefault(" ".join(cmd), {})[flag] = " ".join(new)
262
+ hidden = consts.get("HELP_HIDDEN_FLAGS")
263
+ hidden = sorted(h for h in hidden if isinstance(h, str)) if isinstance(hidden, (tuple, list)) else []
264
+ return {"commands": cmds, "implied": implied, "flags": flags, "modes": modes, "hidden": hidden}
265
+
266
+
267
+ def command_delta(old: dict, new: dict, amap: dict) -> dict:
268
+ """Command paths and their options, old -> new, read through the NEW tree's alias tables: a path the
269
+ new tree spells differently is `renamed` (its old spelling keeps working), not removed; a path that
270
+ became a noun with verbs keeps every option one of its verbs has; a flag spelled differently is
271
+ `renamed` too. An option of the new tree's HELP_HIDDEN_FLAGS (accepted, help shown only where it acts)
272
+ is never removed."""
273
+ def target(path: str) -> str | None:
274
+ if path in new:
275
+ return path
276
+ for o, n in sorted(amap["commands"].items(), key=lambda kv: -len(kv[0])):
277
+ if path == o or path.startswith(o + " "):
278
+ cand = n + path[len(o):]
279
+ if cand in new:
280
+ return cand
281
+ if path in amap["implied"] and f"{path} {amap['implied'][path]}" in new:
282
+ return f"{path} {amap['implied'][path]}"
283
+ return None
284
+
285
+ renamed, removed, options = {}, [], {}
286
+ targets = set()
287
+ for path in sorted(old):
288
+ t = target(path)
289
+ if t is None:
290
+ removed.append(path)
291
+ continue
292
+ targets.add(t)
293
+ if t != path:
294
+ renamed[path] = t
295
+ noun = t.split(" ")[0] if t != path and path in amap["implied"] else None
296
+ have = set(new[t])
297
+ base = noun if noun is not None else (path if path and any(p.startswith(path + " ") for p in new) else None)
298
+ if base is not None: # a noun with verbs: an option of any verb still exists
299
+ have |= {o for p in new if p == base or p.startswith(base + " ") for o in new[p]}
300
+ fl = {o: n for p in new if p == t or (base and p.startswith(base + " "))
301
+ for o, n in amap["flags"].get(p, {}).items()}
302
+ gone = sorted(set(old[path]) - have)
303
+ ren = {o: fl[o] for o in gone if o in fl}
304
+ modes = amap.get("modes", {}).get(t, {}) # a mode split off as its own command (MODE_ALIASES)
305
+ moved = {o: modes[o] for o in gone if o in modes}
306
+ for o in gone:
307
+ if o not in ren and o not in moved:
308
+ hit = next((m for m in sorted(set(modes.values())) if o in new.get(m, ())), None)
309
+ if hit:
310
+ moved[o] = hit
311
+ lost = [o for o in gone if o not in fl and o not in moved and o not in amap.get("hidden", ())]
312
+ added = sorted(set(new[t]) - set(old[path]) - set(ren.values()))
313
+ if lost or ren or added or moved:
314
+ options[path if t == path else f"{path} -> {t}"] = {"added": added, "removed": lost, "renamed": ren,
315
+ "moved": moved}
316
+ added_paths = sorted(p for p in new if p not in old and p not in targets)
317
+ return {"added": added_paths, "removed": removed, "renamed": renamed, "options": options}
318
+
319
+
320
+ def _const(consts: dict, mod: str, name: str):
321
+ """The parsed value of constant `name` (any case) of module `mod`, None when absent. Module `core` falls
322
+ back to `cli`: the shared constants lived in cli.py until the core split (#317), so an older tree
323
+ reads the same as a newer one."""
324
+ found = consts.get(mod, {})
325
+ if mod == "core" and name.upper() not in found:
326
+ found = consts.get("cli", {})
327
+ return found.get(name.upper())
328
+
329
+
330
+ def surface(tree: Tree) -> dict:
331
+ """Everything mechanically derivable about one tree, as JSON-shaped data."""
332
+ py = tree.read("pyproject.toml")
333
+ proj = tomllib.loads(py).get("project", {}) if py else {}
334
+ modules = sorted(f for f in tree.files() if f.startswith(SRC + "/") and f.endswith(".py")
335
+ and "/" not in f[len(SRC) + 1:])
336
+ consts = {f[len(SRC) + 1:-3]: module_constants(tree.read(f)) for f in modules}
337
+ formats: dict[str, int] = {}
338
+ for mod in sorted(consts):
339
+ for _name, v in consts[mod].items():
340
+ if isinstance(v, str) and (m := FORMAT_RE.match(v)):
341
+ formats[m.group(1)] = max(formats.get(m.group(1), 0), int(m.group(2)))
342
+ elif isinstance(v, tuple) and v and all(isinstance(x, str) and FORMAT_RE.match(x) for x in v):
343
+ for x in v:
344
+ m = FORMAT_RE.match(x)
345
+ formats[m.group(1)] = max(formats.get(m.group(1), 0), int(m.group(2)))
346
+ named = {label: _jsonable(_const(consts, *where)) for label, where in NAMED.items()}
347
+ keys = {label: _key_names(_const(consts, *where)) for label, where in KEY_LISTS.items()}
348
+ jk = tree.read(JSON_KEYS)
349
+ try:
350
+ json_keys = {k: sorted(v.get("keys") or []) for k, v in json.loads(jk).items()} if jk else None
351
+ except (ValueError, AttributeError):
352
+ json_keys = None
353
+ data = {}
354
+ for d in DATA_DIRS:
355
+ data.update(tree.blobs(f"{SRC}/{d}"))
356
+ return {
357
+ "version": proj.get("version"),
358
+ "requires_python": proj.get("requires-python"),
359
+ "dependencies": sorted(proj.get("dependencies") or []),
360
+ "optional_dependencies": {k: sorted(v) for k, v in (proj.get("optional-dependencies") or {}).items()},
361
+ "scripts": sorted((proj.get("scripts") or {}).keys()),
362
+ "commands": help_surface(tree),
363
+ "json_keys": json_keys,
364
+ "formats": formats,
365
+ "named": named,
366
+ "keys": keys,
367
+ "aliases": alias_surface(consts.get("command_tree", {})) if "command_tree" in consts else None,
368
+ "alias_map": alias_map(consts.get("command_tree", {})),
369
+ "data_files": data,
370
+ }
371
+
372
+
373
+ # --------------------------------------------------------------------------
374
+ # the delta
375
+
376
+
377
+ def _set_delta(a, b) -> dict:
378
+ a, b = set(a or ()), set(b or ())
379
+ return {"added": sorted(b - a), "removed": sorted(a - b)}
380
+
381
+
382
+ def _map_delta(a: dict | None, b: dict | None) -> dict:
383
+ """Keyed lists: entries added/removed, and per common key the items added/removed."""
384
+ a, b = a or {}, b or {}
385
+ out = {**_set_delta(a.keys(), b.keys()), "changed": {}}
386
+ for k in sorted(set(a) & set(b)):
387
+ d = _set_delta(a[k], b[k])
388
+ if d["added"] or d["removed"]:
389
+ out["changed"][k] = d
390
+ return out
391
+
392
+
393
+ def _scalar(a, b) -> dict:
394
+ return {"from": a, "to": b, "changed": a != b}
395
+
396
+
397
+ def delta(old: dict, new: dict) -> dict:
398
+ formats = {"added": {}, "removed": {}, "changed": {}}
399
+ for fam in sorted(set(old["formats"]) | set(new["formats"])):
400
+ a, b = old["formats"].get(fam), new["formats"].get(fam)
401
+ if a is None:
402
+ formats["added"][fam] = f"{fam}/{b}"
403
+ elif b is None:
404
+ formats["removed"][fam] = f"{fam}/{a}"
405
+ elif a != b:
406
+ formats["changed"][fam] = {"from": f"{fam}/{a}", "to": f"{fam}/{b}"}
407
+ out = {
408
+ "version": _scalar(old["version"], new["version"]),
409
+ "requires_python": _scalar(old["requires_python"], new["requires_python"]),
410
+ "dependencies": _set_delta(old["dependencies"], new["dependencies"]),
411
+ "scripts": _set_delta(old["scripts"], new["scripts"]),
412
+ "commands": None if old["commands"] is None or new["commands"] is None else
413
+ command_delta(old["commands"], new["commands"], new["alias_map"]),
414
+ "json_keys": None if old["json_keys"] is None or new["json_keys"] is None else
415
+ _map_delta(old["json_keys"], new["json_keys"]),
416
+ "formats": formats,
417
+ "named": {k: _scalar(old["named"].get(k), new["named"].get(k)) for k in NAMED},
418
+ "keys": {k: _set_delta(old["keys"].get(k), new["keys"].get(k)) for k in KEY_LISTS},
419
+ "aliases": {k: _set_delta((old["aliases"] or {}).get(k), (new["aliases"] or {}).get(k))
420
+ for k in ("commands", "flags", "implied_verbs")},
421
+ "data_files": {**_set_delta(old["data_files"], new["data_files"]),
422
+ "changed": sorted(k for k in set(old["data_files"]) & set(new["data_files"])
423
+ if old["data_files"][k] != new["data_files"][k])},
424
+ }
425
+ return out
426
+
427
+
428
+ # --------------------------------------------------------------------------
429
+ # curated records
430
+
431
+
432
+ def load_records(tree: Tree) -> tuple[list[dict], list[str]]:
433
+ """Every entry of docs/upgrades/*.yaml at the tree (with its record's version), and problems."""
434
+ entries, problems = [], []
435
+ for f in sorted(x for x in tree.files() if x.startswith(RECORD_DIR + "/") and x.endswith(".yaml")):
436
+ try:
437
+ doc = yaml.safe_load(tree.read(f) or "")
438
+ except yaml.YAMLError as e:
439
+ problems.append(f"{f}: not valid YAML: {e}")
440
+ continue
441
+ problems += [f"{f}: {p}" for p in validate_record(doc)]
442
+ if not isinstance(doc, dict):
443
+ continue
444
+ if isinstance(doc.get("version"), str) and f != f"{RECORD_DIR}/{doc['version']}.yaml":
445
+ problems.append(f"{f}: the file name must be the record's version ({doc['version']}.yaml)")
446
+ for e in doc.get("changes") or []:
447
+ if isinstance(e, dict):
448
+ entries.append({**e, "record": f, "release": doc.get("version")})
449
+ for n in doc.get("no_author_change") or []:
450
+ if isinstance(n, int):
451
+ entries.append({"pr": n, "id": None, "no_author_change": True, "record": f,
452
+ "release": doc.get("version")})
453
+ return entries, problems
454
+
455
+
456
+ def validate_record(doc) -> list[str]:
457
+ """Problems of one curated record (schema lean-pkg-upgrade-record/1)."""
458
+ if not isinstance(doc, dict):
459
+ return ["not a mapping"]
460
+ out = []
461
+ if doc.get("schema") != RECORD_SCHEMA:
462
+ out.append(f"schema must be {RECORD_SCHEMA}")
463
+ if not isinstance(doc.get("version"), str) or not re.fullmatch(r"\d+\.\d+\.\d+", doc.get("version") or ""):
464
+ out.append("version must be X.Y.Z")
465
+ changes = doc.get("changes")
466
+ # Empty only while the release so far has no author-facing change: then no_author_change lists the PRs read.
467
+ if not isinstance(changes, list) or (not changes and not doc.get("no_author_change")):
468
+ return out + ["changes must be a non-empty list (or empty with a non-empty no_author_change)"]
469
+ extra = set(doc) - {"schema", "version", "changes", "no_author_change"}
470
+ if extra:
471
+ out.append(f"unknown key(s) {', '.join(sorted(extra))}")
472
+ nac = doc.get("no_author_change", [])
473
+ if not isinstance(nac, list) or not all(isinstance(n, int) and not isinstance(n, bool) and n > 0 for n in nac):
474
+ out.append("no_author_change must be a list of PR numbers")
475
+ seen = set()
476
+ by_pr: dict[int, list[dict]] = {}
477
+ for i, e in enumerate(changes):
478
+ if not isinstance(e, dict):
479
+ out.append(f"changes[{i}] is not a mapping")
480
+ continue
481
+ extra = set(e) - RECORD_KEYS
482
+ missing = {"pr", "id", "kind", "summary", "action", "breaking"} - set(e)
483
+ if extra:
484
+ out.append(f"changes[{i}]: unknown key(s) {', '.join(sorted(extra))}")
485
+ if missing:
486
+ out.append(f"changes[{i}]: missing {', '.join(sorted(missing))}")
487
+ if "pr" in e and not (isinstance(e["pr"], int) and not isinstance(e["pr"], bool) and e["pr"] > 0):
488
+ out.append(f"changes[{i}].pr must be a PR number")
489
+ if e.get("kind") not in RECORD_KINDS:
490
+ out.append(f"changes[{i}].kind must be one of {', '.join(RECORD_KINDS)}")
491
+ if "breaking" in e and not isinstance(e["breaking"], bool):
492
+ out.append(f"changes[{i}].breaking must be true or false")
493
+ if "split" in e and not isinstance(e["split"], bool):
494
+ out.append(f"changes[{i}].split must be true or false")
495
+ if e.get("id") in seen:
496
+ out.append(f"changes[{i}].id {e.get('id')!r} repeats")
497
+ seen.add(e.get("id"))
498
+ if isinstance(e.get("pr"), int) and not isinstance(e["pr"], bool):
499
+ by_pr.setdefault(e["pr"], []).append(e)
500
+ # One entry per pull request, unless the PR made several separate changes and each of its
501
+ # entries says so (split: true). An unmarked repeat is one change recorded twice, as #285
502
+ # was in 0.19.0 (one entry breaking, the other not).
503
+ for pr, es in by_pr.items():
504
+ ids = ", ".join(str(e.get("id")) for e in es)
505
+ if len(es) > 1 and not all(e.get("split") is True for e in es):
506
+ out.append(f"pr {pr} has {len(es)} entries ({ids}): merge them, or mark each split: true "
507
+ f"when the pull request made separate changes")
508
+ if len(es) == 1 and es[0].get("split") is True:
509
+ out.append(f"pr {pr} has one entry ({ids}) marked split: true")
510
+ if isinstance(nac, list):
511
+ for pr in sorted(set(by_pr) & {n for n in nac if isinstance(n, int)}):
512
+ out.append(f"pr {pr} is both a change and in no_author_change")
513
+ return out
514
+
515
+
516
+ def _released(repo: pathlib.Path, version: str) -> str | None:
517
+ """The commit of release X.Y.Z (tag or `release:` commit), None when it was never cut."""
518
+ try:
519
+ return resolve(repo, version)
520
+ except core.Fail:
521
+ return None
522
+
523
+
524
+ def provisional_problems(repo: pathlib.Path, tree: Tree) -> list[str]:
525
+ """Only the newest record may be unreleased: its name is provisional until the release is cut, when
526
+ scripts/cut-release.py renames it to the version actually cut (RELEASING.md "When to tag",
527
+ docs/design/upgrade-preflight.md). Reported: an older record that was never released, and an
528
+ unreleased record that lists a pull request already shipped in the tree's current version (the
529
+ record of that release kept its provisional name). A clone without any release commit or tag
530
+ compares nothing."""
531
+ recs: dict[str, str] = {}
532
+ for f in tree.files():
533
+ if f.startswith(RECORD_DIR + "/") and f.endswith(".yaml"):
534
+ try:
535
+ doc = yaml.safe_load(tree.read(f) or "")
536
+ except yaml.YAMLError:
537
+ continue
538
+ v = doc.get("version") if isinstance(doc, dict) else None
539
+ if isinstance(v, str) and re.fullmatch(r"\d+\.\d+\.\d+", v):
540
+ recs[v] = f
541
+ if not recs:
542
+ return []
543
+ key = lambda v: tuple(int(x) for x in v.split(".")) # noqa: E731
544
+ order = sorted(recs, key=key)
545
+ released = {v: _released(repo, v) for v in order}
546
+ try:
547
+ current = tomllib.loads(tree.read("pyproject.toml") or "")["project"]["version"]
548
+ except (tomllib.TOMLDecodeError, KeyError, TypeError):
549
+ current = None
550
+ cut = _released(repo, current) if isinstance(current, str) else None
551
+ if not any(released.values()) and cut is None:
552
+ return []
553
+ out = [f"{recs[v]}: {v} was never released (no tag v{v} or `release: {v}` commit); only the newest record "
554
+ f"may carry a provisional name" for v in order[:-1] if released[v] is None]
555
+ newest = order[-1]
556
+ if released[newest] is None:
557
+ if cut and current != newest:
558
+ doc = yaml.safe_load(tree.read(recs[newest]) or "") or {}
559
+ listed = {e.get("pr") for e in doc.get("changes") or [] if isinstance(e, dict)}
560
+ listed |= {n for n in doc.get("no_author_change") or [] if isinstance(n, int)}
561
+ shipped = sorted(n for n in merged_prs(repo, None, cut) if n in listed)
562
+ if shipped:
563
+ fix = (f"move them to {recs[current]}" if current in recs else
564
+ f"the record is {current}'s: rename it (scripts/release-version.py --rename {current})")
565
+ out.append(f"{recs[newest]}: unreleased (provisional name {newest}), but "
566
+ + ", ".join(f"#{n}" for n in shipped) + f" shipped in {current}; {fix}")
567
+ return out
568
+
569
+
570
+ def merged_prs(repo: pathlib.Path, old: str | None, new: str) -> dict[int, dict]:
571
+ """{PR number: {commit, subject}} for the commits in old..new (old None: all of new's history) whose
572
+ subject ends `(#N)`."""
573
+ p = core.git(repo, "log", "--format=%H%x09%s", f"{old}..{new}" if old else new)
574
+ out = {}
575
+ for line in p.stdout.splitlines():
576
+ h, _, subj = line.partition("\t")
577
+ m = re.search(r"\(#(\d+)\)\s*$", subj)
578
+ if m:
579
+ out.setdefault(int(m.group(1)), {"commit": h, "subject": subj})
580
+ return out
581
+
582
+
583
+ # --------------------------------------------------------------------------
584
+ # the command
585
+
586
+
587
+ def default_source() -> pathlib.Path | None:
588
+ """The git checkout the running lean-pkg is imported from (an editable install), else None."""
589
+ d = cli.package_dir()
590
+ p = core.git(d, "rev-parse", "--show-toplevel")
591
+ return pathlib.Path(p.stdout.strip()) if p.returncode == 0 and p.stdout.strip() else None
592
+
593
+
594
+ def preflight(repo: pathlib.Path, old_rev: str, new_rev: str) -> dict:
595
+ old, new = Tree(repo, old_rev), Tree(repo, new_rev)
596
+ if core.git(repo, "merge-base", "--is-ancestor", old.commit, new.commit).returncode != 0:
597
+ raise core.Fail(f"{old_rev} ({old.commit[:12]}) is not an ancestor of {new_rev} ({new.commit[:12]}); "
598
+ f"compare an older revision with a newer one")
599
+ s_old, s_new = surface(old), surface(new)
600
+ # Records are read at the checkout's HEAD when it descends from NEW (a record written after a release
601
+ # still describes it), else at NEW.
602
+ head = Tree(repo, "HEAD")
603
+ rec_tree = head if core.git(repo, "merge-base", "--is-ancestor", new.commit, head.commit).returncode == 0 else new
604
+ entries, problems = load_records(rec_tree)
605
+ problems += provisional_problems(repo, rec_tree)
606
+ prs = merged_prs(repo, old.commit, new.commit)
607
+ applies = [{**e, "commit": prs[e["pr"]]["commit"]} for e in entries if isinstance(e.get("pr"), int)
608
+ and e["pr"] in prs and not e.get("no_author_change")]
609
+ named_prs = {e.get("pr") for e in entries}
610
+ uncurated = [{"pr": n, **prs[n]} for n in sorted(prs) if n not in named_prs]
611
+ d = delta(s_old, s_new)
612
+ return {
613
+ "ok": True, "schema": SCHEMA,
614
+ "from": {"rev": old_rev, "commit": old.commit, "version": s_old["version"]},
615
+ "to": {"rev": new_rev, "commit": new.commit, "version": s_new["version"]},
616
+ "same_version": s_old["version"] == s_new["version"],
617
+ "mechanical": d,
618
+ "behavior": sorted(applies, key=lambda e: e["pr"]),
619
+ "breaking": [e["id"] for e in sorted(applies, key=lambda e: e["pr"]) if e.get("breaking")],
620
+ "uncurated": uncurated,
621
+ "record_problems": problems,
622
+ "records_at": rec_tree.commit,
623
+ "not_derivable": ["what a refusal rule accepts or refuses (curated: behavior[])",
624
+ "the meaning of a key whose name is unchanged",
625
+ "reader compatibility (which old format versions are still accepted)"],
626
+ }
627
+
628
+
629
+ def _lines(payload: dict) -> list[str]:
630
+ d, out = payload["mechanical"], []
631
+ f, t = payload["from"], payload["to"]
632
+ out.append(f"lean-pkg upgrade preflight: {f['rev']} ({f['commit'][:12]}, {f['version']}) -> "
633
+ f"{t['rev']} ({t['commit'][:12]}, {t['version']})")
634
+
635
+ def sec(title: str, items: list[str]) -> None:
636
+ if items:
637
+ out.append(f"{title}:")
638
+ out.extend(f" {x}" for x in items)
639
+
640
+ sec("python", [f"requires-python {d['requires_python']['from']} -> {d['requires_python']['to']}"]
641
+ if d["requires_python"]["changed"] else [])
642
+ sec("dependencies", [f"+ {x}" for x in d["dependencies"]["added"]] + [f"- {x}" for x in d["dependencies"]["removed"]])
643
+ sec("executables", [f"+ {x}" for x in d["scripts"]["added"]] + [f"- {x}" for x in d["scripts"]["removed"]])
644
+ fm = d["formats"]
645
+ sec("formats", [f"+ {v}" for v in fm["added"].values()] + [f"- {v}" for v in fm["removed"].values()]
646
+ + [f"{c['from']} -> {c['to']}" for c in fm["changed"].values()]
647
+ + [f"{k}: {v['from']} -> {v['to']}" for k, v in d["named"].items() if v["changed"]])
648
+ sec("on-disk keys", [f"{k}: " + ", ".join([f"+ {x}" for x in v["added"]] + [f"- {x}" for x in v["removed"]])
649
+ for k, v in d["keys"].items() if v["added"] or v["removed"]])
650
+ if d["commands"] is not None:
651
+ c = d["commands"]
652
+ sec("commands", [f"new: {x or 'lean-pkg'}" for x in c["added"]]
653
+ + [f"removed: {x or 'lean-pkg'}" for x in c["removed"]]
654
+ + [f"renamed: {o} -> {n} (the old spelling keeps working)" for o, n in c["renamed"].items()]
655
+ + [f"{k or 'lean-pkg'}: " + "; ".join(([f"new {', '.join(v['added'])}"] if v["added"] else [])
656
+ + ([f"removed {', '.join(v['removed'])}"] if v["removed"] else [])
657
+ + [f"renamed {o} -> {n}" for o, n in v["renamed"].items()]
658
+ + [f"{o} moved to `{n}` (the old form keeps working)"
659
+ for o, n in v.get("moved", {}).items()])
660
+ for k, v in c["options"].items()])
661
+ if d["json_keys"] is not None:
662
+ j = d["json_keys"]
663
+ sec("--json keys", [f"+ {x}" for x in j["added"]] + [f"- {x}" for x in j["removed"]]
664
+ + [f"{k}: " + ", ".join([f"+ {x}" for x in v["added"]] + [f"- {x}" for x in v["removed"]])
665
+ for k, v in j["changed"].items()])
666
+ a = d["aliases"]
667
+ sec("aliases", [f"+ {x}" for k in a for x in a[k]["added"]] + [f"- {x}" for k in a for x in a[k]["removed"]])
668
+ df = d["data_files"]
669
+ sec("packaged files", [f"+ {x}" for x in df["added"]] + [f"- {x}" for x in df["removed"]]
670
+ + [f"~ {x}" for x in df["changed"]])
671
+ sec("behavior (curated)", [f"#{e['pr']} {e['id']}{' [breaking]' if e.get('breaking') else ''}: {e['summary']}"
672
+ + (f"\n do: {e['action']}" if e.get("action") else "")
673
+ for e in payload["behavior"]])
674
+ sec("uncurated PRs in the range (read their CHANGELOG entries)",
675
+ [f"#{u['pr']} {u['subject']}" for u in payload["uncurated"]])
676
+ sec("record problems", payload["record_problems"])
677
+ out.append(f"breaking (curated): {', '.join(payload['breaking']) or 'none'}")
678
+ return out
679
+
680
+
681
+ def run(args) -> int:
682
+ src = pathlib.Path(args.upgrade_source).expanduser() if args.upgrade_source else default_source()
683
+ if src is None:
684
+ raise core.Fail("--upgrade-from needs a lean-pkg git checkout: this lean-pkg is not imported from one; "
685
+ "pass --source DIR (a clone of the lean-pkg repository)")
686
+ if core.git(src, "rev-parse", "--git-dir").returncode != 0:
687
+ raise core.Fail(f"--source {src}: not a git repository")
688
+ payload = preflight(src, args.upgrade_from, args.upgrade_to or "HEAD")
689
+ if args.json_out:
690
+ core.print_json(payload)
691
+ else:
692
+ print("\n".join(_lines(payload)))
693
+ return 0
694
+
695
+
696
+ def add_arguments(s) -> None:
697
+ s.add_argument("--upgrade-from", dest="upgrade_from", default=None, metavar="OLD",
698
+ help="instead of the diagnostics: what changed for a package author since OLD (a version, "
699
+ "0.9.0 / v0.9.0, or any commit of the lean-pkg repository): formats, on-disk keys, "
700
+ "commands, flags, --json keys, aliases, Python floor, packaged files, and the curated "
701
+ "behaviour changes of docs/upgrades/; read-only (docs/design/upgrade-preflight.md)")
702
+ s.add_argument("--to", dest="upgrade_to", default=None, metavar="NEW",
703
+ help="with --upgrade-from: the newer version or commit (default HEAD of the source)")
704
+ s.add_argument("--source", dest="upgrade_source", default=None, metavar="DIR",
705
+ help="with --upgrade-from: the lean-pkg git checkout to read both trees from (default: the "
706
+ "checkout this lean-pkg runs from)")