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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/seal_bundle.py
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
"""`lean-pkg seal-bundle`: render a hash-bound job bundle from lower-tier receipts and a package template.
|
|
2
|
+
|
|
3
|
+
A seal is a job (an external kernel replay, a fresh rebuild, an axiom audit) that re-checks a commit some
|
|
4
|
+
receipt already verified. Its bundle is the job script plus every input it binds by hash: the source
|
|
5
|
+
archive, module lists and the package's helper scripts, with INPUT-SHA256SUMS over them. Assembled by hand,
|
|
6
|
+
each seal edits the same lines (commit, tree, dependency pins, theorem counts, inline hashes) and can get
|
|
7
|
+
one wrong (#414). Here every such value is derived from the receipts and the commit:
|
|
8
|
+
|
|
9
|
+
- the commit from the first package's receipt; the tree is `git rev-parse COMMIT:./` of --repo;
|
|
10
|
+
- each other package's receipt must name a commit whose tree for that package equals the bundled one,
|
|
11
|
+
apart from .lean-receipts/ (its own receipt, committed after its gate);
|
|
12
|
+
- module lists from each package's umbrella imports, which must equal its .lean files;
|
|
13
|
+
- counts from a pattern over each receipt's sealed verify log (one distinct value, else a refusal);
|
|
14
|
+
- dependency revisions from lake-manifest.json committed at the commit;
|
|
15
|
+
- source.tgz: `git archive --mtime=@<commit time> COMMIT:./`, gzip without a name or time, so the
|
|
16
|
+
same commit always gives the same bytes.
|
|
17
|
+
|
|
18
|
+
The template is the package's own job script with @@NAME@@ placeholders; the job body stays the
|
|
19
|
+
package's. lean-pkg knows no site: paths of a cluster are written in the template as they are.
|
|
20
|
+
`--check DIR` re-derives an existing bundle and lists every difference (calibration of a hand-made one).
|
|
21
|
+
Nothing here writes a receipt, the registry or the event log.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import difflib
|
|
27
|
+
import gzip
|
|
28
|
+
import hashlib
|
|
29
|
+
import io
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import pathlib
|
|
33
|
+
import re
|
|
34
|
+
import subprocess
|
|
35
|
+
import tarfile
|
|
36
|
+
|
|
37
|
+
import yaml
|
|
38
|
+
|
|
39
|
+
from . import core
|
|
40
|
+
from . import gate as gate_mod
|
|
41
|
+
from .core import Fail, UsageError
|
|
42
|
+
|
|
43
|
+
SPEC_SCHEMA = "seal-bundle/1"
|
|
44
|
+
SPEC_KEYS = {"schema", "template", "packages", "script", "source", "sums", "all_list", "pilot_list",
|
|
45
|
+
"counts", "deps", "files"}
|
|
46
|
+
SPEC_REQUIRED = ("schema", "template", "packages")
|
|
47
|
+
PACKAGE_KEYS = {"key", "dir", "umbrella", "list"}
|
|
48
|
+
COUNT_KEYS = {"var", "package", "pattern"}
|
|
49
|
+
DEFAULTS = {"script": "gate.sbatch", "source": "source.tgz", "sums": "INPUT-SHA256SUMS",
|
|
50
|
+
"pilot_list": "modules-pilot.txt"}
|
|
51
|
+
KEY_RE = re.compile(r"^[a-z][a-z0-9-]{0,39}$")
|
|
52
|
+
VAR_RE = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$")
|
|
53
|
+
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") # a bundle file name: no directory
|
|
54
|
+
MODULE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_']*(?:\.[A-Za-z_][A-Za-z0-9_']*)*$")
|
|
55
|
+
IMPORT_RE = re.compile(r"^import\s+(\S+)\s*$")
|
|
56
|
+
PLACEHOLDER_RE = re.compile(r"@@([A-Z][A-Z0-9_]*)(?::([A-Za-z0-9._-]+))?@@")
|
|
57
|
+
BUILTIN_VARS = {"COMMIT", "COMMIT_SHORT", "TREE", "TREE_SHORT", "NOTE", "SHA256"}
|
|
58
|
+
COMMIT_SHORT, TREE_SHORT = 7, 8
|
|
59
|
+
RECEIPTS_DIR = ".lean-receipts"
|
|
60
|
+
NOTE_MAX = 200
|
|
61
|
+
DIFF_LINES = 40
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# --------------------------------------------------------------------------
|
|
65
|
+
# the spec
|
|
66
|
+
|
|
67
|
+
def _rel(value, what: str) -> str:
|
|
68
|
+
"""A relative path inside the spec's (or the package's) directory: no absolute path, no `..`."""
|
|
69
|
+
if not isinstance(value, str) or not value.strip():
|
|
70
|
+
raise Fail(f"{what} must be a nonempty relative path, got {value!r}")
|
|
71
|
+
p = pathlib.PurePosixPath(value)
|
|
72
|
+
if p.is_absolute() or ".." in p.parts:
|
|
73
|
+
raise Fail(f"{what} must stay inside its directory (no absolute path, no ..): {value!r}")
|
|
74
|
+
return str(p)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_spec(path: pathlib.Path) -> dict:
|
|
78
|
+
"""The seal-bundle/1 spec, every problem refused with its key. Unknown keys are refused, not ignored."""
|
|
79
|
+
try:
|
|
80
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
81
|
+
except OSError as e:
|
|
82
|
+
raise Fail(f"cannot read the spec {path}: {e.strerror or e}") from None
|
|
83
|
+
except yaml.YAMLError as e:
|
|
84
|
+
raise Fail(f"{path}: not YAML: {e}") from None
|
|
85
|
+
if not isinstance(data, dict):
|
|
86
|
+
raise Fail(f"{path}: the spec must be a mapping")
|
|
87
|
+
problems = [f"unknown key {k!r}" for k in sorted(set(data) - SPEC_KEYS, key=str)]
|
|
88
|
+
problems += [f"missing key {k!r}" for k in SPEC_REQUIRED if k not in data]
|
|
89
|
+
if data.get("schema", SPEC_SCHEMA) != SPEC_SCHEMA:
|
|
90
|
+
problems.append(f"schema must be {SPEC_SCHEMA!r}, got {data.get('schema')!r}")
|
|
91
|
+
if problems:
|
|
92
|
+
raise Fail(f"{path}: " + "; ".join(problems))
|
|
93
|
+
spec = {k: data.get(k, DEFAULTS.get(k)) for k in SPEC_KEYS}
|
|
94
|
+
spec["template"] = _rel(spec["template"], "template")
|
|
95
|
+
|
|
96
|
+
pkgs = spec["packages"]
|
|
97
|
+
if not isinstance(pkgs, list) or not pkgs:
|
|
98
|
+
raise Fail(f"{path}: packages must be a nonempty list")
|
|
99
|
+
seen: set[str] = set()
|
|
100
|
+
out = []
|
|
101
|
+
for i, p in enumerate(pkgs):
|
|
102
|
+
where = f"packages[{i}]"
|
|
103
|
+
if not isinstance(p, dict):
|
|
104
|
+
raise Fail(f"{path}: {where} must be a mapping")
|
|
105
|
+
bad = sorted(set(p) - PACKAGE_KEYS) + [f"missing {k}" for k in sorted(PACKAGE_KEYS - set(p) - {"dir"})]
|
|
106
|
+
if bad:
|
|
107
|
+
raise Fail(f"{path}: {where}: " + ", ".join(bad))
|
|
108
|
+
key = p["key"]
|
|
109
|
+
if not isinstance(key, str) or not KEY_RE.fullmatch(key):
|
|
110
|
+
raise Fail(f"{path}: {where}.key must match {KEY_RE.pattern}, got {key!r}")
|
|
111
|
+
if key in seen:
|
|
112
|
+
raise Fail(f"{path}: {where}.key {key!r} is used twice")
|
|
113
|
+
seen.add(key)
|
|
114
|
+
umbrella = _rel(p["umbrella"], f"{where}.umbrella")
|
|
115
|
+
if "/" in umbrella or not umbrella.endswith(".lean"):
|
|
116
|
+
raise Fail(f"{path}: {where}.umbrella must be a .lean file in the package directory, got {umbrella!r}")
|
|
117
|
+
out.append({"key": key, "dir": _rel(p.get("dir", ".") or ".", f"{where}.dir"), "umbrella": umbrella,
|
|
118
|
+
"list": _name(p["list"], f"{where}.list")})
|
|
119
|
+
spec["packages"] = out
|
|
120
|
+
|
|
121
|
+
for k in ("script", "source", "sums", "pilot_list"):
|
|
122
|
+
spec[k] = _name(spec[k], k)
|
|
123
|
+
if spec["all_list"] is not None:
|
|
124
|
+
spec["all_list"] = _name(spec["all_list"], "all_list")
|
|
125
|
+
|
|
126
|
+
counts = spec["counts"] or []
|
|
127
|
+
if not isinstance(counts, list):
|
|
128
|
+
raise Fail(f"{path}: counts must be a list")
|
|
129
|
+
spec["counts"] = []
|
|
130
|
+
for i, c in enumerate(counts):
|
|
131
|
+
where = f"counts[{i}]"
|
|
132
|
+
if not isinstance(c, dict) or set(c) != COUNT_KEYS:
|
|
133
|
+
raise Fail(f"{path}: {where} must have exactly the keys {', '.join(sorted(COUNT_KEYS))}")
|
|
134
|
+
if c["package"] not in seen:
|
|
135
|
+
raise Fail(f"{path}: {where}.package {c['package']!r} is not a package key")
|
|
136
|
+
try:
|
|
137
|
+
rx = re.compile(str(c["pattern"]))
|
|
138
|
+
except re.error as e:
|
|
139
|
+
raise Fail(f"{path}: {where}.pattern does not compile: {e}") from None
|
|
140
|
+
if rx.groups != 1:
|
|
141
|
+
raise Fail(f"{path}: {where}.pattern must have exactly one group (the count), it has {rx.groups}")
|
|
142
|
+
spec["counts"].append({"var": _var(c["var"], f"{where}.var"), "package": c["package"], "rx": rx,
|
|
143
|
+
"pattern": str(c["pattern"])})
|
|
144
|
+
|
|
145
|
+
deps = spec["deps"] or {}
|
|
146
|
+
if not isinstance(deps, dict):
|
|
147
|
+
raise Fail(f"{path}: deps must be a mapping VAR: lake-manifest package name")
|
|
148
|
+
spec["deps"] = {}
|
|
149
|
+
for var, name in deps.items():
|
|
150
|
+
if not isinstance(name, str) or not name.strip():
|
|
151
|
+
raise Fail(f"{path}: deps.{var} must name a lake-manifest.json package")
|
|
152
|
+
spec["deps"][_var(var, f"deps.{var}")] = name
|
|
153
|
+
|
|
154
|
+
files = spec["files"] or []
|
|
155
|
+
if not isinstance(files, list):
|
|
156
|
+
raise Fail(f"{path}: files must be a list of paths relative to the spec")
|
|
157
|
+
spec["files"] = [_rel(f, "files[]") for f in files]
|
|
158
|
+
|
|
159
|
+
names = ([spec["source"]] + [p["list"] for p in out] + ([spec["all_list"]] if spec["all_list"] else [])
|
|
160
|
+
+ [spec["pilot_list"]] + [pathlib.PurePosixPath(f).name for f in spec["files"]]
|
|
161
|
+
+ [spec["script"], spec["sums"]])
|
|
162
|
+
dup = sorted({n for n in names if names.count(n) > 1})
|
|
163
|
+
if dup:
|
|
164
|
+
raise Fail(f"{path}: two bundle files would have the same name: {', '.join(dup)}")
|
|
165
|
+
vars_ = [c["var"] for c in spec["counts"]] + list(spec["deps"])
|
|
166
|
+
clash = sorted({v for v in vars_ if vars_.count(v) > 1 or v in BUILTIN_VARS})
|
|
167
|
+
if clash:
|
|
168
|
+
raise Fail(f"{path}: variable name(s) used twice or reserved: {', '.join(clash)}")
|
|
169
|
+
spec["path"] = path
|
|
170
|
+
return spec
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _name(value, what: str) -> str:
|
|
174
|
+
if not isinstance(value, str) or not NAME_RE.fullmatch(value):
|
|
175
|
+
raise Fail(f"{what} must be a plain file name ({NAME_RE.pattern}), got {value!r}")
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _var(value, what: str) -> str:
|
|
180
|
+
if not isinstance(value, str) or not VAR_RE.fullmatch(value):
|
|
181
|
+
raise Fail(f"{what} must be an upper-case variable name ({VAR_RE.pattern}), got {value!r}")
|
|
182
|
+
return value
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# --------------------------------------------------------------------------
|
|
186
|
+
# git at the commit
|
|
187
|
+
|
|
188
|
+
def _git_out(repo: pathlib.Path, *args: str) -> str:
|
|
189
|
+
p = core.git(repo, *args)
|
|
190
|
+
if p.returncode != 0:
|
|
191
|
+
raise Fail(f"git {' '.join(args)} in {repo} failed: {(p.stderr or '').strip()}")
|
|
192
|
+
return p.stdout
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def resolve_commit(repo: pathlib.Path, sha: str) -> str:
|
|
196
|
+
p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{sha}^{{commit}}")
|
|
197
|
+
if p.returncode != 0:
|
|
198
|
+
raise Fail(f"commit {sha[:12]} does not exist in {repo}")
|
|
199
|
+
return p.stdout.strip()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def tree_of(repo: pathlib.Path, commit: str) -> str:
|
|
203
|
+
return _git_out(repo, "rev-parse", f"{commit}:./").strip()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def tree_entries(repo: pathlib.Path, commit: str) -> dict[str, tuple[str, str]]:
|
|
207
|
+
"""{path: (mode, object)} of every blob under the package directory at `commit`. --full-tree: run in a
|
|
208
|
+
subdirectory, ls-tree otherwise lists only the paths under that subdirectory, even of a subtree."""
|
|
209
|
+
out = {}
|
|
210
|
+
for line in _git_out(repo, "ls-tree", "--full-tree", "-r", "-z", f"{commit}:./").split("\0"):
|
|
211
|
+
if not line:
|
|
212
|
+
continue
|
|
213
|
+
meta, rel = line.split("\t", 1)
|
|
214
|
+
mode, _kind, obj = meta.split()
|
|
215
|
+
out[rel] = (mode, obj)
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def source_archive(repo: pathlib.Path, commit: str) -> bytes:
|
|
220
|
+
"""git archive of the package directory at `commit`, every entry stamped with the commit time, gzipped
|
|
221
|
+
with no name and time 0: the same commit gives the same bytes (a bare tree archive is stamped with the
|
|
222
|
+
current time and never repeats). Run from the repository's top level: in a subdirectory, git archive
|
|
223
|
+
keeps only the paths under it, which a subtree of that subdirectory does not have (an empty archive)."""
|
|
224
|
+
ct = _git_out(repo, "log", "-1", "--format=%ct", commit).strip()
|
|
225
|
+
top = _git_out(repo, "rev-parse", "--show-toplevel").strip()
|
|
226
|
+
prefix = _git_out(repo, "rev-parse", "--show-prefix").strip()
|
|
227
|
+
p = subprocess.run(["git", "-C", top, "archive", "--format=tar", f"--mtime=@{ct}", f"{commit}:{prefix}"],
|
|
228
|
+
capture_output=True, env=core.scrubbed_env())
|
|
229
|
+
if p.returncode != 0:
|
|
230
|
+
err = p.stderr.decode("utf-8", "replace").strip()
|
|
231
|
+
raise Fail(f"git archive {commit[:12]} failed in {repo}: {err} (seal-bundle needs git >= 2.43 for "
|
|
232
|
+
f"--mtime)" if "mtime" in err else f"git archive {commit[:12]} failed in {repo}: {err}")
|
|
233
|
+
with tarfile.open(fileobj=io.BytesIO(p.stdout)) as t: # the archive holds exactly the tree's files
|
|
234
|
+
members = {m.name for m in t.getmembers() if not m.isdir()}
|
|
235
|
+
expected = set(tree_entries(repo, commit))
|
|
236
|
+
if members != expected:
|
|
237
|
+
raise Fail(f"git archive {commit[:12]} in {repo} does not hold the package tree "
|
|
238
|
+
f"({len(members)} entries, the tree has {len(expected)}); nothing was written")
|
|
239
|
+
return gzip.compress(p.stdout, compresslevel=9, mtime=0)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# --------------------------------------------------------------------------
|
|
243
|
+
# receipts
|
|
244
|
+
|
|
245
|
+
def load_receipt(pkgdir: pathlib.Path, path: pathlib.Path, key: str) -> dict:
|
|
246
|
+
"""A lower-tier receipt and the checks that hold at its own commit: the schema and fields, a full commit
|
|
247
|
+
that exists, the toolchain and Mathlib committed there, sorry_count 0, the default axioms. Not the gate:
|
|
248
|
+
a seal re-checks a commit after the fact, so the receipt need not bind HEAD."""
|
|
249
|
+
try:
|
|
250
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
251
|
+
except OSError as e:
|
|
252
|
+
raise Fail(f"--receipt {key}={path}: cannot read it: {e.strerror or e}") from None
|
|
253
|
+
except ValueError as e:
|
|
254
|
+
raise Fail(f"--receipt {key}={path}: not JSON: {e}") from None
|
|
255
|
+
if not isinstance(data, dict):
|
|
256
|
+
raise Fail(f"--receipt {key}={path}: not a receipt object")
|
|
257
|
+
label = f"--receipt {key}={path}"
|
|
258
|
+
try:
|
|
259
|
+
gate_mod.check_lower_receipt_schema(data, newer_only=True)
|
|
260
|
+
missing = [f for f in core.RECEIPT_FIELDS if f not in data]
|
|
261
|
+
if missing:
|
|
262
|
+
raise Fail(f"missing field(s) {', '.join(missing)}")
|
|
263
|
+
gate_mod.check_lower_receipt_schema(data)
|
|
264
|
+
commit = str(data["commit"])
|
|
265
|
+
if not re.fullmatch(r"[0-9a-f]{40}", commit):
|
|
266
|
+
raise Fail(f"commit is not a full lowercase 40-hex sha: {commit!r}")
|
|
267
|
+
resolve_commit(pkgdir, commit)
|
|
268
|
+
gate_mod.check_toolchain_at(pkgdir, commit, data["lean_toolchain"], "toolchain mismatch")
|
|
269
|
+
committed = gate_mod.committed_mathlib(pkgdir, commit)
|
|
270
|
+
rev = str(data["mathlib_rev"]).strip()
|
|
271
|
+
if committed is not None and not gate_mod._same_rev(rev, committed):
|
|
272
|
+
raise Fail(f"mathlib_rev {rev!r} is not the mathlib committed at {commit[:12]} ({committed!r})")
|
|
273
|
+
sc = data["sorry_count"]
|
|
274
|
+
if isinstance(sc, bool) or sc != 0:
|
|
275
|
+
raise Fail(f"sorry_count must be 0, got {sc!r}")
|
|
276
|
+
axioms = data["axioms"]
|
|
277
|
+
if not isinstance(axioms, list) or not all(isinstance(a, str) for a in axioms):
|
|
278
|
+
raise Fail("axioms must be a list of strings")
|
|
279
|
+
extra = sorted(set(axioms) - set(core.DEFAULT_AXIOMS))
|
|
280
|
+
if extra:
|
|
281
|
+
raise Fail(f"axioms beyond {', '.join(core.DEFAULT_AXIOMS)}: {', '.join(extra)}")
|
|
282
|
+
except Fail as e:
|
|
283
|
+
raise Fail(f"{label}: {e}") from None
|
|
284
|
+
return data
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def parse_receipt_args(values: list[str] | None, keys: list[str]) -> dict[str, pathlib.Path]:
|
|
288
|
+
out: dict[str, pathlib.Path] = {}
|
|
289
|
+
for v in values or []:
|
|
290
|
+
key, sep, path = v.partition("=")
|
|
291
|
+
if not sep or not path:
|
|
292
|
+
raise UsageError(f"--receipt takes KEY=PATH, got {v!r}")
|
|
293
|
+
if key not in keys:
|
|
294
|
+
raise UsageError(f"--receipt {key}: not a package key of the spec ({', '.join(keys)})")
|
|
295
|
+
if key in out:
|
|
296
|
+
raise UsageError(f"--receipt {key} given twice")
|
|
297
|
+
out[key] = pathlib.Path(path)
|
|
298
|
+
missing = [k for k in keys if k not in out]
|
|
299
|
+
if missing:
|
|
300
|
+
raise UsageError("--receipt KEY=PATH is required for every package of the spec; missing: "
|
|
301
|
+
+ ", ".join(missing))
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# --------------------------------------------------------------------------
|
|
306
|
+
# derived facts
|
|
307
|
+
|
|
308
|
+
def modules_of(pkgdir: pathlib.Path, commit: str, umbrella: str) -> list[str]:
|
|
309
|
+
"""The umbrella's imports at `commit`, which must equal the modules of the .lean files under the
|
|
310
|
+
umbrella's directory (both sorted); one problem per difference."""
|
|
311
|
+
blob = core.git_show_bytes(pkgdir, umbrella, commit)
|
|
312
|
+
if blob is None:
|
|
313
|
+
raise Fail(f"{pkgdir}: {umbrella} is not committed at {commit[:12]}")
|
|
314
|
+
imports = [m.group(1) for ln in blob.decode("utf-8", "replace").splitlines() if (m := IMPORT_RE.match(ln))]
|
|
315
|
+
stem = umbrella[:-len(".lean")]
|
|
316
|
+
p = core.git(pkgdir, "ls-tree", "--full-tree", "-r", "-z", "--name-only", f"{commit}:./{stem}")
|
|
317
|
+
files = sorted(f"{stem}." + f[:-len(".lean")].replace("/", ".")
|
|
318
|
+
for f in (p.stdout.split("\0") if p.returncode == 0 else []) if f.endswith(".lean"))
|
|
319
|
+
problems = []
|
|
320
|
+
bad = [m for m in imports if not MODULE_RE.fullmatch(m)]
|
|
321
|
+
if bad:
|
|
322
|
+
problems.append("unexpected import name(s): " + ", ".join(bad))
|
|
323
|
+
dup = sorted({m for m in imports if imports.count(m) > 1})
|
|
324
|
+
if dup:
|
|
325
|
+
problems.append("imported twice: " + ", ".join(dup))
|
|
326
|
+
only_imp = sorted(set(imports) - set(files))
|
|
327
|
+
only_files = sorted(set(files) - set(imports))
|
|
328
|
+
if only_imp:
|
|
329
|
+
problems.append(f"imported by {umbrella} but no {stem}/ file: " + ", ".join(only_imp))
|
|
330
|
+
if only_files:
|
|
331
|
+
problems.append(f"a {stem}/ file {umbrella} does not import: " + ", ".join(only_files))
|
|
332
|
+
if not files and not problems:
|
|
333
|
+
problems.append(f"no .lean file under {stem}/")
|
|
334
|
+
if problems:
|
|
335
|
+
raise Fail(f"{pkgdir} at {commit[:12]}: the umbrella and the files differ: " + "; ".join(problems))
|
|
336
|
+
return files
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def count_from_log(pkgdir: pathlib.Path, receipt: dict, receipt_path: pathlib.Path, c: dict) -> int:
|
|
340
|
+
rel = os.path.relpath(receipt_path.resolve(), pkgdir.resolve())
|
|
341
|
+
text = gate_mod.sealed_log_text(pkgdir, receipt, rel)
|
|
342
|
+
if text is None:
|
|
343
|
+
raise Fail(f"counts {c['var']}: no verify log of the {c['package']} receipt hashes to its report_sha256 "
|
|
344
|
+
f"({gate_mod.report_log_name(receipt)} beside it or in {RECEIPTS_DIR}/)")
|
|
345
|
+
values = sorted({m.group(1) for m in c["rx"].finditer(text)})
|
|
346
|
+
if len(values) != 1:
|
|
347
|
+
found = ", ".join(values) if values else "no match"
|
|
348
|
+
raise Fail(f"counts {c['var']}: the pattern {c['pattern']!r} must give one value in the {c['package']} "
|
|
349
|
+
f"receipt's log; it gives {found}")
|
|
350
|
+
if not values[0].isdigit():
|
|
351
|
+
raise Fail(f"counts {c['var']}: the pattern matched {values[0]!r}, not a number")
|
|
352
|
+
return int(values[0])
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def manifest_revs(root: pathlib.Path, commit: str, deps: dict[str, str]) -> dict[str, str]:
|
|
356
|
+
if not deps:
|
|
357
|
+
return {}
|
|
358
|
+
blob = core.git_show_bytes(root, "lake-manifest.json", commit)
|
|
359
|
+
if blob is None:
|
|
360
|
+
raise Fail(f"deps: no lake-manifest.json committed at {commit[:12]} in {root}")
|
|
361
|
+
try:
|
|
362
|
+
pkgs = {p.get("name"): p.get("rev") for p in json.loads(blob).get("packages") or [] if isinstance(p, dict)}
|
|
363
|
+
except (ValueError, AttributeError):
|
|
364
|
+
raise Fail(f"deps: lake-manifest.json at {commit[:12]} is not a manifest") from None
|
|
365
|
+
out, missing = {}, []
|
|
366
|
+
for var, name in deps.items():
|
|
367
|
+
rev = pkgs.get(name)
|
|
368
|
+
if not isinstance(rev, str) or not re.fullmatch(r"[0-9a-f]{40}", rev):
|
|
369
|
+
missing.append(f"{var} ({name})")
|
|
370
|
+
else:
|
|
371
|
+
out[var] = rev
|
|
372
|
+
if missing:
|
|
373
|
+
raise Fail(f"deps: lake-manifest.json at {commit[:12]} has no 40-hex rev for " + ", ".join(missing))
|
|
374
|
+
return out
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def read_pilot(path: pathlib.Path, all_modules: list[str]) -> list[str]:
|
|
378
|
+
try:
|
|
379
|
+
lines = [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines()]
|
|
380
|
+
except OSError as e:
|
|
381
|
+
raise Fail(f"--pilot {path}: cannot read it: {e.strerror or e}") from None
|
|
382
|
+
pilot = [ln for ln in lines if ln]
|
|
383
|
+
if not pilot:
|
|
384
|
+
raise Fail(f"--pilot {path}: no module listed")
|
|
385
|
+
dup = sorted({m for m in pilot if pilot.count(m) > 1})
|
|
386
|
+
unknown = [m for m in pilot if m not in all_modules]
|
|
387
|
+
if dup or unknown:
|
|
388
|
+
raise Fail(f"--pilot {path}: " + "; ".join(
|
|
389
|
+
([f"listed twice: {', '.join(dup)}"] if dup else [])
|
|
390
|
+
+ ([f"not a module of the bundle: {', '.join(unknown)}"] if unknown else [])))
|
|
391
|
+
return pilot
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def render(template: str, values: dict[str, str], hashes: dict[str, str], commits: dict[str, str]) -> str:
|
|
395
|
+
"""Fill every @@NAME@@ / @@NAME:ARG@@; an unknown placeholder, or a template without @@COMMIT@@ and
|
|
396
|
+
@@TREE@@ (the job would bind nothing), is refused, all problems at once."""
|
|
397
|
+
problems = []
|
|
398
|
+
for need in ("COMMIT", "TREE"):
|
|
399
|
+
if f"@@{need}@@" not in template:
|
|
400
|
+
problems.append(f"@@{need}@@ is missing (the job must bind the commit and its tree)")
|
|
401
|
+
|
|
402
|
+
def fill(m: re.Match) -> str:
|
|
403
|
+
name, arg = m.group(1), m.group(2)
|
|
404
|
+
if arg is None and name in values:
|
|
405
|
+
return values[name]
|
|
406
|
+
if name == "SHA256" and arg in hashes:
|
|
407
|
+
return hashes[arg]
|
|
408
|
+
if name in ("COMMIT", "COMMIT_SHORT") and arg in commits:
|
|
409
|
+
return commits[arg] if name == "COMMIT" else commits[arg][:COMMIT_SHORT]
|
|
410
|
+
problems.append(m.group(0))
|
|
411
|
+
return m.group(0)
|
|
412
|
+
|
|
413
|
+
out = PLACEHOLDER_RE.sub(fill, template)
|
|
414
|
+
if problems:
|
|
415
|
+
raise Fail("template: unknown or unfilled placeholder(s): " + ", ".join(dict.fromkeys(problems))
|
|
416
|
+
+ " (known: @@COMMIT@@ @@COMMIT_SHORT@@ @@TREE@@ @@TREE_SHORT@@ @@NOTE@@, @@COMMIT:KEY@@, "
|
|
417
|
+
"@@COMMIT_SHORT:KEY@@, @@SHA256:FILE@@ and the spec's counts and deps variables)")
|
|
418
|
+
return out
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
# --------------------------------------------------------------------------
|
|
422
|
+
# the bundle
|
|
423
|
+
|
|
424
|
+
def build(spec: dict, root: pathlib.Path, receipts: dict[str, pathlib.Path], pilot_path: pathlib.Path | None,
|
|
425
|
+
note: str, check_dir: pathlib.Path | None = None) -> dict:
|
|
426
|
+
"""Every file of the bundle in order ({name: bytes}), with the facts behind it. With check_dir, a pilot
|
|
427
|
+
list and the source archive's recorded hash may come from that bundle (reported as taken from it)."""
|
|
428
|
+
notes: list[str] = []
|
|
429
|
+
spec_dir = spec["path"].parent
|
|
430
|
+
pkgs = []
|
|
431
|
+
for p in spec["packages"]:
|
|
432
|
+
pkgdir = root / p["dir"]
|
|
433
|
+
if not pkgdir.is_dir():
|
|
434
|
+
raise Fail(f"packages {p['key']}: {pkgdir} is not a directory")
|
|
435
|
+
rec = load_receipt(pkgdir, receipts[p["key"]], p["key"])
|
|
436
|
+
pkgs.append({**p, "pkgdir": pkgdir, "receipt": rec, "receipt_path": receipts[p["key"]],
|
|
437
|
+
"commit": resolve_commit(pkgdir, rec["commit"])})
|
|
438
|
+
primary = pkgs[0]
|
|
439
|
+
commit = primary["commit"]
|
|
440
|
+
tree = tree_of(root, commit)
|
|
441
|
+
|
|
442
|
+
for p in pkgs[1:]: # each other package's receipt must have verified the tree bundled here
|
|
443
|
+
if p["commit"] == commit:
|
|
444
|
+
continue
|
|
445
|
+
a = {k: v for k, v in tree_entries(p["pkgdir"], commit).items() if RECEIPTS_DIR not in k.split("/")}
|
|
446
|
+
b = {k: v for k, v in tree_entries(p["pkgdir"], p["commit"]).items() if RECEIPTS_DIR not in k.split("/")}
|
|
447
|
+
drift = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k))
|
|
448
|
+
if drift:
|
|
449
|
+
shown = ", ".join(drift[:10]) + (f" (+{len(drift) - 10} more)" if len(drift) > 10 else "")
|
|
450
|
+
raise Fail(f"packages {p['key']}: its receipt verified {p['commit'][:12]}, but {p['dir']}/ at "
|
|
451
|
+
f"{commit[:12]} differs outside {RECEIPTS_DIR}/: {shown}")
|
|
452
|
+
notes.append(f"{p['key']}: the receipt's commit {p['commit'][:12]} has the bundled tree of {p['dir']}/ "
|
|
453
|
+
f"(apart from {RECEIPTS_DIR}/)")
|
|
454
|
+
|
|
455
|
+
for p in pkgs:
|
|
456
|
+
p["modules"] = modules_of(p["pkgdir"], commit, p["umbrella"])
|
|
457
|
+
all_modules = [m for p in pkgs for m in p["modules"]]
|
|
458
|
+
|
|
459
|
+
if pilot_path is not None:
|
|
460
|
+
pilot = read_pilot(pilot_path, all_modules)
|
|
461
|
+
elif check_dir is not None and (check_dir / spec["pilot_list"]).is_file():
|
|
462
|
+
pilot = read_pilot(check_dir / spec["pilot_list"], all_modules)
|
|
463
|
+
notes.append(f"{spec['pilot_list']}: taken from the checked bundle (a pilot list is a choice)")
|
|
464
|
+
else:
|
|
465
|
+
raise UsageError("--pilot FILE is required: the modules the pilot run replays, one per line")
|
|
466
|
+
|
|
467
|
+
counts = {}
|
|
468
|
+
for c in spec["counts"]:
|
|
469
|
+
p = next(q for q in pkgs if q["key"] == c["package"])
|
|
470
|
+
counts[c["var"]] = count_from_log(p["pkgdir"], p["receipt"], p["receipt_path"], c)
|
|
471
|
+
deps = manifest_revs(root, commit, spec["deps"])
|
|
472
|
+
|
|
473
|
+
files: dict[str, bytes] = {}
|
|
474
|
+
files[spec["source"]] = source_archive(root, commit)
|
|
475
|
+
for p in pkgs:
|
|
476
|
+
files[p["list"]] = "".join(m + "\n" for m in p["modules"]).encode()
|
|
477
|
+
if spec["all_list"]:
|
|
478
|
+
files[spec["all_list"]] = "".join(m + "\n" for m in all_modules).encode()
|
|
479
|
+
files[spec["pilot_list"]] = "".join(m + "\n" for m in pilot).encode()
|
|
480
|
+
for f in spec["files"]:
|
|
481
|
+
src = spec_dir / f
|
|
482
|
+
try:
|
|
483
|
+
files[pathlib.PurePosixPath(f).name] = src.read_bytes()
|
|
484
|
+
except OSError as e:
|
|
485
|
+
raise Fail(f"files: cannot read {src}: {e.strerror or e}") from None
|
|
486
|
+
|
|
487
|
+
hashes = {n: hashlib.sha256(b).hexdigest() for n, b in files.items()}
|
|
488
|
+
source_taken = False
|
|
489
|
+
if check_dir is not None:
|
|
490
|
+
recorded = _recorded_sums(check_dir / spec["sums"]).get(spec["source"])
|
|
491
|
+
if recorded is not None and recorded != hashes[spec["source"]]:
|
|
492
|
+
hashes[spec["source"]] = recorded
|
|
493
|
+
source_taken = True
|
|
494
|
+
notes.append(f"{spec['source']}: its hash is taken from the checked bundle's {spec['sums']} (an "
|
|
495
|
+
f"archive made elsewhere is not rebuilt byte for byte; the script binds its tree)")
|
|
496
|
+
|
|
497
|
+
values = {"COMMIT": commit, "COMMIT_SHORT": commit[:COMMIT_SHORT], "TREE": tree, "TREE_SHORT": tree[:TREE_SHORT],
|
|
498
|
+
"NOTE": note, **{k: str(v) for k, v in counts.items()}, **deps}
|
|
499
|
+
try:
|
|
500
|
+
template = (spec_dir / spec["template"]).read_text(encoding="utf-8")
|
|
501
|
+
except OSError as e:
|
|
502
|
+
raise Fail(f"template: cannot read {spec_dir / spec['template']}: {e.strerror or e}") from None
|
|
503
|
+
script = render(template, values, hashes, {p["key"]: p["commit"] for p in pkgs})
|
|
504
|
+
files[spec["script"]] = script.encode()
|
|
505
|
+
hashes[spec["script"]] = hashlib.sha256(files[spec["script"]]).hexdigest()
|
|
506
|
+
files[spec["sums"]] = "".join(f"{hashes[n]} {n}\n" for n in files).encode()
|
|
507
|
+
|
|
508
|
+
return {"files": files, "hashes": hashes, "commit": commit, "tree": tree, "counts": counts, "deps": deps,
|
|
509
|
+
"pilot": pilot, "notes": notes, "source_taken": source_taken,
|
|
510
|
+
"packages": [{"key": p["key"], "dir": p["dir"], "commit": p["commit"], "receipt": str(p["receipt_path"]),
|
|
511
|
+
"modules": len(p["modules"])} for p in pkgs]}
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _recorded_sums(path: pathlib.Path) -> dict[str, str]:
|
|
515
|
+
try:
|
|
516
|
+
text = path.read_text(encoding="utf-8")
|
|
517
|
+
except OSError:
|
|
518
|
+
return {}
|
|
519
|
+
out = {}
|
|
520
|
+
for ln in text.splitlines():
|
|
521
|
+
m = re.fullmatch(r"([0-9a-f]{64}) [ *](\S+)", ln.strip())
|
|
522
|
+
if m:
|
|
523
|
+
out[m.group(2)] = m.group(1)
|
|
524
|
+
return out
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def compare(bundle: dict, spec: dict, check_dir: pathlib.Path) -> tuple[list[dict], list[str]]:
|
|
528
|
+
"""(differences, notes) of check_dir against the derived bundle. The source archive is compared by its
|
|
529
|
+
recorded hash only when check_dir has none to take; files check_dir has beyond the bundle are notes."""
|
|
530
|
+
diffs, notes = [], []
|
|
531
|
+
source = spec["source"]
|
|
532
|
+
for name, data in bundle["files"].items():
|
|
533
|
+
f = check_dir / name
|
|
534
|
+
if name == source:
|
|
535
|
+
if not f.is_file():
|
|
536
|
+
notes.append(f"{source}: not in the checked bundle (not compared; the script binds its tree)")
|
|
537
|
+
elif hashlib.sha256(f.read_bytes()).hexdigest() != bundle["hashes"][source] and not bundle["source_taken"]:
|
|
538
|
+
notes.append(f"{source}: differs byte for byte (not a difference: the script binds its tree)")
|
|
539
|
+
continue
|
|
540
|
+
if not f.is_file():
|
|
541
|
+
diffs.append({"file": name, "kind": "missing", "diff": []})
|
|
542
|
+
continue
|
|
543
|
+
have = f.read_bytes()
|
|
544
|
+
if have != data:
|
|
545
|
+
d = list(difflib.unified_diff(have.decode("utf-8", "replace").splitlines(),
|
|
546
|
+
data.decode("utf-8", "replace").splitlines(),
|
|
547
|
+
f"checked/{name}", f"derived/{name}", n=0, lineterm=""))
|
|
548
|
+
diffs.append({"file": name, "kind": "differs", "diff": d[:DIFF_LINES]})
|
|
549
|
+
extra = sorted(p.name for p in check_dir.iterdir() if p.is_file() and p.name not in bundle["files"])
|
|
550
|
+
if extra:
|
|
551
|
+
notes.append("not produced by seal-bundle (not compared): " + ", ".join(extra))
|
|
552
|
+
return diffs, notes
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def write_bundle(bundle: dict, out: pathlib.Path) -> None:
|
|
556
|
+
if out.exists():
|
|
557
|
+
raise Fail(f"--out {out} already exists; seal-bundle writes a new directory and never overwrites one")
|
|
558
|
+
out.mkdir(parents=True)
|
|
559
|
+
for name, data in bundle["files"].items():
|
|
560
|
+
(out / name).write_bytes(data)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
# --------------------------------------------------------------------------
|
|
564
|
+
# the command
|
|
565
|
+
|
|
566
|
+
def cmd_seal_bundle(args) -> int:
|
|
567
|
+
note = args.note or ""
|
|
568
|
+
if len(note) > NOTE_MAX or any(ord(ch) < 32 or ord(ch) == 127 for ch in note) or "@@" in note:
|
|
569
|
+
raise UsageError(f"--note must be one line of at most {NOTE_MAX} characters, without control characters "
|
|
570
|
+
f"or @@")
|
|
571
|
+
spec = load_spec(pathlib.Path(args.spec))
|
|
572
|
+
root = pathlib.Path(args.repo)
|
|
573
|
+
if core.git(root, "rev-parse", "--is-inside-work-tree").returncode != 0:
|
|
574
|
+
raise Fail(f"--repo {root}: not inside a git work tree")
|
|
575
|
+
receipts = parse_receipt_args(args.receipt, [p["key"] for p in spec["packages"]])
|
|
576
|
+
check_dir = pathlib.Path(args.check) if args.check else None
|
|
577
|
+
if check_dir is not None and not check_dir.is_dir():
|
|
578
|
+
raise Fail(f"--check {check_dir}: not a directory")
|
|
579
|
+
pilot = pathlib.Path(args.pilot) if args.pilot else None
|
|
580
|
+
bundle = build(spec, root, receipts, pilot, note, check_dir)
|
|
581
|
+
|
|
582
|
+
payload = {"ok": True, "mode": "check" if check_dir else "write", "commit": bundle["commit"],
|
|
583
|
+
"tree": bundle["tree"], "packages": bundle["packages"], "counts": bundle["counts"],
|
|
584
|
+
"deps": bundle["deps"], "pilot": bundle["pilot"],
|
|
585
|
+
"files": [{"name": n, "sha256": h} for n, h in bundle["hashes"].items() if n != spec["sums"]],
|
|
586
|
+
"notes": list(bundle["notes"]), "differences": []}
|
|
587
|
+
head = (f"commit {bundle['commit'][:12]}, tree {bundle['tree'][:12]}, "
|
|
588
|
+
+ ", ".join(f"{p['key']} {p['modules']} module(s)" for p in bundle["packages"])
|
|
589
|
+
+ "".join(f", {k}={v}" for k, v in bundle["counts"].items()))
|
|
590
|
+
if check_dir is not None:
|
|
591
|
+
diffs, more = compare(bundle, spec, check_dir)
|
|
592
|
+
payload["notes"] += more
|
|
593
|
+
payload["differences"] = diffs
|
|
594
|
+
payload["ok"] = not diffs
|
|
595
|
+
compared = len(bundle["files"]) - 1
|
|
596
|
+
verdict = (f"seal-bundle --check {check_dir}: " + ("PASS" if not diffs else "FAIL")
|
|
597
|
+
+ f", {compared - len(diffs)}/{compared} file(s) equal ({head})")
|
|
598
|
+
lines = [verdict]
|
|
599
|
+
for d in diffs:
|
|
600
|
+
lines.append(f" {d['kind']}: {d['file']}")
|
|
601
|
+
lines += [f" {ln}" for ln in d["diff"]]
|
|
602
|
+
lines += [f" note: {n}" for n in payload["notes"]]
|
|
603
|
+
if diffs:
|
|
604
|
+
lines.append(verdict)
|
|
605
|
+
else:
|
|
606
|
+
out = pathlib.Path(args.out)
|
|
607
|
+
write_bundle(bundle, out)
|
|
608
|
+
payload["out"] = str(out)
|
|
609
|
+
lines = [f"seal-bundle: wrote {out} ({len(bundle['files'])} files; {head})"]
|
|
610
|
+
lines += [f" {h} {n}" for n, h in bundle["hashes"].items() if n != spec["sums"]]
|
|
611
|
+
lines += [f" note: {n}" for n in payload["notes"]]
|
|
612
|
+
lines.append(f" submit from a copy of {out} on the cluster; nothing was written to the registry")
|
|
613
|
+
if getattr(args, "json_out", False):
|
|
614
|
+
core.print_json(payload)
|
|
615
|
+
else:
|
|
616
|
+
print("\n".join(lines))
|
|
617
|
+
return 0 if payload["ok"] else 1
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def add_parsers(sub, add_json) -> None:
|
|
621
|
+
s = sub.add_parser(
|
|
622
|
+
"seal-bundle",
|
|
623
|
+
help="render a hash-bound seal job bundle (job script, module lists, source archive, INPUT-SHA256SUMS) "
|
|
624
|
+
"from lower-tier receipts and the package's template; --check DIR re-derives an existing bundle",
|
|
625
|
+
description="Every value a hand-assembled seal edits is derived: the commit from the first package's "
|
|
626
|
+
"receipt and its tree, each other package's receipt checked against the bundled tree (apart "
|
|
627
|
+
"from .lean-receipts/), module lists from the umbrella imports (which must equal the .lean "
|
|
628
|
+
"files), counts from each receipt's sealed verify log, dependency revisions from "
|
|
629
|
+
"lake-manifest.json, and a reproducible source archive. The template's @@NAME@@ placeholders "
|
|
630
|
+
"are filled; an unknown one is refused. Writes only --out; never a receipt or the registry.")
|
|
631
|
+
s.add_argument("--spec", required=True, metavar="PATH",
|
|
632
|
+
help="the package's seal-bundle/1 spec (YAML); its template and files are relative to it")
|
|
633
|
+
s.add_argument("--receipt", action="append", metavar="KEY=PATH",
|
|
634
|
+
help="the lower-tier receipt of each package in the spec (repeat per package); the first "
|
|
635
|
+
"package's commit is the one bundled")
|
|
636
|
+
s.add_argument("--repo", default=".", metavar="DIR",
|
|
637
|
+
help="the package directory archived as the source (default: .); package dirs are relative to it")
|
|
638
|
+
s.add_argument("--pilot", default=None, metavar="FILE",
|
|
639
|
+
help="the modules the pilot run replays, one per line (required with --out; with --check the "
|
|
640
|
+
"bundle's own list is used when omitted)")
|
|
641
|
+
s.add_argument("--note", default="", metavar="TEXT", help="one line filled into @@NOTE@@ (what this seal adds)")
|
|
642
|
+
g = s.add_mutually_exclusive_group(required=True)
|
|
643
|
+
g.add_argument("--out", metavar="DIR", help="write the bundle into DIR, which must not exist")
|
|
644
|
+
g.add_argument("--check", metavar="DIR",
|
|
645
|
+
help="re-derive the bundle and compare DIR with it, file by file (exit 1 on a difference)")
|
|
646
|
+
add_json(s)
|
|
647
|
+
s.set_defaults(fn=cmd_seal_bundle)
|