lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/fresh_repo.py ADDED
@@ -0,0 +1,709 @@
1
+ # lean-pkg release --fresh-repo -- a single-commit public export of a package's gated tree
2
+ """`lean-pkg release NAME --fresh-repo DIR [--remote URL] [--keep-receipts] [--source-commit SHA]
3
+ [--dry-run]` (#35): when a package's history cannot be published (it was incubated beside private
4
+ material), export its current gated tree into a NEW repository with one commit, and move the
5
+ registry entry there.
6
+
7
+ 1. The source is the commit the recorded gate receipt binds (or --source-commit SHA).
8
+ 2. `git archive` of that commit (the package directory only) is unpacked into a staging directory
9
+ beside DIR, dropping the `.lean-pkg-private-patterns` file, the internal-file paths of
10
+ `public-safety` (approvals/, notes/, drafts/, scratch/, *.priv, *.private) and `.lean-receipts/`
11
+ (copied from the source checkout's HEAD only with --keep-receipts). Every dropped path is listed.
12
+ 3. The staged tree, the commit message and the commit identity are scanned with the package's
13
+ public-safety patterns; any blocking hit refuses, and nothing is written. The patterns file's
14
+ `allow:` lines that scan used, and only those, are carried into a committed
15
+ `.lean-pkg-public-allow` (#340); none used, no file.
16
+ 4. The staging directory becomes DIR: `git init`, one commit whose message records the source
17
+ commit and the export date, an optional `origin` remote. Its author and committer are explicit
18
+ (#339): --author 'NAME <EMAIL>', else the source repository's local user.name/user.email, never
19
+ the global identity; an address that is not a GitHub noreply one needs --allow-author-email.
20
+ 5. The registry entry is relocated with the `update NAME --path DIR` machinery (reason
21
+ "fresh-history release"): the gate and comparator evidence, bound to the source commit, is
22
+ cleared (verified-private becomes gate-pending), and a dated note keeps the old receipt paths and
23
+ the source commit for provenance. --remote also sets the record's `repo`.
24
+
25
+ Kept receipts do not bind to the new commit: the gate and the comparator must be re-run on it.
26
+ --dry-run stages and scans in a temporary directory, prints the plan, and writes nothing.
27
+
28
+ `--fresh-repo DIR --from-tree SRCDIR` (#37) exports the working tree at SRCDIR instead of a commit:
29
+ a tree cleaned by hand (files removed or edited) that is not a commit of the source repository. In a
30
+ git checkout the files are those `git ls-files --cached --others --exclude-standard` lists (the
31
+ source's .gitignore applies); otherwise every file but `.git/` and `.lake/`. Same exclusions, same
32
+ scan (the commit message too, since it names SRCDIR's basename), same single commit; its message
33
+ records "source commit: none (hand-cleaned tree)" and the registry's gate-bound commit, if any, for
34
+ provenance.
35
+
36
+ `release NAME --adopt-repo DIR [--remote URL] [--allow-history] [--dry-run]` (#37) adopts an
37
+ existing repository that already is the intended public history: refused unless it has exactly one
38
+ commit on all refs (or --allow-history), unless DIR is its top directory, while tracked files are
39
+ modified, and on any blocking public-safety hit in its tree or full history. No export and no new
40
+ commit: the registry entry is relocated to DIR as above, with a dated note naming the adopted commit
41
+ and the previous gate-bound commit.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import os
47
+ import pathlib
48
+ import re
49
+ import shutil
50
+ import subprocess
51
+ import tarfile
52
+ import tempfile
53
+
54
+ from . import cli, gate as gate_mod
55
+ from . import core
56
+ from . import export_paths as xp
57
+ from . import public_safety as ps
58
+
59
+ DEFAULT_REASON = "fresh-history release"
60
+ BRANCH = "main"
61
+ NOT_FROM = ("public", "upstreamed", "archived")
62
+
63
+
64
+ def _archive(repo: pathlib.Path, treeish: str) -> bytes:
65
+ p = subprocess.run(["git", "-C", str(repo), "archive", "--format=tar", treeish], capture_output=True,
66
+ env=core.scrubbed_env(), check=False)
67
+ if p.returncode != 0:
68
+ raise core.Fail(f"git archive {treeish} failed: "
69
+ f"{p.stderr.decode('utf-8', 'replace').strip()[:200]}")
70
+ return p.stdout
71
+
72
+
73
+ def _extract(data: bytes, dest: pathlib.Path, drop) -> list[dict]:
74
+ """Unpack a tar stream into dest, skipping members drop(name) names a reason for; the dropped
75
+ files, as [{path, reason}]."""
76
+ import io
77
+ dropped: list[dict] = []
78
+ with tarfile.open(fileobj=io.BytesIO(data)) as tf:
79
+ keep = []
80
+ for m in tf.getmembers():
81
+ name = m.name.removeprefix("./")
82
+ if not name or name == "pax_global_header":
83
+ continue
84
+ why = drop(name)
85
+ if why:
86
+ if not m.isdir():
87
+ dropped.append({"path": name, "reason": why})
88
+ continue
89
+ keep.append(m)
90
+ try:
91
+ tf.extractall(dest, members=keep, filter="data")
92
+ except TypeError: # a Python without extraction filters: refuse anything outside dest
93
+ for m in keep:
94
+ if os.path.isabs(m.name) or ".." in pathlib.PurePosixPath(m.name).parts or m.issym() \
95
+ or m.islnk():
96
+ raise core.Fail(f"refusing to unpack {m.name!r} (link or path outside the export)") from None
97
+ tf.extractall(dest, members=keep)
98
+ return dropped
99
+
100
+
101
+ def drop_reason(name: str, keep_receipts: bool) -> str | None:
102
+ why = xp.excluded_from_export(name)
103
+ if why:
104
+ return why
105
+ if name == ".lean-receipts" or name.startswith(".lean-receipts/"):
106
+ return None if keep_receipts else ".lean-receipts/ (not copied without --keep-receipts)"
107
+ return None
108
+
109
+
110
+ SKIP_DIRS = (".git", ".lake")
111
+
112
+
113
+ def tree_listing(srcdir: pathlib.Path) -> tuple[list[str], str]:
114
+ """(SRCDIR-relative paths to export, how they were listed): git's view of the working tree
115
+ (tracked + untracked, .gitignore honoured) in a checkout, else a walk; `.git/` and `.lake/`
116
+ never."""
117
+ p = core.git(srcdir, "rev-parse", "--is-inside-work-tree")
118
+ if p.returncode == 0 and p.stdout.strip() == "true":
119
+ ls = core.git(srcdir, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
120
+ if ls.returncode != 0:
121
+ raise core.Fail(f"git ls-files in {srcdir} failed: {(ls.stderr or '').strip()[:200]}")
122
+ files = sorted({x for x in ls.stdout.split("\0") if x})
123
+ how = "git ls-files --cached --others --exclude-standard"
124
+ else:
125
+ files = []
126
+ for d, dirs, names in os.walk(srcdir):
127
+ dirs[:] = sorted(x for x in dirs if x not in SKIP_DIRS)
128
+ files += [os.path.relpath(os.path.join(d, nm), srcdir).replace(os.sep, "/") for nm in names]
129
+ files.sort()
130
+ how = "every file (not a git checkout)"
131
+ return [f for f in files if not set(pathlib.PurePosixPath(f).parts) & set(SKIP_DIRS)], how
132
+
133
+
134
+ def _copy_tree(srcdir: pathlib.Path, dest: pathlib.Path, files: list[str], drop) -> list[dict]:
135
+ """Copy the listed files from srcdir into dest, skipping those drop(name) names a reason for;
136
+ a symlink is kept only when it is relative and stays inside the tree. The dropped files, as
137
+ [{path, reason}]."""
138
+ dropped: list[dict] = []
139
+ for rel in files:
140
+ why = drop(rel)
141
+ src = srcdir / rel
142
+ if not why and src.is_symlink():
143
+ if xp.fs_link_leaves_tree(src, srcdir):
144
+ why = "symlink leaving the tree (not exported)"
145
+ elif not why and src.is_dir():
146
+ why = "submodule or nested repository (not exported)"
147
+ if why:
148
+ dropped.append({"path": rel, "reason": why})
149
+ continue
150
+ if not src.is_symlink() and not src.is_file():
151
+ continue # tracked but deleted in the working tree
152
+ out = dest / rel
153
+ out.parent.mkdir(parents=True, exist_ok=True)
154
+ if src.is_symlink():
155
+ os.symlink(os.readlink(src), out)
156
+ else:
157
+ shutil.copy2(src, out)
158
+ return dropped
159
+
160
+
161
+ def gate_bound_commit(pkg: dict, repo: pathlib.Path) -> str | None:
162
+ """The commit the recorded gate receipt binds, when it can be read; provenance only."""
163
+ rel = (pkg.get("gate") or {}).get("receipt")
164
+ rec = gate_mod.recorded_json(repo, rel) if rel and repo.is_dir() else None
165
+ sha = str((rec or {}).get("commit") or "")
166
+ return sha if core._HEX40.fullmatch(sha) else None
167
+
168
+
169
+ def patterns_root(repo: pathlib.Path, fallback: pathlib.Path) -> pathlib.Path:
170
+ """The package checkout's patterns file applies when it has one; else the given directory's."""
171
+ return repo if (repo / ps.PATTERNS_FILE).is_file() else fallback
172
+
173
+
174
+ def source_commit(pkg: dict, repo: pathlib.Path, given: str | None) -> tuple[str, str]:
175
+ """(40-hex commit, how it was chosen)."""
176
+ name = pkg["name"]
177
+ if given:
178
+ sha = core._rev(repo, given)
179
+ if not sha:
180
+ raise core.Fail(f"{name}: --source-commit {given!r} is not a commit of {repo}")
181
+ return sha, "--source-commit"
182
+ rel = (pkg.get("gate") or {}).get("receipt")
183
+ rec = gate_mod.recorded_json(repo, rel) if rel else None
184
+ sha = str((rec or {}).get("commit") or "")
185
+ if not rel:
186
+ raise core.Fail(f"{name}: no gate receipt recorded, so there is no gate-bound commit to export; "
187
+ f"pass --source-commit SHA")
188
+ if not core._HEX40.fullmatch(sha):
189
+ raise core.Fail(f"{name}: the gate receipt {rel} is unreadable or names no commit; pass --source-commit SHA")
190
+ if not core._rev(repo, sha):
191
+ raise core.Fail(f"{name}: the gate-bound commit {sha[:12]} is not in {repo}; pass --source-commit SHA")
192
+ return sha, f"gate receipt {rel}"
193
+
194
+
195
+ # #339: the export commit is public history, so its identity is set explicitly, never git's ambient one.
196
+ NOREPLY_RE = ps.NOREPLY_EMAIL_RE
197
+ _IDENT_RE = re.compile(r"\s*([^<>]*?)\s*<([^<>\s]+@[^<>\s]+)>\s*")
198
+ AUTHOR_HINT = "--author 'NAME <ID+LOGIN@users.noreply.github.com>'"
199
+
200
+
201
+ def noreply_email(email: str) -> bool:
202
+ """A GitHub noreply address: `ID+LOGIN@users.noreply.github.com` or `LOGIN@users.noreply.github.com`."""
203
+ return NOREPLY_RE.fullmatch(email.strip()) is not None
204
+
205
+
206
+ def parse_identity(text: str) -> tuple[str, str]:
207
+ m = _IDENT_RE.fullmatch(text or "")
208
+ if not m or not m.group(1):
209
+ raise core.UsageError(f"--author {text!r}: give a name and an address, {AUTHOR_HINT}")
210
+ return m.group(1), m.group(2)
211
+
212
+
213
+ def local_identity(repo: pathlib.Path) -> tuple[str, str] | None:
214
+ """(user.name, user.email) of the repository's own (`--local`) git config when both are set; the
215
+ global and system identities are never read."""
216
+ got = []
217
+ for key in ("user.name", "user.email"):
218
+ p = core.git(repo, "config", "--local", "--get", key)
219
+ if p.returncode != 0 or not p.stdout.strip():
220
+ return None
221
+ got.append(p.stdout.strip())
222
+ return got[0], got[1]
223
+
224
+
225
+ def export_identity(name: str, given: str | None, sources: list[pathlib.Path], allow_email: bool) -> dict:
226
+ """#339: the author and committer of the export commit: --author, else the source repository's local
227
+ git config (user.name, user.email); never the global identity. Refused when there is none, and when
228
+ the address is not a GitHub noreply one unless --allow-author-email: the commit is public history."""
229
+ if given is not None:
230
+ ident, how = parse_identity(given), "--author"
231
+ else:
232
+ ident = how = None
233
+ for src in sources:
234
+ if src is not None and src.is_dir():
235
+ ident = local_identity(src)
236
+ if ident:
237
+ how = "the source repository's local git config (user.name, user.email)"
238
+ break
239
+ if ident is None:
240
+ raise core.Fail(f"{name}: repo export: no identity for the export commit: pass {AUTHOR_HINT}, or set "
241
+ f"user.name and user.email in the source repository's local git config (git -C SRC "
242
+ f"config user.email ...); the global git identity is never used, since this commit "
243
+ f"is public history; nothing written")
244
+ full = f"{ident[0]} <{ident[1]}>"
245
+ nr = noreply_email(ident[1])
246
+ if not nr and not allow_email:
247
+ raise core.Fail(f"{name}: repo export: the export commit's author and committer email {ident[1]} (from "
248
+ f"{how}) is not a GitHub noreply address, and the commit is public history: pass "
249
+ f"{AUTHOR_HINT}, or --allow-author-email to publish this address; nothing written")
250
+ return {"author": full, "committer": full, "name": ident[0], "email": ident[1], "source": how, "noreply": nr}
251
+
252
+
253
+ def export_identity_hits(sc: "ps.Scanner", identities: list[tuple[str, str]]) -> list[dict]:
254
+ """The blocking public-safety hits in the author and committer identity the export commit will
255
+ carry (published with it). As for any commit identity: an ordinary mail address is declared by being
256
+ used; a host-like one (`user@hostname`, a local TLD such as `.lan`) is a hit unless consent or an
257
+ `allow:` line names it; every pattern applies to the name and the address."""
258
+ out: list[dict] = []
259
+ for nm, email in dict.fromkeys(identities):
260
+ out += [ps._hit(sc, "tree", "export-commit-identity", None, pat.label, pat.kind, ex, severity=pat.severity)
261
+ for _n, pat, ex in sc.identity_hits(nm, email) if pat.severity == ps.BLOCK]
262
+ return out
263
+
264
+
265
+ def carry_public_allow(name: str, pkg: dict, pat_root: pathlib.Path, email_repo: pathlib.Path,
266
+ stage: pathlib.Path, today: str, used: set[int]) -> dict:
267
+ """#6, #340: the patterns file is dropped (it lists private strings), so the `allow:` lines the export's
268
+ own scan used would be lost and the new repository's own public-safety would report what the export
269
+ scan allowed. Carry ONLY the allow lines that scan used (`used`: line numbers) into the committed
270
+ `.lean-pkg-public-allow` (merged with one the tree already has); never a block/warn line, never an
271
+ unused allow line (an allow pattern names what it allows, so an unused one can still leak, and it
272
+ allows nothing). None used: no file is written. A carried line a private block pattern (the patterns
273
+ file's, a registry-derived name) matches refuses the export: publishing it would publish the private
274
+ string."""
275
+ every = ps.allow_lines(pat_root)
276
+ lines = [(n, t) for n, t in every if n in used]
277
+ view = {"file": None, "carried": 0, "lines": [], "unused": len(every) - len(lines), "present": 0}
278
+ if not lines:
279
+ return view
280
+ sc = ps.Scanner(pkg, pat_root, email_repo)
281
+ bad = [(n, labels) for n, t in lines for labels in [ps.private_matches(sc, t)] if labels]
282
+ if bad:
283
+ raise core.Fail(f"{name}: allow line(s) {', '.join(str(n) for n, _l in bad)} of {ps.PATTERNS_FILE} hold a "
284
+ f"private string (" + "; ".join(f"line {n}: {', '.join(lab)}" for n, lab in bad)
285
+ + f"), so they cannot be carried into the public {ps.PUBLIC_ALLOW_FILE}; nothing written. "
286
+ f"Rewrite each without the private string (a narrower regex, or a path scope "
287
+ f"`allow: GLOB: REGEX`), then re-run")
288
+ dest = stage / ps.PUBLIC_ALLOW_FILE
289
+ if dest.is_symlink():
290
+ raise core.Fail(f"{name}: the exported {ps.PUBLIC_ALLOW_FILE} is a symbolic link; refusing to write "
291
+ f"through it; nothing written")
292
+ existing = dest.read_text(encoding="utf-8").splitlines() if dest.is_file() else []
293
+ have = {x.strip() for x in existing}
294
+ new = []
295
+ for n, t in lines:
296
+ if t not in have:
297
+ have.add(t)
298
+ new.append((n, t))
299
+ view["present"] = len(lines) - len(new)
300
+ if not new:
301
+ return dict(view, file=ps.PUBLIC_ALLOW_FILE)
302
+ head = [] if existing else [
303
+ "# lean-pkg public allow list: `allow:` lines only (public-safety reads them; block and warn lines",
304
+ f"# belong in the untracked {ps.PATTERNS_FILE}). Committed on purpose: nothing here is private."]
305
+ body = existing + head + [f"# carried from {ps.PATTERNS_FILE} by `lean-pkg repo export` ({today})"]
306
+ dest.write_text("\n".join(body + [t for _n, t in new]) + "\n", encoding="utf-8")
307
+ return dict(view, file=ps.PUBLIC_ALLOW_FILE, carried=len(new), lines=[n for n, _t in new])
308
+
309
+
310
+ def _commit_as(target: pathlib.Path, ident: dict, args: tuple) -> subprocess.CompletedProcess:
311
+ """git commit in target with the export identity as author and committer (#339): the environment
312
+ variables take precedence over every git config, so no ambient identity can reach the commit."""
313
+ env = dict(core.scrubbed_env(), GIT_AUTHOR_NAME=ident["name"], GIT_AUTHOR_EMAIL=ident["email"],
314
+ GIT_COMMITTER_NAME=ident["name"], GIT_COMMITTER_EMAIL=ident["email"])
315
+ return subprocess.run(["git", "-C", str(target), *args], capture_output=True, text=True, check=False, env=env)
316
+
317
+
318
+ def commit_message(src: str, today: str) -> str:
319
+ return (f"fresh-history export of {src[:12]}; receipts and gate must be re-run on this commit\n\n"
320
+ f"source commit: {src}\nexport date: {today}\n")
321
+
322
+
323
+ def tree_commit_message(srcdir: pathlib.Path, provenance: str | None, today: str) -> str:
324
+ return (f"fresh-history export of working tree {srcdir.name}; receipts and gate must be re-run on "
325
+ f"this commit\n\nsource commit: none (hand-cleaned tree)\n"
326
+ f"source package commit for provenance: {provenance or 'none'}\nexport date: {today}\n")
327
+
328
+
329
+ def next_commands(name: str, target: pathlib.Path, new12: str, remote: str | None,
330
+ needs_gate_pending: bool) -> list[str]:
331
+ cmds = [f"lean-pkg public-safety {name} # the new repository: its tree and its one commit"]
332
+ if remote:
333
+ cmds.append(f"git -C {target} push -u origin {BRANCH}")
334
+ if needs_gate_pending:
335
+ cmds.append(f"lean-pkg update {name} --status gate-pending --reason 'check job submitted' "
336
+ f"# gate needs gate-pending")
337
+ cmds += [f"lean-pkg gate {name} --receipt R # R: a lower-tier receipt bound to {new12}",
338
+ f"comparator-receipt --repo {target} --prepare",
339
+ f"comparator-receipt --repo {target} # on a host its policy allows",
340
+ f"lean-pkg comparator {name} --receipt .lean-receipts/{new12}-comparator.json",
341
+ f"lean-pkg publish {name} --dry-run --public-safety",
342
+ f"lean-pkg publish {name} --yes --dry-run"]
343
+ return cmds
344
+
345
+
346
+ def do_fresh_repo(reg_path, reg, events_p, name, *, target_arg, remote, keep_receipts, given_commit,
347
+ agent, reason, dry_run, from_tree=None, author=None,
348
+ allow_author_email=False) -> tuple[list[str], int, dict]:
349
+ pkg = core.get_pkg(reg, name)
350
+ status = pkg.get("status")
351
+ if status in NOT_FROM:
352
+ raise core.Fail(f"{name}: status {status}: a fresh-history export is for a package that has not been "
353
+ f"promoted (a public history is already exposed; an archived package is not published)")
354
+ repo = core.repo_path(pkg)
355
+ srcdir = src_stored = None
356
+ if from_tree is None:
357
+ if not repo.is_dir() or core.git_head(repo) is None:
358
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
359
+ else:
360
+ src_stored, _k = core.normalize_local_path(from_tree, "--from-tree")
361
+ srcdir = core.HOME / pathlib.Path(src_stored)
362
+ if not srcdir.is_dir():
363
+ raise core.Fail(f"{name}: --from-tree {srcdir} is not a directory")
364
+ if remote is not None:
365
+ core.require_nonempty("--remote", remote)
366
+ reason = reason or DEFAULT_REASON
367
+ if srcdir is None:
368
+ src, chosen = source_commit(pkg, repo, given_commit)
369
+ provenance = None
370
+ else:
371
+ src, chosen = None, f"working tree {srcdir}"
372
+ provenance = gate_bound_commit(pkg, repo)
373
+ stored, _key = core.normalize_local_path(target_arg, "repo export DIR")
374
+ target = core.HOME / pathlib.Path(stored)
375
+ if target.exists() and (not target.is_dir() or any(target.iterdir())):
376
+ raise core.Fail(f"{name}: repo export: DIR {target} exists and is not an empty directory; refusing")
377
+ tops = []
378
+ if repo.is_dir() and core.git_head(repo) is not None:
379
+ tops.append(("the source repository", core.git(repo, "rev-parse", "--show-toplevel").stdout.strip()))
380
+ if srcdir is not None:
381
+ tops.append(("--from-tree", os.path.realpath(srcdir)))
382
+ for what, top in tops:
383
+ if top and (os.path.realpath(target) == top or pathlib.Path(top) in pathlib.Path(os.path.realpath(target)).parents):
384
+ raise core.Fail(f"{name}: repo export: DIR {target} lies inside {what} {top}; choose a "
385
+ f"directory outside it")
386
+ # #339: an explicit identity, checked before anything is staged (a dry run predicts the refusal too)
387
+ ident = export_identity(name, author, [srcdir, repo] if srcdir is not None else [repo], allow_author_email)
388
+ # the relocation's own refusals (lease, another package's path), before anything is written
389
+ _o, preview = cli.do_relocate(reg_path, reg, events_p, name, new_path=stored, reason=reason,
390
+ agent=agent, redetect=False, dry_run=True)
391
+
392
+ if dry_run:
393
+ stage = pathlib.Path(tempfile.mkdtemp(prefix="lean-pkg-export-"))
394
+ else:
395
+ target.parent.mkdir(parents=True, exist_ok=True)
396
+ stage = pathlib.Path(tempfile.mkdtemp(prefix=".lean-pkg-export-", dir=target.parent))
397
+ moved = False
398
+ try:
399
+ receipts_note = listed = None
400
+ if srcdir is None:
401
+ prefix = core.git(repo, "rev-parse", "--show-prefix").stdout.strip()
402
+ treeish = f"{src}:{prefix.rstrip('/')}" if prefix else src
403
+ dropped = _extract(_archive(repo, treeish), stage, lambda n: drop_reason(n, keep_receipts))
404
+ if keep_receipts:
405
+ rel = f"{prefix}.lean-receipts"
406
+ if core.tracked_at(repo, ".lean-receipts"):
407
+ (stage / ".lean-receipts").mkdir(exist_ok=True)
408
+ _extract(_archive(repo, f"HEAD:{rel}"), stage / ".lean-receipts", lambda n: None)
409
+ receipts_note = (f".lean-receipts/ copied from the source HEAD: bound to {src[:12]} or "
410
+ f"earlier, they do NOT bind to the new commit")
411
+ else:
412
+ receipts_note = "--keep-receipts: no .lean-receipts/ tracked at the source HEAD; nothing copied"
413
+ pat_root, email_repo = repo, repo
414
+ else:
415
+ paths, listed = tree_listing(srcdir)
416
+ dropped = _copy_tree(srcdir, stage, paths, lambda n: drop_reason(n, keep_receipts))
417
+ if keep_receipts:
418
+ receipts_note = (".lean-receipts/ kept from the working tree: they do NOT bind to the new commit"
419
+ if (stage / ".lean-receipts").is_dir()
420
+ else "--keep-receipts: no .lean-receipts/ in the working tree; nothing copied")
421
+ pat_root = patterns_root(repo, srcdir)
422
+ email_repo = repo if repo.is_dir() and core.git_head(repo) else srcdir
423
+ files = sum(1 for _ in (p for p in stage.rglob("*") if p.is_file() or p.is_symlink()))
424
+ if not files:
425
+ raise core.Fail(f"{name}: nothing to export from {srcdir or src[:12]} (every file is excluded or "
426
+ f"ignored); nothing written")
427
+ today = core.utc_today()
428
+ # the export's own scan: the staged tree, the commit message and the commit identity (all of it is
429
+ # published); it also records which allow lines of the patterns file it used (#340)
430
+ used: set[int] = set()
431
+ result = ps.scan(pkg, stage, export=True, patterns_root=pat_root, source_repo=email_repo,
432
+ public_allow_root=stage, used_allow=used)
433
+ blocking = ps.blocking(result["hits"]) # #36: warn-only hits are reported, not refused
434
+ msg = commit_message(src, today) if srcdir is None else tree_commit_message(srcdir, provenance, today)
435
+ sc = ps.Scanner(pkg, pat_root, email_repo, public_allow_root=stage)
436
+ blocking += [ps._hit(sc, "tree", "commit-message", n, pat.label, pat.kind, ex, severity=pat.severity)
437
+ for n, pat, ex in sc.scan_text(msg) if pat.severity == ps.BLOCK]
438
+ blocking += export_identity_hits(sc, [(ident["name"], ident["email"])])
439
+ used.update(sc.used_allow_lines())
440
+ if not blocking:
441
+ carried = carry_public_allow(name, pkg, pat_root, email_repo, stage, today, used)
442
+ if carried["carried"]: # the carried file is published too: scan the tree again with it
443
+ result = ps.scan(pkg, stage, export=True, patterns_root=pat_root, source_repo=email_repo,
444
+ public_allow_root=stage)
445
+ blocking = ps.blocking(result["hits"])
446
+ files = sum(1 for _ in (p for p in stage.rglob("*") if p.is_file() or p.is_symlink()))
447
+ if blocking:
448
+ lines = [ps.hit_line(h) for h in blocking[:20]]
449
+ if srcdir is None:
450
+ raise core.Fail(f"{name}: the exported tree of {src[:12]} has {len(blocking)} public-safety "
451
+ f"hit(s); nothing written:\n" + "\n".join(lines)
452
+ + "\nfix them at the source (commit, then --source-commit SHA), or move them under "
453
+ "an internal path (notes/, drafts/, ...) so the export drops them")
454
+ raise core.Fail(f"{name}: the working tree {srcdir} has {len(blocking)} public-safety hit(s); nothing "
455
+ f"written:\n" + "\n".join(lines)
456
+ + "\nfix them in that tree (a commit-message hit: rename the directory), or move them "
457
+ "under an internal path (notes/, drafts/, ...) so the export drops them")
458
+ what = f"{src[:12]} ({chosen})" if srcdir is None else f"working tree {srcdir} (not a commit; {listed})"
459
+ plan = [f"{name}: fresh-history export of {what} -> {target}",
460
+ f" {files} file(s) exported; {len(dropped)} dropped"]
461
+ if srcdir is not None:
462
+ plan.append(f" source commit: none (hand-cleaned tree); provenance: gate-bound commit "
463
+ f"{provenance[:12] if provenance else 'none'}")
464
+ plan += [f" dropped: {d['path']} ({d['reason']})" for d in dropped]
465
+ if receipts_note:
466
+ plan.append(f" note: {receipts_note}")
467
+ plan.append(f" commit identity: {ident['author']} (author and committer; from {ident['source']})"
468
+ + ("" if ident["noreply"] else "; not a GitHub noreply address: published by --allow-author-email"))
469
+ unused = (f"; {carried['unused']} unused allow line(s) dropped (an allow line names what it allows)"
470
+ if carried["unused"] else "")
471
+ if carried["carried"]:
472
+ plan.append(f" public allow: {carried['carried']} allow line(s) of {ps.PATTERNS_FILE} (line(s) "
473
+ f"{', '.join(map(str, carried['lines']))}) carried into {ps.PUBLIC_ALLOW_FILE} (committed; "
474
+ f"the new repository's public-safety reads it; only the lines the export's scan used, "
475
+ f"never a block or warn line){unused}")
476
+ elif carried["present"]:
477
+ plan.append(f" public allow: the {carried['present']} allow line(s) of {ps.PATTERNS_FILE} the export's "
478
+ f"scan used are already in the tree's {ps.PUBLIC_ALLOW_FILE}; none carried{unused}")
479
+ elif carried["unused"]:
480
+ plan.append(f" public allow: none of the {carried['unused']} allow line(s) of {ps.PATTERNS_FILE} was "
481
+ f"used by the export's scan; none carried, no {ps.PUBLIC_ALLOW_FILE} written")
482
+ nw = result["warn_hits"]
483
+ plan.append(" public-safety on the exported tree: 0 hit(s)" if not nw else
484
+ f" public-safety on the exported tree: 0 blocking hit(s), {nw} warning(s) "
485
+ f"({ps.warn_families(result['hits'])}); review with `lean-pkg public-safety {name} --strict` "
486
+ f"before publishing")
487
+ payload = {"ok": True, "name": name, "dry_run": bool(dry_run), "source_commit": src,
488
+ "source": chosen, "export_path": stored, "files": files, "excluded": dropped,
489
+ "kept_receipts": bool(keep_receipts), "commit_message": msg, "remote": remote,
490
+ "public_allow": carried,
491
+ "identity": {k: ident[k] for k in ("author", "committer", "source", "noreply")},
492
+ "public_safety": {"hits": nw, "tree_hits": nw, "block_hits": 0, "warn_hits": nw}}
493
+ if srcdir is not None:
494
+ payload.update(from_tree=src_stored, provenance_commit=provenance)
495
+ status_after = (preview.get("status") or {}).get("to") or status
496
+ if dry_run:
497
+ nxt = next_commands(name, target, "<new12>", remote, status_after != "gate-pending")
498
+ old = src[:12] if src else f"gate-bound commit {provenance[:12] if provenance else 'none'}"
499
+ plan += [f" new commit (on the real run): one root commit on {BRANCH}, message:",
500
+ *[f" {x}".rstrip() for x in msg.rstrip("\n").split("\n")],
501
+ f" registry: update {name} --path {stored} --reason {reason!r}"
502
+ + (f" --repo {remote}" if remote else "")
503
+ + f"; gate/comparator evidence cleared; status {status} -> {status_after}; dated note "
504
+ f"with the old receipt paths and {old}",
505
+ "DRY RUN — nothing written. Re-run without --dry-run to export.", "next:"]
506
+ plan += [f" {c}" for c in nxt]
507
+ payload.update(new_commit=None, next_commands=nxt, relocation=preview)
508
+ return plan, 0, payload
509
+
510
+ if target.exists():
511
+ target.rmdir()
512
+ os.replace(stage, target)
513
+ moved = True
514
+ finally:
515
+ if not moved:
516
+ shutil.rmtree(stage, ignore_errors=True)
517
+
518
+ for args in (("init", "-q"), ("symbolic-ref", "HEAD", f"refs/heads/{BRANCH}"), ("add", "-A", "-f", "."),
519
+ ("commit", "-q", "--no-verify", "-m", msg)):
520
+ p = core.git(target, *args) if args[0] != "commit" else _commit_as(target, ident, args)
521
+ if p.returncode != 0:
522
+ raise core.Fail(f"{name}: git {args[0]} in {target} failed: {(p.stderr or p.stdout).strip()[:200]} "
523
+ f"(the exported files are in {target}; the registry is unchanged)")
524
+ if remote:
525
+ p = core.git(target, "remote", "add", "origin", remote)
526
+ if p.returncode != 0:
527
+ raise core.Fail(f"{name}: git remote add origin failed: {(p.stderr or p.stdout).strip()[:200]}")
528
+ new = core.git_head(target) or ""
529
+
530
+ old_gate = dict(pkg.get("gate") or {})
531
+ reloc_out, reloc = cli.do_relocate(reg_path, reg, events_p, name, new_path=stored, reason=reason,
532
+ agent=agent, redetect=False, dry_run=False)
533
+ pkg = core.get_pkg(reg, name)
534
+ if srcdir is None:
535
+ note = (f"fresh-history release: exported {src[:12]} to {stored} as {new[:12]} (one commit); earlier "
536
+ f"evidence, bound to {src[:12]} and not to the new commit: gate.receipt="
537
+ f"{old_gate.get('receipt') or 'none'}, gate.comparator={old_gate.get('comparator') or 'none'}")
538
+ else:
539
+ note = (f"fresh-history release: exported the working tree {src_stored} (hand-cleaned, not a commit) to "
540
+ f"{stored} as {new[:12]} (one commit); source package commit for provenance: "
541
+ f"{provenance[:12] if provenance else 'none'}; earlier evidence, not bound to the new commit: "
542
+ f"gate.receipt={old_gate.get('receipt') or 'none'}, "
543
+ f"gate.comparator={old_gate.get('comparator') or 'none'}")
544
+ sets: dict = {"notes": {"text": note, "agent": (agent or "lean-pkg").strip()}}
545
+ if remote:
546
+ sets["repo"] = remote
547
+ cli.do_update(reg_path, reg, events_p, name, sets=sets, status=None, reason=reason, redetect=False,
548
+ agent=agent, force=False)
549
+ status_after = pkg.get("status")
550
+ nxt = next_commands(name, target, new[:12], remote, status_after != "gate-pending")
551
+ lines = plan + [f" new commit: {new[:12]} on {BRANCH}" + (f"; origin {remote}" if remote else "")]
552
+ lines += [f" registry: {ln.strip()}" for ln in reloc_out if ln.strip().startswith(("cleared:", f"{name}:"))]
553
+ lines += [f" status: {status} -> {status_after}", f" note: {note}", "next:"] + [f" {c}" for c in nxt]
554
+ payload.update(new_commit=new, next_commands=nxt, relocation=reloc, note=note,
555
+ status={"from": status, "to": status_after})
556
+ return lines, 0, payload
557
+
558
+
559
+ ADOPT_REASON = "adopted-repository release"
560
+
561
+
562
+ def do_adopt_repo(reg_path, reg, events_p, name, *, target_arg, remote, allow_history, agent, reason,
563
+ dry_run) -> tuple[list[str], int, dict]:
564
+ """`release NAME --adopt-repo DIR` (#37): DIR already is the intended public history (built by
565
+ hand); scan it, then relocate the package there. No export, no new commit."""
566
+ pkg = core.get_pkg(reg, name)
567
+ status = pkg.get("status")
568
+ if status in NOT_FROM:
569
+ raise core.Fail(f"{name}: status {status}: adopting a public history is for a package that has not been "
570
+ f"promoted (a public history is already exposed; an archived package is not published)")
571
+ if remote is not None:
572
+ core.require_nonempty("--remote", remote)
573
+ reason = reason or ADOPT_REASON
574
+ stored, _key = core.normalize_local_path(target_arg, "repo adopt DIR")
575
+ target = core.HOME / pathlib.Path(stored)
576
+ head = core.git_head(target) if target.is_dir() else None
577
+ if head is None:
578
+ raise core.Fail(f"{name}: repo adopt: DIR {target} is not a git repository with a commit")
579
+ top = core.git(target, "rev-parse", "--show-toplevel").stdout.strip()
580
+ if os.path.realpath(top) != os.path.realpath(target):
581
+ raise core.Fail(f"{name}: repo adopt: DIR {target} is inside the repository {top}, not its top directory; "
582
+ f"adopt a repository whose top directory is the package")
583
+ repo = core.repo_path(pkg)
584
+ if repo.is_dir() and core.git_head(repo) is not None:
585
+ src_top = core.git(repo, "rev-parse", "--show-toplevel").stdout.strip()
586
+ if src_top and os.path.realpath(src_top) == os.path.realpath(top):
587
+ raise core.Fail(f"{name}: repo adopt: DIR {target} is the package's own source repository; adopt a "
588
+ f"separate repository, or export one with `lean-pkg repo export {name} DIR`")
589
+ count = core.git(target, "rev-list", "--all", "--count").stdout.strip()
590
+ commits = int(count) if count.isdigit() else 0
591
+ if commits != 1 and not allow_history:
592
+ raise core.Fail(f"{name}: repo adopt: DIR {target} has {commits} commits on its refs; an adopted public "
593
+ f"history must be exactly one commit. Pass --allow-history if every commit is meant to "
594
+ f"be published (public-safety scans them all), or export a single commit with "
595
+ f"`lean-pkg repo export {name} DIR --from-tree {target}`")
596
+ if core.git(target, "status", "--porcelain", "--untracked-files=no").stdout.strip():
597
+ raise core.Fail(f"{name}: repo adopt: DIR {target} has uncommitted changes to tracked files; commit or "
598
+ f"discard them first (the adopted commit is what gets published)")
599
+ origin = core.git(target, "remote", "get-url", "origin")
600
+ origin_url = origin.stdout.strip() if origin.returncode == 0 else None
601
+ if remote and origin_url and origin_url != remote:
602
+ raise core.Fail(f"{name}: repo adopt: DIR {target} already has origin {origin_url}, not --remote {remote}; "
603
+ f"refusing to change it (git remote set-url origin URL yourself)")
604
+ _o, preview = cli.do_relocate(reg_path, reg, events_p, name, new_path=stored, reason=reason,
605
+ agent=agent, redetect=False, dry_run=True)
606
+ pat_root = patterns_root(repo, target)
607
+ result = ps.scan(pkg, target, history=True, patterns_root=pat_root, source_repo=target)
608
+ blocking = ps.blocking(result["hits"])
609
+ if blocking:
610
+ lines = [ps.hit_line(h) for h in blocking[:20]]
611
+ raise core.Fail(f"{name}: repo adopt: DIR {target} has {len(blocking)} blocking public-safety hit(s) in its "
612
+ f"tree or history; nothing written:\n" + "\n".join(lines)
613
+ + "\nfix the tree (a history hit: rebuild the repository), then adopt again")
614
+ provenance = gate_bound_commit(pkg, repo)
615
+ prov12 = provenance[:12] if provenance else "none"
616
+ nw = result["warn_hits"]
617
+ new_remote = remote if remote and not origin_url else None
618
+ plan = [f"{name}: adopt {target} at {head[:12]} ({commits} commit(s) on all refs"
619
+ + ("; --allow-history" if allow_history and commits != 1 else "") + ") as the public history; "
620
+ "no export, no new commit",
621
+ f" previous gate-bound commit: {prov12}",
622
+ " public-safety on its tree and full history: 0 hit(s)" if not nw else
623
+ f" public-safety on its tree and full history: 0 blocking hit(s), {nw} warning(s) "
624
+ f"({ps.warn_families(result['hits'])}); review with `lean-pkg public-safety {name} --strict` "
625
+ f"before publishing"]
626
+ if new_remote:
627
+ plan.append(f" git remote add origin {remote}")
628
+ payload = {"ok": True, "name": name, "dry_run": bool(dry_run), "adopted_path": stored,
629
+ "adopted_commit": head, "commits": commits, "allow_history": bool(allow_history),
630
+ "remote": remote, "provenance_commit": provenance, "new_commit": None,
631
+ "public_safety": {"hits": len(result["hits"]), "tree_hits": result["tree_hits"],
632
+ "history_hits": result["history_hits"], "block_hits": 0, "warn_hits": nw}}
633
+ status_after = (preview.get("status") or {}).get("to") or status
634
+ if dry_run:
635
+ nxt = next_commands(name, target, head[:12], remote or origin_url, status_after != "gate-pending")
636
+ plan += [f" registry: update {name} --path {stored} --reason {reason!r}"
637
+ + (f" --repo {remote}" if remote else "")
638
+ + f"; gate/comparator evidence not bound to {head[:12]} cleared; status {status} -> "
639
+ f"{status_after}; dated note naming {head[:12]} and {prov12}",
640
+ "DRY RUN — nothing written. Re-run without --dry-run to adopt.", "next:"]
641
+ plan += [f" {c}" for c in nxt]
642
+ payload.update(next_commands=nxt, relocation=preview)
643
+ return plan, 0, payload
644
+
645
+ if new_remote:
646
+ p = core.git(target, "remote", "add", "origin", remote)
647
+ if p.returncode != 0:
648
+ raise core.Fail(f"{name}: git remote add origin failed: {(p.stderr or p.stdout).strip()[:200]}")
649
+ old_gate = dict(pkg.get("gate") or {})
650
+ reloc_out, reloc = cli.do_relocate(reg_path, reg, events_p, name, new_path=stored, reason=reason,
651
+ agent=agent, redetect=False, dry_run=False)
652
+ pkg = core.get_pkg(reg, name)
653
+ note = (f"adopted-repository release: adopted {stored} at {head[:12]} ({commits} commit(s)) as the public "
654
+ f"history, no export; previous gate-bound commit: {prov12}; evidence before adoption: gate.receipt="
655
+ f"{old_gate.get('receipt') or 'none'}, gate.comparator={old_gate.get('comparator') or 'none'}")
656
+ sets: dict = {"notes": {"text": note, "agent": (agent or "lean-pkg").strip()}}
657
+ if remote:
658
+ sets["repo"] = remote
659
+ cli.do_update(reg_path, reg, events_p, name, sets=sets, status=None, reason=reason, redetect=False,
660
+ agent=agent, force=False)
661
+ status_after = pkg.get("status")
662
+ nxt = next_commands(name, target, head[:12], remote or origin_url, status_after != "gate-pending")
663
+ lines = plan + [f" registry: {ln.strip()}" for ln in reloc_out
664
+ if ln.strip().startswith(("cleared:", f"{name}:"))]
665
+ lines += [f" status: {status} -> {status_after}", f" note: {note}", "next:"] + [f" {c}" for c in nxt]
666
+ payload.update(next_commands=nxt, relocation=reloc, note=note, status={"from": status, "to": status_after})
667
+ return lines, 0, payload
668
+
669
+
670
+ def cmd_release_adopt(args) -> int:
671
+ extra = [f for f, on in (("--force", args.force), ("--fresh-repo", args.fresh_repo is not None),
672
+ ("--author", getattr(args, "author", None) is not None),
673
+ ("--allow-author-email", getattr(args, "allow_author_email", False)),
674
+ ("--from-tree", args.from_tree is not None), ("--keep-receipts", args.keep_receipts),
675
+ ("--source-commit", args.source_commit is not None)) if on]
676
+ if extra:
677
+ raise core.UsageError(f"{', '.join(extra)} do(es) not go with `repo adopt NAME DIR` (no export: the "
678
+ f"repository is adopted as it is)")
679
+ reg_path, events_p = core.registry_path(args), core.events_path(args)
680
+ lines, rc, payload = do_adopt_repo(reg_path, core.load_registry(reg_path), events_p, args.name,
681
+ target_arg=args.adopt_repo, remote=args.remote,
682
+ allow_history=args.allow_history, agent=args.agent, reason=args.reason,
683
+ dry_run=args.dry_run)
684
+ if getattr(args, "json_out", False):
685
+ core.print_json(payload)
686
+ else:
687
+ print("\n".join(lines))
688
+ return rc
689
+
690
+
691
+ def cmd_release_fresh(args) -> int:
692
+ if args.force:
693
+ raise core.UsageError("--force releases a lease; it does not go with `repo export`")
694
+ if args.allow_history:
695
+ raise core.UsageError("--allow-history goes with `repo adopt NAME DIR`")
696
+ if args.from_tree is not None and args.source_commit is not None:
697
+ raise core.UsageError("--from-tree exports a working tree, --source-commit a commit; give one")
698
+ reg_path, events_p = core.registry_path(args), core.events_path(args)
699
+ lines, rc, payload = do_fresh_repo(reg_path, core.load_registry(reg_path), events_p, args.name,
700
+ target_arg=args.fresh_repo, remote=args.remote,
701
+ keep_receipts=args.keep_receipts, given_commit=args.source_commit,
702
+ agent=args.agent, reason=args.reason, dry_run=args.dry_run,
703
+ from_tree=args.from_tree, author=getattr(args, "author", None),
704
+ allow_author_email=getattr(args, "allow_author_email", False))
705
+ if getattr(args, "json_out", False):
706
+ core.print_json(payload)
707
+ else:
708
+ print("\n".join(lines))
709
+ return rc