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,512 @@
1
+ #!/usr/bin/env python3
2
+ """`receipt slurm --preflight-deps`: before a job is submitted, check that a staged dependency cache (a
3
+ DEPS_TAR tarball, or a directory holding `.lake/packages`) holds every external module the verifier's own
4
+ entry files need, at the pins of the package's lake-manifest.json. Read-only; nothing is built or written.
5
+
6
+ Field report (#5): a job restored a tarball holding the dependency builds of the library target's import
7
+ cone; `lake build` passed, then `lake env lean Audit/.../Solution.lean` (which imports the `Mathlib`
8
+ umbrella) failed because `Mathlib.olean` was not in the tarball. The build target's cone is not the audit's.
9
+
10
+ The rule (fail-closed). Entry files are the .lean files the verifier elaborates, matched by --entries globs
11
+ in the tree committed at --commit (never the working tree). From their `import` headers the closure is
12
+ followed through the package's own committed modules and then through the dependencies' sources inside the
13
+ cache, so `import Mathlib` requires `Mathlib.olean` AND the .olean of every module Mathlib.lean imports,
14
+ transitively. Every external module in the closure must be found in exactly one manifest package of the
15
+ cache with its source (to read its imports) and its built .olean and .ilean (regular files); a module no
16
+ package provides is a problem unless its root is a toolchain one (Init, Std, Lean, Lake). Every git package
17
+ of the manifest must be in the cache, checked out at the manifest's rev (`.git/HEAD`, resolved through
18
+ `refs/` or `packed-refs`); a path package, an unreadable pin or a missing package is a problem. Nothing the
19
+ template checks inside the job (fresh build, shadowing, restored root modules) is relaxed by passing this."""
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import pathlib
26
+ import re
27
+ import tarfile
28
+ from collections import deque
29
+
30
+ from . import build_scope
31
+ from . import core
32
+
33
+ TOOLCHAIN_ROOTS = ("Init", "Std", "Lean", "Lake")
34
+ # The .lean files a verifier typically elaborates besides the build: the receipt template's Verify/, the lab
35
+ # template's AxiomCheck/TypeCheck/Examples/OwnedAudit files, and Audit/ trees. --entries replaces the list.
36
+ DEFAULT_ENTRIES = ("Verify/**/*.lean", "Audit/**/*.lean", "OwnedAudit/**/*.lean", "**/AxiomCheck*.lean",
37
+ "**/TypeCheck*.lean", "**/Examples*.lean", "**/OwnedAudit*.lean")
38
+ PACKAGES = ".lake/packages/"
39
+ # Where Lake writes a package's .olean/.ilean: .lake/build/lib/lean (current Lake), .lake/build/lib (earlier
40
+ # .lake layouts), build/lib (the old lake-packages layout).
41
+ BUILD_LIBS = (".lake/build/lib/lean/", ".lake/build/lib/", "build/lib/")
42
+ MAX_SOURCE = 8 * 1024 * 1024 # bytes read of one dependency .lean file (Mathlib.lean is < 1 MiB)
43
+ MAX_GIT_FILE = 64 * 1024 * 1024 # bytes read of .git/HEAD, a ref or packed-refs
44
+ SHOW_MISSING = 20
45
+ JSON_MISSING = 500 # display cap of missing[]; check() keeps every module in missing_all
46
+ OLEAN_HEADER = 80 # .olean marker, format version, Lean version string, Lean commit
47
+ HEX40 = re.compile(r"[0-9a-f]{40}")
48
+
49
+
50
+ # --------------------------------------------------------------------------
51
+ # import headers
52
+
53
+ _NAME = re.compile(r"(?:«[^»]*»|[^\s«»()\[\]{},:;/-])+")
54
+ _MODIFIERS = {"public", "private", "meta"}
55
+
56
+
57
+ def _skip(text: str, pos: int) -> int:
58
+ """Past whitespace, `--` line comments and (nested) `/- -/` block comments."""
59
+ n = len(text)
60
+ while pos < n:
61
+ c = text[pos]
62
+ if c.isspace():
63
+ pos += 1
64
+ elif text.startswith("--", pos):
65
+ nl = text.find("\n", pos)
66
+ pos = n if nl < 0 else nl + 1
67
+ elif text.startswith("/-", pos):
68
+ depth, pos = 1, pos + 2
69
+ while depth and pos < n:
70
+ if text.startswith("/-", pos):
71
+ depth, pos = depth + 1, pos + 2
72
+ elif text.startswith("-/", pos):
73
+ depth, pos = depth - 1, pos + 2
74
+ else:
75
+ pos += 1
76
+ else:
77
+ break
78
+ return pos
79
+
80
+
81
+ def header_imports(text: str) -> list[str]:
82
+ """The modules a Lean 4 file imports: its header is an optional `module` and `prelude`, then
83
+ `[public|private] [meta] import [all] Name` commands; the first other token ends it."""
84
+ out: list[str] = []
85
+ pos = 0
86
+ while True:
87
+ pos = _skip(text, pos)
88
+ m = _NAME.match(text, pos)
89
+ if not m:
90
+ return out
91
+ tok = m.group(0)
92
+ pos = m.end()
93
+ if tok in ("module", "prelude") or tok in _MODIFIERS:
94
+ continue
95
+ if tok != "import":
96
+ return out
97
+ while True:
98
+ pos = _skip(text, pos)
99
+ m = _NAME.match(text, pos)
100
+ if not m:
101
+ return out
102
+ pos = m.end()
103
+ if m.group(0) not in ("all",) and m.group(0) not in _MODIFIERS:
104
+ out.append(m.group(0).replace("«", "").replace("»", ""))
105
+ break
106
+
107
+
108
+ def module_path(module: str) -> str:
109
+ return module.replace(".", "/")
110
+
111
+
112
+ # --------------------------------------------------------------------------
113
+ # entry globs
114
+
115
+ def glob_regex(pattern: str) -> re.Pattern:
116
+ """`**/` = any number of directories, `*` and `?` within one path component."""
117
+ out, i = [], 0
118
+ while i < len(pattern):
119
+ if pattern.startswith("**/", i):
120
+ out.append("(?:[^/]+/)*")
121
+ i += 3
122
+ elif pattern.startswith("**", i):
123
+ out.append(".*")
124
+ i += 2
125
+ elif pattern[i] == "*":
126
+ out.append("[^/]*")
127
+ i += 1
128
+ elif pattern[i] == "?":
129
+ out.append("[^/]")
130
+ i += 1
131
+ else:
132
+ out.append(re.escape(pattern[i]))
133
+ i += 1
134
+ return re.compile("".join(out) + r"\Z")
135
+
136
+
137
+ # --------------------------------------------------------------------------
138
+ # the staged cache: a tarball (read in one pass, nothing extracted) or a directory
139
+
140
+ class Cache:
141
+ """What the job's `.lake/packages` would hold: regular-file paths (relative to the directory holding
142
+ `.lake/`), the imports of each dependency .lean source, and the small .git files the pins need."""
143
+
144
+ def __init__(self, label: str, headers: bool = False):
145
+ self.label = label
146
+ self.files: set[str] = set()
147
+ self.imports: dict[str, list[str]] = {}
148
+ self.git: dict[str, bytes] = {}
149
+ self.unreadable: list[str] = []
150
+ # --fill-plan only: the first OLEAN_HEADER bytes of each built .olean, and (tarball) every member name
151
+ # of any type ("f" regular, "l" hard link, "d" directory, "s" symlink, "o" other), inside .lake/packages
152
+ # or not, for the additions-only check.
153
+ self.want_headers = headers
154
+ self.headers: dict[str, bytes] = {}
155
+ self.members: dict[str, str] = {}
156
+
157
+ def take(self, rel: str, read) -> None:
158
+ """Record one regular file at `rel`; `read(limit)` returns its first bytes."""
159
+ if not rel.startswith(PACKAGES):
160
+ return
161
+ self.files.add(rel)
162
+ rest = rel[len(PACKAGES):]
163
+ pkg, _, inner = rest.partition("/")
164
+ if not inner:
165
+ return
166
+ if self.want_headers and inner.endswith(".olean") and any(inner.startswith(b) for b in BUILD_LIBS):
167
+ self.headers[rel] = read(OLEAN_HEADER)
168
+ return
169
+ if inner.startswith(".git/"):
170
+ name = inner[len(".git/"):]
171
+ if name in ("HEAD", "packed-refs") or name.startswith("refs/"):
172
+ self.git[rel] = read(MAX_GIT_FILE)
173
+ elif inner.endswith(".lean") and not inner.startswith((".lake/", "build/", "lake-packages/")):
174
+ data = read(MAX_SOURCE + 1)
175
+ if len(data) > MAX_SOURCE:
176
+ self.unreadable.append(f"{rel}: over {MAX_SOURCE} bytes")
177
+ return
178
+ self.imports[rel] = header_imports(data.decode("utf-8", "replace"))
179
+
180
+
181
+ def _norm(name: str) -> str | None:
182
+ parts = [p for p in name.split("/") if p not in ("", ".")]
183
+ if ".." in parts:
184
+ return None
185
+ return "/".join(parts)
186
+
187
+
188
+ def read_tar(path: pathlib.Path, headers: bool = False) -> Cache:
189
+ cache = Cache(f"tarball {path.name}", headers)
190
+ links: list[tuple[str, str | None]] = [] # a hard link reads as its target, an earlier member
191
+ with tarfile.open(path, "r|*") as tf:
192
+ for member in tf:
193
+ rel = _norm(member.name)
194
+ if rel is not None and headers:
195
+ cache.members[rel] = ("f" if member.isreg() else "l" if member.islnk() else
196
+ "d" if member.isdir() else "s" if member.issym() else "o")
197
+ if rel is None or not (member.isreg() or member.islnk()):
198
+ continue
199
+ if member.islnk():
200
+ links.append((rel, _norm(member.linkname)))
201
+ continue
202
+
203
+ def read(limit, member=member):
204
+ f = tf.extractfile(member)
205
+ return f.read(limit) if f is not None else b""
206
+ cache.take(rel, read)
207
+ for rel, target in links:
208
+ if target is None or target not in cache.files:
209
+ cache.unreadable.append(f"{rel}: a hard link to a member that is not a regular file under "
210
+ f".lake/packages/ ({target})")
211
+ continue
212
+ data = cache.git.get(target)
213
+ if target in cache.headers:
214
+ cache.take(rel, lambda limit, h=cache.headers[target]: h[:limit])
215
+ elif target in cache.imports:
216
+ cache.take(rel, lambda limit: b"")
217
+ cache.imports[rel] = list(cache.imports[target])
218
+ elif data is not None:
219
+ cache.take(rel, lambda limit, data=data: data[:limit])
220
+ else:
221
+ cache.take(rel, lambda limit: b"")
222
+ return cache
223
+
224
+
225
+ def read_dir(root: pathlib.Path, headers: bool = False) -> Cache:
226
+ cache = Cache(f"directory {root.name}", headers)
227
+ base = root / ".lake" / "packages"
228
+ if base.is_symlink() or (root / ".lake").is_symlink():
229
+ return cache
230
+ for dirpath, _dirnames, filenames in os.walk(base, followlinks=False):
231
+ for fn in filenames:
232
+ p = pathlib.Path(dirpath) / fn
233
+ if p.is_symlink() or not p.is_file():
234
+ continue
235
+ rel = p.relative_to(root).as_posix()
236
+
237
+ def read(limit, p=p):
238
+ with open(p, "rb") as f:
239
+ return f.read(limit)
240
+ cache.take(rel, read)
241
+ return cache
242
+
243
+
244
+ # --------------------------------------------------------------------------
245
+ # pins
246
+
247
+ def head_sha(cache: Cache, pkg: str) -> tuple[str | None, str | None]:
248
+ """(sha, None) or (None, why) for `.lake/packages/<pkg>/.git/HEAD`."""
249
+ gitdir = f"{PACKAGES}{pkg}/.git/"
250
+ head = cache.git.get(gitdir + "HEAD")
251
+ if head is None:
252
+ return None, "no .git/HEAD in the cache (a stripped checkout: the pin cannot be checked)"
253
+ text = head.decode("utf-8", "replace").strip()
254
+ if HEX40.fullmatch(text):
255
+ return text, None
256
+ if not text.startswith("ref: "):
257
+ return None, f".git/HEAD is neither a commit nor a ref ({text[:40]!r})"
258
+ ref = text[len("ref: "):].strip()
259
+ loose = cache.git.get(gitdir + ref)
260
+ if loose is not None and HEX40.fullmatch(loose.decode("utf-8", "replace").strip()):
261
+ return loose.decode().strip(), None
262
+ for line in cache.git.get(gitdir + "packed-refs", b"").decode("utf-8", "replace").splitlines():
263
+ parts = line.split()
264
+ if len(parts) == 2 and parts[1] == ref and HEX40.fullmatch(parts[0]):
265
+ return parts[0], None
266
+ return None, f".git/HEAD names {ref}, which the cache does not resolve"
267
+
268
+
269
+ # --------------------------------------------------------------------------
270
+ # the closure
271
+
272
+ class Packages:
273
+ """The manifest's git packages present in the cache: their sources and built files by module path."""
274
+
275
+ def __init__(self, cache: Cache, names: list[str]):
276
+ self.cache = cache
277
+ self.names = names
278
+ self.sources: dict[str, dict[str, str]] = {n: {} for n in names} # pkg -> {module path: rel}
279
+ self.nested: dict[str, dict[str, str]] = {n: {} for n in names} # one srcDir level down
280
+ for rel in cache.imports:
281
+ pkg, _, inner = rel[len(PACKAGES):].partition("/")
282
+ if pkg not in self.sources:
283
+ continue
284
+ self.sources[pkg][inner[:-len(".lean")]] = rel
285
+ if "/" in inner:
286
+ self.nested[pkg].setdefault(inner.split("/", 1)[1][:-len(".lean")], rel)
287
+
288
+ def source(self, pkg: str, mpath: str) -> str | None:
289
+ """The module's source: at the package root, else (only for a module built in this package) one
290
+ srcDir level down, for a lakefile `srcDir`. Never the other way round: Mathlib/Lean/Expr.lean is
291
+ Mathlib.Lean.Expr, not the toolchain's Lean.Expr."""
292
+ if mpath in self.sources[pkg]:
293
+ return self.sources[pkg][mpath]
294
+ return self.nested[pkg].get(mpath) if self.built(pkg, mpath)[".olean"] else None
295
+
296
+ def built(self, pkg: str, mpath: str) -> dict[str, bool]:
297
+ for lib in BUILD_LIBS:
298
+ olean = f"{PACKAGES}{pkg}/{lib}{mpath}.olean"
299
+ if olean in self.cache.files:
300
+ return {".olean": True, ".ilean": f"{PACKAGES}{pkg}/{lib}{mpath}.ilean" in self.cache.files}
301
+ return {".olean": False, ".ilean": any(f"{PACKAGES}{pkg}/{lib}{mpath}.ilean" in self.cache.files
302
+ for lib in BUILD_LIBS)}
303
+
304
+ def provider(self, module: str) -> list[str]:
305
+ """The packages providing `module`: a built .olean or a source at the package root."""
306
+ mpath = module_path(module)
307
+ return [p for p in self.names if mpath in self.sources[p] or self.built(p, mpath)[".olean"]]
308
+
309
+
310
+ def local_modules(files: list[str]) -> dict[str, str]:
311
+ """Module path -> committed .lean path of the package itself (at the package root)."""
312
+ return {f[:-len(".lean")]: f for f in files if f.endswith(".lean") and not f.startswith(".lake/")}
313
+
314
+
315
+ def manifest_pins(repo: pathlib.Path, commit: str, problems: list[str]) -> tuple[list[str], dict[str, str]]:
316
+ """The git packages of lake-manifest.json committed at `commit` and their revs; problems appended."""
317
+ manifest_raw = core.git_show_bytes(repo, "./lake-manifest.json", commit)
318
+ names: list[str] = []
319
+ pins: dict[str, str] = {}
320
+ if manifest_raw is None:
321
+ problems.append(f"no lake-manifest.json committed at {commit[:12]}: the dependency pins are unknown")
322
+ return names, pins
323
+ try:
324
+ pkgs = json.loads(manifest_raw.decode("utf-8")).get("packages") or []
325
+ except (ValueError, UnicodeDecodeError, AttributeError):
326
+ pkgs = None
327
+ if not isinstance(pkgs, list):
328
+ problems.append("lake-manifest.json: not a manifest with a `packages` list")
329
+ pkgs = []
330
+ for p in pkgs:
331
+ if not isinstance(p, dict) or not p.get("name"):
332
+ problems.append("lake-manifest.json: a package entry without a name")
333
+ continue
334
+ # Lake's directory name for the escaped manifest name (`«dep-x»` is checked out as dep-x)
335
+ name = build_scope.lake_dir_name(str(p["name"]))
336
+ if name is None or "/" in name or "\\" in name or name in (".", ".."):
337
+ problems.append(f"lake-manifest.json: package name {str(p['name'])!r} is not a Lake package name")
338
+ continue
339
+ if name in pins:
340
+ problems.append(f"lake-manifest.json: package {name} is listed twice")
341
+ continue
342
+ if p.get("type", "git") != "git":
343
+ problems.append(f"manifest package {name}: type {p.get('type')!r} is not restored from a "
344
+ f"DEPS_TAR (only .lake/packages is), so its modules cannot be checked")
345
+ continue
346
+ names.append(name)
347
+ pins[name] = str(p.get("rev") or "")
348
+ return names, pins
349
+
350
+
351
+ def pin_check(cache: Cache, names: list[str], pins: dict[str, str], problems: list[str],
352
+ checks: list[str]) -> dict[str, str]:
353
+ """Every manifest git package present in `cache` at its rev; returns {package: sha} of those that are."""
354
+ at: dict[str, str] = {}
355
+ for name in names:
356
+ if not any(f.startswith(f"{PACKAGES}{name}/") for f in cache.files):
357
+ problems.append(f"manifest package {name}: not in the staged cache ({PACKAGES}{name}/ is absent)")
358
+ continue
359
+ sha, why = head_sha(cache, name)
360
+ if why:
361
+ problems.append(f"manifest package {name}: {why}")
362
+ elif sha != pins[name]:
363
+ problems.append(f"manifest package {name}: the cache is at {sha[:12]}, the manifest pins "
364
+ f"{pins[name][:12] or '(no rev)'}")
365
+ else:
366
+ at[name] = sha
367
+ checks.append(f"✓ {name} at {sha[:12]} = the manifest's rev")
368
+ return at
369
+
370
+
371
+ def check(repo: pathlib.Path, commit: str, cache: Cache, entries: list[str]) -> dict:
372
+ """Every problem and check line, the entry files and the missing modules; nothing is written."""
373
+ problems: list[str] = []
374
+ checks: list[str] = []
375
+ ls = core.git(repo, "ls-tree", "-r", "--name-only", "-z", commit, "--", ".")
376
+ files = [f for f in ls.stdout.split("\0") if f] if ls.returncode == 0 else []
377
+ pats = [glob_regex(g) for g in entries]
378
+ entry_files = sorted(f for f in files if f.endswith(".lean") and any(p.match(f) for p in pats))
379
+ if not entry_files:
380
+ problems.append(f"no committed .lean file at {commit[:12]} matches the entries "
381
+ f"({', '.join(entries)}): nothing to check; pass --entries GLOB for the files the "
382
+ f"verifier elaborates")
383
+ else:
384
+ checks.append(f"✓ {len(entry_files)} entry file(s) at {commit[:12]}: " + ", ".join(entry_files[:5])
385
+ + (f" (and {len(entry_files) - 5} more)" if len(entry_files) > 5 else ""))
386
+
387
+ names, pins = manifest_pins(repo, commit, problems)
388
+ for u in cache.unreadable:
389
+ problems.append(f"{cache.label}: {u}")
390
+ pin_check(cache, names, pins, problems, checks)
391
+ present = [n for n in names if any(f.startswith(f"{PACKAGES}{n}/") for f in cache.files)]
392
+ deps = Packages(cache, present)
393
+
394
+ local = local_modules(files)
395
+ missing: dict[str, dict] = {}
396
+ unresolved: dict[str, str] = {}
397
+ required: set[str] = set()
398
+ seen_local: set[str] = set()
399
+ queue: deque[tuple[str, str, bool]] = deque() # (module, required by, may be local)
400
+
401
+ def file_imports(rel: str) -> list[str]:
402
+ blob = core.git_show_bytes(repo, f"./{rel}", commit)
403
+ return header_imports(blob.decode("utf-8", "replace")) if blob is not None else []
404
+
405
+ for f in entry_files:
406
+ queue.extend((m, f, True) for m in file_imports(f))
407
+ while queue:
408
+ module, by, may_be_local = queue.popleft()
409
+ mpath = module_path(module)
410
+ found = deps.provider(module)
411
+ if may_be_local and mpath in local and not found:
412
+ if mpath not in seen_local:
413
+ seen_local.add(mpath)
414
+ queue.extend((m, local[mpath], True) for m in file_imports(local[mpath]))
415
+ continue
416
+ if module in required or module in unresolved:
417
+ continue
418
+ if not found:
419
+ if module.split(".")[0] in TOOLCHAIN_ROOTS:
420
+ continue
421
+ unresolved[module] = by
422
+ continue
423
+ if len(found) > 1:
424
+ problems.append(f"module {module}: provided by more than one manifest package ({', '.join(found)})")
425
+ pkg = found[0]
426
+ required.add(module)
427
+ have = deps.built(pkg, mpath)
428
+ lacking = [k for k, ok in have.items() if not ok]
429
+ if lacking:
430
+ missing[module] = {"module": module, "package": pkg, "files": lacking, "required_by": by}
431
+ src = deps.source(pkg, mpath)
432
+ if src is None:
433
+ problems.append(f"module {module} ({pkg}): no source in the staged cache, so its imports cannot be "
434
+ f"followed (stage the dependency's checkout with its build)")
435
+ continue
436
+ queue.extend((m, f"{module} ({pkg})", False) for m in cache.imports.get(src, []))
437
+
438
+ for module, by in sorted(unresolved.items()):
439
+ problems.append(f"module {module} (imported by {by}): provided by no manifest package in the cache and "
440
+ f"not a committed module of the package")
441
+ other_problems = list(problems)
442
+ # Modules an entry or a package module imports directly first, then the rest, each by name.
443
+ order = sorted(missing.values(), key=lambda d: (not d["required_by"].endswith(".lean"), d["module"]))
444
+ if order:
445
+ shown = ", ".join(f"{d['module']} ({'/'.join(d['files'])})" for d in order[:SHOW_MISSING])
446
+ more = f" (and {len(order) - SHOW_MISSING} more)" if len(order) > SHOW_MISSING else ""
447
+ problems.append(f"{len(order)} required external module(s) not built in the staged cache: {shown}{more}; "
448
+ f"build them into the dependency before staging (e.g. `lake build` of the modules the "
449
+ f"entry files import, such as `lake build {order[0]['module']}`), then stage again")
450
+ if required and not missing:
451
+ checks.append(f"✓ {len(required)} external module(s) in the entries' import closure, each with its "
452
+ f".olean and .ilean in the {cache.label}")
453
+ return {"entries": entry_files, "required_external_modules": len(required), "missing_count": len(order),
454
+ "missing": order[:JSON_MISSING], "checks": checks, "problems": problems,
455
+ # internal (never printed): every missing module, and the problems that are not missing files
456
+ "missing_all": order, "other_problems": other_problems, "local_modules": sorted(local)}
457
+
458
+
459
+ def cmd(args) -> int:
460
+ """`receipt slurm --preflight-deps` (with --fill-plan DONOR: deps_fill.cmd)."""
461
+ if bool(args.deps_tar) == bool(args.deps_dir):
462
+ raise core.UsageError("--preflight-deps needs exactly one of --deps-tar PATH or --deps-dir DIR")
463
+ if getattr(args, "fill_plan", None):
464
+ from . import deps_fill
465
+ return deps_fill.cmd(args)
466
+ repo = pathlib.Path(args.repo).resolve() if args.repo else pathlib.Path.cwd()
467
+ rev = args.commit_sha or "HEAD"
468
+ p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}")
469
+ commit = p.stdout.strip() if p.returncode == 0 else ""
470
+ if not commit:
471
+ raise core.UsageError(f"--commit {rev}: not a commit in the --repo checkout (default the current directory)")
472
+ problems: list[str] = []
473
+ cache = None
474
+ if args.deps_tar:
475
+ path = pathlib.Path(args.deps_tar)
476
+ if not path.is_file():
477
+ raise core.UsageError(f"--deps-tar {args.deps_tar}: not a file")
478
+ try:
479
+ cache = read_tar(path)
480
+ except (tarfile.TarError, OSError, EOFError) as e:
481
+ problems.append(f"--deps-tar: cannot read the tarball ({type(e).__name__}: {e}); gzip, bzip2, xz and "
482
+ f"plain tar are read: for another compression pass --deps-dir on an extracted copy")
483
+ else:
484
+ path = pathlib.Path(args.deps_dir)
485
+ if not path.is_dir():
486
+ raise core.UsageError(f"--deps-dir {args.deps_dir}: not a directory")
487
+ cache = read_dir(path)
488
+ result = {"entries": [], "required_external_modules": 0, "missing_count": 0, "missing": [], "checks": [],
489
+ "problems": problems}
490
+ if cache is not None:
491
+ if not any(f.startswith(PACKAGES) for f in cache.files):
492
+ problems.append(f"{cache.label}: no regular file under .lake/packages/ (the job restores only that "
493
+ f"directory)")
494
+ else:
495
+ entries = list(args.entries) or list(DEFAULT_ENTRIES)
496
+ result = check(repo, commit, cache, entries)
497
+ for k in ("missing_all", "other_problems", "local_modules"):
498
+ del result[k]
499
+ result["problems"] = problems + result["problems"]
500
+ ok = not result["problems"]
501
+ if getattr(args, "json_out", False):
502
+ core.print_json({"ok": ok, "preflight_deps": True, "commit": commit, **result})
503
+ else:
504
+ n = len(result["problems"])
505
+ print(f"receipt slurm --preflight-deps: {'ok' if ok else f'{n} problem(s)'}; nothing written")
506
+ for c in result["checks"]:
507
+ print(f" {c}")
508
+ for pr in result["problems"]:
509
+ print(f" ✗ {pr}")
510
+ if not ok:
511
+ print(f"receipt slurm --preflight-deps: {n} problem(s); do not submit this cache")
512
+ return 0 if ok else 1