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
@@ -0,0 +1,615 @@
1
+ # lean-pkg command tree: canonical spellings, permanent aliases, the newcomer page
2
+ """The 1.0 command tree's spellings (docs/design/1.0-command-tree.md, accepted 2026-10-17).
3
+
4
+ Every renamed command or flag keeps its old spelling as a PERMANENT alias: the old argv parses to the
5
+ same namespace as the canonical one, JSON output and exit codes are unchanged, and text mode prints one
6
+ stderr note (`note: 'lean-pkg claim' is now 'lean-pkg lease claim' (the old spelling keeps working)`),
7
+ which LEAN_PKG_NO_ALIAS_NOTE=1 silences. Deprecation applies to behavior only, never to a spelling
8
+ (RELEASING.md).
9
+
10
+ This module is pure data plus argv rewriting: nothing here reads the registry or the network. Public API
11
+ (the CLI, the contract tests and the command-reference generator read it; keep it stable):
12
+
13
+ - COMMAND_ALIASES: tuple[CommandAlias, ...]. `old` words -> `new` (canonical) words, rewritten as an argv
14
+ prefix before argparse runs (`claim NAME ...` -> `lease claim NAME ...`).
15
+ - IMPLIED_VERBS: {noun: ImpliedVerb}. `noun ARG ...` where ARG is not one of the noun's verbs means
16
+ `noun verb ARG ...` (`lease NAME` -> `lease claim NAME`, `comparator NAME --receipt R` ->
17
+ `comparator attach NAME --receipt R`, `formalization NAME` -> `formalization render NAME`).
18
+ - MODE_ALIASES: tuple[ModeAlias, ...]. On command `command`, the flag `flag` selected another job before 1.0;
19
+ the argv is rewritten to the command `new`, the flag's value (if it takes one) becoming that command's
20
+ last positional (`lease release NAME --fresh-repo DIR` -> `repo export NAME DIR`).
21
+ - FLAG_ALIASES: tuple[FlagAlias, ...]. On the canonical command `command`, the option `old` is another
22
+ option string of `new` (same dest, same namespace); `apply_flag_aliases(root)` wires them.
23
+ - PROGRAM_FLAG_ALIASES: tuple[FlagAlias, ...]. The same for the programs beside lean-pkg (`comparator-receipt`,
24
+ `python3 -m lean_pkg.claim_axioms`, `python3 -m lean_pkg.dup_constants`), keyed on the program as typed;
25
+ `apply_program_flag_aliases(parser, program)` wires them, `program_notes(argv, program)` are their notes.
26
+ - HELP_HIDDEN_FLAGS: the options accepted by every command with --json but shown only where they act (the
27
+ commit flags, on write commands); the upgrade diff never counts them as removed.
28
+ - TIERS: {top-level command: tier}; `apply_tiers(root)` stores each tier on its parser (`parser.tier`), where
29
+ the tiered root --help and the command reference read it. TIER_TITLES names the tiers.
30
+ - aliases_of(path) / flag_aliases_of(path): the alias spellings of one canonical command, for its page.
31
+ - canonical_command(args): the canonical command path ("lease claim") a parsed namespace selects.
32
+ - rewrite_argv(argv) / rewrite_words(words): the rewriting itself; each returns (new argv, hits).
33
+ - NEWCOMER_VERBS, TRACKS, newcomer_text(), aliases_text(): the newcomer page and `lean-pkg help aliases`.
34
+
35
+ Internally a moved command keeps its pre-1.0 `cmd` value in the namespace (`lease claim` parses with
36
+ cmd == "claim"), so every predicate keyed on it (is_write_invocation, the lease warning, committed mode)
37
+ is unchanged; LEGACY_CMD maps it to the canonical path.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import os
44
+ import textwrap
45
+ from dataclasses import dataclass
46
+
47
+ NOTE_ENV = "LEAN_PKG_NO_ALIAS_NOTE" # 1/true/yes/on: no alias note on stderr
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class CommandAlias:
52
+ old: tuple[str, ...] # the old spelling, as argv words after the global flags
53
+ new: tuple[str, ...] # the canonical words it is rewritten to
54
+ unless: tuple[str, tuple[str, ...]] | None = None # (flag, words): without the flag, these words follow
55
+ # the new command (`promote NAME` -> `publish --yes --dry-run NAME`)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class ModeAlias:
60
+ command: tuple[str, ...] # canonical command path the old argv names (after COMMAND_ALIASES)
61
+ flag: str # the flag that selected another job
62
+ new: tuple[str, ...] # the command that job is now
63
+ value: bool # the flag takes a value, which becomes the new command's last positional
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class ImpliedVerb:
68
+ verb: str # inserted after the noun
69
+ verbs: tuple[str, ...] # the noun's verbs: a first word among them is never rewritten
70
+ unless_flag: str | None = None # ...unless this flag is present: then a verb other than `verb` names a
71
+ # package, as before 1.0 (`comparator config --receipt R`)
72
+ named: tuple[str, ...] = () # verbs that take NAME first and also take the flag: such a verb names a
73
+ # package only when no NAME follows it (`comparator check --receipt R`)
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class FlagAlias:
78
+ command: tuple[str, ...] # canonical command path
79
+ old: str # the old option string
80
+ new: str # the canonical option string (same dest)
81
+
82
+
83
+ COMMAND_ALIASES: tuple[CommandAlias, ...] = (
84
+ # coordination: leases (multi-agent registries)
85
+ CommandAlias(("claim",), ("lease", "claim")),
86
+ CommandAlias(("renew",), ("lease", "renew")),
87
+ CommandAlias(("release",), ("lease", "release")),
88
+ CommandAlias(("leases",), ("lease", "list")),
89
+ # maintenance: the registry file itself
90
+ CommandAlias(("init",), ("registry", "init")),
91
+ CommandAlias(("migrate",), ("registry", "migrate")),
92
+ CommandAlias(("validate",), ("registry", "validate")),
93
+ CommandAlias(("audit",), ("registry", "audit")),
94
+ CommandAlias(("board",), ("registry", "board")),
95
+ CommandAlias(("wiki",), ("registry", "wiki")),
96
+ # evidence
97
+ CommandAlias(("receipt", "local"), ("receipt", "systemd")),
98
+ CommandAlias(("verify-receipts",), ("receipt", "check")),
99
+ # publication: `promote NAME` was the dry run of `promote NAME --yes`
100
+ CommandAlias(("promote",), ("publish",), unless=("--yes", ("--yes", "--dry-run"))),
101
+ )
102
+
103
+ # (the old form's tail after the command, the new form's tail after the new command), for notes and docs
104
+ MODE_USAGE: dict[str, tuple[str, str]] = {
105
+ "--fresh-repo": ("NAME --fresh-repo DIR", "NAME DIR"),
106
+ "--adopt-repo": ("NAME --adopt-repo DIR", "NAME DIR"),
107
+ "--check": ("NAME --receipt R --check", "NAME --receipt R"),
108
+ "--coverage": ("--coverage NAME", "NAME"),
109
+ "--migrate-signoff": ("--migrate-signoff PATH", "PATH"),
110
+ }
111
+
112
+ MODE_ALIASES: tuple[ModeAlias, ...] = (
113
+ # `release` released a lease, or exported/adopted a repository
114
+ # (adopt first: release checked --adopt-repo first, so an argv naming both is refused as before)
115
+ ModeAlias(("lease", "release"), "--adopt-repo", ("repo", "adopt"), True),
116
+ ModeAlias(("lease", "release"), "--fresh-repo", ("repo", "export"), True),
117
+ # `comparator NAME --receipt R --check` validated without attaching
118
+ ModeAlias(("comparator", "attach"), "--check", ("comparator", "check"), False),
119
+ # `comparator config` had three modes; the two that are not "write a configuration" are verbs now
120
+ ModeAlias(("comparator", "config"), "--coverage", ("comparator", "coverage"), True),
121
+ ModeAlias(("comparator", "config"), "--migrate-signoff", ("comparator", "migrate-signoff"), True),
122
+ )
123
+
124
+ IMPLIED_VERBS: dict[str, ImpliedVerb] = {
125
+ # `lease NAME` was the alias of `claim NAME` (0.7)
126
+ "lease": ImpliedVerb("claim", ("claim", "renew", "release", "list")),
127
+ # `comparator NAME --receipt R [--check]`; `comparator config|host-check --receipt R` named a package
128
+ # (`comparator check NAME --receipt R` is the check verb; `comparator check --receipt R` the package)
129
+ "comparator": ImpliedVerb("attach", ("attach", "check", "config", "coverage", "migrate-signoff", "host-check"),
130
+ unless_flag="--receipt", named=("check",)),
131
+ # `formalization NAME [--write]` renders formalization.yaml
132
+ "formalization": ImpliedVerb("render", ("render", "anchor", "kept")),
133
+ }
134
+
135
+ FLAG_ALIASES: tuple[FlagAlias, ...] = (
136
+ # the DOI track, not the product track (`new --kind paper|library`)
137
+ FlagAlias(("record",), "--track", "--doi-track"),
138
+ FlagAlias(("update",), "--track", "--doi-track"),
139
+ # the receipt's commit, not the global --commit (commit the registry files)
140
+ FlagAlias(("receipt", "slurm"), "--commit", "--receipt-commit"),
141
+ FlagAlias(("receipt", "systemd"), "--commit", "--receipt-commit"),
142
+ FlagAlias(("receipt", "ci"), "--commit", "--receipt-commit"),
143
+ # --repo is a checkout directory; a remote URL is --url, a GitHub slug --target-repo
144
+ FlagAlias(("register",), "--repo", "--url"),
145
+ FlagAlias(("update",), "--repo", "--url"),
146
+ FlagAlias(("index", "add"), "--repo", "--url"),
147
+ FlagAlias(("index", "check"), "--repo-dir", "--repo"),
148
+ FlagAlias(("search",), "--repo-dir", "--repo"),
149
+ FlagAlias(("comparator", "config"), "--checkout", "--repo"),
150
+ FlagAlias(("report",), "--repo", "--target-repo"),
151
+ # --repo is the package checkout on every command; the comparator receipt said --project
152
+ FlagAlias(("receipt", "comparator"), "--project", "--repo"),
153
+ # a command that changes the registry and previews without the flag says --write
154
+ FlagAlias(("registry", "audit"), "--fix", "--write"),
155
+ )
156
+
157
+ # The same for the programs beside lean-pkg (their own parsers): `command` is the program as typed.
158
+ # `comparator-receipt` is `lean-pkg receipt comparator`; the two python3 -m checkers name the package
159
+ # checkout --repo, as every lean-pkg command does.
160
+ PROGRAM_FLAG_ALIASES: tuple[FlagAlias, ...] = (
161
+ FlagAlias(("comparator-receipt",), "--project", "--repo"),
162
+ FlagAlias(("python3 -m lean_pkg.claim_axioms",), "--project", "--repo"),
163
+ FlagAlias(("python3 -m lean_pkg.dup_constants",), "--project", "--repo"),
164
+ )
165
+
166
+ # Options every lean-pkg command with --json accepts, but whose help shows them only where they act: the
167
+ # commit flags, on the commands that can write the registry (cli.show_commit_flags_on_writes). Hidden is
168
+ # not removed: the upgrade diff (upgrade.command_delta), which reads the help goldens, never reports them
169
+ # as lost by a command.
170
+ HELP_HIDDEN_FLAGS: tuple[str, ...] = ("--commit", "--push", "--no-commit")
171
+
172
+ # The pre-1.0 `cmd` a moved command keeps in its namespace -> its canonical path.
173
+ LEGACY_CMD: dict[str, str] = {
174
+ "claim": "lease claim", "renew": "lease renew", "release": "lease release", "leases": "lease list",
175
+ "init": "registry init", "migrate": "registry migrate", "validate": "registry validate",
176
+ "audit": "registry audit", "board": "registry board", "wiki": "registry wiki",
177
+ }
178
+
179
+ # Top-level commands by tier (the root --help, the command reference index). Every top-level parser has one
180
+ # (apply_tiers fails loudly otherwise); an alias has none (it is not a parser).
181
+ TIER_TITLES: dict[str, str] = {
182
+ "newcomer": "START HERE: one package on your own machine",
183
+ "author": "PACKAGE AUTHOR: evidence, publication, the catalog",
184
+ "coordination": "COORDINATION AND MAINTENANCE: shared registries, leases, the registry file",
185
+ }
186
+ TIERS: dict[str, str] = {
187
+ "new": "newcomer", "verify": "newcomer", "status": "newcomer", "page": "newcomer", "publish": "newcomer",
188
+ "doctor": "newcomer", "help": "newcomer",
189
+ "register": "author", "update": "author", "record": "author", "gate": "author", "next": "author",
190
+ "list": "author", "search": "author", "receipt": "author", "comparator": "author", "claims": "author",
191
+ "coverage": "author", "formalization": "author", "palomar": "author", "reservoir": "author",
192
+ "blueprint": "author", "public-safety": "author", "report": "author", "seal-bundle": "author",
193
+ "lease": "coordination", "registry": "coordination", "repo": "coordination", "index": "coordination",
194
+ "llms": "coordination",
195
+ }
196
+
197
+ # argparse dests of the nouns' verb (and of the older nested commands), for canonical_command.
198
+ NOUN_DESTS = {"lease": "lease_cmd", "registry": "registry_cmd", "repo": "repo_cmd",
199
+ "comparator": "comparator_cmd", "formalization": "formalization_cmd"}
200
+ NESTED_DESTS = ("index_cmd", "claims_cmd", "reservoir_cmd", "blueprint_cmd", "palomar_cmd", "receipt_cmd",
201
+ "coverage_cmd")
202
+
203
+ # Root options that take a value (skipped when looking for the command word).
204
+ GLOBAL_VALUE_FLAGS = ("--registry", "--events", "--registry-snapshot")
205
+
206
+
207
+ # --------------------------------------------------------------------------
208
+ # rewriting
209
+
210
+
211
+ @dataclass(frozen=True)
212
+ class Hit:
213
+ old: str # the old spelling as typed, e.g. "claim" or "lease NAME" or "record --track"
214
+ new: str # the canonical spelling
215
+
216
+
217
+ def _command_index(argv: list[str], value_flags=GLOBAL_VALUE_FLAGS) -> int | None:
218
+ """Index of the command word in argv (after the global flags), else None."""
219
+ i = 0
220
+ while i < len(argv):
221
+ t = argv[i]
222
+ if t == "--":
223
+ return None
224
+ if t.startswith("-") and t != "-":
225
+ takes_value = "=" not in t and (t in value_flags or (
226
+ t.startswith("--") and len(t) > 2 and sum(f.startswith(t) for f in value_flags) == 1
227
+ and not any(f.startswith(t) for f in ("--json", "--commit", "--push", "--no-commit", "--version",
228
+ "--help"))))
229
+ i += 2 if takes_value else 1
230
+ continue
231
+ return i
232
+ return None
233
+
234
+
235
+ def _flag_at(words: list[str], flag: str, stop: int) -> int | None:
236
+ """Index of `flag` (or `flag=VALUE`) among words[:stop], else None."""
237
+ return next((i for i, w in enumerate(words[:stop]) if w == flag or w.startswith(flag + "=")), None)
238
+
239
+
240
+ def rewrite_words(words: list[str], implied: bool = True) -> tuple[list[str], list[Hit]]:
241
+ """Rewrite command words (no global flags in front) to their canonical spelling."""
242
+ words, hits = list(words), []
243
+ typed = "" # the old command words as typed, for a mode alias's note
244
+ for a in sorted(COMMAND_ALIASES, key=lambda a: -len(a.old)):
245
+ if tuple(words[:len(a.old)]) == a.old:
246
+ rest = words[len(a.old):]
247
+ stop = rest.index("--") if "--" in rest else len(rest)
248
+ new, old_text, new_text = list(a.new), " ".join(a.old), " ".join(a.new)
249
+ if a.unless is not None:
250
+ flag, extra = a.unless
251
+ if _flag_at(rest, flag, stop) is None:
252
+ new += list(extra)
253
+ new_text = " ".join(list(a.new) + list(extra))
254
+ else:
255
+ old_text, new_text = f"{old_text} {flag}", f"{new_text} {flag}"
256
+ words = new + rest
257
+ hits.append(Hit(old_text, new_text))
258
+ typed = " ".join(a.old)
259
+ break
260
+ if implied and len(words) > 1 and words[0] in IMPLIED_VERBS:
261
+ noun, iv, nxt = words[0], IMPLIED_VERBS[words[0]], words[1]
262
+ guarded = iv.unless_flag is not None and nxt != iv.verb and any(
263
+ w == iv.unless_flag or w.startswith(iv.unless_flag + "=") for w in words[2:]) and (
264
+ nxt not in iv.named or len(words) < 3 or words[2].startswith("-"))
265
+ if nxt not in ("-h", "--help") and (nxt not in iv.verbs or guarded):
266
+ words = [noun, iv.verb] + words[1:]
267
+ old = " ".join(h.old for h in hits) or noun
268
+ hits = [Hit(f"{old} NAME", f"{noun} {iv.verb} NAME")]
269
+ typed = f"{old} NAME"
270
+ for m in MODE_ALIASES:
271
+ n = len(m.command)
272
+ if tuple(words[:n]) != m.command:
273
+ continue
274
+ rest = words[n:]
275
+ stop = rest.index("--") if "--" in rest else len(rest)
276
+ i = _flag_at(rest, m.flag, stop)
277
+ if i is None:
278
+ continue
279
+ tok = rest[i]
280
+ if not m.value:
281
+ if "=" in tok: # `--check=x`: not this flag's spelling; argparse refuses it as before
282
+ continue
283
+ del rest[i]
284
+ stop -= 1
285
+ elif "=" in tok:
286
+ value = tok.split("=", 1)[1]
287
+ del rest[i]
288
+ stop -= 1
289
+ rest.insert(stop, value)
290
+ elif i + 1 < stop:
291
+ value = rest[i + 1]
292
+ del rest[i:i + 2]
293
+ stop -= 2
294
+ rest.insert(stop, value)
295
+ else: # the flag without its value: leave it, argparse names the problem on the new command
296
+ continue
297
+ old_cmd = typed or " ".join(m.command)
298
+ if old_cmd.endswith(" NAME"):
299
+ old_cmd = old_cmd[:-len(" NAME")]
300
+ words = list(m.new) + rest
301
+ hits = [Hit(f"{old_cmd} {MODE_USAGE[m.flag][0]}", f"{' '.join(m.new)} {MODE_USAGE[m.flag][1]}")]
302
+ break
303
+ return words, hits
304
+
305
+
306
+ def rewrite_argv(argv: list[str], value_flags=GLOBAL_VALUE_FLAGS) -> tuple[list[str], list[Hit]]:
307
+ """The whole argv (global flags included) with its command words canonical."""
308
+ argv = list(argv)
309
+ i = _command_index(argv, value_flags)
310
+ if i is None:
311
+ return argv, []
312
+ words, hits = rewrite_words(argv[i:])
313
+ return argv[:i] + words, hits
314
+
315
+
316
+ def flag_hits(argv: list[str], path: str) -> list[Hit]:
317
+ """The old flag spellings used on canonical command `path` (as returned by canonical_command)."""
318
+ i = _command_index(argv)
319
+ tokens = argv[i:] if i is not None else []
320
+ if "--" in tokens:
321
+ tokens = tokens[:tokens.index("--")]
322
+ out = []
323
+ for fa in FLAG_ALIASES:
324
+ if " ".join(fa.command) == path and any(t == fa.old or t.startswith(fa.old + "=") for t in tokens):
325
+ out.append(Hit(f"{path} {fa.old}", f"{path} {fa.new}"))
326
+ return out
327
+
328
+
329
+ def note_lines(hits: list[Hit], program: str = "lean-pkg") -> list[str]:
330
+ return [f"note: '{program} {h.old}' is now '{program} {h.new}' (the old spelling keeps working)" for h in hits]
331
+
332
+
333
+ def program_flag_hits(argv: list[str], program: str) -> list[Hit]:
334
+ """The old flag spellings (PROGRAM_FLAG_ALIASES) used in argv, the arguments after `program`."""
335
+ tokens = argv[:argv.index("--")] if "--" in argv else list(argv)
336
+ return [Hit(fa.old, fa.new) for fa in PROGRAM_FLAG_ALIASES if fa.command == (program,)
337
+ and any(t == fa.old or t.startswith(fa.old + "=") for t in tokens)]
338
+
339
+
340
+ def program_notes(argv: list[str], program: str, json_out: bool = False) -> list[str]:
341
+ """The stderr notes of a program beside lean-pkg for the old flag spellings in argv: text mode only,
342
+ silenced by LEAN_PKG_NO_ALIAS_NOTE=1, as lean-pkg's own."""
343
+ if json_out or not notes_enabled():
344
+ return []
345
+ return note_lines(program_flag_hits(argv, program), program)
346
+
347
+
348
+ def notes_enabled() -> bool:
349
+ return os.environ.get(NOTE_ENV, "").strip().lower() not in ("1", "true", "yes", "on")
350
+
351
+
352
+ # --------------------------------------------------------------------------
353
+ # the parser side
354
+
355
+
356
+ def _sub_action(parser: argparse.ArgumentParser):
357
+ return next((a for a in parser._actions if isinstance(a, argparse._SubParsersAction)), None)
358
+
359
+
360
+ def find_parser(root: argparse.ArgumentParser, path: tuple[str, ...]) -> argparse.ArgumentParser | None:
361
+ p = root
362
+ for word in path:
363
+ action = _sub_action(p)
364
+ if action is None or word not in action.choices:
365
+ return None
366
+ p = action.choices[word]
367
+ return p
368
+
369
+
370
+ def _alias_option(p: argparse.ArgumentParser, fa: FlagAlias, table: str) -> None:
371
+ action = p._option_string_actions.get(fa.new)
372
+ if action is None:
373
+ raise AssertionError(f"{table}: {' '.join(fa.command)} has no {fa.new}")
374
+ if fa.old in p._option_string_actions:
375
+ raise AssertionError(f"{table}: {' '.join(fa.command)} already has {fa.old}")
376
+ # Parsed exactly like the canonical option, but named in its help text rather than added to
377
+ # option_strings: argparse lays out a multi-spelling option differently across Python versions,
378
+ # and the help goldens are compared word by word.
379
+ p._option_string_actions[fa.old] = action
380
+ if action.help and action.help is not argparse.SUPPRESS:
381
+ action.help = f"{action.help} (old spelling {fa.old}, kept working)"
382
+
383
+
384
+ def apply_flag_aliases(root: argparse.ArgumentParser) -> None:
385
+ """Make each FLAG_ALIASES old spelling parse as its canonical option (same action, same dest)."""
386
+ for fa in FLAG_ALIASES:
387
+ p = find_parser(root, fa.command)
388
+ if p is None:
389
+ raise AssertionError(f"FLAG_ALIASES: no command {' '.join(fa.command)!r}")
390
+ _alias_option(p, fa, "FLAG_ALIASES")
391
+
392
+
393
+ def apply_program_flag_aliases(parser: argparse.ArgumentParser, program: str) -> None:
394
+ """The same for a program beside lean-pkg: each PROGRAM_FLAG_ALIASES row of `program` on its parser."""
395
+ for fa in PROGRAM_FLAG_ALIASES:
396
+ if fa.command == (program,):
397
+ _alias_option(parser, fa, "PROGRAM_FLAG_ALIASES")
398
+
399
+
400
+ def apply_tiers(root: argparse.ArgumentParser) -> None:
401
+ """Store each top-level command's tier on its parser (`parser.tier`); the root --help and the command
402
+ reference group by it. A top-level command without a tier, or a tier for no command, fails loudly."""
403
+ action = _sub_action(root)
404
+ names = set(action.choices)
405
+ missing, unknown = sorted(names - set(TIERS)), sorted(set(TIERS) - names)
406
+ if missing or unknown:
407
+ raise AssertionError(f"command_tree.TIERS: no tier for {missing}; no command {unknown}")
408
+ for name, p in action.choices.items():
409
+ p.tier = TIERS[name]
410
+
411
+
412
+ def tier_rows(root: argparse.ArgumentParser) -> list[tuple[str, list[tuple[str, str]]]]:
413
+ """[(tier, [(command, one-line help)])] in TIER_TITLES order, commands in TIERS order, read from the
414
+ parser (`parser.tier`, set by apply_tiers; the help from each command's add_parser)."""
415
+ action = _sub_action(root)
416
+ helps = {a.dest: a.help or "" for a in action._choices_actions}
417
+ out = []
418
+ for tier in TIER_TITLES:
419
+ names = [n for n in TIERS if getattr(action.choices.get(n), "tier", None) == tier]
420
+ out.append((tier, [(n, helps.get(n, "")) for n in names]))
421
+ return out
422
+
423
+
424
+ def root_help(root: argparse.ArgumentParser) -> str:
425
+ """The root --help in tiers: usage, the commands grouped newcomer / package author / coordination (from
426
+ the parser's tier data), then the global options and the epilog."""
427
+ fmt = root._get_formatter()
428
+ width = max(fmt._width, 60)
429
+ out = [root.format_usage().rstrip(), ""]
430
+ if root.description:
431
+ out += [textwrap.fill(root.description, width), ""]
432
+ rows = tier_rows(root)
433
+ col = max(len(n) for _t, names in rows for n, _h in names) + 4
434
+ for tier, names in rows:
435
+ out.append(TIER_TITLES[tier])
436
+ for name, text in names:
437
+ body = textwrap.wrap(text, max(width - col, 30)) or [""]
438
+ out.append(f" {name.ljust(col - 2)}{body[0]}")
439
+ out += [" " * col + more for more in body[1:]]
440
+ out.append("")
441
+ fmt = root._get_formatter()
442
+ fmt.start_section("global options")
443
+ fmt.add_arguments([a for a in root._actions if a.option_strings])
444
+ fmt.end_section()
445
+ out.append(fmt.format_help().strip("\n"))
446
+ if root.epilog:
447
+ out += ["", textwrap.fill(root.epilog, width)]
448
+ return "\n".join(out) + "\n"
449
+
450
+
451
+ def tier_of(root: argparse.ArgumentParser, name: str) -> str | None:
452
+ action = _sub_action(root)
453
+ p = action.choices.get(name) if action else None
454
+ return getattr(p, "tier", None)
455
+
456
+
457
+ def canonical_command(args) -> str:
458
+ """The canonical command path a parsed namespace selects ("" for a bare `lean-pkg`)."""
459
+ cmd = getattr(args, "cmd", None)
460
+ if cmd is None:
461
+ return ""
462
+ if getattr(args, "repo_cmd", None): # `repo move|export|adopt` keep update's / release's cmd
463
+ return f"repo {args.repo_cmd}"
464
+ if cmd in LEGACY_CMD:
465
+ return LEGACY_CMD[cmd]
466
+ if cmd in NOUN_DESTS and getattr(args, NOUN_DESTS[cmd], None):
467
+ return f"{cmd} {getattr(args, NOUN_DESTS[cmd])}"
468
+ for dest in NESTED_DESTS:
469
+ sub = getattr(args, dest, None)
470
+ if sub:
471
+ return f"{cmd} {sub}"
472
+ return cmd
473
+
474
+
475
+ def aliases_of(path: tuple[str, ...] | str) -> list[str]:
476
+ """The old spellings of a canonical command, e.g. aliases_of("lease claim") == ["claim", "lease NAME"]."""
477
+ path = tuple(path.split()) if isinstance(path, str) else tuple(path)
478
+ out = [" ".join(a.old) for a in COMMAND_ALIASES if a.new == path]
479
+ if len(path) == 2 and path[0] in IMPLIED_VERBS and IMPLIED_VERBS[path[0]].verb == path[1]:
480
+ out.append(f"{path[0]} NAME")
481
+ for m in MODE_ALIASES:
482
+ if m.new == path:
483
+ tail = MODE_USAGE[m.flag][0]
484
+ out.append(f"{' '.join(m.command)} {tail}")
485
+ out += [f"{' '.join(a.old)} {tail}" for a in COMMAND_ALIASES if a.new == m.command]
486
+ if len(m.command) == 2 and m.command[0] in IMPLIED_VERBS and IMPLIED_VERBS[m.command[0]].verb == m.command[1]:
487
+ out.append(f"{m.command[0]} {tail}")
488
+ return out
489
+
490
+
491
+ def flag_aliases_of(path: tuple[str, ...] | str) -> dict[str, list[str]]:
492
+ """{canonical flag: [old spellings]} on one canonical command."""
493
+ path = tuple(path.split()) if isinstance(path, str) else tuple(path)
494
+ out: dict[str, list[str]] = {}
495
+ for fa in FLAG_ALIASES:
496
+ if fa.command == path:
497
+ out.setdefault(fa.new, []).append(fa.old)
498
+ return out
499
+
500
+
501
+ # --------------------------------------------------------------------------
502
+ # the newcomer page and `help aliases`
503
+
504
+ # (verb, usage, one line). Availability is read from the parser, never assumed.
505
+ NEWCOMER_VERBS: tuple[tuple[str, str, str], ...] = (
506
+ ("new", "new NAME", "scaffold a Lean package that the receipts, the gate and the page accept"),
507
+ ("verify", "verify NAME", "run the lower-tier receipt, the comparator receipt and the gate in one step"),
508
+ ("status", "status NAME", "the package's record, history and scope"),
509
+ ("page", "page NAME", "the README verification section: what is verified, at which commit"),
510
+ ("publish", "publish NAME", "the checklist from verified-private to public"),
511
+ )
512
+
513
+ # What to run until a newcomer verb arrives.
514
+ UNTIL_THEN = {
515
+ "new": "registry init, then register NAME --url URL --path DIR",
516
+ }
517
+
518
+ # (step, track P: the paper is the product, track L: the Lean package is the product)
519
+ TRACKS: tuple[tuple[str, str, str], ...] = (
520
+ ("start", "new NAME --kind paper", "new NAME --kind library"),
521
+ ("bind the source", "formalization anchor NAME --arxiv IDvN", "(none: the rows are the main results)"),
522
+ ("verify", "verify NAME", "verify NAME"),
523
+ ("page", "page NAME --write", "page NAME --write"),
524
+ ("publish", "publish NAME --yes", "publish NAME --yes"),
525
+ ("after", "palomar prepare NAME", "index add NAME"),
526
+ )
527
+
528
+ _ROOT: list[argparse.ArgumentParser] = [] # the parser main built, for availability
529
+
530
+
531
+ def register_root(root: argparse.ArgumentParser) -> None:
532
+ _ROOT[:] = [root]
533
+
534
+
535
+ def missing(command: str, root: argparse.ArgumentParser | None = None) -> str | None:
536
+ """What of `command` (words, placeholders in capitals, flags) the parser lacks: "verify" (a command),
537
+ "new --kind" (a flag of it), else None. None too when no parser is known (nothing to check)."""
538
+ root = root or (_ROOT[0] if _ROOT else None)
539
+ if root is None or command.startswith("("):
540
+ return None
541
+ p, path = root, []
542
+ for word in command.split():
543
+ if word.startswith("-") or not word.islower():
544
+ break
545
+ action = _sub_action(p)
546
+ if action is None:
547
+ break
548
+ if word not in action.choices:
549
+ return " ".join(path + [word])
550
+ p = action.choices[word]
551
+ path.append(word)
552
+ flag = next((f for f in command.split() if f.startswith("--") and f not in p._option_string_actions), None)
553
+ return f"{' '.join(path)} {flag}" if flag else None
554
+
555
+
556
+ def available(command: str, root: argparse.ArgumentParser | None = None) -> bool:
557
+ return missing(command, root) is None
558
+
559
+
560
+ def newcomer_text(root: argparse.ArgumentParser | None = None) -> str:
561
+ """The newcomer page: five verbs, one line each, and the two product tracks as two columns. A command
562
+ the installed lean-pkg does not have yet is marked `*`, with what to run until then."""
563
+ pending: list[str] = []
564
+
565
+ def mark(c: str) -> str:
566
+ m = missing(c, root)
567
+ if m is None:
568
+ return c
569
+ if m not in pending:
570
+ pending.append(m)
571
+ return c + " *"
572
+
573
+ out = ["lean-pkg: a registry and trust gate for Lean 4 formalization packages.", "",
574
+ "START HERE: five verbs"]
575
+ for _verb, usage, line in NEWCOMER_VERBS:
576
+ out.append(f" {mark(usage).ljust(16)}{line}")
577
+ out += ["", "TWO TRACKS: what you publish"]
578
+ rows = [("", "paper (the paper is the product)", "library (the Lean package is)")]
579
+ rows += [(step, mark(p), mark(lib)) for step, p, lib in TRACKS]
580
+ w0 = max(len(r[0]) for r in rows) + 2
581
+ w1 = max(len(r[1]) for r in rows) + 2
582
+ out += [f" {step.ljust(w0)}{p.ljust(w1)}{lib}".rstrip() for step, p, lib in rows]
583
+ if pending:
584
+ out += ["", "* coming in the next release; until then:"]
585
+ out += [f" {m}: {UNTIL_THEN.get(m, 'see lean-pkg help')}" for m in pending]
586
+ out += ["", "MORE",
587
+ " lean-pkg help every command and the help topics",
588
+ " lean-pkg help aliases old spellings that keep working",
589
+ " lean-pkg <command> -h one command's flags"]
590
+ return "\n".join(out) + "\n"
591
+
592
+
593
+ def aliases_text() -> str:
594
+ """`lean-pkg help aliases`: every permanent alias, command and flag."""
595
+ out = ["Old spellings are permanent aliases: they parse exactly like the canonical spelling, with the",
596
+ "same JSON output and exit codes. In text mode each use prints one stderr note; set",
597
+ f"{NOTE_ENV}=1 to silence it. Deprecation applies to behavior, never to a spelling.", "",
598
+ "COMMANDS"]
599
+ rows = [(" ".join(a.old), " ".join(a.new) + (f" (without {a.unless[0]}: {' '.join(a.new + a.unless[1])})"
600
+ if a.unless else "")) for a in COMMAND_ALIASES]
601
+ rows += [(f"{noun} NAME ...", f"{noun} {iv.verb} NAME ...") for noun, iv in IMPLIED_VERBS.items()]
602
+ rows += [(f"{' '.join(m.command)} {MODE_USAGE[m.flag][0]}", f"{' '.join(m.new)} {MODE_USAGE[m.flag][1]}")
603
+ for m in MODE_ALIASES]
604
+ width = max(len(o) for o, _ in rows) + 4
605
+ out += [f" lean-pkg {o.ljust(width)}lean-pkg {n}" for o, n in rows]
606
+ out += ["", "FLAGS"]
607
+ rows = [(f"{' '.join(fa.command)} {fa.old}", fa.new) for fa in FLAG_ALIASES]
608
+ rows += [(f"{fa.command[0]} {fa.old}", fa.new) for fa in PROGRAM_FLAG_ALIASES]
609
+ width = max(len(o) for o, _ in rows) + 4
610
+ out += [f" {o.ljust(width)}{n}" for o, n in rows]
611
+ out += ["", "PROGRAMS",
612
+ " comparator-receipt ... lean-pkg receipt comparator ... (the same code and flags; both stay)"]
613
+ out += ["", textwrap.fill("`comparator config|host-check|check|coverage --receipt R` (no NAME after the verb) "
614
+ "still attaches a receipt to a package named so, as before.", 100)]
615
+ return "\n".join(out) + "\n"