lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/prior_art.py ADDED
@@ -0,0 +1,286 @@
1
+ # lean-pkg prior art -- the citable search record and its event line
2
+ """`lean-pkg search TERM --record` writes two things, with different roles:
3
+
4
+ - `docs/prior-art/<YYYY-MM-DD>-<slug>.md` in the research repository (the
5
+ package's checkout, or --repo): terms, date, every source with its
6
+ revision, state and hit count (zeros included), the top candidates, and a
7
+ `decision: pending` line a human edits to require | reuse | vendor |
8
+ contribute | build with a reason;
9
+ - one `prior-art-searched` line in the registry's event log.
10
+
11
+ It never writes into the registry directory and never overwrites a record.
12
+ Claims of private packages other than the target appear only when the target
13
+ package is itself private, and the record then says `private-claims: yes`. A
14
+ record written into a folder that is not the package's own checkout (--repo)
15
+ lists the package's own claims only when the package is public.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import pathlib
21
+
22
+ from . import __version__
23
+ from . import core
24
+
25
+ RECORD_DIR = "docs/prior-art"
26
+ TOP_PER_SOURCE = 5
27
+ DECISIONS = ("require", "reuse", "vendor", "contribute", "build")
28
+
29
+
30
+ SLUG_MAX = 60
31
+ NAV_REASON = "a strict MkDocs build needs a nav entry (or a literate-nav glob) for it"
32
+
33
+
34
+ MKDOCS_CONFIGS = ("mkdocs.yml", "mkdocs.yaml")
35
+
36
+
37
+ def has_mkdocs(target: pathlib.Path) -> bool:
38
+ return any((target / f).is_file() for f in MKDOCS_CONFIGS)
39
+
40
+
41
+ def nav_hint(rel: str, target: pathlib.Path | None = None) -> dict | None:
42
+ """#50: the new page is an error under `mkdocs build --strict` until nav lists it. A hint only:
43
+ lean-pkg never edits the consumer's mkdocs.yml. None when the repository has no MkDocs config: a plain
44
+ Lean repository has no nav to update (field report)."""
45
+ if target is not None and not has_mkdocs(target):
46
+ return None
47
+ return {"path": rel, "reason": NAV_REASON}
48
+
49
+
50
+ def record_slug(term: str) -> str:
51
+ """Kebab slug of the search term; a term longer than SLUG_MAX is cut there and gets an
52
+ 8-hex suffix of the full slug, so two long terms that agree on their first 60 characters
53
+ still get distinct record files."""
54
+ import hashlib
55
+ from .search import tokens
56
+ full = "-".join(tokens(term)).strip("-")
57
+ if not full:
58
+ return "search"
59
+ if len(full) <= SLUG_MAX:
60
+ return full
61
+ return full[:SLUG_MAX].strip("-") + "-" + hashlib.sha256(full.encode()).hexdigest()[:8]
62
+
63
+
64
+ def record_rel(date: str, term: str) -> str:
65
+ return f"{RECORD_DIR}/{date}-{record_slug(term)}.md"
66
+
67
+
68
+ def _cell(s) -> str:
69
+ return str(s).replace("|", "\\|").replace("\n", " ")
70
+
71
+
72
+ def _q(term: str) -> str:
73
+ return '"' + term.replace('"', "'") + '"'
74
+
75
+
76
+ def not_found_line(payload: dict) -> str | None:
77
+ """The spec's zero-hit wording, over exactly the sources that ran and found nothing."""
78
+ zero = [f"{b['source']} at {b['revision'] or 'unknown revision'}"
79
+ + (f" ({', '.join(b['partial'])} search failed, not searched)" if b.get("partial") else "")
80
+ for b in payload["sources"] if b["state"] == "ok" and not b["hits"] and not b.get("withheld")
81
+ and not b.get("incomplete")]
82
+ if not zero:
83
+ return None
84
+ return f"Not found in {', '.join(zero)} on {payload['date']} for {_q(payload['term'])}."
85
+
86
+
87
+ def not_fully_searched_line(payload: dict) -> str | None:
88
+ """A local source that answered without reading everything (the registry's file cap or unreadable files,
89
+ an unreadable index entry) is never `not found`: the record names what it did not read."""
90
+ part = [f"{b['source']} ({b['incomplete']})" for b in payload["sources"]
91
+ if b["state"] == "ok" and b.get("incomplete")]
92
+ if not part:
93
+ return None
94
+ return f"Not fully searched, so a zero there is not an absence: {'; '.join(part)}."
95
+
96
+
97
+ def coverage_sentence(payload: dict) -> str | None:
98
+ """Counts only (no package names: the record may land in a public repository)."""
99
+ cov = payload.get("coverage")
100
+ if not cov:
101
+ return None
102
+ from . import search as srch # local: search imports this module
103
+ blind = cov["declaration_only"] + len(cov["not_searched"])
104
+ if not blind:
105
+ return None
106
+ text = (f"{blind} of {blind + cov['claims']} registered packages have no synced claims: "
107
+ f"{cov['declaration_only']} searched by declaration only, {len(cov['not_searched'])} not searched "
108
+ f"({srch.not_searched_groups(cov, names=False)})")
109
+ capped = cov.get("declaration_files_capped") or []
110
+ if capped:
111
+ inspected = sum(c["inspected"] for c in capped)
112
+ candidates = sum(c["candidates"] for c in capped)
113
+ unreadable = sum(c.get("unreadable") or 0 for c in capped)
114
+ why = (["file cap"] if candidates - inspected - unreadable > 0 else []) + \
115
+ ([f"{unreadable} unreadable"] if unreadable else [])
116
+ text += (f"; in {len(capped)} of them only {inspected} of {candidates} candidate file(s) were inspected "
117
+ f"({'; '.join(why)}), so a zero there is not an absence")
118
+ return text + "."
119
+
120
+
121
+ def _candidate(h: dict) -> str:
122
+ if h.get("hit_kind") == "declaration (unclaimed)":
123
+ return (f"- `{h['decl']}` in package `{h['package']}` ({h['kind']}, declaration (unclaimed), trust "
124
+ f"{h['trust']}, `{_cell(h['file'])}`). {_cell(h.get('summary') or '')}")
125
+ if h.get("hit_kind") == "package":
126
+ repo = f": {_cell(h['repo'])}" if h.get("repo") else ""
127
+ return f"- package `{h['package']}` ({h['status']}){repo}"
128
+ if "id" in h:
129
+ pin = f", pin `{str(h['pin'])[:12]}`" if h.get("pin") else ""
130
+ return (f"- `{h['id']}` (`{h['decl']}`): {h['kind']}, {h['status']}, trust {h['trust']}{pin}. "
131
+ f"{_cell(h.get('summary') or '')}")
132
+ name = f"[{_cell(h['name'])}]({h['url']})" if h.get("url") else f"`{h['name']}`"
133
+ return f"- {name}: {_cell(h.get('summary') or '')}".rstrip()
134
+
135
+
136
+ def render_record(payload: dict, *, withheld: int, private_claims: bool) -> str:
137
+ term, date = payload["term"], payload["date"]
138
+ lines = [f"# Prior-art search: {_q(term)}", "",
139
+ f"- date: {date}",
140
+ f"- term: {_q(term)}",
141
+ f"- package: {payload.get('package') or 'none'}",
142
+ f"- tool: lean-pkg {__version__} (lean-pkg search --record)",
143
+ f"- private-claims: {'yes' if private_claims else 'no'}", "",
144
+ "## Sources", "",
145
+ "| Source | Revision | State | Hits |", "|---|---|---|---|"]
146
+ for b in payload["sources"]:
147
+ state = "ok" if b["state"] == "ok" else f"skipped: {b['reason']}"
148
+ if b["state"] == "ok" and (b.get("partial") or b.get("capped")):
149
+ from . import search as srch # local: search imports this module
150
+ state = ("partial: " if b.get("partial") else "capped: ") + ", ".join(srch.part_problems(b))
151
+ elif b["state"] == "ok" and b.get("incomplete"):
152
+ state = f"incomplete: {b['incomplete']}"
153
+ w = b.get("withheld") or 0
154
+ hits = (f"{len(b['hits'])} shown (+{w} withheld)" if w else str(len(b["hits"]))) if b["state"] == "ok" else "-"
155
+ lines.append(f"| {b['source']} | {_cell(b['revision'] or '-')} | {_cell(state)} | {hits} |")
156
+ lines.append("")
157
+ nf = not_found_line(payload)
158
+ if nf:
159
+ lines += [nf, ""]
160
+ nfs = not_fully_searched_line(payload)
161
+ if nfs:
162
+ lines += [nfs, ""]
163
+ cs = coverage_sentence(payload)
164
+ if cs:
165
+ lines += [cs, ""]
166
+ capped = [b for b in payload["sources"] if b["state"] == "ok" and b.get("capped")]
167
+ if capped: # a source at its result limit lists only the first matches (field report)
168
+ from . import search as srch
169
+ lines += ["Incomplete: " + "; ".join(f"{b['source']}: {', '.join(srch.part_problems(b))}" for b in capped)
170
+ + "; more matches may exist than the ones listed.", ""]
171
+ lines += ["A skipped source was not searched: it is not a zero. Zero hits do not prove absence.", ""]
172
+ if withheld:
173
+ lines += [f"{withheld} registry hit(s) of private packages matched and are not listed here.", ""]
174
+ lines += ["## Candidates", ""]
175
+ any_hits = False
176
+ for b in payload["sources"]:
177
+ if b["state"] != "ok" or not b["hits"]:
178
+ continue
179
+ any_hits = True
180
+ lines += [f"### {b['source']}", ""]
181
+ lines += [_candidate(h) for h in b["hits"][:TOP_PER_SOURCE]]
182
+ if len(b["hits"]) > TOP_PER_SOURCE:
183
+ lines.append(f"- and {len(b['hits']) - TOP_PER_SOURCE} more not listed")
184
+ lines.append("")
185
+ if not any_hits:
186
+ lines += ["None.", ""]
187
+ lines += ["## Decision", "",
188
+ "decision: pending",
189
+ "reason:", "",
190
+ f"Replace `pending` with one of {' | '.join(DECISIONS)} and give the reason, "
191
+ f"including why each candidate above was rejected.", ""]
192
+ return "\n".join(lines)
193
+
194
+
195
+ def _target(reg_path: pathlib.Path, reg: dict | None, package: str | None,
196
+ repo_dir: str | None) -> tuple[pathlib.Path, str, bool]:
197
+ """(research repository directory, the target's visibility: private | public | unknown, whether the
198
+ directory is the package's own checkout)."""
199
+ pkgs = (reg or {}).get("packages") or {}
200
+ pkg = pkgs.get(package) if package else None
201
+ if repo_dir:
202
+ target = pathlib.Path(repo_dir).expanduser()
203
+ elif pkg is not None:
204
+ target = core.repo_path(pkg)
205
+ elif package:
206
+ raise core.Fail(f"--record --package {package}: not in the registry; pass --repo DIR")
207
+ else:
208
+ raise core.UsageError("--record needs --package NAME (its checkout) or --repo DIR")
209
+ if not target.is_dir():
210
+ raise core.Fail(f"record target is not a directory: {target}")
211
+ reg_dir = reg_path.parent.resolve()
212
+ if reg_dir in (target.resolve(), (target / RECORD_DIR).resolve()):
213
+ raise core.Fail("refusing to write a search record into the registry directory; "
214
+ "records live in the research repository (--package or --repo)")
215
+ vis = pkg.get("visibility") if pkg is not None else "unknown"
216
+ own_checkout = pkg is not None
217
+ if repo_dir and pkg is not None:
218
+ try:
219
+ own = core.repo_path(pkg).resolve()
220
+ except Exception:
221
+ own = None
222
+ if own is None or own != target.resolve():
223
+ vis, own_checkout = "unknown", False # the privacy level follows the folder written into
224
+ return target, vis if vis in ("private", "public") else "unknown", own_checkout
225
+
226
+
227
+ def _withhold(payload: dict, reg: dict | None, package: str | None, visibility: str,
228
+ own_checkout: bool = True) -> tuple[dict, int, bool]:
229
+ """A copy of the payload whose registry block hides other private packages' hits unless the target is
230
+ private. The package's own hits are exempt only when the record goes into its own checkout: written into
231
+ any other folder (--repo), a non-public package's hits are withheld like any other private package's.
232
+ Returns (payload copy, number withheld, whether hits of private packages other than the target's own
233
+ checkout are listed)."""
234
+ pkgs = (reg or {}).get("packages") or {}
235
+ private = {n for n, p in pkgs.items() if isinstance(p, dict) and p.get("visibility") != "public"}
236
+ exempt = package if own_checkout else None
237
+ blocks, withheld, listed_private = [], 0, False
238
+ for b in payload["sources"]:
239
+ if b["source"] == "registry" and b["hits"]:
240
+ keep = []
241
+ for h in b["hits"]:
242
+ foreign_private = h["package"] in private and h["package"] != exempt
243
+ if foreign_private and visibility != "private":
244
+ withheld += 1
245
+ continue
246
+ listed_private = listed_private or foreign_private
247
+ keep.append(h)
248
+ b = {**b, "hits": keep, "withheld": len(b["hits"]) - len(keep)}
249
+ blocks.append(b)
250
+ return {**payload, "sources": blocks}, withheld, listed_private
251
+
252
+
253
+ def write_record(payload: dict, *, reg_path: pathlib.Path, events_p: pathlib.Path | None,
254
+ repo_dir: str | None, actor: str | None = None) -> tuple[list[str], dict]:
255
+ reg = core.load_registry(reg_path) if reg_path.is_file() else None
256
+ package = payload.get("package")
257
+ target, visibility, own_checkout = _target(reg_path, reg, package, repo_dir)
258
+ rel = record_rel(payload["date"], payload["term"])
259
+ dest = target / rel
260
+ if dest.exists() or dest.is_symlink():
261
+ raise core.Fail(f"{rel} already exists in {target}; a record is never overwritten "
262
+ f"(edit it, or search with another phrasing)")
263
+ shown, withheld, private_claims = _withhold(payload, reg, package, visibility, own_checkout)
264
+ text = render_record(shown, withheld=withheld, private_claims=private_claims)
265
+ dest.parent.mkdir(parents=True, exist_ok=True)
266
+ try:
267
+ with open(dest, "x", encoding="utf-8") as f: # atomic create; refuses a symlink or a race
268
+ f.write(text)
269
+ except FileExistsError:
270
+ raise core.Fail(f"{rel} appeared in {target} during the write; nothing overwritten") from None
271
+ out = [f"record written: {dest} (decision: pending; edit it, then commit it in that repository)"]
272
+ if has_mkdocs(target):
273
+ out.append(f"note: {rel} is new; {NAV_REASON}")
274
+ sources = {b["source"]: (b["state"] if b["state"] == "ok" else f"skipped: {b['reason']}")
275
+ for b in payload["sources"]}
276
+ hits = {b["source"]: (len(b["hits"]) if b["state"] == "ok" else None) for b in payload["sources"]}
277
+ if events_p is not None:
278
+ core.append_event(events_p, core.now_iso(), package, "prior-art-searched",
279
+ term=payload["term"], sources=sources, hits=hits, record=rel,
280
+ decision="pending", **({"actor": actor} if actor else {}))
281
+ event = "prior-art-searched"
282
+ else:
283
+ out.append("no event log (no registry here and no --events): prior-art-searched not recorded")
284
+ event = None
285
+ return out, {"path": rel, "event": event, "withheld": withheld, "private_claims": private_claims,
286
+ "mkdocs": has_mkdocs(target)}
lean_pkg/producer.py ADDED
@@ -0,0 +1,212 @@
1
+ # lean-pkg producer -- a fingerprint of the running lean-pkg, so a long run notices its own code changing
2
+ """The producer of a receipt is the lean-pkg that writes it. A `receipt systemd --run` (alias `receipt local
3
+ --run`) lives for the whole verification run, hours for a large package, and only collects the evidence at the
4
+ end. When lean-pkg runs from a shared editable checkout, a `git pull` or `git checkout` there during the run
5
+ replaces its own sources underneath it: the receipt would be written by a mix of the code that started the run
6
+ (already imported) and the code now on disk (imported lazily, and the shipped scripts and templates). A version
7
+ string or the entry-point script alone does not show it; the package's internal sources do.
8
+
9
+ `fingerprint()` records, at run start, the SHA-256 of
10
+
11
+ - every file of the imported `lean_pkg` package directory (`cli.package_dir()`: Python sources, shipped
12
+ scripts, schemas, templates; `__pycache__/` and `*.pyc` are skipped, they are caches of the sources),
13
+ - the installed distribution's metadata (`*.dist-info`: RECORD, METADATA, direct_url.json, entry_points.txt)
14
+ when it is the one this package was imported from,
15
+ - the Python interpreter (`sys.executable`, resolved) and the entry-point script (`sys.argv[0]`) when it is a
16
+ file outside the package.
17
+
18
+ `changes(before, after)` names every entry added, removed or changed; `receipt systemd --run` checks it while
19
+ it waits (a WARN, once) and again at final collection, before anything is written (a refusal naming the files).
20
+
21
+ `sources_sha256` is reproducible by anyone from the same release: it is the SHA-256 of the `sha256sum` listing
22
+ of the package files, paths relative to the package directory, sorted bytewise:
23
+
24
+ cd "$(python3 -c 'import lean_pkg, os; print(os.path.dirname(lean_pkg.__file__))')" &&
25
+ find . -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | sed 's|^\\./||' | LC_ALL=C sort |
26
+ xargs -d '\\n' sha256sum | sha256sum
27
+
28
+ `sources_sha256` identifies the SOURCES only, not the bytecode the interpreter executes: Python runs a module
29
+ from its cached `__pycache__/<name>.<cache_tag>.pyc` when that cache is valid for the source, and those files
30
+ are left out above. `bytecode_files(pkg)` therefore reports, separately, the running interpreter's own caches
31
+ (`__pycache__/*.<tag>.pyc` and `*.<tag>.opt-N.pyc`, `tag` = `sys.implementation.cache_tag`) and counts every
32
+ other `.pyc`/`.pyo` in the package (another interpreter's caches, or a sourceless/untagged file). It is a
33
+ snapshot at run start and never part of `changes()`: on a writable install the interpreter adds its own
34
+ caches while a long run imports modules lazily, which is not a producer change. A read-only install (the lab
35
+ seals release venvs) keeps it fixed. The own-tag listing hashes like the sources:
36
+
37
+ cd PKGDIR && TAG=$(python3 -c 'import sys; print(sys.implementation.cache_tag)') &&
38
+ find . -type f -path '*/__pycache__/*' \\( -name "*.$TAG.pyc" -o -name "*.$TAG.opt-*.pyc" \\) |
39
+ sed 's|^\\./||' | LC_ALL=C sort | xargs -d '\\n' sha256sum | sha256sum
40
+
41
+ `receipt_producer(fp)` is the part sealed into the receipt as the additive key `producer` (gate and
42
+ `receipt check` ignore it): the version, the install kind (editable / installed / unknown, as `--version`
43
+ detects it), the editable checkout's commit and dirtiness, `sources_sha256`, the number of source files, the
44
+ Python version, and the bytecode at run start: `bytecode_tag`, `bytecode_files`, `bytecode_sha256` (the
45
+ own-tag listing; null when the interpreter has no cache tag) and `other_bytecode_files`. No path, host or user
46
+ name is written."""
47
+
48
+ from __future__ import annotations
49
+
50
+ import hashlib
51
+ import importlib.metadata as md
52
+ import json
53
+ import os
54
+ import pathlib
55
+ import platform
56
+ import sys
57
+ import urllib.parse
58
+ import urllib.request
59
+
60
+ from . import cli
61
+ from . import core
62
+
63
+ SKIP_DIRS = ("__pycache__",)
64
+ SKIP_SUFFIXES = (".pyc", ".pyo")
65
+ DIST_FILES = ("RECORD", "METADATA", "direct_url.json", "entry_points.txt")
66
+ SHOWN = 9
67
+
68
+
69
+ def _sha(path: pathlib.Path) -> str:
70
+ h = hashlib.sha256()
71
+ try:
72
+ with open(path, "rb") as f:
73
+ for chunk in iter(lambda: f.read(1 << 20), b""):
74
+ h.update(chunk)
75
+ except OSError as e:
76
+ return f"unreadable ({e.__class__.__name__})"
77
+ return h.hexdigest()
78
+
79
+
80
+ def source_files(pkg: pathlib.Path) -> dict[str, str]:
81
+ """{path relative to the package directory: SHA-256} for every file of the package, caches skipped."""
82
+ out = {}
83
+ for root, dirs, files in os.walk(pkg):
84
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
85
+ for name in files:
86
+ if name.endswith(SKIP_SUFFIXES):
87
+ continue
88
+ p = pathlib.Path(root, name)
89
+ out[p.relative_to(pkg).as_posix()] = _sha(p)
90
+ return out
91
+
92
+
93
+ def bytecode_files(pkg: pathlib.Path, tag: str | None = None) -> tuple[dict[str, str], int]:
94
+ """({path: SHA-256} of the interpreter's own caches `__pycache__/<name>.<tag>[.opt-N].pyc`, the number of
95
+ every other `.pyc`/`.pyo` in the package). `tag` defaults to `sys.implementation.cache_tag`; with no tag
96
+ (an interpreter that writes no caches) every bytecode file counts as other."""
97
+ tag = sys.implementation.cache_tag if tag is None else tag
98
+ own, other = {}, 0
99
+ for root, dirs, files in os.walk(pkg):
100
+ dirs.sort()
101
+ in_cache = os.path.basename(root) == "__pycache__"
102
+ for name in files:
103
+ if not name.endswith(SKIP_SUFFIXES):
104
+ continue
105
+ parts = name[:-len(".pyc")].split(".") if name.endswith(".pyc") else []
106
+ mine = (in_cache and tag and len(parts) in (2, 3) and parts[1] == tag
107
+ and (len(parts) == 2 or parts[2].startswith("opt-")))
108
+ if mine:
109
+ p = pathlib.Path(root, name)
110
+ own[p.relative_to(pkg).as_posix()] = _sha(p)
111
+ else:
112
+ other += 1
113
+ return own, other
114
+
115
+
116
+ def sources_sha256(files: dict[str, str]) -> str:
117
+ """SHA-256 of the `sha256sum` listing of `files`, sorted bytewise by path (reproducible with coreutils)."""
118
+ listing = "".join(f"{files[rel]} {rel}\n" for rel in sorted(files, key=lambda r: r.encode()))
119
+ return hashlib.sha256(listing.encode()).hexdigest()
120
+
121
+
122
+ def _dist_info(pkg: pathlib.Path) -> pathlib.Path | None:
123
+ """The `*.dist-info` directory of the installed lean-pkg distribution this package was imported from: a
124
+ regular install whose files hold this package, or an editable install whose direct_url.json names a
125
+ directory containing it. None otherwise (e.g. run from PYTHONPATH=src beside an unrelated install)."""
126
+ try:
127
+ dist = md.distribution("lean-pkg")
128
+ except md.PackageNotFoundError:
129
+ return None
130
+ base = getattr(dist, "_path", None)
131
+ if base is None:
132
+ return None
133
+ base = pathlib.Path(base)
134
+ try:
135
+ if pathlib.Path(dist.locate_file("lean_pkg/__init__.py")).resolve() == (pkg / "__init__.py").resolve():
136
+ return base
137
+ direct = json.loads(dist.read_text("direct_url.json") or "{}")
138
+ except (OSError, ValueError):
139
+ return None
140
+ url = direct.get("url", "")
141
+ if direct.get("dir_info", {}).get("editable") and url.startswith("file:"):
142
+ root = pathlib.Path(urllib.request.url2pathname(urllib.parse.urlparse(url).path)).resolve()
143
+ if root == pkg.resolve() or root in pkg.resolve().parents:
144
+ return base
145
+ return None
146
+
147
+
148
+ def fingerprint(pkg: pathlib.Path | None = None) -> dict:
149
+ """{"version", "sources": {rel: sha}, "environment": {label: sha}} of the running lean-pkg."""
150
+ from . import __version__
151
+ pkg = (pkg or cli.package_dir()).resolve()
152
+ env = {}
153
+ exe = os.path.realpath(sys.executable) if sys.executable else ""
154
+ if exe:
155
+ env["python interpreter"] = _sha(pathlib.Path(exe))
156
+ entry = pathlib.Path(sys.argv[0]).resolve() if sys.argv and sys.argv[0] else None
157
+ if entry is not None and entry.is_file() and pkg not in entry.parents:
158
+ env[f"entry point {entry.name}"] = _sha(entry)
159
+ info = _dist_info(pkg)
160
+ if info is not None:
161
+ for name in DIST_FILES:
162
+ if (info / name).is_file():
163
+ env[f"dist-info {name}"] = _sha(info / name)
164
+ own, other = bytecode_files(pkg)
165
+ return {"version": __version__, "pkg": str(pkg), "sources": source_files(pkg), "environment": env,
166
+ "bytecode": own, "other_bytecode": other}
167
+
168
+
169
+ def changes(before: dict, after: dict) -> list[str]:
170
+ """Every source file (package-relative, `lean_pkg/...`) and environment entry added, removed or changed."""
171
+ out = []
172
+ for kind, prefix in (("sources", "lean_pkg/"), ("environment", "")):
173
+ a, b = before.get(kind, {}), after.get(kind, {})
174
+ for key in sorted(set(a) | set(b)):
175
+ if key not in b:
176
+ out.append(f"{prefix}{key} (removed)")
177
+ elif key not in a:
178
+ out.append(f"{prefix}{key} (added)")
179
+ elif a[key] != b[key]:
180
+ out.append(f"{prefix}{key}")
181
+ if before.get("version") != after.get("version") and not out:
182
+ out.append(f"version {before.get('version')} -> {after.get('version')}")
183
+ return out
184
+
185
+
186
+ def shown(names: list[str]) -> str:
187
+ return ", ".join(names[:SHOWN]) + (f" (+{len(names) - SHOWN} more)" if len(names) > SHOWN else "")
188
+
189
+
190
+ def changed_message(names: list[str], when: str) -> str:
191
+ """The refusal (or WARN) text for a producer that changed."""
192
+ return (f"lean-pkg itself changed {when}: {len(names)} file(s) of the running lean-pkg differ from the run "
193
+ f"start: {shown(names)}; the receipt would be written by other code than the one that started the "
194
+ f"run. Run long jobs from a frozen install (pipx/venv from a release tag), never a shared editable "
195
+ f"checkout: docs/receipts.md, \"Long runs: freeze the producer\"")
196
+
197
+
198
+ def receipt_producer(fp: dict) -> dict:
199
+ """The additive receipt key `producer`: what wrote the receipt, without any path."""
200
+ info = cli.install_detect(pathlib.Path(fp["pkg"]))
201
+ commit = None
202
+ if info["install"] == "editable":
203
+ p = core.registry_git(pathlib.Path(info["path"]), "--no-optional-locks", "rev-parse", "HEAD")
204
+ commit = p.stdout.strip() if p.returncode == 0 else None
205
+ tag = sys.implementation.cache_tag
206
+ own = fp.get("bytecode", {})
207
+ return {"lean_pkg": fp["version"], "install": info["install"], "commit": commit, "dirty": info["dirty"],
208
+ "sources_sha256": sources_sha256(fp["sources"]), "source_files": len(fp["sources"]),
209
+ "python": platform.python_version(),
210
+ "bytecode_tag": tag, "bytecode_files": len(own),
211
+ "bytecode_sha256": sources_sha256(own) if tag else None,
212
+ "other_bytecode_files": fp.get("other_bytecode", 0)}