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
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
# lean-exercise --forbid: which constants a judged theorem's proof depends on, read from a kernel export.
|
|
2
|
+
"""Forbidden constants for lean-exercise, computed on the compiled environment, never on the source text.
|
|
3
|
+
|
|
4
|
+
The Solution is exported with the toolchain's own `leanexport` (NDJSON, the format `lake comparator`
|
|
5
|
+
replays), inside the same kind of bwrap sandbox `lake comparator` uses: the learner's `.olean` files are
|
|
6
|
+
never loaded into this process. The export is then read here as data.
|
|
7
|
+
|
|
8
|
+
Scope `solution` (the default): start at the judged theorem's proof term, follow every constant the
|
|
9
|
+
Solution itself declares (helper lemmas, private lemmas, `_proof_n` and `match_n` auxiliaries, local
|
|
10
|
+
definitions and instances: everything not found in the environment of the Solution's own imports), and
|
|
11
|
+
report every constant reached whose name matches a pattern. Library constants (Mathlib, Defs, Lean core)
|
|
12
|
+
are reported but not entered. A helper lemma therefore cannot launder a forbidden dependency, while a
|
|
13
|
+
Mathlib lemma that Mathlib happens to prove with a forbidden one is not held against the learner.
|
|
14
|
+
Scope `all` enters every constant, library ones included.
|
|
15
|
+
|
|
16
|
+
Constants that occur in the judged theorem's statement are never reported: the statement is fixed by the
|
|
17
|
+
Challenge, so the learner cannot avoid them.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import pathlib
|
|
24
|
+
import shutil
|
|
25
|
+
import subprocess
|
|
26
|
+
|
|
27
|
+
DECL_KEYS = ("axiom", "def", "opaque", "thm", "quot", "inductive")
|
|
28
|
+
NAME_CHUNK = 400_000 # bytes of constant names per leanexport call (argv stays far below ARG_MAX)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ExportError(Exception):
|
|
32
|
+
"""The export could not be produced or read: the forbidden-constant check fails closed."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def match(name: str, prefixes: list[str], exact: list[str]) -> bool:
|
|
36
|
+
return name in exact or any(name.startswith(p) for p in prefixes)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
40
|
+
# Reading an NDJSON export (lean4export format 3.x)
|
|
41
|
+
|
|
42
|
+
class Export:
|
|
43
|
+
"""The parts of an export the dependency walk needs: names, expression edges, declaration roots."""
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
self.names: dict[int, tuple] = {} # name id -> component tuple
|
|
47
|
+
self.exprs: dict[int, tuple] = {} # expr id -> (const name ids, child expr ids)
|
|
48
|
+
self.decls: dict[tuple, tuple] = {} # name -> (type expr ids, value expr ids, extra name ids)
|
|
49
|
+
|
|
50
|
+
def text(self, comps: tuple) -> str:
|
|
51
|
+
return ".".join(str(c) for c in comps)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _name(ex: Export, obj: dict) -> None:
|
|
55
|
+
if "str" in obj:
|
|
56
|
+
pre, s = obj["str"]["pre"], obj["str"]["str"]
|
|
57
|
+
else:
|
|
58
|
+
pre, s = obj["num"]["pre"], int(obj["num"]["i"])
|
|
59
|
+
ex.names[obj["in"]] = ex.names.get(pre, ()) + (s,)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _expr(ex: Export, obj: dict) -> None:
|
|
63
|
+
i = obj.pop("ie")
|
|
64
|
+
(kind, body), = obj.items()
|
|
65
|
+
if kind == "const":
|
|
66
|
+
ex.exprs[i] = ((body["name"],), ())
|
|
67
|
+
elif kind == "app":
|
|
68
|
+
ex.exprs[i] = ((), (body["fn"], body["arg"]))
|
|
69
|
+
elif kind in ("lam", "forallE"):
|
|
70
|
+
ex.exprs[i] = ((), (body["type"], body["body"]))
|
|
71
|
+
elif kind == "letE":
|
|
72
|
+
ex.exprs[i] = ((), (body["type"], body["value"], body["body"]))
|
|
73
|
+
elif kind == "proj":
|
|
74
|
+
ex.exprs[i] = ((body["typeName"],), (body["struct"],))
|
|
75
|
+
elif kind == "mdata":
|
|
76
|
+
ex.exprs[i] = ((), (body["expr"],))
|
|
77
|
+
else: # bvar, sort, natVal, strVal
|
|
78
|
+
ex.exprs[i] = ((), ())
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _decl(ex: Export, kind: str, body: dict, with_exprs: bool) -> None:
|
|
82
|
+
def put(name_id, types, values, extra):
|
|
83
|
+
ex.decls[ex.names[name_id]] = (tuple(types), tuple(values), tuple(extra)) if with_exprs else ((), (), ())
|
|
84
|
+
if kind != "inductive":
|
|
85
|
+
put(body["name"], [body["type"]], [body["value"]] if "value" in body else [], [])
|
|
86
|
+
return
|
|
87
|
+
members = [t["name"] for t in body["types"]] + [c["name"] for c in body["ctors"]] + \
|
|
88
|
+
[r["name"] for r in body["recs"]]
|
|
89
|
+
types = [x["type"] for x in body["types"] + body["ctors"] + body["recs"]]
|
|
90
|
+
rhs = [rule["rhs"] for r in body["recs"] for rule in r["rules"]]
|
|
91
|
+
for m in members: # a block is one unit: any member reaches all of it
|
|
92
|
+
put(m, types, rhs, members)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def read_export(path: pathlib.Path, with_exprs: bool = True) -> Export:
|
|
96
|
+
ex = Export()
|
|
97
|
+
try:
|
|
98
|
+
with open(path, encoding="utf-8") as f:
|
|
99
|
+
for n, line in enumerate(f, 1):
|
|
100
|
+
if not line.strip():
|
|
101
|
+
continue
|
|
102
|
+
obj = json.loads(line)
|
|
103
|
+
if "in" in obj:
|
|
104
|
+
_name(ex, obj)
|
|
105
|
+
elif "ie" in obj:
|
|
106
|
+
if with_exprs:
|
|
107
|
+
_expr(ex, obj)
|
|
108
|
+
elif "il" in obj or "meta" in obj:
|
|
109
|
+
continue
|
|
110
|
+
else:
|
|
111
|
+
kind = next((k for k in DECL_KEYS if k in obj), None)
|
|
112
|
+
if kind is None:
|
|
113
|
+
raise ExportError(f"export line {n}: unknown record {sorted(obj)[:3]}")
|
|
114
|
+
_decl(ex, kind, obj[kind], with_exprs)
|
|
115
|
+
except (OSError, ValueError, KeyError, TypeError) as e:
|
|
116
|
+
raise ExportError(f"cannot read the export: {e}") from None
|
|
117
|
+
return ex
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
121
|
+
# The walk
|
|
122
|
+
|
|
123
|
+
def _refs(ex: Export, roots, seen: set[int]) -> set[tuple]:
|
|
124
|
+
"""Constant names reachable inside the expressions `roots` (no unfolding of constants)."""
|
|
125
|
+
out: set[tuple] = set()
|
|
126
|
+
stack = [r for r in roots if r not in seen]
|
|
127
|
+
while stack:
|
|
128
|
+
e = stack.pop()
|
|
129
|
+
if e in seen:
|
|
130
|
+
continue
|
|
131
|
+
seen.add(e)
|
|
132
|
+
consts, kids = ex.exprs.get(e, ((), ()))
|
|
133
|
+
for c in consts:
|
|
134
|
+
out.add(ex.names[c])
|
|
135
|
+
stack.extend(k for k in kids if k not in seen)
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def literal(comps: tuple) -> str | None:
|
|
140
|
+
"""A name literal `leanexport` decodes back to these components, or None if there is none."""
|
|
141
|
+
parts = []
|
|
142
|
+
for c in comps:
|
|
143
|
+
if not isinstance(c, str) or "»" in c or not c:
|
|
144
|
+
return None
|
|
145
|
+
parts.append(f"«{c}»") # always escaped: `leanexport` decodes «x» as x
|
|
146
|
+
return ".".join(parts)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def find_forbidden(ex: Export, theorem: str, prefixes: list[str], exact: list[str], scope: str,
|
|
150
|
+
classify) -> list[dict]:
|
|
151
|
+
"""[{constant, via}] for the theorem `theorem` in `ex`. `classify(names) -> set of library names`
|
|
152
|
+
is called with batches of names not yet known to be library or local (scope `solution` only)."""
|
|
153
|
+
root = tuple(theorem.split("."))
|
|
154
|
+
if root not in ex.decls:
|
|
155
|
+
raise ExportError(f"{theorem} is not in the Solution's export")
|
|
156
|
+
rtypes, rvalues, _ = ex.decls[root]
|
|
157
|
+
statement = _refs(ex, rtypes, set())
|
|
158
|
+
seen_exprs: set[int] = set()
|
|
159
|
+
parent: dict[tuple, tuple] = {}
|
|
160
|
+
local: set[tuple] = {root}
|
|
161
|
+
library: set[tuple] = set()
|
|
162
|
+
frontier = [root]
|
|
163
|
+
reached: dict[tuple, tuple] = {} # constant -> the local constant that mentions it
|
|
164
|
+
while frontier:
|
|
165
|
+
found: set[tuple] = set()
|
|
166
|
+
for c in frontier:
|
|
167
|
+
types, values, extra = ex.decls.get(c, ((), (), ()))
|
|
168
|
+
refs = _refs(ex, values if c == root else types + values, seen_exprs)
|
|
169
|
+
refs |= {ex.names[x] for x in extra}
|
|
170
|
+
for r in refs:
|
|
171
|
+
if r not in reached and r != c:
|
|
172
|
+
reached[r] = c
|
|
173
|
+
found.add(r)
|
|
174
|
+
unknown = {r for r in found if r not in local and r not in library and r in ex.decls}
|
|
175
|
+
if scope == "all":
|
|
176
|
+
new_local = unknown
|
|
177
|
+
else:
|
|
178
|
+
new_local = unknown - classify(unknown)
|
|
179
|
+
library |= unknown - new_local
|
|
180
|
+
for r in new_local:
|
|
181
|
+
parent[r] = reached[r]
|
|
182
|
+
local |= new_local
|
|
183
|
+
frontier = sorted(new_local)
|
|
184
|
+
hits = []
|
|
185
|
+
for r, by in sorted(reached.items()):
|
|
186
|
+
name = ex.text(r)
|
|
187
|
+
if r in statement or not match(name, prefixes, exact):
|
|
188
|
+
continue
|
|
189
|
+
chain, x = [], by
|
|
190
|
+
while x != root:
|
|
191
|
+
chain.append(ex.text(x))
|
|
192
|
+
x = parent[x]
|
|
193
|
+
hits.append({"constant": name, "via": chain[::-1]})
|
|
194
|
+
return hits
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def private_module(comps: tuple) -> str | None:
|
|
198
|
+
"""`_private.Mod.Sub.0.x` -> "Mod.Sub" (a private name carries its module)."""
|
|
199
|
+
if not comps or comps[0] != "_private":
|
|
200
|
+
return None
|
|
201
|
+
mod = []
|
|
202
|
+
for c in comps[1:]:
|
|
203
|
+
if not isinstance(c, str):
|
|
204
|
+
return ".".join(mod)
|
|
205
|
+
mod.append(c)
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
210
|
+
# Running leanexport (sandboxed unless the run is a self-check)
|
|
211
|
+
|
|
212
|
+
def bwrap_args(readable: list[pathlib.Path], env: dict[str, str], cwd: pathlib.Path) -> list[str]:
|
|
213
|
+
"""The bwrap command line `lake comparator` uses for its exporter: `/` read-only, the home
|
|
214
|
+
directories, /tmp, /run and /var covered, `readable` bound back read-only, nothing writable, no
|
|
215
|
+
network, a cleared environment."""
|
|
216
|
+
bw = os.environ.get("COMPARATOR_BWRAP") or shutil.which("bwrap") or "bwrap"
|
|
217
|
+
args = [bw, "--ro-bind", "/", "/", "--tmpfs", "/home", "--tmpfs", "/root", "--tmpfs", "/run/user",
|
|
218
|
+
"--tmpfs", "/tmp", "--dir", "/tmp/home", "--dev", "/dev", "--proc", "/proc", "--clearenv",
|
|
219
|
+
"--tmpfs", "/run", "--tmpfs", "/var"]
|
|
220
|
+
for p in dict.fromkeys(str(x) for x in readable):
|
|
221
|
+
args += ["--ro-bind", p, p]
|
|
222
|
+
for k, v in env.items():
|
|
223
|
+
args += ["--setenv", k, v]
|
|
224
|
+
return args + ["--setenv", "HOME", "/tmp/home", "--unshare-all", "--die-with-parent", "--new-session",
|
|
225
|
+
"--chdir", str(cwd), "--"]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def run_export(prefix: pathlib.Path, lean_path: list[pathlib.Path], readable: list[pathlib.Path],
|
|
229
|
+
cwd: pathlib.Path, modules: list[str], names: list[str], out: pathlib.Path, sandboxed: bool,
|
|
230
|
+
timeout: float, ignore_missing: bool = False) -> None:
|
|
231
|
+
exe = prefix / "bin" / "leanexport"
|
|
232
|
+
env = {"PATH": f"{prefix / 'bin'}:/usr/bin:/bin", "LEAN_PATH": os.pathsep.join(map(str, lean_path)),
|
|
233
|
+
"LEAN_ABORT_ON_PANIC": "1"}
|
|
234
|
+
cmd = [str(exe)] + modules + ["--"] + names + (["--ignore-missing"] if ignore_missing else [])
|
|
235
|
+
if sandboxed:
|
|
236
|
+
cmd = bwrap_args([prefix, cwd] + readable, env, cwd) + cmd
|
|
237
|
+
run_env = {}
|
|
238
|
+
else:
|
|
239
|
+
run_env = {**os.environ, **env}
|
|
240
|
+
try:
|
|
241
|
+
with open(out, "wb") as f:
|
|
242
|
+
p = subprocess.run(cmd, cwd=cwd, env=run_env, stdin=subprocess.DEVNULL, stdout=f,
|
|
243
|
+
stderr=subprocess.PIPE, timeout=timeout, start_new_session=True)
|
|
244
|
+
except subprocess.TimeoutExpired:
|
|
245
|
+
raise ExportError("leanexport did not finish in time (--timeout)") from None
|
|
246
|
+
except OSError as e:
|
|
247
|
+
raise ExportError(f"cannot run leanexport: {e}") from None
|
|
248
|
+
if p.returncode != 0:
|
|
249
|
+
tail = p.stderr.decode("utf-8", "replace").strip().splitlines()[-1:] or [f"exit {p.returncode}"]
|
|
250
|
+
raise ExportError(f"leanexport failed: {tail[0][:300]}")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def library_classifier(prefix, lean_path, readable, cwd, imports: list[str], solution_module: str,
|
|
254
|
+
scratch: pathlib.Path, sandboxed: bool, timeout: float):
|
|
255
|
+
"""classify(names) -> the subset declared in the environment of `imports` (the Solution's own imports,
|
|
256
|
+
plus Init), found by exporting those names from that environment with --ignore-missing."""
|
|
257
|
+
modules = list(dict.fromkeys(["Init"] + imports))
|
|
258
|
+
calls = [0]
|
|
259
|
+
|
|
260
|
+
def classify(names: set[tuple]) -> set[tuple]:
|
|
261
|
+
lib: set[tuple] = set()
|
|
262
|
+
ask: dict[str, tuple] = {}
|
|
263
|
+
for n in names:
|
|
264
|
+
mod = private_module(n)
|
|
265
|
+
if mod is not None:
|
|
266
|
+
if mod != solution_module:
|
|
267
|
+
lib.add(n)
|
|
268
|
+
continue
|
|
269
|
+
lit = literal(n)
|
|
270
|
+
if lit is not None: # a name with no literal stays local: walked, not trusted
|
|
271
|
+
ask[lit] = n
|
|
272
|
+
batch: list[str] = []
|
|
273
|
+
size = 0
|
|
274
|
+
lits = sorted(ask)
|
|
275
|
+
for i, lit in enumerate(lits):
|
|
276
|
+
batch.append(lit)
|
|
277
|
+
size += len(lit) + 1
|
|
278
|
+
if size >= NAME_CHUNK or i == len(lits) - 1:
|
|
279
|
+
calls[0] += 1
|
|
280
|
+
out = scratch / f"library-{calls[0]}.ndjson"
|
|
281
|
+
run_export(prefix, lean_path, readable, cwd, modules, batch, out, sandboxed, timeout,
|
|
282
|
+
ignore_missing=True)
|
|
283
|
+
found = set(read_export(out, with_exprs=False).decls)
|
|
284
|
+
out.unlink()
|
|
285
|
+
lib |= {ask[x] for x in batch if ask[x] in found}
|
|
286
|
+
batch, size = [], 0
|
|
287
|
+
return lib
|
|
288
|
+
return classify
|
lean_pkg/export_paths.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# lean-pkg export_paths -- path and link safety rules shared by every export of a tree
|
|
2
|
+
"""The path rules `release --fresh-repo` and `lean-pkg-extract` share.
|
|
3
|
+
|
|
4
|
+
- `excluded_from_export(rel)`: why a path never leaves the source (the private patterns file and the
|
|
5
|
+
internal paths `public-safety` knows: approvals/, notes/, drafts/, scratch/, *.priv, *.private).
|
|
6
|
+
- `fs_link_leaves_tree(path, root)`: a symlink on disk that is absolute or resolves outside the
|
|
7
|
+
tree (followed through the filesystem; `release --fresh-repo --from-tree`).
|
|
8
|
+
- `link_target(link_rel, target)`: the same question asked of a symlink stored in a git tree,
|
|
9
|
+
answered lexically (nothing on disk is followed): the target as a repository-relative path, or
|
|
10
|
+
why it cannot be one.
|
|
11
|
+
- `bad_rel_path(p)`: why a manifest path is not a plain repository-relative POSIX path.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import pathlib
|
|
18
|
+
import posixpath
|
|
19
|
+
|
|
20
|
+
from . import public_safety as ps
|
|
21
|
+
|
|
22
|
+
RECEIPTS_DIR = ".lean-receipts"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def excluded_from_export(rel: str) -> str | None:
|
|
26
|
+
"""Why a path is dropped from a fresh-history export, else None."""
|
|
27
|
+
if rel == ps.PATTERNS_FILE or rel.endswith("/" + ps.PATTERNS_FILE):
|
|
28
|
+
return "patterns file"
|
|
29
|
+
return ps.internal_path(rel)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def is_receipts_path(rel: str) -> bool:
|
|
33
|
+
return RECEIPTS_DIR in pathlib.PurePosixPath(rel).parts
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fs_link_leaves_tree(path: pathlib.Path, root: pathlib.Path) -> bool:
|
|
37
|
+
"""True when the symlink at `path` is absolute or its real path lies outside `root`'s."""
|
|
38
|
+
real_root = os.path.realpath(root)
|
|
39
|
+
real = os.path.realpath(path)
|
|
40
|
+
return os.path.isabs(os.readlink(path)) or not (real == real_root or real.startswith(real_root + os.sep))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def bad_rel_path(p, allow_dot: bool = False) -> str | None:
|
|
44
|
+
"""Why `p` is not a plain repository-relative POSIX path (no `..`, no `.` segment unless the whole
|
|
45
|
+
path is `.` and allow_dot, no empty segment, no trailing `/`, no backslash, not absolute), else None."""
|
|
46
|
+
if not isinstance(p, str) or not p:
|
|
47
|
+
return "must be a non-empty string"
|
|
48
|
+
if p == ".":
|
|
49
|
+
return None if allow_dot else "must name a path, not `.`"
|
|
50
|
+
if p.startswith("/") or (len(p) > 1 and p[1] == ":"):
|
|
51
|
+
return "must be relative, not absolute"
|
|
52
|
+
if "\\" in p or "\0" in p:
|
|
53
|
+
return "must use `/` separators (no backslash or NUL)"
|
|
54
|
+
parts = p.split("/")
|
|
55
|
+
if ".." in parts:
|
|
56
|
+
return "must not contain `..` (path traversal)"
|
|
57
|
+
if any(s in ("", ".") for s in parts):
|
|
58
|
+
return "must be normalized (no empty or `.` segment, no trailing `/`)"
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def link_target(link_rel: str, target: str) -> tuple[str | None, str | None]:
|
|
63
|
+
"""(repository-relative target, None) for a stored symlink at `link_rel` pointing at `target`, or
|
|
64
|
+
(None, why) when the target is absolute or climbs out of the repository."""
|
|
65
|
+
if not target:
|
|
66
|
+
return None, "empty symlink target"
|
|
67
|
+
if target.startswith("/"):
|
|
68
|
+
return None, f"absolute symlink target {target!r}"
|
|
69
|
+
joined = posixpath.normpath(posixpath.join(posixpath.dirname(link_rel), target))
|
|
70
|
+
if joined == ".." or joined.startswith("../"):
|
|
71
|
+
return None, f"symlink target {target!r} leaves the repository"
|
|
72
|
+
return joined, None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def under(path: str, root: str) -> bool:
|
|
76
|
+
"""`path` is `root` or lies below it (`.` contains everything)."""
|
|
77
|
+
return root == "." or path == root or path.startswith(root + "/")
|