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/extract.py
ADDED
|
@@ -0,0 +1,1172 @@
|
|
|
1
|
+
# lean-pkg-extract -- plan a standalone public Lean-verification repository from a mixed working repository
|
|
2
|
+
"""lean-pkg-extract: materialize a public Lean-verification repository from a mixed TeX+Lean working
|
|
3
|
+
repository, with exact provenance. This release has the dry run only: `plan` writes nothing.
|
|
4
|
+
|
|
5
|
+
`lean-pkg-extract plan --repo SRC --commit COMMIT --manifest PATH [--json] [--report PATH]`
|
|
6
|
+
|
|
7
|
+
The declaration-level extraction ledger, `ledger` and `recheck` (proposal 0009), lives in
|
|
8
|
+
extract_ledger.py (its elaborated-type method `types/1` in extract_types.py), and `decls`, which writes the target modules and records their ledger, in
|
|
9
|
+
extract_decls.py (its write step, shared with the file-level write mode to come, in extract_write.py);
|
|
10
|
+
the public summary of a recheck (`--public-summary`) in extract_summary.py; this module parses and
|
|
11
|
+
dispatches them.
|
|
12
|
+
|
|
13
|
+
Read-only by construction: it reads git objects at COMMIT (`git ls-tree -r -z --full-tree`,
|
|
14
|
+
`git cat-file --batch`), never the working tree, the index or a registry; no network (lazy fetches of
|
|
15
|
+
a partial clone are disabled, so a missing object is a refusal). The only write is `--report PATH`,
|
|
16
|
+
which must lie outside SRC. Every file under a declared root is classified, default deny; anything
|
|
17
|
+
that cannot be classified, any unsafe path or link, a missing or floating pin, an unpinned
|
|
18
|
+
dependency, an invalid claims file and an unresolved import is a refusal, all listed together.
|
|
19
|
+
Files adopted from another project whose license is not carried into the target are a warning
|
|
20
|
+
(manifest `adopted`, and a heuristic for a LICENSE left behind), and so is a disabled Lean source
|
|
21
|
+
(`*.lean.<suffix>`) the plan excludes or refuses, which no import check reads; warnings never change
|
|
22
|
+
the verdict.
|
|
23
|
+
|
|
24
|
+
Exit codes: 0 the plan is clean, 1 refused (every reason listed), 2 usage (argparse, SRC is not a
|
|
25
|
+
git repository). Output is deterministic: sorted, no timestamps, no host paths.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import argparse
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import pathlib
|
|
34
|
+
import posixpath
|
|
35
|
+
import re
|
|
36
|
+
import subprocess
|
|
37
|
+
import sys
|
|
38
|
+
import tomllib
|
|
39
|
+
|
|
40
|
+
from . import claims as cl
|
|
41
|
+
from . import export_paths as xp
|
|
42
|
+
from . import lean_scan
|
|
43
|
+
from . import public_safety as ps
|
|
44
|
+
from .core import scrubbed_env
|
|
45
|
+
|
|
46
|
+
MANIFEST_SCHEMA = "lean-pkg-extract/1"
|
|
47
|
+
PLAN_SCHEMA = "lean-pkg-extract-plan/1"
|
|
48
|
+
ROOT_KINDS = ("lean-package", "verification", "docs", "data")
|
|
49
|
+
MANIFEST_KEYS = ("schema", "source_commit", "roots", "pins", "exclude", "allow_private", "lean_libs",
|
|
50
|
+
"dependency_namespaces", "allow_unresolved_imports", "adopted")
|
|
51
|
+
REQUIRED_KEYS = ("schema", "roots", "pins")
|
|
52
|
+
ROOT_KEYS = ("from", "to", "kind")
|
|
53
|
+
PIN_KEYS = ("lean_toolchain", "lake_manifest", "claims", "verification")
|
|
54
|
+
REQUIRED_PINS = ("lean_toolchain", "lake_manifest")
|
|
55
|
+
RULE_KEYS = ("path", "reason")
|
|
56
|
+
LIB_KEYS = ("name", "src_dir", "roots")
|
|
57
|
+
UNRESOLVED_KEYS = ("import", "reason")
|
|
58
|
+
ADOPTED_KEYS = ("paths", "upstream", "upstream_commit", "upstream_license_file", "license", "license_file",
|
|
59
|
+
"provenance")
|
|
60
|
+
ADOPTED_REQUIRED = ("paths", "upstream", "upstream_commit", "upstream_license_file", "license")
|
|
61
|
+
SPDX_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9.+-]*")
|
|
62
|
+
# a license file that governs the files beside and below it (the heuristic for undeclared adoption)
|
|
63
|
+
DIR_LICENSE = re.compile(r"^(LICEN[SC]E|COPYING)([.-][A-Za-z0-9.-]+)?$", re.I)
|
|
64
|
+
HEX40 = re.compile(r"[0-9a-f]{40}")
|
|
65
|
+
# a Lean source kept out of the build by an extra suffix (Foo.lean.disabled, .lean.off, .lean.skip):
|
|
66
|
+
# `*.lean.<suffix>` only, never `*.lean`, `*.olean` or `*.ilean`
|
|
67
|
+
DISABLED_LEAN = re.compile(r"^[^/]+\.lean\.[^/]+$")
|
|
68
|
+
DISABLED_LEAN_DOC = 'docs/extract.md, "Disabled negative fixtures after a namespace or import transport"'
|
|
69
|
+
|
|
70
|
+
CORE_NAMESPACES = ("Init", "Std", "Lean", "Lake")
|
|
71
|
+
# lake-manifest package name -> the root namespaces it provides, where capitalizing the name is wrong.
|
|
72
|
+
KNOWN_NAMESPACES = {"proofwidgets": ("ProofWidgets",), "importGraph": ("ImportGraph",)}
|
|
73
|
+
FLOATING_TOOLCHAIN = re.compile(r"(^|:)(stable|beta|nightly|latest)$")
|
|
74
|
+
|
|
75
|
+
GIT_LINK, SYMLINK = "160000", "120000"
|
|
76
|
+
|
|
77
|
+
# ----------------------------------------------------------------------------------------------------
|
|
78
|
+
# classification: default-denied classes first, then what each root kind may carry
|
|
79
|
+
|
|
80
|
+
LEGAL = re.compile(r"^(LICEN[SC]E|COPYING|NOTICE|README|AUTHORS|CHANGELOG|CONTRIBUTING|CITATION)"
|
|
81
|
+
r"([.-][A-Za-z0-9.-]+)?$", re.I)
|
|
82
|
+
GIT_META = {".gitignore", ".gitattributes"}
|
|
83
|
+
LAKE_FILES = {"lakefile.toml", "lakefile.lean", "lake-manifest.json", "lean-toolchain"}
|
|
84
|
+
EXT_CLASS = {".lean": "lean-source", ".md": "doc", ".txt": "doc", ".rst": "doc", ".html": "doc",
|
|
85
|
+
".css": "doc", ".toml": "config", ".json": "config", ".yaml": "config", ".yml": "config",
|
|
86
|
+
".sh": "script", ".py": "script", ".svg": "image", ".png": "image", ".jpg": "image",
|
|
87
|
+
".jpeg": "image", ".gif": "image", ".csv": "data", ".tsv": "data", ".expected": "expected-output"}
|
|
88
|
+
KIND_EXTS = {
|
|
89
|
+
"lean-package": {".lean", ".md", ".txt", ".toml", ".json", ".yaml", ".yml"},
|
|
90
|
+
"verification": {".lean", ".sh", ".py", ".md", ".txt", ".toml", ".json", ".yaml", ".yml", ".expected"},
|
|
91
|
+
"docs": {".md", ".txt", ".rst", ".html", ".css", ".svg", ".png", ".jpg", ".jpeg", ".gif"},
|
|
92
|
+
"data": {".json", ".csv", ".tsv", ".txt", ".yaml", ".yml", ".toml", ".md"},
|
|
93
|
+
}
|
|
94
|
+
REVIEW_DIRS = {"reviews", "prompts", "transcripts"}
|
|
95
|
+
MAIL_DIRS = {"mail", "correspondence"}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def deny_class(rel: str) -> tuple[str, str] | None:
|
|
99
|
+
"""(class, reason) for a default-denied path, else None. Overridable only by allow_private."""
|
|
100
|
+
parts = pathlib.PurePosixPath(rel).parts
|
|
101
|
+
name, dirs = parts[-1], {d.lower() for d in parts[:-1]}
|
|
102
|
+
low = name.lower()
|
|
103
|
+
if name == ps.PATTERNS_FILE:
|
|
104
|
+
return "private-patterns", f"{ps.PATTERNS_FILE}: the private patterns file is never published"
|
|
105
|
+
if xp.is_receipts_path(rel):
|
|
106
|
+
return "receipts", f"{xp.RECEIPTS_DIR}/: receipts bind the source repository's commits, not the extract"
|
|
107
|
+
if {".lake", ".git"} & set(parts[:-1]):
|
|
108
|
+
return "build-output", ".lake/ or .git/ content"
|
|
109
|
+
if dirs & REVIEW_DIRS or ".transcript" in low or low.endswith(".jsonl"):
|
|
110
|
+
return "review-material", "review packets, prompts, model transcripts, *.jsonl event streams"
|
|
111
|
+
if low.endswith((".eml", ".mbox")) or dirs & MAIL_DIRS:
|
|
112
|
+
return "correspondence", "email and correspondence"
|
|
113
|
+
rule = ps.internal_path(rel)
|
|
114
|
+
if rule:
|
|
115
|
+
return "private-marker", rule
|
|
116
|
+
if name.startswith("TODO-private"):
|
|
117
|
+
return "private-marker", "TODO-private*"
|
|
118
|
+
if low.endswith((".tex", ".bib", ".pdf", ".bbl")):
|
|
119
|
+
return "manuscript", ".tex/.bib/.pdf/.bbl: manuscript material, published only when allowlisted"
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def allow_class(rel: str, kind: str) -> str | None:
|
|
124
|
+
"""The class a root of `kind` may carry this file as, else None (unclassified: a refusal)."""
|
|
125
|
+
name = posixpath.basename(rel)
|
|
126
|
+
if LEGAL.match(name):
|
|
127
|
+
return "legal-readme"
|
|
128
|
+
if name in GIT_META:
|
|
129
|
+
return "git-meta"
|
|
130
|
+
if kind == "lean-package" and name in LAKE_FILES:
|
|
131
|
+
return "lake-config"
|
|
132
|
+
if kind == "verification" and name == "Makefile":
|
|
133
|
+
return "script"
|
|
134
|
+
ext = posixpath.splitext(name)[1].lower()
|
|
135
|
+
return EXT_CLASS.get(ext) if ext in KIND_EXTS[kind] else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ----------------------------------------------------------------------------------------------------
|
|
139
|
+
# git: read-only, no network
|
|
140
|
+
|
|
141
|
+
class Usage(Exception):
|
|
142
|
+
"""Exit 2: argparse-level problems, SRC is not a git repository."""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _git(repo: pathlib.Path, *args: str, data: bytes | None = None) -> subprocess.CompletedProcess:
|
|
146
|
+
env = scrubbed_env()
|
|
147
|
+
env.update(GIT_NO_LAZY_FETCH="1", GIT_TERMINAL_PROMPT="0", GIT_OPTIONAL_LOCKS="0")
|
|
148
|
+
return subprocess.run(["git", "--no-optional-locks", "-c", "protocol.allow=never", "-C", str(repo), *args],
|
|
149
|
+
input=data, capture_output=True, env=env, check=False)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def resolve_commit(repo: pathlib.Path, rev: str) -> str | None:
|
|
153
|
+
if not rev or rev.startswith("-"):
|
|
154
|
+
return None
|
|
155
|
+
p = _git(repo, "rev-parse", "--verify", "-q", "--end-of-options", rev + "^{commit}")
|
|
156
|
+
out = p.stdout.decode().strip()
|
|
157
|
+
return out if p.returncode == 0 and HEX40.fullmatch(out) else None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def ls_tree(repo: pathlib.Path, sha: str) -> dict[str, dict]:
|
|
161
|
+
p = _git(repo, "ls-tree", "-r", "-l", "-z", "--full-tree", sha)
|
|
162
|
+
if p.returncode != 0:
|
|
163
|
+
raise Usage(f"git ls-tree {sha[:12]} failed: {p.stderr.decode('utf-8', 'replace').strip()[:200]}")
|
|
164
|
+
out = {}
|
|
165
|
+
for item in p.stdout.split(b"\0"):
|
|
166
|
+
if not item:
|
|
167
|
+
continue
|
|
168
|
+
meta, path = item.split(b"\t", 1)
|
|
169
|
+
mode, typ, oid, size = meta.decode().split()
|
|
170
|
+
# size is `-` for a tree or gitlink and `BAD` for a blob missing from the object store (a partial
|
|
171
|
+
# clone): None, and the blob read refuses it
|
|
172
|
+
out[path.decode("utf-8", "surrogateescape")] = {"mode": mode, "type": typ, "oid": oid,
|
|
173
|
+
"size": int(size) if size.isdigit() else None}
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def read_blobs(repo: pathlib.Path, oids: list[str]) -> dict[str, bytes]:
|
|
178
|
+
"""Raw blob contents via `git cat-file --batch` (no filters, no textconv); a missing object is
|
|
179
|
+
left out (the caller refuses it)."""
|
|
180
|
+
uniq = sorted(set(oids))
|
|
181
|
+
if not uniq:
|
|
182
|
+
return {}
|
|
183
|
+
p = _git(repo, "cat-file", "--batch", data=("\n".join(uniq) + "\n").encode())
|
|
184
|
+
out, buf, i = {}, p.stdout, 0
|
|
185
|
+
for oid in uniq:
|
|
186
|
+
nl = buf.find(b"\n", i)
|
|
187
|
+
if p.returncode != 0 or nl < 0:
|
|
188
|
+
break
|
|
189
|
+
head = buf[i:nl].decode().split()
|
|
190
|
+
i = nl + 1
|
|
191
|
+
if len(head) < 3 or head[1] == "missing":
|
|
192
|
+
continue
|
|
193
|
+
size = int(head[2])
|
|
194
|
+
out[oid] = buf[i:i + size]
|
|
195
|
+
i += size + 1
|
|
196
|
+
return out
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ----------------------------------------------------------------------------------------------------
|
|
200
|
+
# the manifest: strict JSON
|
|
201
|
+
|
|
202
|
+
def _no_dups(pairs):
|
|
203
|
+
seen = {}
|
|
204
|
+
for k, v in pairs:
|
|
205
|
+
if k in seen:
|
|
206
|
+
raise ValueError(f"duplicate key {k!r}")
|
|
207
|
+
seen[k] = v
|
|
208
|
+
return seen
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _bad_constant(name):
|
|
212
|
+
raise ValueError(f"non-standard JSON constant {name}")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def load_json_strict(data: bytes, where: str) -> tuple[object, str | None]:
|
|
216
|
+
try:
|
|
217
|
+
return json.loads(data.decode("utf-8"), object_pairs_hook=_no_dups, parse_constant=_bad_constant), None
|
|
218
|
+
except UnicodeDecodeError:
|
|
219
|
+
return None, f"{where}: not UTF-8"
|
|
220
|
+
except ValueError as e:
|
|
221
|
+
return None, f"{where}: not strict JSON ({e})"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _keys(obj, allowed, required, where, refusals) -> bool:
|
|
225
|
+
if not isinstance(obj, dict):
|
|
226
|
+
refusals.append(f"{where} must be an object")
|
|
227
|
+
return False
|
|
228
|
+
extra = sorted(set(obj) - set(allowed))
|
|
229
|
+
missing = [k for k in required if k not in obj]
|
|
230
|
+
if extra:
|
|
231
|
+
refusals.append(f"{where}: unknown key(s) {extra} (allowed: {list(allowed)})")
|
|
232
|
+
if missing:
|
|
233
|
+
refusals.append(f"{where}: missing key(s) {missing}")
|
|
234
|
+
return not extra and not missing
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _reason(v) -> bool:
|
|
238
|
+
return isinstance(v, str) and bool(v.strip()) and "\n" not in v
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def validate_manifest(m, commit: str, refusals: list[str]) -> dict | None:
|
|
242
|
+
"""The manifest normalized, or None when it is too broken to plan with (refusals say why)."""
|
|
243
|
+
if not _keys(m, MANIFEST_KEYS, REQUIRED_KEYS, "manifest", refusals):
|
|
244
|
+
return None
|
|
245
|
+
ok = True
|
|
246
|
+
if m["schema"] != MANIFEST_SCHEMA:
|
|
247
|
+
refusals.append(f"manifest.schema must be {MANIFEST_SCHEMA!r}, got {m['schema']!r}")
|
|
248
|
+
ok = False
|
|
249
|
+
sc = m.get("source_commit")
|
|
250
|
+
if sc is not None and not (isinstance(sc, str) and HEX40.fullmatch(sc)):
|
|
251
|
+
refusals.append(f"manifest.source_commit must be a full 40-hex commit, got {sc!r}")
|
|
252
|
+
elif sc is not None and sc != commit:
|
|
253
|
+
refusals.append(f"manifest.source_commit {sc} differs from --commit {commit}")
|
|
254
|
+
roots = []
|
|
255
|
+
if not isinstance(m["roots"], list) or not m["roots"]:
|
|
256
|
+
refusals.append("manifest.roots must be a non-empty list")
|
|
257
|
+
ok = False
|
|
258
|
+
else:
|
|
259
|
+
for i, r in enumerate(m["roots"]):
|
|
260
|
+
w = f"roots[{i}]"
|
|
261
|
+
if not _keys(r, ROOT_KEYS, ROOT_KEYS, w, refusals):
|
|
262
|
+
ok = False
|
|
263
|
+
continue
|
|
264
|
+
for k in ("from", "to"):
|
|
265
|
+
why = xp.bad_rel_path(r[k], allow_dot=True)
|
|
266
|
+
if why:
|
|
267
|
+
refusals.append(f"{w}.{k} {r[k]!r} {why}")
|
|
268
|
+
ok = False
|
|
269
|
+
if r["kind"] not in ROOT_KINDS:
|
|
270
|
+
refusals.append(f"{w}.kind must be one of {list(ROOT_KINDS)}, got {r['kind']!r}")
|
|
271
|
+
ok = False
|
|
272
|
+
roots.append(dict(r, index=i))
|
|
273
|
+
pins = m["pins"]
|
|
274
|
+
if _keys(pins, PIN_KEYS, REQUIRED_PINS, "pins", refusals):
|
|
275
|
+
for k in ("lean_toolchain", "lake_manifest", "claims"):
|
|
276
|
+
if k in pins and xp.bad_rel_path(pins[k]):
|
|
277
|
+
refusals.append(f"pins.{k} {pins[k]!r} {xp.bad_rel_path(pins[k])}")
|
|
278
|
+
ok = False
|
|
279
|
+
ver = pins.get("verification", [])
|
|
280
|
+
if not isinstance(ver, list):
|
|
281
|
+
refusals.append("pins.verification must be a list of paths")
|
|
282
|
+
ok = False
|
|
283
|
+
else:
|
|
284
|
+
for j, v in enumerate(ver):
|
|
285
|
+
if xp.bad_rel_path(v):
|
|
286
|
+
refusals.append(f"pins.verification[{j}] {v!r} {xp.bad_rel_path(v)}")
|
|
287
|
+
ok = False
|
|
288
|
+
else:
|
|
289
|
+
ok = False
|
|
290
|
+
rules = {}
|
|
291
|
+
for key in ("exclude", "allow_private"):
|
|
292
|
+
lst = m.get(key, [])
|
|
293
|
+
rules[key] = []
|
|
294
|
+
if not isinstance(lst, list):
|
|
295
|
+
refusals.append(f"manifest.{key} must be a list")
|
|
296
|
+
continue
|
|
297
|
+
for i, r in enumerate(lst):
|
|
298
|
+
w = f"{key}[{i}]"
|
|
299
|
+
if not _keys(r, RULE_KEYS, RULE_KEYS, w, refusals):
|
|
300
|
+
continue
|
|
301
|
+
if not isinstance(r["path"], str) or not r["path"] or ".." in r["path"].split("/"):
|
|
302
|
+
refusals.append(f"{w}.path must be a path glob without `..`, got {r['path']!r}")
|
|
303
|
+
continue
|
|
304
|
+
if not _reason(r["reason"]):
|
|
305
|
+
refusals.append(f"{w}.reason must be a one-line, non-empty string")
|
|
306
|
+
continue
|
|
307
|
+
rules[key].append({"index": i, "path": r["path"], "reason": r["reason"].strip(),
|
|
308
|
+
"rx": ps.glob_regex(r["path"])})
|
|
309
|
+
libs = None
|
|
310
|
+
if "lean_libs" in m:
|
|
311
|
+
libs = []
|
|
312
|
+
if not isinstance(m["lean_libs"], list) or not m["lean_libs"]:
|
|
313
|
+
refusals.append("manifest.lean_libs must be a non-empty list")
|
|
314
|
+
else:
|
|
315
|
+
for i, lib in enumerate(m["lean_libs"]):
|
|
316
|
+
w = f"lean_libs[{i}]"
|
|
317
|
+
if not _keys(lib, LIB_KEYS, ("name",), w, refusals):
|
|
318
|
+
continue
|
|
319
|
+
src_dir = lib.get("src_dir", ".")
|
|
320
|
+
lib_roots = lib.get("roots", [lib["name"]])
|
|
321
|
+
if not isinstance(lib["name"], str) or not lean_scan.is_name(lib["name"]):
|
|
322
|
+
refusals.append(f"{w}.name must be a Lean name, got {lib['name']!r}")
|
|
323
|
+
elif xp.bad_rel_path(src_dir, allow_dot=True):
|
|
324
|
+
refusals.append(f"{w}.src_dir {src_dir!r} {xp.bad_rel_path(src_dir, allow_dot=True)}")
|
|
325
|
+
elif not (isinstance(lib_roots, list) and lib_roots
|
|
326
|
+
and all(isinstance(x, str) and lean_scan.is_name(x) for x in lib_roots)):
|
|
327
|
+
refusals.append(f"{w}.roots must be a non-empty list of Lean module names")
|
|
328
|
+
else:
|
|
329
|
+
libs.append({"name": lib["name"], "src_dir": src_dir, "roots": list(lib_roots), "globs": []})
|
|
330
|
+
dep_ns = m.get("dependency_namespaces", {})
|
|
331
|
+
if not (isinstance(dep_ns, dict) and all(
|
|
332
|
+
isinstance(v, list) and v and all(isinstance(x, str) and lean_scan.is_name(x) for x in v)
|
|
333
|
+
for v in dep_ns.values())):
|
|
334
|
+
refusals.append("manifest.dependency_namespaces must map a lake-manifest package name to a "
|
|
335
|
+
"non-empty list of root namespaces")
|
|
336
|
+
dep_ns = {}
|
|
337
|
+
unresolved = []
|
|
338
|
+
lst = m.get("allow_unresolved_imports", [])
|
|
339
|
+
if not isinstance(lst, list):
|
|
340
|
+
refusals.append("manifest.allow_unresolved_imports must be a list")
|
|
341
|
+
else:
|
|
342
|
+
for i, r in enumerate(lst):
|
|
343
|
+
w = f"allow_unresolved_imports[{i}]"
|
|
344
|
+
if not _keys(r, UNRESOLVED_KEYS, UNRESOLVED_KEYS, w, refusals):
|
|
345
|
+
continue
|
|
346
|
+
if not (isinstance(r["import"], str) and lean_scan.is_name(r["import"])):
|
|
347
|
+
refusals.append(f"{w}.import must be a Lean module name, got {r['import']!r}")
|
|
348
|
+
elif not _reason(r["reason"]):
|
|
349
|
+
refusals.append(f"{w}.reason must be a one-line, non-empty string")
|
|
350
|
+
else:
|
|
351
|
+
unresolved.append({"index": i, "import": r["import"], "reason": r["reason"].strip()})
|
|
352
|
+
adopted = []
|
|
353
|
+
lst = m.get("adopted", [])
|
|
354
|
+
if not isinstance(lst, list):
|
|
355
|
+
refusals.append("manifest.adopted must be a list")
|
|
356
|
+
else:
|
|
357
|
+
for i, a in enumerate(lst):
|
|
358
|
+
w = f"adopted[{i}]"
|
|
359
|
+
if not _keys(a, ADOPTED_KEYS, ADOPTED_REQUIRED, w, refusals):
|
|
360
|
+
continue
|
|
361
|
+
bad = []
|
|
362
|
+
paths = a["paths"]
|
|
363
|
+
if not (isinstance(paths, list) and paths and all(
|
|
364
|
+
isinstance(g, str) and g and ".." not in g.split("/") for g in paths)):
|
|
365
|
+
bad.append(f"{w}.paths must be a non-empty list of path globs without `..`")
|
|
366
|
+
if not _reason(a["upstream"]):
|
|
367
|
+
bad.append(f"{w}.upstream must be a one-line, non-empty string (the upstream repository URL)")
|
|
368
|
+
if not (isinstance(a["upstream_commit"], str) and HEX40.fullmatch(a["upstream_commit"])):
|
|
369
|
+
bad.append(f"{w}.upstream_commit must be the full 40-hex upstream commit, got "
|
|
370
|
+
f"{a['upstream_commit']!r}")
|
|
371
|
+
if not (isinstance(a["upstream_license_file"], str) and not xp.bad_rel_path(a["upstream_license_file"])):
|
|
372
|
+
bad.append(f"{w}.upstream_license_file must be a relative path in the upstream repository, "
|
|
373
|
+
f"got {a['upstream_license_file']!r}")
|
|
374
|
+
if not (isinstance(a["license"], str) and SPDX_ID.fullmatch(a["license"])):
|
|
375
|
+
bad.append(f"{w}.license must be an SPDX identifier (MIT, Apache-2.0, LicenseRef-...), "
|
|
376
|
+
f"got {a['license']!r}")
|
|
377
|
+
for k in ("license_file", "provenance"):
|
|
378
|
+
if k in a and not (isinstance(a[k], str) and not xp.bad_rel_path(a[k])):
|
|
379
|
+
bad.append(f"{w}.{k} must be a relative path in the source repository, got {a[k]!r}")
|
|
380
|
+
if bad:
|
|
381
|
+
refusals.extend(bad)
|
|
382
|
+
continue
|
|
383
|
+
adopted.append({"index": i, "paths": list(paths), "rxs": [ps.glob_regex(g) for g in paths],
|
|
384
|
+
"upstream": a["upstream"].strip(), "upstream_commit": a["upstream_commit"],
|
|
385
|
+
"upstream_license_file": a["upstream_license_file"], "license": a["license"],
|
|
386
|
+
"license_file": a.get("license_file"), "provenance": a.get("provenance")})
|
|
387
|
+
if not ok:
|
|
388
|
+
return None
|
|
389
|
+
return {"roots": roots, "pins": pins, "exclude": rules["exclude"], "allow_private": rules["allow_private"],
|
|
390
|
+
"lean_libs": libs, "dependency_namespaces": dep_ns, "allow_unresolved_imports": unresolved,
|
|
391
|
+
"adopted": adopted}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# ----------------------------------------------------------------------------------------------------
|
|
395
|
+
# Lake: libraries, dependencies, imports
|
|
396
|
+
|
|
397
|
+
def toml_libs(text: str, where: str, refusals: list[str]) -> list[dict] | None:
|
|
398
|
+
try:
|
|
399
|
+
doc = tomllib.loads(text)
|
|
400
|
+
except tomllib.TOMLDecodeError as e:
|
|
401
|
+
refusals.append(f"{where}: not valid TOML ({e})")
|
|
402
|
+
return None
|
|
403
|
+
pkg_src = doc.get("srcDir", ".")
|
|
404
|
+
libs = []
|
|
405
|
+
for kind, tables in (("lean_lib", doc.get("lean_lib", [])), ("lean_exe", doc.get("lean_exe", []))):
|
|
406
|
+
for t in tables if isinstance(tables, list) else []:
|
|
407
|
+
name = t.get("name")
|
|
408
|
+
if not isinstance(name, str):
|
|
409
|
+
refusals.append(f"{where}: a [[{kind}]] without a name")
|
|
410
|
+
continue
|
|
411
|
+
src_dir = posixpath.normpath(t.get("srcDir", pkg_src))
|
|
412
|
+
roots = t.get("roots", [name]) if kind == "lean_lib" else [t.get("root", name)]
|
|
413
|
+
globs = t.get("globs", []) if kind == "lean_lib" else []
|
|
414
|
+
if xp.bad_rel_path(src_dir, allow_dot=True):
|
|
415
|
+
refusals.append(f"{where}: [[{kind}]] {name} srcDir {src_dir!r} {xp.bad_rel_path(src_dir, True)}")
|
|
416
|
+
continue
|
|
417
|
+
libs.append({"name": name, "src_dir": src_dir, "roots": [str(r) for r in roots],
|
|
418
|
+
"globs": [str(g) for g in globs]})
|
|
419
|
+
return libs
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def lib_owns(lib: dict, mod: str) -> bool:
|
|
423
|
+
"""Lake's `LeanLib.isLocalModule`: a root is a name prefix of mod, or a glob matches it."""
|
|
424
|
+
if any(mod == r or mod.startswith(r + ".") for r in lib["roots"]):
|
|
425
|
+
return True
|
|
426
|
+
for g in lib["globs"]:
|
|
427
|
+
if g.endswith(".+") and mod.startswith(g[:-2] + "."):
|
|
428
|
+
return True
|
|
429
|
+
if g.endswith(".*") and (mod == g[:-2] or mod.startswith(g[:-2] + ".")):
|
|
430
|
+
return True
|
|
431
|
+
if mod == g:
|
|
432
|
+
return True
|
|
433
|
+
return False
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
_IMPORT = re.compile(r"^[ \t]*(?:(?:public|private)[ \t]+)?(?:meta[ \t]+)?import[ \t]+(?:all[ \t]+)?([^\s]+)", re.M)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def imports(text: str) -> list[str]:
|
|
440
|
+
masked = lean_scan._mask(text)[0]
|
|
441
|
+
return [m.replace("«", "").replace("»", "") for m in _IMPORT.findall(masked)]
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def dep_namespaces(name: str, override: dict) -> list[str]:
|
|
445
|
+
if name in override:
|
|
446
|
+
return list(override[name])
|
|
447
|
+
if name in KNOWN_NAMESPACES:
|
|
448
|
+
return list(KNOWN_NAMESPACES[name])
|
|
449
|
+
return sorted({name, name[:1].upper() + name[1:]})
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
# ----------------------------------------------------------------------------------------------------
|
|
453
|
+
# the plan
|
|
454
|
+
|
|
455
|
+
def _sha(b: bytes) -> str:
|
|
456
|
+
return hashlib.sha256(b).hexdigest()
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _to_path(root: dict, src: str) -> str:
|
|
460
|
+
"""The output path of `src` under `root` (a file root maps to its `to` itself)."""
|
|
461
|
+
if src == root["from"]:
|
|
462
|
+
return root["to"]
|
|
463
|
+
rel = src if root["from"] == "." else src[len(root["from"]) + 1:]
|
|
464
|
+
return rel if root["to"] == "." else f"{root['to']}/{rel}"
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _depth(p: str) -> int:
|
|
468
|
+
return 0 if p == "." else p.count("/") + 1
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def build_plan(repo: pathlib.Path, commit_arg: str, manifest_bytes: bytes) -> dict:
|
|
472
|
+
refusals: list[str] = []
|
|
473
|
+
plan = {"schema": PLAN_SCHEMA, "ok": False, "source": {"commit": None,
|
|
474
|
+
"manifest_sha256": _sha(manifest_bytes)}, "roots": [], "included": [], "excluded": [],
|
|
475
|
+
"allowed_private": [], "weakened": [], "modules": [], "unowned_lean_files": [], "claims": [],
|
|
476
|
+
"pins": {}, "adopted": [], "refusals": refusals, "warnings": [], "totals": {}}
|
|
477
|
+
commit = resolve_commit(repo, commit_arg)
|
|
478
|
+
if not commit:
|
|
479
|
+
refusals.append(f"--commit {commit_arg!r} is not a commit of the source repository")
|
|
480
|
+
return _finish(plan)
|
|
481
|
+
plan["source"]["commit"] = commit
|
|
482
|
+
raw, err = load_json_strict(manifest_bytes, "manifest")
|
|
483
|
+
if err:
|
|
484
|
+
refusals.append(err)
|
|
485
|
+
return _finish(plan)
|
|
486
|
+
man = validate_manifest(raw, commit, refusals)
|
|
487
|
+
if man is None:
|
|
488
|
+
return _finish(plan)
|
|
489
|
+
tree = ls_tree(repo, commit)
|
|
490
|
+
dirs = {"."}
|
|
491
|
+
for p in tree:
|
|
492
|
+
d = posixpath.dirname(p)
|
|
493
|
+
while d and d not in dirs:
|
|
494
|
+
dirs.add(d)
|
|
495
|
+
d = posixpath.dirname(d)
|
|
496
|
+
roots = man["roots"]
|
|
497
|
+
plan["roots"] = [{"from": r["from"], "to": r["to"], "kind": r["kind"]} for r in roots]
|
|
498
|
+
|
|
499
|
+
# roots: each `from` exists; no two roots share a `from` or a `to`
|
|
500
|
+
froms, tos = {}, {}
|
|
501
|
+
for r in roots:
|
|
502
|
+
if r["from"] not in tree and r["from"] not in dirs:
|
|
503
|
+
refusals.append(f"roots[{r['index']}].from {r['from']!r} does not exist at {commit[:12]}")
|
|
504
|
+
elif r["from"] in tree and r["to"] == ".":
|
|
505
|
+
refusals.append(f"roots[{r['index']}]: a file root needs a file `to`, not `.`")
|
|
506
|
+
if r["from"] in froms:
|
|
507
|
+
refusals.append(f"roots[{r['index']}].from {r['from']!r} repeats roots[{froms[r['from']]}].from")
|
|
508
|
+
if r["to"] in tos:
|
|
509
|
+
refusals.append(f"roots[{r['index']}].to {r['to']!r} overlaps roots[{tos[r['to']]}].to (same target)")
|
|
510
|
+
froms.setdefault(r["from"], r["index"])
|
|
511
|
+
tos.setdefault(r["to"], r["index"])
|
|
512
|
+
|
|
513
|
+
def owner(path: str) -> dict | None: # the deepest root containing path; nested roots carve out
|
|
514
|
+
cands = [r for r in roots if xp.under(path, r["from"])]
|
|
515
|
+
return max(cands, key=lambda r: (_depth(r["from"]), -r["index"])) if cands else None
|
|
516
|
+
|
|
517
|
+
root_at = {r["index"]: r for r in roots}
|
|
518
|
+
|
|
519
|
+
pins = man["pins"]
|
|
520
|
+
pin_role = {pins["lean_toolchain"]: "lean_toolchain", pins["lake_manifest"]: "lake_manifest"}
|
|
521
|
+
if pins.get("claims"):
|
|
522
|
+
pin_role[pins["claims"]] = "claims"
|
|
523
|
+
for v in pins.get("verification", []):
|
|
524
|
+
pin_role.setdefault(v, "verification")
|
|
525
|
+
|
|
526
|
+
used_allow: set[int] = set()
|
|
527
|
+
included: dict[str, dict] = {} # to-path -> entry
|
|
528
|
+
by_src: dict[str, dict] = {} # from-path -> entry (included only)
|
|
529
|
+
excluded: list[dict] = []
|
|
530
|
+
unclassified: list[str] = [] # under a root, refused as unclassified
|
|
531
|
+
symlinks: list[dict] = []
|
|
532
|
+
for path in sorted(tree):
|
|
533
|
+
r = owner(path)
|
|
534
|
+
if r is None:
|
|
535
|
+
continue
|
|
536
|
+
ent = tree[path]
|
|
537
|
+
to = _to_path(r, path)
|
|
538
|
+
if ent["mode"] == GIT_LINK:
|
|
539
|
+
refusals.append(f"{path}: a gitlink (submodule) at {commit[:12]}; submodules are refused, "
|
|
540
|
+
f"not dropped (vendor the files or exclude the path)")
|
|
541
|
+
continue
|
|
542
|
+
rule = next((x for x in man["exclude"] if x["rx"].match(path)), None)
|
|
543
|
+
if rule:
|
|
544
|
+
excluded.append({"from": path, "class": "manifest-exclude", "reason": rule["reason"]})
|
|
545
|
+
continue
|
|
546
|
+
cls = None
|
|
547
|
+
denied = deny_class(path)
|
|
548
|
+
if denied:
|
|
549
|
+
allow = next((x for x in man["allow_private"] if x["rx"].match(path)), None)
|
|
550
|
+
if not allow:
|
|
551
|
+
excluded.append({"from": path, "class": denied[0], "reason": denied[1]})
|
|
552
|
+
continue
|
|
553
|
+
used_allow.add(allow["index"])
|
|
554
|
+
cls = "allowed-private"
|
|
555
|
+
plan["allowed_private"].append({"to": to, "from": path, "denied_class": denied[0],
|
|
556
|
+
"glob": allow["path"], "reason": allow["reason"]})
|
|
557
|
+
if cls is None and path in pin_role:
|
|
558
|
+
cls = "pin:" + pin_role[path]
|
|
559
|
+
if cls is None:
|
|
560
|
+
cls = allow_class(path, r["kind"])
|
|
561
|
+
if cls is None:
|
|
562
|
+
unclassified.append(path)
|
|
563
|
+
refusals.append(f"{path}: unclassified in a {r['kind']} root (default deny); exclude it, move it, "
|
|
564
|
+
f"or put it in a root whose kind carries it")
|
|
565
|
+
continue
|
|
566
|
+
e = {"to": to, "from": path, "size": ent["size"], "sha256": None, "blob": ent["oid"],
|
|
567
|
+
"mode": ent["mode"], "class": cls, "root": r["index"]}
|
|
568
|
+
if to in included:
|
|
569
|
+
refusals.append(f"{path} and {included[to]['from']} both map to {to!r} (overlapping targets)")
|
|
570
|
+
continue
|
|
571
|
+
included[to] = e
|
|
572
|
+
by_src[path] = e
|
|
573
|
+
if ent["mode"] == SYMLINK:
|
|
574
|
+
symlinks.append(e)
|
|
575
|
+
|
|
576
|
+
# interleaved targets: an output file that is also an output directory, or an outer root writing
|
|
577
|
+
# inside an inner root's target directory
|
|
578
|
+
to_dirs = {}
|
|
579
|
+
for to, e in included.items():
|
|
580
|
+
d = posixpath.dirname(to)
|
|
581
|
+
while d:
|
|
582
|
+
to_dirs.setdefault(d, e)
|
|
583
|
+
d = posixpath.dirname(d)
|
|
584
|
+
for to, e in sorted(included.items()):
|
|
585
|
+
if to in to_dirs:
|
|
586
|
+
refusals.append(f"{to!r} is both a file (from {e['from']}) and a directory (from "
|
|
587
|
+
f"{to_dirs[to]['from']}) in the output (overlapping targets)")
|
|
588
|
+
for r in roots:
|
|
589
|
+
outer_to = root_at[e["root"]]["to"]
|
|
590
|
+
if r["index"] != e["root"] and xp.under(to, r["to"]) and xp.under(r["to"], outer_to):
|
|
591
|
+
refusals.append(f"{e['from']} maps to {to!r}, inside roots[{r['index']}].to {r['to']!r} "
|
|
592
|
+
f"(overlapping targets)")
|
|
593
|
+
|
|
594
|
+
for rule in man["allow_private"]:
|
|
595
|
+
if rule["index"] not in used_allow:
|
|
596
|
+
refusals.append(f"allow_private[{rule['index']}] {rule['path']!r} matches no default-denied file "
|
|
597
|
+
f"under the roots (a stale allowance is refused)")
|
|
598
|
+
|
|
599
|
+
blobs = read_blobs(repo, [e["blob"] for e in included.values()])
|
|
600
|
+
for e in included.values():
|
|
601
|
+
b = blobs.get(e["blob"])
|
|
602
|
+
if b is None:
|
|
603
|
+
refusals.append(f"{e['from']}: blob {e['blob'][:12]} is not in the object store (partial clone?)")
|
|
604
|
+
continue
|
|
605
|
+
e["sha256"] = _sha(b)
|
|
606
|
+
|
|
607
|
+
def text_of(src: str) -> str | None:
|
|
608
|
+
e = by_src.get(src)
|
|
609
|
+
b = blobs.get(e["blob"]) if e else None
|
|
610
|
+
return None if b is None else b.decode("utf-8", "replace")
|
|
611
|
+
|
|
612
|
+
# symlinks: relative, inside their root, pointing at an included file (or a directory of them)
|
|
613
|
+
excluded_src = {x["from"] for x in excluded}
|
|
614
|
+
for e in symlinks:
|
|
615
|
+
target = text_of(e["from"]) or ""
|
|
616
|
+
res, why = xp.link_target(e["from"], target)
|
|
617
|
+
if why:
|
|
618
|
+
refusals.append(f"{e['from']}: {why}")
|
|
619
|
+
continue
|
|
620
|
+
r = root_at[e["root"]]
|
|
621
|
+
if not xp.under(res, r["from"]):
|
|
622
|
+
refusals.append(f"{e['from']}: symlink target {target!r} leaves its root {r['from']!r}")
|
|
623
|
+
elif res in excluded_src or any(xp.under(x, res) for x in excluded_src):
|
|
624
|
+
refusals.append(f"{e['from']}: symlink target {target!r} is (or contains) an excluded file")
|
|
625
|
+
elif res not in by_src and res not in dirs:
|
|
626
|
+
refusals.append(f"{e['from']}: symlink target {target!r} does not exist at {commit[:12]}")
|
|
627
|
+
elif res in dirs and not any(xp.under(s, res) for s in by_src):
|
|
628
|
+
refusals.append(f"{e['from']}: symlink target {target!r} has no included file")
|
|
629
|
+
|
|
630
|
+
# pins
|
|
631
|
+
pin_out = {}
|
|
632
|
+
for role, src in [("lean_toolchain", pins["lean_toolchain"]), ("lake_manifest", pins["lake_manifest"])] + \
|
|
633
|
+
([("claims", pins["claims"])] if pins.get("claims") else []) + \
|
|
634
|
+
[("verification", v) for v in pins.get("verification", [])]:
|
|
635
|
+
e = by_src.get(src)
|
|
636
|
+
if src not in tree:
|
|
637
|
+
refusals.append(f"pins.{role} {src}: missing at {commit[:12]}")
|
|
638
|
+
continue
|
|
639
|
+
if e is None:
|
|
640
|
+
why = next((f"{x['class']}: {x['reason']}" for x in excluded if x["from"] == src), "outside every root")
|
|
641
|
+
refusals.append(f"pins.{role} {src}: not included ({why})")
|
|
642
|
+
continue
|
|
643
|
+
if e["mode"] == SYMLINK:
|
|
644
|
+
refusals.append(f"pins.{role} {src}: a symlink; pin the file itself")
|
|
645
|
+
continue
|
|
646
|
+
rec = {"from": src, "to": e["to"], "sha256": e["sha256"], "blob": e["blob"]}
|
|
647
|
+
if role == "verification":
|
|
648
|
+
pin_out.setdefault("verification", []).append(rec)
|
|
649
|
+
else:
|
|
650
|
+
pin_out[role] = rec
|
|
651
|
+
plan["pins"] = pin_out
|
|
652
|
+
if "verification" in pin_out:
|
|
653
|
+
pin_out["verification"].sort(key=lambda x: x["to"])
|
|
654
|
+
|
|
655
|
+
tc = pin_out.get("lean_toolchain")
|
|
656
|
+
if tc:
|
|
657
|
+
value = (text_of(tc["from"]) or "").strip()
|
|
658
|
+
tc["value"] = value
|
|
659
|
+
if not value or "\n" in value or FLOATING_TOOLCHAIN.search(value):
|
|
660
|
+
refusals.append(f"pins.lean_toolchain {tc['from']}: {value!r} is not a pinned toolchain "
|
|
661
|
+
f"(a floating channel or empty)")
|
|
662
|
+
|
|
663
|
+
# lake-manifest: every dependency a git dep at a full SHA, or a path dep inside the included roots
|
|
664
|
+
dep_ns: set[str] = set()
|
|
665
|
+
lm = pin_out.get("lake_manifest")
|
|
666
|
+
pkgdir = posixpath.dirname(pins["lake_manifest"]) or "."
|
|
667
|
+
if lm:
|
|
668
|
+
doc, err = load_json_strict((text_of(lm["from"]) or "").encode(), f"pins.lake_manifest {lm['from']}")
|
|
669
|
+
pkgs = doc.get("packages") if isinstance(doc, dict) else None
|
|
670
|
+
if err or not isinstance(pkgs, list):
|
|
671
|
+
refusals.append(err or f"pins.lake_manifest {lm['from']}: no `packages` list")
|
|
672
|
+
pkgs = []
|
|
673
|
+
lm["packages"] = []
|
|
674
|
+
names = set()
|
|
675
|
+
for p in pkgs:
|
|
676
|
+
if isinstance(p, dict) and "type" not in p and len(p) == 1 and next(iter(p)) in ("git", "path"):
|
|
677
|
+
p = dict(next(iter(p.values())), type=next(iter(p))) # the pre-v7 nested form
|
|
678
|
+
if not isinstance(p, dict):
|
|
679
|
+
refusals.append("pins.lake_manifest: a package entry is not an object")
|
|
680
|
+
continue
|
|
681
|
+
name, typ = p.get("name"), p.get("type")
|
|
682
|
+
names.add(name)
|
|
683
|
+
row = {"name": name, "type": typ}
|
|
684
|
+
if typ == "git":
|
|
685
|
+
rev = p.get("rev")
|
|
686
|
+
row.update(url=p.get("url"), rev=rev, inputRev=p.get("inputRev"))
|
|
687
|
+
if not (isinstance(rev, str) and HEX40.fullmatch(rev)):
|
|
688
|
+
refusals.append(f"lake-manifest package {name!r}: git rev {rev!r} is not a full 40-hex SHA")
|
|
689
|
+
elif typ == "path":
|
|
690
|
+
d = p.get("dir")
|
|
691
|
+
row["dir"] = d
|
|
692
|
+
full = posixpath.normpath(posixpath.join(pkgdir, d)) if isinstance(d, str) else None
|
|
693
|
+
if full is None or full == ".." or full.startswith("../") or (isinstance(d, str) and d.startswith("/")):
|
|
694
|
+
refusals.append(f"lake-manifest package {name!r}: path dependency {d!r} leaves the repository")
|
|
695
|
+
elif not any(xp.under(s, full) for s in by_src):
|
|
696
|
+
refusals.append(f"lake-manifest package {name!r}: path dependency {d!r} is not inside "
|
|
697
|
+
f"the included roots")
|
|
698
|
+
else:
|
|
699
|
+
refusals.append(f"lake-manifest package {name!r}: type {typ!r} is neither git (pinned) nor path")
|
|
700
|
+
if isinstance(name, str):
|
|
701
|
+
dep_ns.update(dep_namespaces(name, man["dependency_namespaces"]))
|
|
702
|
+
lm["packages"].append(row)
|
|
703
|
+
lm["packages"].sort(key=lambda x: str(x["name"]))
|
|
704
|
+
for k in sorted(set(man["dependency_namespaces"]) - names):
|
|
705
|
+
refusals.append(f"dependency_namespaces names {k!r}, which is not a lake-manifest package")
|
|
706
|
+
|
|
707
|
+
# libraries and the module map
|
|
708
|
+
libs = None
|
|
709
|
+
lakefile_toml, lakefile_lean = (posixpath.join(pkgdir, n) if pkgdir != "." else n
|
|
710
|
+
for n in ("lakefile.toml", "lakefile.lean"))
|
|
711
|
+
if lakefile_lean in tree:
|
|
712
|
+
if lakefile_lean not in by_src:
|
|
713
|
+
refusals.append(f"{lakefile_lean}: not included")
|
|
714
|
+
if man["lean_libs"] is None:
|
|
715
|
+
refusals.append(f"{lakefile_lean}: a lakefile.lean package must declare its libraries in the "
|
|
716
|
+
f"manifest (lean_libs), since lean-pkg-extract does not run Lean")
|
|
717
|
+
libs = man["lean_libs"]
|
|
718
|
+
elif lakefile_toml in tree:
|
|
719
|
+
if man["lean_libs"] is not None:
|
|
720
|
+
refusals.append("manifest.lean_libs is only for lakefile.lean packages; this package has "
|
|
721
|
+
f"{lakefile_toml}, which is read instead")
|
|
722
|
+
if lakefile_toml not in by_src:
|
|
723
|
+
refusals.append(f"{lakefile_toml}: not included")
|
|
724
|
+
else:
|
|
725
|
+
libs = toml_libs(text_of(lakefile_toml) or "", lakefile_toml, refusals)
|
|
726
|
+
elif lm:
|
|
727
|
+
refusals.append(f"no lakefile.toml or lakefile.lean beside pins.lake_manifest ({pkgdir})")
|
|
728
|
+
libs = libs or []
|
|
729
|
+
|
|
730
|
+
lean_files = sorted(s for s in by_src if s.endswith(".lean") and by_src[s]["mode"] != SYMLINK)
|
|
731
|
+
module_of: dict[str, dict] = {}
|
|
732
|
+
for src in lean_files:
|
|
733
|
+
if src in (lakefile_lean,):
|
|
734
|
+
continue
|
|
735
|
+
owners = []
|
|
736
|
+
for lib in libs:
|
|
737
|
+
base = posixpath.normpath(posixpath.join(pkgdir, lib["src_dir"]))
|
|
738
|
+
if xp.under(src, base) and src != base:
|
|
739
|
+
rel = src if base == "." else src[len(base) + 1:]
|
|
740
|
+
mod = rel[:-len(".lean")].replace("/", ".")
|
|
741
|
+
if lib_owns(lib, mod):
|
|
742
|
+
owners.append((lib["name"], mod))
|
|
743
|
+
if len(owners) > 1:
|
|
744
|
+
refusals.append(f"{src}: owned by more than one library ({', '.join(n for n, _ in owners)})")
|
|
745
|
+
if owners:
|
|
746
|
+
name, mod = owners[0]
|
|
747
|
+
if mod in module_of:
|
|
748
|
+
refusals.append(f"module {mod}: two files ({module_of[mod]['from']}, {src})")
|
|
749
|
+
module_of[mod] = {"module": mod, "file": by_src[src]["to"], "from": src, "lib": name}
|
|
750
|
+
else:
|
|
751
|
+
plan["unowned_lean_files"].append(by_src[src]["to"])
|
|
752
|
+
plan["modules"] = sorted(module_of.values(), key=lambda x: x["module"])
|
|
753
|
+
|
|
754
|
+
# imports: an included module, core, a pinned dependency's namespace, or an explicit weakening
|
|
755
|
+
allow_unres = {x["import"]: x for x in man["allow_unresolved_imports"]}
|
|
756
|
+
used_unres: set[str] = set()
|
|
757
|
+
for src in lean_files:
|
|
758
|
+
for mod in imports(text_of(src) or ""):
|
|
759
|
+
top = mod.split(".")[0]
|
|
760
|
+
if top in CORE_NAMESPACES or mod in module_of:
|
|
761
|
+
continue
|
|
762
|
+
local = next((lib for lib in libs if lib_owns(lib, mod)), None)
|
|
763
|
+
if local is not None:
|
|
764
|
+
refusals.append(f"{src}: imports {mod}, a module of library {local['name']} whose file is "
|
|
765
|
+
f"not included")
|
|
766
|
+
continue
|
|
767
|
+
if top in dep_ns:
|
|
768
|
+
continue
|
|
769
|
+
if mod in allow_unres:
|
|
770
|
+
used_unres.add(mod)
|
|
771
|
+
continue
|
|
772
|
+
refusals.append(f"{src}: imports {mod}, which resolves to no included module and no pinned "
|
|
773
|
+
f"dependency namespace")
|
|
774
|
+
for mod, x in sorted(allow_unres.items()):
|
|
775
|
+
if mod in used_unres:
|
|
776
|
+
plan["weakened"].append({"rule": "allow_unresolved_imports", "import": mod, "reason": x["reason"]})
|
|
777
|
+
else:
|
|
778
|
+
refusals.append(f"allow_unresolved_imports[{x['index']}] {mod!r} is never imported unresolved "
|
|
779
|
+
f"(a stale allowance is refused)")
|
|
780
|
+
|
|
781
|
+
# claims: the claims check schema, and every claim's file included
|
|
782
|
+
cp = pin_out.get("claims")
|
|
783
|
+
if cp:
|
|
784
|
+
text = text_of(cp["from"]) or ""
|
|
785
|
+
_count, errors = cl.schema_check_text(text, cp["from"])
|
|
786
|
+
refusals.extend(f"pins.claims {cp['from']}: {e}" for e in errors)
|
|
787
|
+
if not errors:
|
|
788
|
+
base = posixpath.dirname(cp["to"])
|
|
789
|
+
doc = cl.load_claims_text(text, cp["from"])
|
|
790
|
+
files = {}
|
|
791
|
+
for c in doc["claims"]:
|
|
792
|
+
out = posixpath.normpath(posixpath.join(base, c["file"])) if base else c["file"]
|
|
793
|
+
e = included.get(out)
|
|
794
|
+
if e is None:
|
|
795
|
+
refusals.append(f"claim {c['id']}: file {c['file']} (output {out}) is not included")
|
|
796
|
+
continue
|
|
797
|
+
files[c["file"]] = (blobs.get(e["blob"]) or b"").decode("utf-8", "replace")
|
|
798
|
+
mod = next((m["module"] for m in module_of.values() if m["file"] == out), None)
|
|
799
|
+
plan["claims"].append({"id": c["id"], "decl": c["decl"], "file": out, "module": mod})
|
|
800
|
+
ok_claims = [c for c in doc["claims"] if c["file"] in files]
|
|
801
|
+
refusals.extend(f"claim {p}" for p in cl.decl_problems(files.get, ok_claims))
|
|
802
|
+
plan["claims"].sort(key=lambda x: x["id"])
|
|
803
|
+
|
|
804
|
+
license_checks(plan, man["adopted"], tree, by_src, excluded, blobs, commit)
|
|
805
|
+
disabled_lean_check(plan, excluded, unclassified)
|
|
806
|
+
|
|
807
|
+
plan["included"] = [included[k] for k in sorted(included)]
|
|
808
|
+
plan["excluded"] = sorted(excluded, key=lambda x: x["from"])
|
|
809
|
+
plan["allowed_private"].sort(key=lambda x: x["to"])
|
|
810
|
+
plan["unowned_lean_files"].sort()
|
|
811
|
+
return _finish(plan)
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
# ----------------------------------------------------------------------------------------------------
|
|
815
|
+
# licenses of adopted (vendored) files: warnings, never refusals
|
|
816
|
+
|
|
817
|
+
LIST_CAP = 10
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _listed(paths: list[str]) -> str:
|
|
821
|
+
"""paths joined, at most LIST_CAP of them, the rest counted (the cap is stated, never silent)."""
|
|
822
|
+
head = ", ".join(paths[:LIST_CAP])
|
|
823
|
+
return head if len(paths) <= LIST_CAP else f"{head} (and {len(paths) - LIST_CAP} more)"
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def scoped_license_name(upstream: str, spdx: str) -> str:
|
|
827
|
+
"""The REUSE-valid scoped license path recommended for an upstream: LICENSES/LicenseRef-<Upstream>-<SPDX>.txt
|
|
828
|
+
(a LicenseRef- id, because the file keeps the upstream's own copyright line byte for byte)."""
|
|
829
|
+
if spdx.startswith("LicenseRef-"):
|
|
830
|
+
return f"LICENSES/{spdx}.txt"
|
|
831
|
+
tail = upstream.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git")
|
|
832
|
+
slug = re.sub(r"[^A-Za-z0-9.-]+", "-", tail).strip("-.") or "Upstream"
|
|
833
|
+
return f"LICENSES/LicenseRef-{slug}-{spdx}.txt"
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _why_not_carried(src: str, tree: dict, excluded: list[dict], commit: str) -> str:
|
|
837
|
+
if src not in tree:
|
|
838
|
+
return f"missing at {commit[:12]}"
|
|
839
|
+
x = next((x for x in excluded if x["from"] == src), None)
|
|
840
|
+
return f"excluded, {x['class']}: {x['reason']}" if x else "outside every root"
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def license_checks(plan: dict, adopted: list[dict], tree: dict, by_src: dict, excluded: list[dict],
|
|
844
|
+
blobs: dict, commit: str) -> None:
|
|
845
|
+
"""Warn when included files come from a source whose license the extract does not carry.
|
|
846
|
+
|
|
847
|
+
Declared adoption (manifest `adopted`): the upstream license must be carried as an included
|
|
848
|
+
`license_file`, and an optional `provenance` list must name every adopted file. Undeclared: an
|
|
849
|
+
included file whose nearest LICENSE/COPYING (in its own source directory or above) is not
|
|
850
|
+
included. Warnings only: the plan's verdict and exit code do not change."""
|
|
851
|
+
warn = plan["warnings"]
|
|
852
|
+
covered: set[str] = set()
|
|
853
|
+
for a in adopted:
|
|
854
|
+
own = {a["license_file"], a["provenance"]} - {None}
|
|
855
|
+
files = sorted((e for s, e in by_src.items() if s not in own and any(rx.match(s) for rx in a["rxs"])),
|
|
856
|
+
key=lambda e: e["to"])
|
|
857
|
+
covered.update(e["from"] for e in files)
|
|
858
|
+
w = f"adopted[{a['index']}]"
|
|
859
|
+
up = f"{a['upstream']} @ {a['upstream_commit'][:12]} ({a['license']}, {a['upstream_license_file']})"
|
|
860
|
+
tos = [e["to"] for e in files]
|
|
861
|
+
rec = {"index": a["index"], "paths": a["paths"], "upstream": a["upstream"],
|
|
862
|
+
"upstream_commit": a["upstream_commit"], "upstream_license_file": a["upstream_license_file"],
|
|
863
|
+
"license": a["license"], "files": tos, "license_file": None, "provenance": None}
|
|
864
|
+
if not files:
|
|
865
|
+
warn.append(f"{w} {a['paths']}: matches no included file (a stale adoption entry)")
|
|
866
|
+
lf = a["license_file"]
|
|
867
|
+
if lf is None:
|
|
868
|
+
if files:
|
|
869
|
+
warn.append(f"{w}: {len(files)} file(s) adopted from {up} are extracted without the upstream "
|
|
870
|
+
f"license: {_listed(tos)}. Copy {a['upstream_license_file']} at "
|
|
871
|
+
f"{a['upstream_commit'][:12]} byte for byte to "
|
|
872
|
+
f"{scoped_license_name(a['upstream'], a['license'])}, list the files it covers, "
|
|
873
|
+
f"and name it in license_file")
|
|
874
|
+
elif lf not in by_src:
|
|
875
|
+
warn.append(f"{w}: license_file {lf} is not carried into the target "
|
|
876
|
+
f"({_why_not_carried(lf, tree, excluded, commit)}); the {len(files)} file(s) adopted "
|
|
877
|
+
f"from {up} would ship without their license: {_listed(tos)}")
|
|
878
|
+
else:
|
|
879
|
+
to = by_src[lf]["to"]
|
|
880
|
+
rec["license_file"] = {"from": lf, "to": to, "sha256": by_src[lf]["sha256"]}
|
|
881
|
+
parent, stem = posixpath.basename(posixpath.dirname(to)), posixpath.splitext(posixpath.basename(to))[0]
|
|
882
|
+
if parent == "LICENSES" and stem != a["license"] and not stem.startswith("LicenseRef-"):
|
|
883
|
+
warn.append(f"{w}: license_file {to} is under LICENSES/ but its name is neither the SPDX id "
|
|
884
|
+
f"{a['license']!r} nor a LicenseRef- id; `reuse lint` reports it as a bad license. Name it "
|
|
885
|
+
f"{scoped_license_name(a['upstream'], a['license'])} and use that id in REUSE.toml")
|
|
886
|
+
pv = a["provenance"]
|
|
887
|
+
if pv is not None:
|
|
888
|
+
if pv not in by_src:
|
|
889
|
+
warn.append(f"{w}: provenance {pv} is not carried into the target "
|
|
890
|
+
f"({_why_not_carried(pv, tree, excluded, commit)})")
|
|
891
|
+
else:
|
|
892
|
+
text = (blobs.get(by_src[pv]["blob"]) or b"").decode("utf-8", "replace")
|
|
893
|
+
missing = [e["to"] for e in files if e["to"] not in text and e["from"] not in text]
|
|
894
|
+
if missing:
|
|
895
|
+
warn.append(f"{w}: provenance {by_src[pv]['to']} does not list {len(missing)} adopted "
|
|
896
|
+
f"file(s): {_listed(missing)}")
|
|
897
|
+
rec["provenance"] = {"from": pv, "to": by_src[pv]["to"], "sha256": by_src[pv]["sha256"]}
|
|
898
|
+
plan["adopted"].append(rec)
|
|
899
|
+
|
|
900
|
+
# undeclared: the nearest license file above an included file is not carried
|
|
901
|
+
licenses: dict[str, list[str]] = {}
|
|
902
|
+
for path in tree:
|
|
903
|
+
if DIR_LICENSE.match(posixpath.basename(path)) and tree[path]["mode"] != GIT_LINK:
|
|
904
|
+
licenses.setdefault(posixpath.dirname(path), []).append(path)
|
|
905
|
+
license_paths = {p for group in licenses.values() for p in group}
|
|
906
|
+
orphaned: dict[tuple[str, ...], list[str]] = {}
|
|
907
|
+
for src, e in by_src.items():
|
|
908
|
+
if src in covered or src in license_paths:
|
|
909
|
+
continue
|
|
910
|
+
d = posixpath.dirname(src)
|
|
911
|
+
while True:
|
|
912
|
+
if d in licenses:
|
|
913
|
+
if not any(p in by_src for p in licenses[d]):
|
|
914
|
+
orphaned.setdefault(tuple(sorted(licenses[d])), []).append(e["to"])
|
|
915
|
+
break
|
|
916
|
+
if not d:
|
|
917
|
+
break
|
|
918
|
+
d = posixpath.dirname(d)
|
|
919
|
+
for lic, tos in sorted(orphaned.items()):
|
|
920
|
+
where = "the source repository's license" if not posixpath.dirname(lic[0]) else "the license"
|
|
921
|
+
whys = "; ".join(f"{p}: {_why_not_carried(p, tree, excluded, commit)}" for p in lic)
|
|
922
|
+
warn.append(f"{', '.join(lic)}: {where} over {len(tos)} included file(s) is not carried into the target "
|
|
923
|
+
f"({whys}): {_listed(sorted(tos))}. If these files were adopted from another project, "
|
|
924
|
+
f"declare them under `adopted` and carry the upstream license as a scoped LICENSES/ file; "
|
|
925
|
+
f"otherwise include or replace the license deliberately")
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
def disabled_lean_check(plan: dict, excluded: list[dict], unclassified: list[str]) -> None:
|
|
929
|
+
"""Warn about `*.lean.<suffix>` files under a root that the plan excludes or refuses as unclassified.
|
|
930
|
+
|
|
931
|
+
The module inventory, unowned_lean_files and the import check read `*.lean` only, so a disabled
|
|
932
|
+
negative fixture with a stale `open` or `import` (after a namespace or import transport) would go
|
|
933
|
+
unreported. A warning: the plan's verdict and exit code do not change."""
|
|
934
|
+
names = sorted({x["from"] for x in excluded} | set(unclassified))
|
|
935
|
+
hits = [p for p in names if DISABLED_LEAN.match(posixpath.basename(p))]
|
|
936
|
+
if hits:
|
|
937
|
+
plan["warnings"].append(
|
|
938
|
+
f"{len(hits)} disabled Lean source file(s) (*.lean.<suffix>) are excluded or refused, so the module "
|
|
939
|
+
f"inventory and the import check skip them: {', '.join(hits)}. After a namespace or import "
|
|
940
|
+
f"transport, a stale `open` or `import` in them goes unreported: run each one's expected-reason "
|
|
941
|
+
f"check (`python3 -m lean_pkg.lean_diag LOG --error-code CODE --file NAME`; {DISABLED_LEAN_DOC})")
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def _finish(plan: dict) -> dict:
|
|
945
|
+
ref = sorted(set(plan["refusals"]))
|
|
946
|
+
plan["refusals"] = ref
|
|
947
|
+
plan["warnings"] = sorted(set(plan.get("warnings", [])))
|
|
948
|
+
plan["ok"] = not ref
|
|
949
|
+
plan["totals"] = {"included_files": len(plan["included"]),
|
|
950
|
+
"included_bytes": sum(e["size"] or 0 for e in plan["included"]),
|
|
951
|
+
"excluded_files": len(plan["excluded"]), "allowed_private": len(plan["allowed_private"]),
|
|
952
|
+
"weakened": len(plan["weakened"]), "modules": len(plan["modules"]),
|
|
953
|
+
"claims": len(plan["claims"]), "refusals": len(ref), "warnings": len(plan["warnings"])}
|
|
954
|
+
return plan
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
# ----------------------------------------------------------------------------------------------------
|
|
958
|
+
# output
|
|
959
|
+
|
|
960
|
+
def verdict(plan: dict) -> str:
|
|
961
|
+
t = plan["totals"]
|
|
962
|
+
head = "plan: OK" if plan["ok"] else f"plan: REFUSED ({t['refusals']} refusal(s))"
|
|
963
|
+
commit = plan["source"]["commit"] or "unresolved"
|
|
964
|
+
warned = f", {t['warnings']} warning(s)" if t.get("warnings") else ""
|
|
965
|
+
return (f"{head}: {t['included_files']} file(s) included ({t['included_bytes']} bytes), "
|
|
966
|
+
f"{t['excluded_files']} excluded, {t['allowed_private']} allowed private, {t['modules']} module(s), "
|
|
967
|
+
f"{t['claims']} claim(s), {t['weakened']} weakening(s){warned}; source commit {commit}")
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def render(plan: dict) -> str:
|
|
971
|
+
out = [verdict(plan)]
|
|
972
|
+
if plan["refusals"]:
|
|
973
|
+
out.append("refusals:")
|
|
974
|
+
out += [f" - {r}" for r in plan["refusals"]]
|
|
975
|
+
if plan["warnings"]:
|
|
976
|
+
out.append("warnings (reported, not refused):")
|
|
977
|
+
out += [f" - {w}" for w in plan["warnings"]]
|
|
978
|
+
if plan["included"]:
|
|
979
|
+
out.append("included (to <- from, size, sha256, blob, mode, class):")
|
|
980
|
+
out += [f" {e['to']} <- {e['from']} {e['size']} {e['sha256']} {e['blob']} {e['mode']} {e['class']}"
|
|
981
|
+
for e in plan["included"]]
|
|
982
|
+
if plan["excluded"]:
|
|
983
|
+
out.append("excluded (PRIVATE: keep this list out of anything published):")
|
|
984
|
+
out += [f" {e['from']} {e['class']}: {e['reason']}" for e in plan["excluded"]]
|
|
985
|
+
if plan["allowed_private"]:
|
|
986
|
+
out.append("allowed private (default-denied, included by allow_private; disclosed):")
|
|
987
|
+
out += [f" {e['to']} <- {e['from']} {e['denied_class']} allow_private {e['glob']!r}: {e['reason']}"
|
|
988
|
+
for e in plan["allowed_private"]]
|
|
989
|
+
if plan["weakened"]:
|
|
990
|
+
out.append("weakened checks (disclosed):")
|
|
991
|
+
out += [f" {w['rule']} {w['import']}: {w['reason']}" for w in plan["weakened"]]
|
|
992
|
+
if plan["modules"]:
|
|
993
|
+
out.append("modules (module -> file, library):")
|
|
994
|
+
out += [f" {m['module']} -> {m['file']} ({m['lib']})" for m in plan["modules"]]
|
|
995
|
+
if plan["unowned_lean_files"]:
|
|
996
|
+
out.append("lean files owned by no library (import-checked, not modules):")
|
|
997
|
+
out += [f" {f}" for f in plan["unowned_lean_files"]]
|
|
998
|
+
if plan["adopted"]:
|
|
999
|
+
out.append("adopted files (upstream @ commit, license; license file carried; provenance):")
|
|
1000
|
+
for a in plan["adopted"]:
|
|
1001
|
+
lf = a["license_file"]["to"] if a["license_file"] else "NOT CARRIED"
|
|
1002
|
+
pv = a["provenance"]["to"] if a["provenance"] else "none"
|
|
1003
|
+
out.append(f" adopted[{a['index']}] {a['upstream']} @ {a['upstream_commit']}, {a['license']} "
|
|
1004
|
+
f"({a['upstream_license_file']}); license file {lf}; provenance {pv}")
|
|
1005
|
+
out += [f" {f}" for f in a["files"]]
|
|
1006
|
+
if plan["claims"]:
|
|
1007
|
+
out.append("claims (id -> decl -> file):")
|
|
1008
|
+
out += [f" {c['id']} -> {c['decl']} -> {c['file']}" for c in plan["claims"]]
|
|
1009
|
+
pins = plan["pins"]
|
|
1010
|
+
if pins:
|
|
1011
|
+
out.append("pins:")
|
|
1012
|
+
for role in ("lean_toolchain", "lake_manifest", "claims"):
|
|
1013
|
+
p = pins.get(role)
|
|
1014
|
+
if p:
|
|
1015
|
+
extra = f" {p['value']}" if "value" in p else ""
|
|
1016
|
+
out.append(f" {role}: {p['to']} <- {p['from']} sha256 {p['sha256']}{extra}")
|
|
1017
|
+
for d in p.get("packages", []):
|
|
1018
|
+
where = f"{d.get('url')} @ {d.get('rev')}" if d["type"] == "git" else f"path {d.get('dir')}"
|
|
1019
|
+
out.append(f" {d['name']}: {d['type']} {where}")
|
|
1020
|
+
for p in pins.get("verification", []):
|
|
1021
|
+
out.append(f" verification: {p['to']} <- {p['from']} sha256 {p['sha256']}")
|
|
1022
|
+
t = plan["totals"]
|
|
1023
|
+
out.append("totals: " + ", ".join(f"{k} {v}" for k, v in t.items()))
|
|
1024
|
+
out.append(verdict(plan))
|
|
1025
|
+
return "\n".join(out)
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def public_json(plan: dict) -> str:
|
|
1029
|
+
return json.dumps(plan, indent=2, ensure_ascii=False) + "\n"
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
# ----------------------------------------------------------------------------------------------------
|
|
1033
|
+
# CLI
|
|
1034
|
+
|
|
1035
|
+
EXAMPLES = """\
|
|
1036
|
+
examples:
|
|
1037
|
+
lean-pkg-extract plan --repo . --commit HEAD --manifest extract.json
|
|
1038
|
+
lean-pkg-extract plan --repo ~/paper --commit 0123abc --manifest extract.json --json
|
|
1039
|
+
lean-pkg-extract plan --repo . --commit v1.0 --manifest extract.json --report ../extract-plan.json
|
|
1040
|
+
lean-pkg-extract ledger @ledger-args.txt
|
|
1041
|
+
lean-pkg-extract recheck --ledger ../newlib-ledger.json --repo . --target ../newlib
|
|
1042
|
+
lean-pkg-extract decls @decls-args.txt --output ../newlib --scaffold newlib --ledger ../newlib-ledger.json
|
|
1043
|
+
|
|
1044
|
+
Dry run only: `plan` reads git objects at COMMIT and writes nothing (--report PATH, outside SRC, is the
|
|
1045
|
+
one exception). The file-level `write --output DIR` step comes next. `ledger` writes only its ledger,
|
|
1046
|
+
outside SRC and the target; `recheck` writes nothing but its public summary on request (--public-summary);
|
|
1047
|
+
`decls` writes the target modules into a new directory outside SRC (staged, scanned with public-safety,
|
|
1048
|
+
moved into place) and its ledger.
|
|
1049
|
+
exit codes: 0 plan clean, 1 refused (every reason listed), 2 usage.
|
|
1050
|
+
docs: https://lean-pkg.github.io/lean-pkg/extract.html"""
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
class _Parser(argparse.ArgumentParser):
|
|
1054
|
+
json_requested = False
|
|
1055
|
+
|
|
1056
|
+
def error(self, message):
|
|
1057
|
+
if _Parser.json_requested:
|
|
1058
|
+
print(json.dumps({"ok": False, "error": message, "usage": True}))
|
|
1059
|
+
super().error(message)
|
|
1060
|
+
|
|
1061
|
+
def convert_arg_line_to_args(self, arg_line):
|
|
1062
|
+
"""An @ARGSFILE line: `--flag value` is the flag and the rest of the line (a reason may hold
|
|
1063
|
+
spaces), any other line one argument; blank lines and `#` lines are skipped."""
|
|
1064
|
+
line = arg_line.strip()
|
|
1065
|
+
if not line or line.startswith("#"):
|
|
1066
|
+
return []
|
|
1067
|
+
head, _, rest = line.partition(" ")
|
|
1068
|
+
if head.startswith("--") and "=" not in head and rest.strip():
|
|
1069
|
+
return [head, rest.strip()]
|
|
1070
|
+
return [line]
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def parser() -> argparse.ArgumentParser:
|
|
1074
|
+
fmt = argparse.RawDescriptionHelpFormatter
|
|
1075
|
+
ap = _Parser(prog="lean-pkg-extract", formatter_class=fmt, epilog=EXAMPLES,
|
|
1076
|
+
description="Plan a standalone public Lean-verification repository from a mixed working "
|
|
1077
|
+
"repository, with exact provenance. Read-only; no registry, no network.")
|
|
1078
|
+
sub = ap.add_subparsers(dest="verb", metavar="{plan,ledger,recheck,decls}", required=True)
|
|
1079
|
+
p = sub.add_parser("plan", formatter_class=fmt, epilog=EXAMPLES,
|
|
1080
|
+
help="dry run: classify, check and inventory what an extract at COMMIT would contain",
|
|
1081
|
+
description="Dry run: classify every file under the manifest's roots at COMMIT "
|
|
1082
|
+
"(default deny), check paths, links, pins, dependencies, claims and "
|
|
1083
|
+
"imports, and print the inventory. Writes nothing.")
|
|
1084
|
+
p.add_argument("--repo", required=True, metavar="SRC", help="the source git repository (its top directory)")
|
|
1085
|
+
p.add_argument("--commit", required=True, metavar="COMMIT", help="the source commit; recorded as a full SHA")
|
|
1086
|
+
p.add_argument("--manifest", required=True, metavar="PATH",
|
|
1087
|
+
help=f"the extract manifest, strict JSON, schema {MANIFEST_SCHEMA}")
|
|
1088
|
+
p.add_argument("--json", dest="json_out", action="store_true", help=f"JSON on stdout (schema {PLAN_SCHEMA})")
|
|
1089
|
+
p.add_argument("--report", metavar="PATH",
|
|
1090
|
+
help="also write the JSON plan (with the private excluded list) to PATH, outside SRC")
|
|
1091
|
+
from . import extract_decls, extract_ledger
|
|
1092
|
+
extract_ledger.add_parsers(sub, _Parser, fmt)
|
|
1093
|
+
extract_decls.add_parser(sub, _Parser, fmt)
|
|
1094
|
+
return ap
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _src_top(repo: pathlib.Path, flag: str = "--repo") -> tuple[pathlib.Path | None, pathlib.Path]:
|
|
1098
|
+
"""(work tree top or None for a bare repository, git dir); Usage when repo is not a git repository
|
|
1099
|
+
or is a subdirectory of one."""
|
|
1100
|
+
if not repo.is_dir():
|
|
1101
|
+
raise Usage(f"{flag} {repo}: not a directory")
|
|
1102
|
+
p = _git(repo, "rev-parse", "--is-bare-repository", "--absolute-git-dir")
|
|
1103
|
+
if p.returncode != 0:
|
|
1104
|
+
raise Usage(f"{flag} {repo}: not a git repository")
|
|
1105
|
+
bare, gitdir = p.stdout.decode().split("\n")[:2]
|
|
1106
|
+
if bare == "true":
|
|
1107
|
+
return None, pathlib.Path(gitdir)
|
|
1108
|
+
top = _git(repo, "rev-parse", "--show-toplevel").stdout.decode().strip()
|
|
1109
|
+
if pathlib.Path(top).resolve() != repo.resolve():
|
|
1110
|
+
raise Usage(f"{flag} {repo}: a subdirectory of a git repository; pass its top directory "
|
|
1111
|
+
f"(manifest paths are relative to it)")
|
|
1112
|
+
return pathlib.Path(top).resolve(), pathlib.Path(gitdir).resolve()
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def run(args) -> tuple[dict, int]:
|
|
1116
|
+
repo = pathlib.Path(args.repo).expanduser()
|
|
1117
|
+
top, gitdir = _src_top(repo)
|
|
1118
|
+
pre: list[str] = []
|
|
1119
|
+
report = None
|
|
1120
|
+
if args.report:
|
|
1121
|
+
report = pathlib.Path(args.report).expanduser()
|
|
1122
|
+
rp = report.parent.resolve() / report.name
|
|
1123
|
+
for inside in (top, gitdir):
|
|
1124
|
+
if inside is not None and (rp == inside or inside in rp.parents):
|
|
1125
|
+
pre.append(f"--report {args.report}: inside the source repository; the report lists private "
|
|
1126
|
+
f"paths and a dry run leaves SRC unchanged, so write it outside SRC")
|
|
1127
|
+
break
|
|
1128
|
+
if report.is_symlink() or (report.exists() and not report.is_file()):
|
|
1129
|
+
pre.append(f"--report {args.report}: exists and is not a regular file")
|
|
1130
|
+
elif not rp.parent.is_dir():
|
|
1131
|
+
pre.append(f"--report {args.report}: its directory does not exist")
|
|
1132
|
+
try:
|
|
1133
|
+
mbytes = pathlib.Path(args.manifest).expanduser().read_bytes()
|
|
1134
|
+
except OSError as e:
|
|
1135
|
+
mbytes = b""
|
|
1136
|
+
pre.append(f"--manifest {args.manifest}: cannot be read ({e.strerror or e})")
|
|
1137
|
+
plan = build_plan(repo, args.commit, mbytes)
|
|
1138
|
+
if pre:
|
|
1139
|
+
plan["refusals"] = pre + plan["refusals"]
|
|
1140
|
+
plan = _finish(plan)
|
|
1141
|
+
if report is not None and not pre:
|
|
1142
|
+
report.write_text(public_json(plan), encoding="utf-8")
|
|
1143
|
+
return plan, (0 if plan["ok"] else 1)
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1147
|
+
raw = list(sys.argv[1:] if argv is None else argv)
|
|
1148
|
+
from . import extract_ledger
|
|
1149
|
+
_Parser.json_requested = "--json" in raw or extract_ledger.argsfile_requests_json(raw)
|
|
1150
|
+
args = parser().parse_args(raw)
|
|
1151
|
+
try:
|
|
1152
|
+
if args.verb == "decls":
|
|
1153
|
+
from . import extract_decls
|
|
1154
|
+
text, rc = extract_decls.run(args)
|
|
1155
|
+
sys.stdout.write(text)
|
|
1156
|
+
return rc
|
|
1157
|
+
if args.verb != "plan":
|
|
1158
|
+
text, rc = extract_ledger.run(args)
|
|
1159
|
+
sys.stdout.write(text)
|
|
1160
|
+
return rc
|
|
1161
|
+
plan, rc = run(args)
|
|
1162
|
+
except Usage as e:
|
|
1163
|
+
if args.json_out:
|
|
1164
|
+
print(json.dumps({"ok": False, "error": str(e), "usage": True}, indent=2))
|
|
1165
|
+
print(f"lean-pkg-extract: {e}", file=sys.stderr)
|
|
1166
|
+
return 2
|
|
1167
|
+
sys.stdout.write(public_json(plan) if args.json_out else render(plan) + "\n")
|
|
1168
|
+
return rc
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
if __name__ == "__main__":
|
|
1172
|
+
sys.exit(main())
|