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,446 @@
1
+ """The committed docs-only opt-in, `lean-pkg-binding.yaml` (proposal 0002, #319).
2
+
3
+ A package opts in to the docs-only descendant rule (docs/receipts.md) with a small file committed in its
4
+ own directory:
5
+
6
+ schema: lean-pkg-binding/1
7
+ docs_descendants: true
8
+ build_inputs: # optional: files the build reads that Lake does not declare
9
+ - data/*.csv
10
+
11
+ Every command that binds a receipt to its commit X reads the file at X and nowhere else (read_at): never the
12
+ working tree, HEAD, the published ref or a commit between X and HEAD, so a later commit cannot grant itself
13
+ the rule. The file itself is always a build input under the docs-only rule (core.DOCS_ALWAYS_REFUSED), so a
14
+ reader at HEAD sees either no file or the very bytes that bound X.
15
+
16
+ resolve_opt_in applies the registry precedence of the proposal: a registry `docs_descendants: false` vetoes,
17
+ a registry `true` with no file still opts in (the deprecated route), and once the file exists at X it
18
+ decides. The parse is strict and fails closed: a file that does not validate does not opt in, and the output
19
+ names the file and the key.
20
+
21
+ Stage G3: render() is the file `new`, `page --write` and `update NAME --write-binding-file` write (write_into
22
+ never overwrites), and the registry route is deprecated: the deprecations[] entries and their stderr
23
+ `WARN: deprecated:` line (RELEASING.md, "Aliases and deprecations") come from here.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import dataclasses
29
+ import functools
30
+ import pathlib
31
+ import re
32
+ import subprocess
33
+
34
+ import yaml
35
+
36
+ from .core import scrubbed_env
37
+
38
+ FILE = "lean-pkg-binding.yaml"
39
+ SCHEMA = "lean-pkg-binding/1"
40
+ MAX_BYTES = 64 * 1024
41
+ KEYS = ("schema", "docs_descendants", "build_inputs")
42
+ _SCHEMA_RE = re.compile(r"lean-pkg-binding/([0-9]+)")
43
+ _STR_TAG = "tag:yaml.org,2002:str"
44
+ _HEX40 = re.compile(r"[0-9a-f]{40}")
45
+
46
+
47
+ @dataclasses.dataclass(frozen=True)
48
+ class BindingRead:
49
+ """The file at one commit. state: "absent", "valid" or "invalid"; doc: the parsed keys when valid."""
50
+ state: str
51
+ doc: dict | None = None
52
+ problems: tuple[str, ...] = ()
53
+
54
+
55
+ @dataclasses.dataclass(frozen=True)
56
+ class OptIn:
57
+ """The opt-in that binds evidence bound to `commit`. rule: "docs-only" or "evidence-only"; source:
58
+ "committed" (the file at X), "registry" (the record's docs_descendants: true, no file at X), "referee"
59
+ (receipt check --docs-descendants) or None; file_state: "absent", "true", "false" or "invalid";
60
+ build_inputs: the globs applied (the file's at X, then the registry record's); notes: what the output
61
+ says about a file or a record that did not decide the rule."""
62
+ rule: str
63
+ source: str | None
64
+ commit: str
65
+ path: str | None = None
66
+ file_state: str = "absent"
67
+ build_inputs: tuple[str, ...] = ()
68
+ problems: tuple[str, ...] = ()
69
+ notes: tuple[str, ...] = ()
70
+
71
+ @property
72
+ def label(self) -> str:
73
+ """Where the opt-in came from, for the admission line and its refusal."""
74
+ if self.source == "committed":
75
+ return f"opted in at {self.commit[:12]} by {FILE}"
76
+ if self.source == "registry":
77
+ return "opted in by the registry record"
78
+ return "opted in" # the referee's: receipt check adds "(accepted with --docs-descendants)"
79
+
80
+ def view(self) -> dict:
81
+ """The additive `opt_in` of the gate/regate/comparator events and --json."""
82
+ return {"source": self.source, "commit": self.commit, "path": self.path}
83
+
84
+
85
+ # --------------------------------------------------------------------------
86
+ # parse: strict, node level (YAML 1.1 would read `yes`/`on` as true)
87
+
88
+ def _events_problem(text: str) -> str | None:
89
+ """Anchors, aliases and explicit tags are refused: the file grants a rule, so what it says must be what
90
+ it reads as."""
91
+ for ev in yaml.parse(text, Loader=yaml.SafeLoader):
92
+ if isinstance(ev, yaml.AliasEvent):
93
+ return f"alias *{ev.anchor} is not allowed"
94
+ if getattr(ev, "anchor", None):
95
+ return f"anchor &{ev.anchor} is not allowed"
96
+ if isinstance(ev, (yaml.ScalarEvent, yaml.CollectionStartEvent)) and ev.tag is not None:
97
+ return f"explicit tag {ev.tag} is not allowed"
98
+ return None
99
+
100
+
101
+ def _scalar_value(node):
102
+ """A sequence item as build_inputs_errors expects it: the string of a str scalar, else a non-string."""
103
+ if isinstance(node, yaml.ScalarNode):
104
+ if node.tag == _STR_TAG:
105
+ return node.value
106
+ return yaml.safe_load(node.value) if node.value else None
107
+ return [] if isinstance(node, yaml.SequenceNode) else {}
108
+
109
+
110
+ def parse(raw: bytes, where: str = FILE) -> tuple[dict | None, list[str]]:
111
+ """(doc, problems) of the bytes of a lean-pkg-binding.yaml. doc is {schema, docs_descendants (bool),
112
+ build_inputs (list)} when there are no problems, else None. Each problem starts with `where`."""
113
+ from .audit import build_inputs_errors # audit imports gate, which imports this module
114
+ if len(raw) > MAX_BYTES:
115
+ return None, [f"{where}: {len(raw)} bytes, larger than the {MAX_BYTES}-byte limit"]
116
+ try:
117
+ text = raw.decode("utf-8-sig")
118
+ except UnicodeDecodeError as e:
119
+ return None, [f"{where}: not valid UTF-8 (byte {e.start})"]
120
+ try:
121
+ problem = _events_problem(text)
122
+ if problem:
123
+ return None, [f"{where}: {problem}"]
124
+ root = yaml.compose(text, Loader=yaml.SafeLoader)
125
+ except yaml.YAMLError as e:
126
+ return None, [f"{where}: not valid YAML: {' '.join(str(e).split())}"]
127
+ if root is None:
128
+ return None, [f"{where}: empty; it needs schema: {SCHEMA} and docs_descendants"]
129
+ if not isinstance(root, yaml.MappingNode):
130
+ return None, [f"{where}: top level is not a mapping"]
131
+ problems: list[str] = []
132
+ nodes: dict[str, yaml.Node] = {}
133
+ for k, v in root.value:
134
+ if not isinstance(k, yaml.ScalarNode) or k.tag != _STR_TAG:
135
+ problems.append(f"{where}: a key must be a plain string, got {getattr(k, 'value', k)!r}")
136
+ continue
137
+ if k.value in nodes:
138
+ problems.append(f"{where}: {k.value}: repeated key")
139
+ continue
140
+ if k.value not in KEYS:
141
+ problems.append(f"{where}: unknown key {k.value!r} (keys: {', '.join(KEYS)})")
142
+ continue
143
+ nodes[k.value] = v
144
+ sch = nodes.get("schema")
145
+ if sch is None:
146
+ problems.append(f"{where}: schema: missing; it must be {SCHEMA}")
147
+ elif not isinstance(sch, yaml.ScalarNode) or sch.tag != _STR_TAG or sch.value != SCHEMA:
148
+ val = getattr(sch, "value", None)
149
+ m = _SCHEMA_RE.fullmatch(val) if isinstance(val, str) else None
150
+ if m and int(m.group(1)) > 1:
151
+ problems.append(f"{where}: schema: {val} is newer than this lean-pkg reads ({SCHEMA}); "
152
+ f"upgrade lean-pkg")
153
+ else:
154
+ problems.append(f"{where}: schema: must be {SCHEMA}, got {val!r}")
155
+ dd = nodes.get("docs_descendants")
156
+ value = None
157
+ if dd is None:
158
+ problems.append(f"{where}: docs_descendants: missing; it must be true or false")
159
+ elif not (isinstance(dd, yaml.ScalarNode) and dd.style is None and dd.value in ("true", "false")):
160
+ shown = dd.value if isinstance(dd, yaml.ScalarNode) else type(dd).__name__
161
+ quoted = isinstance(dd, yaml.ScalarNode) and dd.style is not None
162
+ problems.append(f"{where}: docs_descendants: must be the literal true or false"
163
+ + (" (unquoted)" if quoted else "") + f", got {shown!r}")
164
+ else:
165
+ value = dd.value == "true"
166
+ globs: list = []
167
+ bi = nodes.get("build_inputs")
168
+ if bi is not None:
169
+ if not isinstance(bi, yaml.SequenceNode):
170
+ problems.append(f"{where}: build_inputs: must be a list of globs")
171
+ else:
172
+ globs = [_scalar_value(n) for n in bi.value]
173
+ problems += [f"{where}: {e.lstrip('.')}" for e in build_inputs_errors(globs, "")]
174
+ if problems:
175
+ return None, problems
176
+ return {"schema": SCHEMA, "docs_descendants": value, "build_inputs": list(globs)}, []
177
+
178
+
179
+ # --------------------------------------------------------------------------
180
+ # read_at: the file at the bound commit, from that commit's tree only
181
+
182
+ def _git(repo: pathlib.Path, *args: str) -> subprocess.CompletedProcess:
183
+ return subprocess.run(["git", "-C", str(repo), *args], capture_output=True, env=scrubbed_env())
184
+
185
+
186
+ @functools.lru_cache(maxsize=256)
187
+ def _location(repo: str) -> tuple[str, str] | None:
188
+ p = _git(pathlib.Path(repo), "rev-parse", "--show-toplevel", "--show-prefix")
189
+ if p.returncode != 0:
190
+ return None
191
+ lines = p.stdout.decode("utf-8", "replace").splitlines()
192
+ return (lines[0], lines[1] if len(lines) > 1 else "") if lines else None
193
+
194
+
195
+ @functools.lru_cache(maxsize=1024)
196
+ def _read(top: str, prefix: str, commit: str) -> BindingRead:
197
+ where = f"{FILE} at {commit[:12]}"
198
+ root = pathlib.Path(top)
199
+ path = f"{prefix}{FILE}"
200
+ # --full-tree from the toplevel: the path is exactly <prefix>/lean-pkg-binding.yaml, nothing else (rule 5)
201
+ p = _git(root, "ls-tree", "-l", "-z", "--full-tree", commit, "--", path)
202
+ if p.returncode != 0:
203
+ err = p.stderr.decode("utf-8", "replace").strip().splitlines()
204
+ return BindingRead("invalid", problems=(f"{where}: cannot read the tree"
205
+ + (f" ({err[0]})" if err else ""),))
206
+ recs = [r for r in p.stdout.decode("utf-8", "replace").split("\0") if r]
207
+ rec = next((r for r in recs if r.partition("\t")[2] == path), None)
208
+ if rec is None:
209
+ return BindingRead("absent")
210
+ mode, kind, sha, size = rec.partition("\t")[0].split()
211
+ if mode not in ("100644", "100755"):
212
+ what = {"120000": "a symlink", "160000": "a gitlink", "040000": "a directory"}.get(mode, f"mode {mode}")
213
+ return BindingRead("invalid", problems=(f"{where}: {what}, not a regular file",))
214
+ if size.isdigit() and int(size) > MAX_BYTES:
215
+ return BindingRead("invalid", problems=(f"{where}: {size} bytes, larger than the {MAX_BYTES}-byte limit",))
216
+ b = _git(root, "cat-file", "blob", sha) # the bytes of the very entry whose mode was checked
217
+ if b.returncode != 0:
218
+ return BindingRead("invalid", problems=(f"{where}: cannot read the blob {sha[:12]}",))
219
+ doc, problems = parse(b.stdout, where)
220
+ if problems:
221
+ return BindingRead("invalid", problems=tuple(problems))
222
+ return BindingRead("valid", doc=doc)
223
+
224
+
225
+ def read_at(repo: pathlib.Path, commit: str) -> BindingRead:
226
+ """The package's lean-pkg-binding.yaml as committed at `commit`: the entry <package dir>/FILE of that
227
+ commit's tree and nothing else (no working tree, no index, no other commit; a copy at the repository
228
+ root, under .lean-receipts/ or in a nested package's directory is another path). Only a regular file
229
+ (mode 100644 or 100755) of at most 64 KiB is read. Memoized by (toplevel, prefix, commit) for a full
230
+ commit id, which addresses the content."""
231
+ loc = _location(str(pathlib.Path(repo).resolve()))
232
+ if loc is None:
233
+ return BindingRead("invalid", problems=(f"{FILE} at {commit[:12]}: {repo} is not a git checkout",))
234
+ if _HEX40.fullmatch(commit or ""):
235
+ return _read(loc[0], loc[1], commit)
236
+ return _read.__wrapped__(loc[0], loc[1], commit)
237
+
238
+
239
+ # --------------------------------------------------------------------------
240
+ # resolve_opt_in: the registry precedence (proposal 0002, "Registry precedence")
241
+
242
+ def _globs(value) -> list[str]:
243
+ return [g for g in (value or []) if isinstance(g, str) and g.strip()] if isinstance(value, list) else []
244
+
245
+
246
+ def resolve_opt_in(repo: pathlib.Path, bound: str, pkg: dict | None) -> OptIn:
247
+ """The opt-in for evidence bound to `bound`, from the file at `bound` and the registry record `pkg`:
248
+
249
+ | file at X | record docs_descendants | rule | source |
250
+ |-----------|-------------------------|---------------|-----------|
251
+ | absent | absent or false | evidence-only | None |
252
+ | absent | true | docs-only | registry |
253
+ | true | absent or true | docs-only | committed |
254
+ | true | false | evidence-only | None (the record's veto is named) |
255
+ | false/invalid | any | evidence-only | None (the file is named; a record true is ignored) |
256
+
257
+ build_inputs is the file's globs (when it opts in) followed by the record's, without repeats: the
258
+ record can only add inputs."""
259
+ pkg = pkg or {}
260
+ reg = pkg.get("docs_descendants")
261
+ reg_globs = _globs(pkg.get("build_inputs"))
262
+ b = read_at(repo, bound)
263
+ x12 = bound[:12]
264
+ if b.state == "absent":
265
+ rule, source = ("docs-only", "registry") if reg is True else ("evidence-only", None)
266
+ return OptIn(rule, source, bound, None, "absent", tuple(reg_globs))
267
+ if b.state == "invalid":
268
+ notes = [f"{FILE} at {x12} does not opt in: {b.problems[0].split(': ', 1)[-1]}"]
269
+ if reg is True:
270
+ notes.append(f"the registry record's docs_descendants: true is ignored once {FILE} exists at {x12}")
271
+ return OptIn("evidence-only", None, bound, FILE, "invalid", tuple(reg_globs), b.problems, tuple(notes))
272
+ doc = b.doc or {}
273
+ if doc["docs_descendants"] is not True:
274
+ notes = [f"{FILE} at {x12} says docs_descendants: false"]
275
+ if reg is True:
276
+ notes.append(f"the registry record's docs_descendants: true is ignored once {FILE} exists at {x12}")
277
+ return OptIn("evidence-only", None, bound, FILE, "false", tuple(reg_globs), (), tuple(notes))
278
+ union = list(dict.fromkeys(_globs(doc.get("build_inputs")) + reg_globs))
279
+ if reg is False:
280
+ return OptIn("evidence-only", None, bound, FILE, "true", tuple(union), (), (
281
+ f"the registry record refuses the docs-only rule (docs_descendants: false), over {FILE} at {x12}",))
282
+ return OptIn("docs-only", "committed", bound, FILE, "true", tuple(union))
283
+
284
+
285
+ def referee_opt_in(repo: pathlib.Path, bound: str, accepted: bool = False, evidence_only: bool = False) -> OptIn:
286
+ """The opt-in of `receipt check`, which reads no registry (proposal 0002, stage G2; open questions 4 and 5):
287
+
288
+ | file at X | flags | rule | source |
289
+ |----------------|---------------------|---------------|-----------|
290
+ | true | none | docs-only | committed |
291
+ | any | --evidence-only | evidence-only | None (a file at X is named as ignored) |
292
+ | absent | --docs-descendants | docs-only | referee |
293
+ | absent | none | evidence-only | None |
294
+ | false/invalid | --docs-descendants | evidence-only | None (the flag is named as overridden) |
295
+
296
+ `accepted` is --docs-descendants, `evidence_only` --evidence-only; both at once is a usage error. The
297
+ file is read at `bound` only (read_at), so the referee's working tree is never consulted. build_inputs
298
+ keeps the file's globs even where the file is ignored, so the output can say what it declared."""
299
+ if accepted and evidence_only:
300
+ raise ValueError("--docs-descendants and --evidence-only are mutually exclusive")
301
+ oi = resolve_opt_in(repo, bound, None)
302
+ x12 = bound[:12]
303
+ if evidence_only:
304
+ notes = (f"{FILE} at {x12} opts in but is ignored: --evidence-only",) if oi.file_state == "true" else oi.notes
305
+ return dataclasses.replace(oi, rule="evidence-only", source=None, notes=notes)
306
+ if oi.file_state == "absent":
307
+ return OptIn("docs-only", "referee", bound) if accepted else oi
308
+ if oi.file_state == "true" or not accepted:
309
+ return oi
310
+ return dataclasses.replace(oi, notes=oi.notes + (
311
+ f"--docs-descendants is overridden: {FILE} at {x12} is the author's committed choice",))
312
+
313
+
314
+ # --------------------------------------------------------------------------
315
+ # render: the file `new`, `page --write` and `update NAME --write-binding-file` write (proposal 0002, stage G3)
316
+
317
+ COMMENT = f"""\
318
+ # {FILE}: this package's docs-only opt-in (lean-pkg docs/receipts.md, "Docs-only descendants").
319
+ # docs_descendants: true lets a receipt bound to commit X also bind a later commit that changes only files
320
+ # the build does not read (README.md, coverage.yaml, notes). A change to a build input (*.lean, lakefile.*,
321
+ # lake-manifest.json, lean-toolchain, a build_inputs glob, claims.yaml, this file) still needs a new receipt.
322
+ # lean-pkg reads this file at X only, never in the working tree: commit it before the verify run.
323
+ # Say false (or delete the file) to keep the strict evidence-only rule.
324
+ """
325
+
326
+
327
+ def render(docs_descendants: bool = True, build_inputs=(), comment: bool = True) -> str:
328
+ """The text of a lean-pkg-binding.yaml; parse() reads it back to the same keys. Each glob is written as
329
+ a double-quoted YAML string, so `*` and `:` never need thought."""
330
+ import json
331
+ text = (COMMENT if comment else "") + (f"schema: {SCHEMA}\n"
332
+ f"docs_descendants: {'true' if docs_descendants else 'false'}\n")
333
+ globs = _globs(list(build_inputs))
334
+ if globs:
335
+ text += "build_inputs:\n" + "".join(f" - {json.dumps(g, ensure_ascii=False)}\n" for g in globs)
336
+ return text
337
+
338
+
339
+ # --------------------------------------------------------------------------
340
+ # the deprecated registry route (RELEASING.md, "Aliases and deprecations"; its removal is stage G4)
341
+
342
+ DEPRECATION_ID = "registry-docs-descendants"
343
+ EARLIEST_REMOVAL = "1.0.0"
344
+ REMOVAL_RULE = ("the latest of 1.0.0, one minor release after the release that deprecated it, and two minor "
345
+ "releases plus 60 days")
346
+ DOCS = "docs/receipts.md#docs-only-descendants-opt-in"
347
+
348
+
349
+ def replacement(name: str) -> str:
350
+ return (f"`lean-pkg update {name} --write-binding-file`, then commit {FILE} in a commit of its own right "
351
+ f"before the next verify run")
352
+
353
+
354
+ def deprecation(name: str, what: str) -> dict:
355
+ """One `deprecations[]` entry of --json: the registry record's docs_descendants: true as the opt-in."""
356
+ return {"id": DEPRECATION_ID, "message": f"{name}: {what}", "replacement": replacement(name),
357
+ "earliest_removal": EARLIEST_REMOVAL, "removal_rule": REMOVAL_RULE}
358
+
359
+
360
+ def deprecation_line(d: dict) -> str:
361
+ """The stderr line of a deprecation: `WARN: deprecated: ...`, naming the replacement and the removal."""
362
+ return (f"WARN: deprecated: {d['message']}; replacement: {d['replacement']}; removed no earlier than "
363
+ f"{d['earliest_removal']} ({DOCS})")
364
+
365
+
366
+ def registry_admission_deprecation(name: str, commit: str) -> dict:
367
+ """gate, gate --check, comparator: the docs-only rule admitted HEAD through the registry record."""
368
+ return deprecation(name, f"the docs-only rule admitted HEAD through the registry record's docs_descendants: "
369
+ f"true, with no {FILE} at {commit[:12]}")
370
+
371
+
372
+ def registry_only_deprecation(name: str, commit: str | None) -> dict:
373
+ """publish --dry-run, page --write: the opt-in exists only in the registry record."""
374
+ where = f" at {commit[:12]}" if commit else ""
375
+ return deprecation(name, f"the docs-only opt-in exists only in the registry record (docs_descendants: true; "
376
+ f"no {FILE}{where})")
377
+
378
+
379
+ def accept_flag_deprecation(name: str) -> dict:
380
+ """update --accept-docs-descendants: it sets the registry route."""
381
+ return deprecation(name, "`update --accept-docs-descendants` sets the registry record's docs_descendants: "
382
+ "true, the deprecated route of the docs-only opt-in")
383
+
384
+
385
+ def admission_deprecations(name: str, docs_view: dict) -> dict:
386
+ """{"deprecations": [...]} when the docs-only rule admitted HEAD through the registry record's
387
+ docs_descendants: true (docs_view: gate.docs_admission's), else {}: the payload key is present only then,
388
+ so a package that uses neither route keeps its output byte for byte. Never part of an event (the events
389
+ carry opt_in.source)."""
390
+ view = docs_view.get("opt_in") or {}
391
+ if view.get("source") != "registry":
392
+ return {}
393
+ return {"deprecations": [registry_admission_deprecation(name, str(view.get("commit") or ""))]}
394
+
395
+
396
+ def print_deprecations(payload: dict) -> None:
397
+ """One stderr `WARN: deprecated: ...` line per payload deprecations[] entry, in text and --json mode
398
+ alike (stdout keeps the one JSON object)."""
399
+ import sys
400
+ for d in payload.get("deprecations") or []:
401
+ print(deprecation_line(d), file=sys.stderr)
402
+
403
+
404
+ def registry_only(repo: pathlib.Path, commit: str | None, pkg: dict | None) -> bool:
405
+ """Does the package's opt-in exist only in the registry record: the record says docs_descendants: true and
406
+ there is no lean-pkg-binding.yaml at `commit` (the gate-bound commit)?"""
407
+ if (pkg or {}).get("docs_descendants") is not True:
408
+ return False
409
+ if not commit:
410
+ return True
411
+ return read_at(repo, commit).state == "absent"
412
+
413
+
414
+ def commit_advice(x12: str) -> str:
415
+ """What to do with a written, uncommitted file (proposal 0002 plan, open question 1)."""
416
+ return (f"commit it in a commit of its own right before the next verify run, not together with README.md: "
417
+ f"it takes effect only for receipts bound at a commit that contains it, and a commit that adds it "
418
+ f"after {x12} unbinds the current receipts until that run ({DOCS})")
419
+
420
+
421
+ def write_into(directory: pathlib.Path, text: str, dry_run: bool = False) -> tuple[str, str | None]:
422
+ """Write `text` as directory/lean-pkg-binding.yaml unless something is there: (state, problem). state:
423
+ "written", "would-write" (dry run), "unchanged" (the same bytes, or a file that parses to the same keys),
424
+ "refused" (a symlink, a non-file, an unreadable file or a different one: never overwritten)."""
425
+ path = directory / FILE
426
+ if path.is_symlink():
427
+ return "refused", f"{path} is a symlink; nothing written (remove it, then run again)"
428
+ if path.exists():
429
+ if not path.is_file():
430
+ return "refused", f"{path} exists and is not a regular file; nothing written"
431
+ try:
432
+ old = path.read_bytes()
433
+ except OSError as e:
434
+ return "refused", f"{path}: cannot read it ({e.strerror}); nothing written"
435
+ if old == text.encode("utf-8"):
436
+ return "unchanged", None
437
+ have, _p = parse(old, str(path))
438
+ want, _w = parse(text.encode("utf-8"))
439
+ if have is not None and have == want:
440
+ return "unchanged", None
441
+ return "refused", (f"{path} already exists and says something else; nothing written (edit it by hand, "
442
+ f"or remove it and run again)")
443
+ if dry_run:
444
+ return "would-write", None
445
+ path.write_text(text, encoding="utf-8")
446
+ return "written", None
lean_pkg/blueprint.py ADDED
@@ -0,0 +1,213 @@
1
+ # lean-pkg blueprint -- cross-check a leanblueprint's declaration list with checkdecls
2
+ """`lean-pkg blueprint check NAME [--decls PATH]`: the blueprint cross-check (two-tracks gap #17).
3
+
4
+ leanblueprint writes every name in the blueprint's `\\lean{...}` tags to `blueprint/lean_decls`, one per
5
+ line. checkdecls (PatrickMassot/checkdecls, Apache-2.0) is a Lake executable that imports the package's
6
+ root modules and prints `NAME is missing.` for every listed name the environment does not contain. This
7
+ command runs it; it does not reimplement it, and it never vendors its code:
8
+
9
+ 1. the checkout must be clean (tracked files as committed at HEAD), so the answer is about HEAD;
10
+ 2. checkdecls must be a dependency in `lake-manifest.json` at HEAD: the package adds the `require`
11
+ (REQUIRE_LEAN / REQUIRE_TOML, pinned to CHECKDECLS_REV); lean-pkg never edits a lakefile;
12
+ 3. `lake build`, then `lake exe checkdecls PATH`; the `is missing.` lines are the missing names;
13
+ 4. claims.yaml at HEAD: every claim whose `decl` the blueprint names must be a name checkdecls accepts.
14
+ Claims outside the blueprint and blueprint names no claim carries are listed, never refused.
15
+
16
+ A package without a blueprint (no `blueprint/` directory and no declaration list) is skipped, exit 0.
17
+ Exit 0 when nothing is missing, 1 otherwise (a refusal is 1 as well). Nothing is written.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import pathlib
24
+ import re
25
+
26
+ from . import core
27
+
28
+ DEFAULT_DECLS = "blueprint/lean_decls"
29
+ CHECKDECLS_URL = "https://github.com/PatrickMassot/checkdecls.git"
30
+ # The latest tag (lean4.18.0) and the default branch's head when this was written; lake builds it with the
31
+ # package's own toolchain (run on v4.29.0 for this check's design).
32
+ CHECKDECLS_REV = "3d425859e73fcfbef85b9638c2a91708ef4a22d4"
33
+ REQUIRE_LEAN = f'require checkdecls from git "{CHECKDECLS_URL}" @ "{CHECKDECLS_REV}"'
34
+ REQUIRE_TOML = f'[[require]]\nname = "checkdecls"\ngit = "{CHECKDECLS_URL}"\nrev = "{CHECKDECLS_REV}"'
35
+ MISSING_RE = re.compile(r"^(?P<name>\S.*?) is missing\.$")
36
+ TAIL = 12
37
+
38
+
39
+ def run_lake(repo: pathlib.Path, *args: str):
40
+ """`lake ARGS` in the checkout, without the repository-selecting Git variables (#27)."""
41
+ return core.run(["lake", *args], cwd=str(repo), scrub=True)
42
+
43
+
44
+ def read_names(text: str) -> list[str]:
45
+ """The declaration list as leanblueprint writes it: one name per line (blank lines ignored)."""
46
+ out: list[str] = []
47
+ for line in text.splitlines():
48
+ name = line.strip()
49
+ if name and name not in out:
50
+ out.append(name)
51
+ return out
52
+
53
+
54
+ def parse_missing(output: str) -> list[str]:
55
+ """The names a checkdecls run reported (`NAME is missing.`), in output order."""
56
+ out: list[str] = []
57
+ for line in output.splitlines():
58
+ m = MISSING_RE.match(line.strip())
59
+ if m and m.group("name") not in out:
60
+ out.append(m.group("name"))
61
+ return out
62
+
63
+
64
+ def manifest_entry(repo: pathlib.Path) -> dict | None:
65
+ """checkdecls's entry in lake-manifest.json at HEAD, or None."""
66
+ raw = core.git_show_bytes(repo, "lake-manifest.json")
67
+ if raw is None:
68
+ return None
69
+ try:
70
+ doc = json.loads(raw.decode("utf-8", errors="replace"))
71
+ except ValueError:
72
+ return None
73
+ packages = doc.get("packages") if isinstance(doc, dict) else None
74
+ for p in packages if isinstance(packages, list) else []:
75
+ if isinstance(p, dict) and p.get("name") == "checkdecls":
76
+ return p
77
+ return None
78
+
79
+
80
+ def how_to_add(name: str) -> str:
81
+ return (f"{name}: checkdecls is not a dependency in lake-manifest.json at HEAD. Add it to the lakefile "
82
+ f"yourself (lean-pkg never edits it):\n"
83
+ f" lakefile.lean: {REQUIRE_LEAN}\n"
84
+ f" lakefile.toml: " + REQUIRE_TOML.replace("\n", "\n ") + "\n"
85
+ "then run `lake update checkdecls`, commit the lakefile and lake-manifest.json, and rerun")
86
+
87
+
88
+ def tail(text: str) -> str:
89
+ lines = [x for x in (text or "").strip().splitlines() if x.strip()]
90
+ return "\n ".join(lines[-TAIL:]) or "(no output)"
91
+
92
+
93
+ def safe_rel(path: str) -> str:
94
+ pp = pathlib.PurePosixPath(path)
95
+ if not path.strip() or pp.is_absolute() or ".." in pp.parts:
96
+ raise core.Fail(f"--decls must be a path relative to the checkout without '..': {path!r}")
97
+ return path
98
+
99
+
100
+ def claims_cross_check(pkg: dict, repo: pathlib.Path, names: list[str], missing: list[str]) -> dict:
101
+ from . import claims as claims_mod
102
+ rel = pkg.get("claims_file") or claims_mod.DEFAULT_CLAIMS_FILE
103
+ raw = core.git_show_bytes(repo, rel)
104
+ if raw is None:
105
+ return {"file": rel, "present": False, "checked": 0, "problems": [], "outside_blueprint": [],
106
+ "blueprint_without_claim": names}
107
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), f"{rel} at HEAD")
108
+ errors = claims_mod.validate_claims(doc, pkg["name"])
109
+ if errors:
110
+ raise core.Fail(f"{rel} at HEAD is not a valid claims/1 file:\n " + "\n ".join(errors[:10]))
111
+ claims = [c for c in doc.get("claims") or [] if isinstance(c, dict)]
112
+ in_bp, gone = set(names), set(missing)
113
+ problems = [f"claim {c['id']} names blueprint declaration {c['decl']}, which checkdecls reports missing"
114
+ for c in claims if c["decl"] in in_bp and c["decl"] in gone]
115
+ decls = {c["decl"] for c in claims}
116
+ return {"file": rel, "present": True, "checked": sum(c["decl"] in in_bp for c in claims),
117
+ "problems": problems,
118
+ "outside_blueprint": [c["id"] for c in claims if c["decl"] not in in_bp],
119
+ "blueprint_without_claim": [n for n in names if n not in decls]}
120
+
121
+
122
+ def skipped(name: str, commit: str, decls_rel: str, why: str) -> tuple[list[str], dict, int]:
123
+ payload = {"ok": True, "name": name, "commit": commit, "skipped": True, "reason": why,
124
+ "decls_file": decls_rel, "declarations": 0, "missing": [], "checkdecls": None, "claims": None}
125
+ return [f"{name}: blueprint check: skipped ({why})"], payload, 0
126
+
127
+
128
+ def do_blueprint_check(reg: dict, name: str, decls_rel: str = DEFAULT_DECLS) -> tuple[list[str], dict, int]:
129
+ pkg = core.get_pkg(reg, name)
130
+ repo = core.repo_path(pkg)
131
+ commit = core.git_head(repo) if repo.is_dir() else None
132
+ if commit is None:
133
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
134
+ decls_rel = safe_rel(decls_rel)
135
+ decls = repo / decls_rel
136
+ if not decls.is_file():
137
+ if decls_rel == DEFAULT_DECLS and not (repo / "blueprint").is_dir():
138
+ return skipped(name, commit, decls_rel, "no blueprint: neither blueprint/ nor a declaration list")
139
+ raise core.Fail(f"{name}: {decls_rel} does not exist; leanblueprint writes it when it builds the "
140
+ f"blueprint (`leanblueprint web`), or pass --decls PATH")
141
+ names = read_names(decls.read_text(encoding="utf-8", errors="replace"))
142
+ if not names:
143
+ return skipped(name, commit, decls_rel, f"{decls_rel} names no Lean declaration")
144
+ dirty = core.git(repo, "status", "--porcelain", "--untracked-files=no")
145
+ if dirty.returncode != 0 or dirty.stdout.strip():
146
+ raise core.Fail(f"{name}: the checkout has uncommitted changes to tracked files; commit or stash them, "
147
+ f"so the check is about HEAD ({commit[:12]})")
148
+ entry = manifest_entry(repo)
149
+ if entry is None:
150
+ raise core.Fail(how_to_add(name))
151
+ build = run_lake(repo, "build")
152
+ if build.returncode != 0:
153
+ raise core.Fail(f"{name}: `lake build` failed at {commit[:12]} (exit {build.returncode}); checkdecls "
154
+ f"imports the built package:\n {tail(build.stdout + build.stderr)}")
155
+ run = run_lake(repo, "exe", "checkdecls", decls_rel)
156
+ missing = parse_missing(run.stdout)
157
+ if run.returncode != 0 and not missing:
158
+ raise core.Fail(f"{name}: `lake exe checkdecls {decls_rel}` failed (exit {run.returncode}) without "
159
+ f"naming a missing declaration:\n {tail(run.stdout + run.stderr)}")
160
+ if run.returncode == 0 and missing:
161
+ raise core.Fail(f"{name}: checkdecls exited 0 but reported missing names; refusing the ambiguous run")
162
+ claims = claims_cross_check(pkg, repo, names, missing)
163
+ ok = not missing and not claims["problems"]
164
+ rev = str(entry.get("rev") or "")
165
+ payload = {"ok": ok, "name": name, "commit": commit, "skipped": False, "reason": None,
166
+ "decls_file": decls_rel, "declarations": len(names), "missing": missing,
167
+ "checkdecls": {"rev": rev, "url": entry.get("url"), "pinned": rev == CHECKDECLS_REV},
168
+ "claims": claims}
169
+ head = (f"{name}: blueprint check at {commit[:12]}: " +
170
+ ("OK" if ok else "FAILED") + f"; {len(names)} declaration(s) in {decls_rel}, {len(missing)} missing"
171
+ f"; checkdecls {rev[:12] or '?'}")
172
+ lines = [head] + [f" missing: {n}" for n in missing]
173
+ if claims["present"]:
174
+ lines.append(f" claims: {claims['checked']} claim(s) in {claims['file']} name a blueprint declaration")
175
+ lines += [f" problem: {p}" for p in claims["problems"]]
176
+ if claims["outside_blueprint"]:
177
+ lines.append(f" note: {len(claims['outside_blueprint'])} claim(s) outside the blueprint: "
178
+ + ", ".join(claims["outside_blueprint"]))
179
+ if claims["blueprint_without_claim"]:
180
+ lines.append(f" note: {len(claims['blueprint_without_claim'])} blueprint declaration(s) no claim "
181
+ f"carries: " + ", ".join(claims["blueprint_without_claim"]))
182
+ else:
183
+ lines.append(f" claims: no {claims['file']} at HEAD; claim cross-check skipped")
184
+ if rev != CHECKDECLS_REV:
185
+ lines.append(f" note: checkdecls at {rev[:12] or 'an unknown rev'}, not the documented pin "
186
+ f"{CHECKDECLS_REV[:12]}")
187
+ return lines, payload, 0 if ok else 1
188
+
189
+
190
+ def cmd_blueprint(args) -> int:
191
+ if getattr(args, "blueprint_cmd", None) != "check":
192
+ raise core.UsageError("usage: lean-pkg blueprint check NAME [--decls PATH]")
193
+ lines, payload, rc = do_blueprint_check(core.load_registry(core.registry_path(args)), args.name, args.decls)
194
+ if getattr(args, "json_out", False):
195
+ core.print_json(payload)
196
+ else:
197
+ print("\n".join(lines))
198
+ return rc
199
+
200
+
201
+ def add_parsers(sub, add_json) -> None:
202
+ s = sub.add_parser("blueprint", help="blueprint: check (\\lean{} names with checkdecls)")
203
+ add_json(s)
204
+ s.set_defaults(fn=cmd_blueprint, blueprint_cmd=None)
205
+ bsub = s.add_subparsers(dest="blueprint_cmd")
206
+ c = bsub.add_parser("check", help="run checkdecls on the blueprint's declaration list at HEAD and check "
207
+ "claims.yaml against it; exit 0 nothing missing / 1; writes nothing")
208
+ c.add_argument("name")
209
+ c.add_argument("--decls", default=DEFAULT_DECLS, metavar="PATH",
210
+ help=f"the declaration list, relative to the checkout (default {DEFAULT_DECLS}, written by "
211
+ f"leanblueprint)")
212
+ add_json(c)
213
+ c.set_defaults(fn=cmd_blueprint)