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,501 @@
1
+ # lean-pkg-extract decls -- write the target modules of a declaration-level extraction, then record its ledger
2
+ """lean-pkg-extract decls (proposal 0009, stage S3): write the target modules and record the ledger.
3
+
4
+ `lean-pkg-extract decls --repo SRC --commit C --output DIR [--scaffold NAME [--author TEXT] [--license SPDX]]
5
+ --from-module SRC/Path.lean:New.Module ... [--namespace ...] [--rename ...] [--drop ...] [--allow-differs ...]
6
+ --ledger PATH [--dry-run] [--json] [@ARGSFILE]`
7
+
8
+ Each mapped source module is read at C (git objects only) and written as its target module
9
+ (`New/Module.lean` under DIR): every top-level command in source order with the namespace and rename maps
10
+ applied as `ledger` applies them (`lean_scan.apply_map`, the command's own namespace scope), the
11
+ declarations named in `--drop` left out with their docstrings, the header's imports of mapped modules
12
+ rewritten to their target modules, and every comment except docstrings removed (so no source path or
13
+ provenance note is carried). An import of a module of the source that is not extracted is refused.
14
+
15
+ With `--scaffold NAME` DIR also becomes a package: the pins copied from the source commit (the Lake package
16
+ holding the modules): `lean-toolchain` byte for byte, and `lake-manifest.json` with every dependency pin
17
+ as it is and only its root package name set to NAME (the source's name may be private), a `lakefile.toml` naming one
18
+ library per target root and requiring the source manifest's direct dependencies at their pinned
19
+ revisions, a README skeleton, and the package files of `lean-pkg new` (`scaffold.package_files`:
20
+ .gitignore, CITATION.cff, LICENSE, LICENSES/, REUSE.toml); then `git init`, nothing committed.
21
+
22
+ The tree is compared with the source exactly as `ledger` compares a hand-ported one (method text/1) before
23
+ anything is written; a refusal or a failure writes nothing. Then it is written through
24
+ `extract_write.write_tree`: staged beside DIR, scanned with public-safety (a blocking hit writes nothing),
25
+ the ledger written (`target.commit: null`, since nothing is committed), and the tree moved into place
26
+ with one `os.replace`. `--dry-run` does all of it but the writing.
27
+
28
+ After `git add -A && git commit` in DIR (the tree as written), `lean-pkg-extract recheck --ledger PATH
29
+ --repo SRC --target DIR --target-commit HEAD` recomputes the ledger byte for byte.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import datetime as dt
35
+ import json
36
+ import pathlib
37
+ import re
38
+ import subprocess
39
+
40
+ from . import core
41
+ from . import extract as ex
42
+ from . import extract_ledger as el
43
+ from . import extract_write as xw
44
+ from . import lean_scan
45
+ from . import scaffold
46
+
47
+ TOOL = "lean-pkg-extract decls"
48
+ WRITTEN = "the written tree"
49
+ LAKEFILES = el.LAKEFILES
50
+ _IMPORT_AT = re.compile(r"(?<![\w'.!?«»])(import[ \t]+(?:all[ \t]+)?)(" + lean_scan._NAME.pattern + ")")
51
+ README = """\
52
+ # {name}
53
+
54
+ A Lean 4 library, written with `lean-pkg-extract decls` from the declarations of an existing project.
55
+ Its modules:
56
+
57
+ {modules}
58
+
59
+ Build it with `lake build`. Its extraction ledger (lean-pkg-extract-ledger/1), which records that every
60
+ declaration is the source's, is kept outside this repository: it names the private source.
61
+
62
+ {credit}
63
+ """
64
+
65
+
66
+ # ----------------------------------------------------------------------------------------------------
67
+ # rendering one target module
68
+
69
+ def _keep_text(text: str) -> str:
70
+ """The file with every comment blanked except docstrings (`/-- -/`), same length and lines."""
71
+ return lean_scan._blank(text, lean_scan._lex(text), ("comment", "moddoc"))
72
+
73
+
74
+ def _doc_lines_before(text: str, span_start_line: int) -> set[int]:
75
+ """0-based line numbers of the docstring standing right before the line span_start_line (1-based)."""
76
+ regions = lean_scan._lex(text)
77
+ masked = lean_scan._blank(text, regions, lean_scan._COMMENT_KINDS + ("string", "char"))
78
+ starts = [0]
79
+ for i, ch in enumerate(text):
80
+ if ch == "\n":
81
+ starts.append(i + 1)
82
+ pos = starts[span_start_line - 1]
83
+ for a, b, kind in reversed(regions):
84
+ if b > pos:
85
+ continue
86
+ if kind == "doc" and not masked[b:pos].strip():
87
+ first, last = text.count("\n", 0, a), text.count("\n", 0, b)
88
+ return set(range(first, last + 1))
89
+ break
90
+ return set()
91
+
92
+
93
+ def render_module(text: str, decls, context, *, ns, rn, declared, dropped: set[str],
94
+ rewrite_import) -> str:
95
+ """The target text of one source module: every command with the maps applied (a header import
96
+ through rewrite_import(name) -> new name), the dropped declarations removed with their docstrings,
97
+ non-doc comments removed, comment-only lines and runs of blank lines between commands removed."""
98
+ orig = text.split("\n")
99
+ keep = _keep_text(text).split("\n")
100
+ out = list(keep)
101
+ removed: set[int] = set()
102
+ in_span: set[int] = set()
103
+ for s in sorted(list(decls) + list(context), key=lambda s: s.start):
104
+ lines = range(s.start - 1, s.end)
105
+ in_span.update(lines)
106
+ if s.key in dropped:
107
+ removed.update(lines)
108
+ removed.update(_doc_lines_before(text, s.start))
109
+ continue
110
+ chunk = "\n".join(keep[s.start - 1:s.end])
111
+ if s.kind == "import":
112
+ chunk = _IMPORT_AT.sub(lambda m: m.group(1) + rewrite_import(m.group(2)), chunk)
113
+ elif s.kind not in lean_scan._HEADER_WORDS:
114
+ chunk = lean_scan.apply_map(chunk, ns, rn, src_scope=s.scope, declared=declared)
115
+ new = chunk.split("\n")
116
+ if len(new) != len(lines): # apply_map rewrites identifiers only
117
+ raise lean_scan.ScanError(f"line {s.start}: the mapped command changed its line count")
118
+ out[s.start - 1:s.end] = new
119
+ lines_out: list[str] = []
120
+ for i, line in enumerate(out):
121
+ if i in removed:
122
+ continue
123
+ if keep[i] != orig[i]: # a comment was blanked on this line
124
+ line = line.rstrip()
125
+ if not line.strip() and orig[i].strip():
126
+ continue # a comment-only line
127
+ if not line.strip() and i not in in_span and (not lines_out or not lines_out[-1].strip()):
128
+ continue # a second blank line between commands
129
+ lines_out.append(line)
130
+ while lines_out and not lines_out[-1].strip():
131
+ lines_out.pop()
132
+ return "\n".join(lines_out) + "\n"
133
+
134
+
135
+ # ----------------------------------------------------------------------------------------------------
136
+ # the target tree
137
+
138
+ def _source_modules(src: el.Tree, spec: dict, refusals: list[str]):
139
+ """[(path, source module, target module, text, root)] of the mapped modules readable at the commit, and
140
+ the pins' Lake root."""
141
+ warnings: list[str] = []
142
+ paths = [p for p, _ in sorted(spec["modules"]) if not ex.xp.bad_rel_path(p)]
143
+ tree, texts, _recs, _pins = el._side(src, paths, "source", refusals, warnings)
144
+ roots = sorted({el._lake_root(p, tree) for p in texts})
145
+ out = []
146
+ for path, tmod in sorted(spec["modules"]):
147
+ if path in texts:
148
+ root = el._lake_root(path, tree)
149
+ out.append((path, el._module_name(path, root), tmod, texts[path], root))
150
+ return out, (roots[0] if roots else "")
151
+
152
+
153
+ def generate(src: el.Tree, spec: dict, refusals: list[str]) -> dict[str, bytes]:
154
+ """{target path: bytes} of the target modules (refusals for what cannot be written)."""
155
+ mods, _root = _source_modules(src, spec, refusals)
156
+ split = {}
157
+ for path, smod, _tmod, text, _r in mods:
158
+ try:
159
+ split[path] = lean_scan.decl_spans(text, smod)
160
+ except lean_scan.ScanError as e:
161
+ refusals.append(f"source {path}: cannot be split into declarations ({e}); text/1 refuses the file whole")
162
+ if refusals:
163
+ return {}
164
+ units = [(path, s) for path, (decls, _c) in split.items() for s in decls]
165
+ declared = sorted({n for _p, s in units for n in s.names})
166
+ dropped: dict[str, set[str]] = {}
167
+ for decl, _reason in spec["drops"]:
168
+ for path, s in units:
169
+ if decl == s.key or decl in s.names:
170
+ dropped.setdefault(path, set()).add(s.key)
171
+ break
172
+ mod_map = {lean_scan._canon(lean_scan.split_name(smod)): tmod for _p, smod, tmod, _t, _r in mods}
173
+ files: dict[str, bytes] = {}
174
+ for path, _smod, tmod, text, root in mods:
175
+ def rewrite(name: str, path=path, root=root) -> str:
176
+ parts = lean_scan.split_name(name)
177
+ if parts is None:
178
+ return name
179
+ new = mod_map.get(lean_scan._canon(parts))
180
+ if new is not None:
181
+ return new
182
+ rel = lean_scan.module_file(name)
183
+ if rel is not None and ((f"{root}/" if root else "") + rel) in src.tree:
184
+ refusals.append(f"source {path} imports {name}, a module of the source at {src.label} that is not "
185
+ f"extracted: map it with --from-module, or remove the import from the source")
186
+ return name
187
+ decls, context = split[path]
188
+ try:
189
+ body = render_module(text, decls, context, ns=spec["namespaces"], rn=spec["renames"],
190
+ declared=declared, dropped=dropped.get(path, set()), rewrite_import=rewrite)
191
+ except (lean_scan.MapError, lean_scan.ScanError) as e:
192
+ refusals.append(f"source {path}: cannot be written as {tmod} ({e})")
193
+ continue
194
+ files[lean_scan.module_file(tmod)] = body.encode("utf-8")
195
+ return files
196
+
197
+
198
+ def _toml(s: str) -> str:
199
+ return json.dumps(s, ensure_ascii=False) # a JSON string is a TOML basic string
200
+
201
+
202
+ def lakefile(name: str, target_modules: list[str], manifest: bytes | None, warnings: list[str]) -> str:
203
+ """lakefile.toml: one library per target root (globbing the root module and everything under it), and
204
+ a require for each direct dependency of the source's lake-manifest.json at its pinned input revision."""
205
+ roots: dict[str, list[str]] = {}
206
+ for m in sorted(target_modules):
207
+ r = lean_scan.split_name(m)[0]
208
+ globs = roots.setdefault(r, [])
209
+ g = r if m == r else f"{r}.+"
210
+ if g not in globs:
211
+ globs.append(g)
212
+ lines = [f"name = {_toml(name)}", "defaultTargets = [" + ", ".join(_toml(r) for r in roots) + "]"]
213
+ doc = None
214
+ if manifest is not None:
215
+ doc, _err = ex.load_json_strict(manifest, "lake-manifest.json")
216
+ for p in (doc.get("packages") if isinstance(doc, dict) else None) or []:
217
+ if not isinstance(p, dict) or p.get("inherited") is not False or not isinstance(p.get("name"), str):
218
+ continue
219
+ rev = p.get("inputRev") or p.get("rev")
220
+ if p.get("type") != "git" or not isinstance(rev, str):
221
+ warnings.append(f"lake-manifest.json: dependency {p['name']} is not a git dependency with a revision "
222
+ f"(type {p.get('type')!r}); lakefile.toml does not require it: add it by hand")
223
+ continue
224
+ lines += ["", "[[require]]", f"name = {_toml(p['name'])}"]
225
+ if isinstance(p.get("scope"), str) and p["scope"]:
226
+ lines.append(f"scope = {_toml(p['scope'])}")
227
+ else:
228
+ lines.append(f"git = {_toml(str(p.get('url')))}")
229
+ lines.append(f"rev = {_toml(rev)}")
230
+ for r, globs in roots.items():
231
+ lines += ["", "[[lean_lib]]", f"name = {_toml(r)}", "globs = [" + ", ".join(_toml(g) for g in globs) + "]"]
232
+ return "\n".join(lines) + "\n"
233
+
234
+
235
+ def _renamed_manifest(data: bytes, name: str, warnings: list[str]) -> bytes:
236
+ """The source's lake-manifest.json with its root package `name` set to the new package's: the
237
+ dependency pins are kept as they are, and the source package's own name (which may be private) is not
238
+ carried into the public tree. A manifest that is not strict JSON is copied unchanged, with a warning."""
239
+ doc, err = ex.load_json_strict(data, "lake-manifest.json")
240
+ if err or not isinstance(doc, dict):
241
+ warnings.append("--scaffold: the source lake-manifest.json is not a JSON object; copied unchanged (its "
242
+ "root package name is the source's)")
243
+ return data
244
+ if doc.get("name") == name or "name" not in doc:
245
+ return data
246
+ doc["name"] = name
247
+ return (json.dumps(doc, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
248
+
249
+
250
+ def scaffold_files(src: el.Tree, root: str, name: str, author: str, license_spdx: str, target_modules: list[str],
251
+ refusals: list[str], warnings: list[str]) -> dict[str, bytes]:
252
+ """The package around the modules: the pins copied from the source commit, lakefile.toml, README.md and
253
+ `scaffold.package_files` (the files of `lean-pkg new` without its example theorem)."""
254
+ where = f"{root}/" if root else ""
255
+ ents = {f: src.tree.get(where + f) for f in ("lean-toolchain", "lake-manifest.json")}
256
+ blobs = src.read([e["oid"] for e in ents.values() if e])
257
+ pins = {f: blobs.get(e["oid"]) if e else None for f, e in ents.items()}
258
+ if pins["lean-toolchain"] is None:
259
+ refusals.append(f"--scaffold: no {where}lean-toolchain at {src.label} beside the modules; the pins are "
260
+ f"copied from the source commit, so it needs one")
261
+ if pins["lake-manifest.json"] is None:
262
+ warnings.append(f"--scaffold: no {where}lake-manifest.json at {src.label}; none is written and "
263
+ f"lakefile.toml requires nothing (run `lake update` in the new package)")
264
+ out: dict[str, bytes] = {f: b for f, b in pins.items() if b is not None}
265
+ if pins["lake-manifest.json"] is not None:
266
+ out["lake-manifest.json"] = _renamed_manifest(pins["lake-manifest.json"], name, warnings)
267
+ out["lakefile.toml"] = lakefile(name, target_modules, pins["lake-manifest.json"], warnings).encode("utf-8")
268
+ from . import page as page_mod
269
+ out["README.md"] = README.format(name=name, modules="\n".join(f"- `{m}`" for m in sorted(target_modules)),
270
+ credit=page_mod.CREDIT).encode("utf-8")
271
+ for rel, text in scaffold.package_files(name, author, license_spdx, dt.date.today().year, tool=TOOL).items():
272
+ out[rel] = text.encode("utf-8")
273
+ return out
274
+
275
+
276
+ def _inside_package(out: pathlib.Path) -> pathlib.Path | None:
277
+ """The nearest ancestor of DIR (resolved) holding a Lake configuration file, or None."""
278
+ for d in xw._resolved(out).parents:
279
+ if any((d / f).is_file() for f in LAKEFILES):
280
+ return d
281
+ return None
282
+
283
+
284
+ def _object_format(path: pathlib.Path | None) -> str:
285
+ """The object format of the repository at path, or (path None) of a repository `git init` would make."""
286
+ args = ["git", "-C", str(path), "rev-parse", "--show-object-format"] if path is not None else \
287
+ ["git", "config", "--get", "init.defaultObjectFormat"]
288
+ p = subprocess.run(args, capture_output=True, text=True, env=core.scrubbed_env(), stdin=subprocess.DEVNULL,
289
+ check=False)
290
+ fmt = p.stdout.strip()
291
+ return fmt if p.returncode == 0 and fmt in ("sha1", "sha256") else "sha1"
292
+
293
+
294
+ # ----------------------------------------------------------------------------------------------------
295
+ # the verb
296
+
297
+ def run_decls(args) -> tuple[dict, int]:
298
+ repo = pathlib.Path(args.repo).expanduser()
299
+ top, gitdir = ex._src_top(repo)
300
+ if args.scaffold is None and (args.author is not None or args.license is not None):
301
+ raise ex.Usage("--author and --license describe the package of --scaffold NAME; pass --scaffold")
302
+ refusals: list[str] = []
303
+ warnings: list[str] = []
304
+ spec = el.parse_spec(args, refusals)
305
+ out_dir = pathlib.Path(args.output).expanduser()
306
+ refusals += xw.output_refusals(out_dir, "--output", [("the source repository", top),
307
+ ("the source repository's git directory", gitdir)])
308
+ name = author = None
309
+ lic = args.license or "Apache-2.0"
310
+ if args.scaffold is not None:
311
+ name = args.scaffold
312
+ if not scaffold.NAME_RE.match(name) or len(name) > scaffold.NAME_MAX:
313
+ refusals.append(f"--scaffold {name!r}: lower-case letters, digits and single hyphens, starting with a "
314
+ f"letter, at most {scaffold.NAME_MAX} characters (e.g. my-lib), as `lean-pkg new`")
315
+ author = (args.author if args.author is not None else scaffold._git_author() or "").strip()
316
+ if not author or "\n" in author:
317
+ refusals.append("--scaffold: CITATION.cff needs an author: pass --author 'Given Family' (or set git "
318
+ "config user.name)")
319
+ else:
320
+ warnings += scaffold.author_warnings(author)
321
+ pkg_dir = _inside_package(out_dir)
322
+ if pkg_dir is not None:
323
+ refusals.append(f"--scaffold: --output {args.output} lies inside an existing Lake package ({pkg_dir.name}/ "
324
+ f"holds a lakefile); --scaffold writes a new package, so name a directory outside it")
325
+ target_root = xw._resolved(out_dir)
326
+ refusals += el.ledger_path_refusals(args.ledger, (top, gitdir), (target_root,), "inside --output DIR")
327
+ c = ex.resolve_commit(repo, args.commit)
328
+ if not c:
329
+ refusals.append(f"--commit {args.commit!r} is not a commit of the source repository")
330
+ files: dict[str, bytes] = {}
331
+ fmt = "sha1"
332
+ led, failures = el.skeleton(spec), []
333
+ led["source"]["commit"] = c
334
+ if c:
335
+ src = el.git_tree(repo, c)
336
+ el.check_spec(spec, refusals)
337
+ if not refusals:
338
+ files = generate(src, spec, refusals)
339
+ if not refusals and args.scaffold is not None:
340
+ _mods, root = _source_modules(src, spec, [])
341
+ files.update(scaffold_files(src, root, name, author, lic, [m for _p, m in spec["modules"]],
342
+ refusals, warnings))
343
+ if not refusals:
344
+ fmt = _object_format(None) if args.scaffold is not None else "sha1"
345
+ led, failures = el.compute(repo, c, None, None, spec, refusals,
346
+ target=el.files_tree(files, WRITTEN, fmt))
347
+ else:
348
+ el.check_spec(spec, refusals)
349
+ out = el._output(led, refusals, failures)
350
+ out["warnings"] = sorted(set(out["warnings"]) | set(warnings))
351
+ out["ledger_path"] = args.ledger
352
+ out["output"] = {"dir": args.output, "files": sorted(files), "scaffold": name, "dry_run": bool(args.dry_run),
353
+ "written": False, "git_init": False, "committed": False, "object_format": fmt}
354
+ out["public_safety"] = None
355
+ if not out["ok"]:
356
+ return out, 1
357
+ if args.dry_run:
358
+ return out, 0
359
+
360
+ state = {"led": led}
361
+
362
+ def prepare(stage: pathlib.Path) -> None:
363
+ if args.scaffold is None:
364
+ return
365
+ p = subprocess.run(["git", "-c", "init.defaultBranch=main", "init", "-q", str(stage)], capture_output=True,
366
+ text=True, env=core.scrubbed_env(), stdin=subprocess.DEVNULL, check=False)
367
+ if p.returncode != 0:
368
+ raise xw.WriteRefused([f"git init failed: {(p.stderr or p.stdout).strip()}; nothing written"])
369
+ actual = _object_format(stage)
370
+ if actual != fmt: # the blob ids follow the new repository's format
371
+ again: list[str] = []
372
+ led2, fail2 = el.compute(repo, c, None, None, spec, again, target=el.files_tree(files, WRITTEN, actual))
373
+ if again or fail2:
374
+ raise xw.WriteRefused(again + fail2)
375
+ state["led"] = led2
376
+ out["output"]["object_format"] = actual
377
+
378
+ def before_move(_stage: pathlib.Path):
379
+ ledger = pathlib.Path(args.ledger).expanduser()
380
+ with open(ledger, "x", encoding="utf-8") as f:
381
+ f.write(el.ledger_json(state["led"]))
382
+ return lambda: ledger.unlink(missing_ok=True)
383
+
384
+ try:
385
+ scan = xw.write_tree(out_dir, files, scan_pkg={"name": name or "lean-pkg-extract-decls"}, patterns_root=top,
386
+ source_repo=top or gitdir, prepare=prepare, before_move=before_move)
387
+ except xw.WriteRefused as e:
388
+ out["refusals"] = sorted(set(out["refusals"]) | set(e.reasons))
389
+ if e.scan is not None:
390
+ out["public_safety"] = _scan_summary(e.scan)
391
+ out["ok"] = False
392
+ return out, 1
393
+ except OSError as e:
394
+ out["refusals"].append(f"--output {args.output}: writing failed ({e.strerror or e}); nothing written, "
395
+ f"the staging directory removed")
396
+ out["ok"] = False
397
+ return out, 1
398
+ out.update({k: state["led"][k] for k in el.LEDGER_KEYS if k not in ("ok",)})
399
+ out["warnings"] = sorted(set(state["led"]["warnings"]) | set(warnings))
400
+ out["public_safety"] = _scan_summary(scan)
401
+ out["written"] = True
402
+ out["output"].update(written=True, git_init=args.scaffold is not None)
403
+ return out, 0
404
+
405
+
406
+ def _scan_summary(scan: dict) -> dict:
407
+ return {"ok": scan["ok"], "block_hits": scan["block_hits"], "warn_hits": scan["warn_hits"]}
408
+
409
+
410
+ def render(out: dict) -> str:
411
+ """The text report: the ledger's (verdict first and last), then what was or would be written."""
412
+ lines = el.render("decls", out).split("\n")
413
+ o = out["output"]
414
+ extra = []
415
+ if o["files"]:
416
+ verb = "written" if o["written"] else "to write"
417
+ extra.append(f"files {verb} under {o['dir']} ({len(o['files'])}):")
418
+ extra += [f" {f}" for f in o["files"]]
419
+ ps_ = out.get("public_safety")
420
+ if ps_ is not None:
421
+ extra.append(f"public-safety of the staged tree: {ps_['block_hits']} blocking, {ps_['warn_hits']} warn-only")
422
+ if o["written"]:
423
+ nxt = [f"cd {o['dir']}"]
424
+ if o["git_init"]:
425
+ nxt += ["git add -A && git commit -m 'extracted library'"]
426
+ else:
427
+ nxt += ["git init && git add -A && git commit -m 'extracted library' # or place the modules in your "
428
+ "package and record a new ledger there with `lean-pkg-extract ledger`"]
429
+ nxt.append(f"lean-pkg-extract recheck --ledger {out['ledger_path']} --repo SRC --target {o['dir']} "
430
+ f"--target-commit HEAD")
431
+ extra.append("next (nothing is committed):")
432
+ extra += [f" {n}" for n in nxt]
433
+ return "\n".join(lines[:-1] + extra + lines[-1:])
434
+
435
+
436
+ def json_text(out: dict) -> str:
437
+ o = dict(out)
438
+ o["output"] = {k: v for k, v in out["output"].items() if k != "dir"}
439
+ return el.public_json(o)
440
+
441
+
442
+ def run(args) -> tuple[str, int]:
443
+ out, rc = run_decls(args)
444
+ return (json_text(out) if args.json_out else render(out) + "\n"), rc
445
+
446
+
447
+ def add_parser(sub, parser_cls, fmt) -> None:
448
+ epilog = """\
449
+ examples:
450
+ lean-pkg-extract decls --repo ~/paper --commit HEAD --output ~/newlib \\
451
+ --from-module Paper/Bounds.lean:NewLib.Bounds --namespace Paper.Bounds=NewLib.Bounds \\
452
+ --rename Paper.Bounds.main=NewLib.Bounds.main_bound --drop 'Paper.Bounds.scratch:exploration only' \\
453
+ --scaffold newlib --author 'Ada Lovelace' --ledger ~/ledgers/newlib-1.json
454
+ lean-pkg-extract decls @decls-args.txt --dry-run
455
+
456
+ @ARGSFILE: as for `ledger` (one argument per line; `--flag value` lines keep the rest of the line).
457
+ exit codes: 0 written (or, with --dry-run, writable) and every declaration IDENTICAL or dropped, 1 refused
458
+ (nothing written), 2 usage.
459
+ docs: https://lean-pkg.github.io/lean-pkg/extract.html#writing-the-target-modules-decls"""
460
+ p = sub.add_parser("decls", formatter_class=fmt, epilog=epilog, fromfile_prefix_chars="@",
461
+ help="write the target modules of a declaration-level extraction (optionally a whole "
462
+ "package) and record its extraction ledger",
463
+ description="Read the mapped source modules at COMMIT, write each as its target module "
464
+ "(the namespace and rename maps applied, --drop declarations left out, imports "
465
+ "of mapped modules rewritten, comments other than docstrings removed) into "
466
+ "--output DIR, which must be absent or empty and outside SRC, and record the "
467
+ f"ledger ({el.EXTRACT_LEDGER_SCHEMA}, target.commit null) to --ledger PATH. "
468
+ "The tree is compared with the source (text/1) before anything is written, "
469
+ "staged beside DIR, scanned with public-safety and moved into place in one "
470
+ "step. --scaffold NAME adds the package files and runs git init; nothing is "
471
+ "committed.")
472
+ p.add_argument("--repo", required=True, metavar="SRC", help="the source git repository (its top directory)")
473
+ p.add_argument("--commit", required=True, metavar="COMMIT", help="the source commit; recorded as a full SHA")
474
+ p.add_argument("--output", required=True, metavar="DIR",
475
+ help="where to write: a new or empty directory, outside SRC, not a symbolic link")
476
+ p.add_argument("--from-module", action="append", required=True, metavar="SRC/Path.lean:New.Module",
477
+ help="a source module and the target module to write it as (repeatable, at least one)")
478
+ p.add_argument("--namespace", action="append", metavar="OLD.Ns=NEW.Ns",
479
+ help="a namespace prefix map (repeatable; the longest prefix wins)")
480
+ p.add_argument("--rename", action="append", metavar="OLD.qual=NEW.qual",
481
+ help="a declaration renamed, fully qualified (repeatable; takes precedence over --namespace)")
482
+ p.add_argument("--drop", action="append", metavar="OLD.qual:REASON",
483
+ help="a source declaration left out of the target, with a one-line reason")
484
+ p.add_argument("--scaffold", metavar="NAME",
485
+ help="also write the package: lean-toolchain and lake-manifest.json copied from the source "
486
+ "commit, lakefile.toml, README.md, CITATION.cff, LICENSE, REUSE.toml; then git init "
487
+ "(nothing committed)")
488
+ p.add_argument("--author", metavar="TEXT", help="with --scaffold: the CITATION.cff author (default: git config "
489
+ "user.name)")
490
+ p.add_argument("--license", choices=scaffold.LICENSES, help="with --scaffold: the LICENSE written (default "
491
+ "Apache-2.0)")
492
+ p.add_argument("--ledger", required=True, metavar="PATH",
493
+ help="where to write the ledger: a new file outside SRC and outside DIR")
494
+ p.add_argument("--dry-run", action="store_true",
495
+ help="read and compare, report what would be written, and write nothing (the public-safety scan "
496
+ "of the staged tree runs only when writing)")
497
+ p.add_argument("--json", dest="json_out", action="store_true",
498
+ help="JSON on stdout: the ledger plus refusals, failures, written, output and public_safety")
499
+ # a written target holds every source declaration as written or dropped: nothing is NEW and nothing
500
+ # DIFFERS, so `decls` takes no --new or --allow-differs (the ledger's map records them empty)
501
+ p.set_defaults(new=None, allow_differs=None)