Repository navigation
Expand file tree
/
Copy pathsync
More file actions
executable file
·753 lines (649 loc) · 30.2 KB
/
Copy pathsync
File metadata and controls
executable file
·753 lines (649 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# dependencies = ["pyyaml"]
# ///
"""tools/sync — reconstruct the read-only ``mirror/`` from pinned upstream SHAs.
This repository is DOWNSTREAM of six live QuantEcon lecture series. It mirrors
an allowlisted subset of each series (``lectures/`` and ``environment.yml``) into
``mirror/<key>/``. That mirror is a pure function of ``(repo, pinned SHA,
allowlist)``, so it is never committed — only the pinned SHAs in
``sync/state.yml`` are committed, and the mirror is rebuilt on demand from them.
Two files drive this script:
* ``sync/manifest.yml`` — HUMAN INTENT: which repos feed the mirror, on which
branch, and which paths are allowlisted.
* ``sync/state.yml`` — MACHINE STATE: the exact SHA each series is pinned to
(written by this script; do not hand-edit).
Each reconstructed mirror records the commit it was taken at in
``mirror/<key>/.pin``, outside its ``lectures/``, so a tool that reads the
mirror can tell one that lags its pin (``tools/promote`` and
``tools/drift-check`` refuse it).
A series that has CUT OVER keeps its stanza in the manifest, marked
``cutover: {date, pin}`` by ``tools/promote --switch`` (and, once a later pin
is accepted, ``accepted: {pin, date}``). The pool is then its source of
truth, so this script never re-pins it: its pin in ``sync/state.yml`` stays
frozen. Its mirror is rebuilt only when its key is named (``tools/sync dp``),
at that frozen pin; a run that names no keys leaves it alone. The name
``pool`` is reserved (the canonical value of a lecture the pool owns), so no
series may take it.
The page-history boundary of a cut-over series is in two parts, both from
the records: the series side is the mark's ``pin``, which never changes (a
pin accepted later goes in ``accepted``); the monorepo side is the commit
that added the series' ``cutover:`` line to ``sync/manifest.yml`` (on main,
the cutover pull request's merge commit), found from git history.
``--boundary SERIES`` prints both. Dates are UTC.
Usage
-----
tools/sync # reconstruct all series at their pinned SHAs
tools/sync dp jax # reconstruct only the named series
tools/sync --update # re-pin every series to HEAD, then rebuild
tools/sync --update dp # re-pin + rebuild only dp
tools/sync --update --pin-only # re-pin every series, but do NOT download
tools/sync --pin-only # (implies resolve) write SHAs, skip rebuild
tools/sync --boundary dp # print a cut-over series' page-history boundary
Flags
-----
--update re-resolve each selected series' HEAD via ``git ls-remote`` and
re-pin the SHA (with a UTC ``synced_at`` timestamp) into
sync/state.yml — but only when the resolved HEAD actually
differs from the already-pinned SHA.
--pin-only resolve and write SHAs but SKIP reconstruction (no downloads).
--boundary SERIES
print the page-history boundary of a cut-over series: its
mark's pin, and the commit that added the mark (needs the
full history of this repository). Exit 2 if SERIES is not
marked, no commit adds the mark, the history is shallow,
or git cannot read it.
-h/--help show help and exit.
Neither ``--update`` nor ``--pin-only`` ever re-pins a series marked
``cutover:``; they say so and leave its pin as it is.
This script NEVER commits anything — CI is responsible for committing the
refreshed sync/state.yml.
"""
from __future__ import annotations
import argparse
import re
import shutil
import subprocess
import sys
from datetime import date, datetime, timezone
from pathlib import Path
try:
import yaml
except ImportError: # pragma: no cover - dependency is declared in PEP-723 block
sys.stderr.write(
"error: PyYAML is required. Run this script via `uv run` (the shebang\n"
" `#!/usr/bin/env -S uv run --script` handles the dependency), or\n"
" install it with `pip install pyyaml`.\n"
)
sys.exit(1)
# --------------------------------------------------------------------------- #
# Paths (resolved relative to the repo root, derived from this script's own #
# location, so the script works from any current working directory). #
# --------------------------------------------------------------------------- #
SCRIPT_PATH = Path(__file__).resolve()
REPO_ROOT = SCRIPT_PATH.parent.parent
SYNC_DIR = REPO_ROOT / "sync"
MANIFEST_PATH = SYNC_DIR / "manifest.yml"
STATE_PATH = SYNC_DIR / "state.yml"
MIRROR_DIR = REPO_ROOT / "mirror"
# Sensible fallbacks if the manifest omits a `defaults` block.
DEFAULT_BRANCH = "main"
DEFAULT_PATHS = ["lectures/", "environment.yml"]
# The commit a reconstructed mirror was taken at: mirror/<key>/.pin, beside
# (never inside) the series' lectures/, so no reader of the mirror sees it.
MIRROR_PIN = ".pin"
# A cut-over series' mark on its manifest stanza (tools/promote --switch
# writes it), and the canonical value of a pool-owned lecture, which no
# series key may take.
CUTOVER_FIELD = "cutover"
RESERVED_KEYS = ("pool",)
SHA_RE = re.compile(r"[0-9a-f]{40}")
# Byte-identical to the committed sync/state.yml header, so round-tripping the
# state file (regenerate then diff) is a no-op when nothing upstream moved.
STATE_HEADER = (
"# generated by tools/sync — do not hand-edit\n"
"# Machine state: the exact commit each series is pinned to.\n"
"# Refresh with `tools/sync --update` (or `--update --pin-only` in CI).\n"
)
class SyncError(Exception):
"""A recoverable, per-series error. Reported, then the run continues."""
# --------------------------------------------------------------------------- #
# Small helpers #
# --------------------------------------------------------------------------- #
def now_iso() -> str:
"""Current time as an RFC-3339 UTC timestamp, e.g. 2026-07-08T04:15:09Z."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def repo_url(owner_name: str) -> str:
"""Build the HTTPS clone URL for an ``owner/name`` GitHub repo reference."""
return f"https://github.com/{owner_name}.git"
def git(args, cwd=None) -> str:
"""Run a git command, returning combined stdout+stderr on success.
Raises SyncError with the captured output on failure so callers can report
a clear per-series message and carry on.
"""
try:
proc = subprocess.run(
["git", *args],
cwd=str(cwd) if cwd is not None else None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
except OSError as exc: # git vanished mid-run, permissions, etc.
raise SyncError(f"failed to run `git {' '.join(args)}`: {exc}") from exc
if proc.returncode != 0:
detail = proc.stdout.strip()
raise SyncError(
f"`git {' '.join(args)}` exited {proc.returncode}"
+ (f":\n {detail}" if detail else "")
)
return proc.stdout
# --------------------------------------------------------------------------- #
# Manifest + state I/O #
# --------------------------------------------------------------------------- #
def load_yaml(path: Path):
"""Load a YAML mapping, tolerating an empty/None document (-> {})."""
if not path.exists():
return None
try:
data = yaml.safe_load(path.read_text()) or {}
except yaml.YAMLError as exc:
raise SystemExit(f"error: could not parse {path}:\n{exc}")
if not isinstance(data, dict):
raise SystemExit(f"error: expected a mapping at the top of {path}.")
return data
def parse_mark(key, mark):
"""A series' ``cutover:`` mark, checked and normalised: ``{date, pin}``,
and ``accepted: {pin, date}`` once a re-run of the switch has accepted a
later pin. A malformed mark is an error, never ignored: it decides
whether the series is ever re-pinned. ``tools/promote``'s ``parse_mark``
applies the same rules."""
def bad(why):
raise SystemExit(
f"error: series '{key}' in {MANIFEST_PATH} has a malformed `{CUTOVER_FIELD}:` mark: {why}.\n"
f" Correct the line by hand (`tools/promote --switch {key}` reads it too, so it cannot): "
f"`{CUTOVER_FIELD}: {{date: 'YYYY-MM-DD', pin: <the 40-hex commit>}}`, with "
"`accepted: {pin, date}` beside them once a re-run of the switch has accepted a later pin."
)
def day(value, name):
if isinstance(value, date) and not isinstance(value, datetime):
return value.isoformat() # written unquoted, YAML reads a date
try:
if isinstance(value, str) and len(value) == 10:
return date.fromisoformat(value).isoformat()
except ValueError:
pass
bad(f"`{name}` must be a date, YYYY-MM-DD")
def pin(value, name):
if not (isinstance(value, str) and SHA_RE.fullmatch(value)):
bad(f"`{name}` must be a full commit SHA (40 lowercase hex digits)")
return value
if not isinstance(mark, dict):
bad("expected a mapping")
unknown = sorted(str(k) for k in mark if k not in ("date", "pin", "accepted"))
if unknown:
bad(f"unknown field(s): {', '.join(unknown)}")
out = {"date": day(mark.get("date"), "date"), "pin": pin(mark.get("pin"), "pin")}
if "accepted" in mark:
accepted = mark["accepted"]
if not isinstance(accepted, dict) or sorted(map(str, accepted)) != ["date", "pin"]:
bad("`accepted` must be {pin, date}")
out["accepted"] = {"pin": pin(accepted["pin"], "accepted.pin"), "date": day(accepted["date"], "accepted.date")}
return out
def manifest_series():
"""The manifest's ``series:`` block, checked for a reserved key."""
data = load_yaml(MANIFEST_PATH)
if data is None:
raise SystemExit(
f"error: manifest not found at {MANIFEST_PATH}.\n"
" This file is the source of truth for which repos feed the "
"mirror.\n"
" Restore sync/manifest.yml before running tools/sync."
)
series_block = data.get("series") or {}
reserved = [k for k in RESERVED_KEYS if isinstance(series_block, dict) and k in series_block]
if reserved:
raise SystemExit(
f"error: {MANIFEST_PATH} has a series named '{reserved[0]}', a reserved name "
"(the canonical value of a lecture the pool owns): rename the series."
)
return data, series_block
def load_marks():
"""Return ``{key: mark}`` for every series marked ``cutover:``, in
manifest order (see ``parse_mark``)."""
_, series_block = manifest_series()
if not isinstance(series_block, dict):
return {}
return {
key: parse_mark(key, cfg[CUTOVER_FIELD])
for key, cfg in series_block.items()
if isinstance(cfg, dict) and CUTOVER_FIELD in cfg
}
def mark_note(mark) -> str:
"""How a log line names a cut-over series' mark."""
note = f"cut over at {mark['pin'][:7]} ({mark['date']})"
if mark.get("accepted"):
note += f", pin {mark['accepted']['pin'][:7]} accepted ({mark['accepted']['date']})"
return note
def load_manifest():
"""Return an ordered mapping ``key -> {repo, branch, paths}``.
``defaults`` (branch/paths) apply to every series unless a series stanza
overrides them. A cut-over series is in it like any other: ``load_marks``
says which are marked.
"""
data, _ = manifest_series()
defaults = data.get("defaults") or {}
default_branch = defaults.get("branch", DEFAULT_BRANCH)
default_paths = defaults.get("paths", DEFAULT_PATHS)
series_block = data.get("series") or {}
if not isinstance(series_block, dict) or not series_block:
raise SystemExit(
f"error: {MANIFEST_PATH} has no `series:` mapping — nothing to sync."
)
manifest = {}
for key, cfg in series_block.items():
cfg = cfg or {}
repo = cfg.get("repo")
if not repo:
raise SystemExit(
f"error: series '{key}' in {MANIFEST_PATH} is missing `repo:`."
)
manifest[key] = {
"repo": repo,
"branch": cfg.get("branch", default_branch),
"paths": cfg.get("paths", default_paths),
}
return manifest
def load_state():
"""Return the pinned-SHA state mapping (``{}`` if the file is absent)."""
data = load_yaml(STATE_PATH)
return data if data else {}
def write_state(state, order):
"""Write sync/state.yml in manifest order, with the do-not-edit header.
Every series key from the manifest is represented, so the file stays a
complete template even when only a subset was refreshed.
"""
ordered = {}
for key in order:
entry = state.get(key) or {}
ordered[key] = {
"sha": entry.get("sha", "") or "",
"synced_at": entry.get("synced_at", "") or "",
}
SYNC_DIR.mkdir(parents=True, exist_ok=True)
body = yaml.safe_dump(ordered, sort_keys=False, default_flow_style=False)
STATE_PATH.write_text(STATE_HEADER + body)
def mirror_pin(key: str) -> str:
"""The commit ``mirror/<key>/`` was reconstructed at, or "" when it
records none (a mirror built before ``.pin``, or one that failed)."""
try:
return (MIRROR_DIR / key / MIRROR_PIN).read_text(encoding="utf-8").strip()
except OSError:
return ""
# --------------------------------------------------------------------------- #
# Core operations #
# --------------------------------------------------------------------------- #
def resolve_head(url: str, branch: str) -> str:
"""Resolve the current HEAD SHA of ``refs/heads/<branch>`` on ``url``."""
out = git(["ls-remote", url, f"refs/heads/{branch}"])
lines = [ln for ln in out.splitlines() if ln.strip()]
if not lines:
raise SyncError(
f"no ref `refs/heads/{branch}` advertised by {url} "
"(wrong branch name, private repo, or network failure?)"
)
sha = lines[0].split()[0]
if not sha:
raise SyncError(f"could not parse a SHA from `git ls-remote` on {url}")
return sha
def sparse_patterns(paths):
"""Translate the allowlist into anchored ``--no-cone`` sparse patterns.
Non-cone sparse-checkout takes gitignore-style patterns. Anchoring each
allowlist entry with a leading ``/`` restricts the checkout to exactly the
named top-level directories and files — so ``mirror/<key>/`` is a true
byte-for-byte function of (repo, SHA, allowlist), with no stray root files.
Cone mode is deliberately NOT used: it always materialises every top-level
file, which would over-include beyond the declared allowlist.
"""
patterns = []
seen = set()
for raw in paths:
p = str(raw).strip()
if not p:
continue
pattern = p if p.startswith("/") else "/" + p
if pattern not in seen:
seen.add(pattern)
patterns.append(pattern)
return patterns
def reconstruct(key: str, url: str, sha: str, paths):
"""Rebuild ``mirror/<key>/`` as plain files pinned to ``sha``.
Fresh directory, git init, remote, non-cone sparse-checkout anchored to the
allowlist, a shallow fetch of the exact SHA, checkout, then the nested
``.git`` is removed so the mirror is inert plain files. The ``.git`` removal
runs in a ``finally`` so a mid-run failure never leaves a live nested repo.
Only a checkout that succeeded writes ``mirror/<key>/.pin``, so a mirror
that failed part-way records no pin and is refused by its readers.
"""
dest = MIRROR_DIR / key
if dest.exists():
shutil.rmtree(dest)
dest.mkdir(parents=True)
try:
git(["init", "-q"], cwd=dest)
git(["remote", "add", "origin", url], cwd=dest)
git(["sparse-checkout", "set", "--no-cone", *sparse_patterns(paths)], cwd=dest)
try:
git(["fetch", "--depth", "1", "origin", sha], cwd=dest)
except SyncError as exc:
raise SyncError(
f"{exc}\n the pinned SHA {sha[:12]} may be stale or "
f"unreachable; try `tools/sync --update {key}` to re-pin to "
"the current HEAD."
)
git(["checkout", "-q", "FETCH_HEAD"], cwd=dest)
finally:
# Drop the nested repository so mirror/<key>/ is a plain, inert tree —
# even if fetch/checkout failed part-way through.
git_dir = dest / ".git"
if git_dir.exists():
shutil.rmtree(git_dir, ignore_errors=True)
(dest / MIRROR_PIN).write_text(sha + "\n", encoding="utf-8")
# --------------------------------------------------------------------------- #
# The page-history boundary #
# --------------------------------------------------------------------------- #
def git_here(args):
"""``git`` in this repository: ``(returncode, stdout)``."""
proc = subprocess.run(
["git", "-C", str(REPO_ROOT), *args],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
return proc.returncode, proc.stdout
class GitFailed(Exception):
"""A git command the boundary needs failed: the message names it."""
def git_read(args):
"""``git`` in this repository: its stdout, or ``GitFailed`` naming the
command and git's own error."""
proc = subprocess.run(["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True)
if proc.returncode != 0:
said = proc.stderr.strip().splitlines()
raise GitFailed(f"`git {' '.join(args)}` failed: " + (said[-1] if said else f"exit {proc.returncode}"))
return proc.stdout
# The commits on HEAD's first-parent line whose diff against their first
# parent adds or removes a line holding the pin. A merge is diffed against
# its first parent, so a mark merged from a branch is found at the merge
# commit, the one on main. git before 2.31 has no --diff-merges, and there
# -m with --first-parent does the same. --no-patch: only the commits are
# wanted, and a recent git prints a merge's patch with --diff-merges.
FIRST_PARENT_LOGS = (["--first-parent", "--diff-merges=first-parent"], ["--first-parent", "-m"])
def utc_time(epoch: str) -> str:
return datetime.fromtimestamp(int(epoch), timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def boundary(key: str) -> int:
"""Print the page-history boundary of a cut-over series (exit 0), or say
why there is none (exit 2).
The series side is the mark's ``pin``: the commit the pool was taken at,
written once by the switch and never changed. The monorepo side is the
most recent commit on HEAD's first-parent line (on main, the cutover
pull request's merge commit) at which the series' own ``cutover.pin``,
read by parsing ``sync/manifest.yml``, became the mark's pin: git's
``-G`` finds the commits whose diff against their first parent touches
a line holding the pin, and the first, newest first, at which the
series' mark has that pin and its first parent's does not is the one.
So an ``accepted`` field added later, a comment quoting the pin before
or after, a stanza moved or another series' mark never moves it, and
after a revert and a re-apply the re-apply wins. It needs the full
history: a shallow clone's oldest commit would seem to add everything.
A git command that fails (a partial clone offline, say) is an error of
its own.
"""
manifest = load_manifest()
if key not in manifest:
sys.stderr.write(f"error: unknown series key '{key}' (valid keys: {', '.join(manifest)})\n")
return 2
mark = load_marks().get(key)
if mark is None:
sys.stderr.write(
f"error: {key} is not marked `{CUTOVER_FIELD}:` in sync/manifest.yml, so it has no "
f"page-history boundary: `tools/promote --switch {key}` marks it at its cutover.\n"
)
return 2
rc, top = git_here(["rev-parse", "--show-toplevel"])
if rc != 0 or Path(top.strip()).resolve() != REPO_ROOT.resolve():
sys.stderr.write(f"error: {REPO_ROOT} is not a git repository: the boundary is read from its history.\n")
return 2
rc, out = git_here(["rev-parse", "--is-shallow-repository"])
if out.strip() == "true":
sys.stderr.write(
"error: the boundary needs full history, and this clone is shallow: run "
"`git fetch --unshallow` (in CI, check out with `fetch-depth: 0`).\n"
)
return 2
pin = mark["pin"]
rel = "sync/manifest.yml"
def pin_at(rev):
"""``key``'s mark pin in sync/manifest.yml at ``rev``; None when there
is no manifest there, no mark, or one that does not parse."""
if not git_read(["ls-tree", "--name-only", rev, "--", rel]).strip():
return None
try:
node = yaml.safe_load(git_read(["show", f"{rev}:{rel}"]))
except yaml.YAMLError:
return None
for field in ("series", key, CUTOVER_FIELD, "pin"):
node = node.get(field) if isinstance(node, dict) else None
return node if isinstance(node, str) else None
def first_parent_log():
# The last failure is the one to report: on a git before 2.31 the
# first is only its refusal of --diff-merges.
for flags in FIRST_PARENT_LOGS:
try:
return git_read(["log", *flags, "--no-patch", f"-G{pin}", "--format=%H %ct", "HEAD", "--", rel])
except GitFailed as exc:
failed = exc
raise failed
added = None
try:
if pin_at("HEAD") == pin:
for line in first_parent_log().splitlines():
if not line.strip():
continue
sha, stamp = line.split()
parents = git_read(["rev-list", "--parents", "-n", "1", sha]).split()
if pin_at(sha) == pin and (len(parents) < 2 or pin_at(parents[1]) != pin):
added = (sha, utc_time(stamp))
break
except GitFailed as exc:
sys.stderr.write(
f"error: git could not read the history of sync/manifest.yml, and the boundary is read from it: "
f"{exc}. In a partial (blobless) clone, fetch with the network on, or clone in full.\n"
)
return 2
if added is None:
sys.stderr.write(
f"error: no commit adds the mark: {key}'s `{CUTOVER_FIELD}:` line (pin {pin[:12]}) is not in "
"sync/manifest.yml at HEAD. Commit it first (on main, the cutover pull request's merge commit "
"adds it).\n"
)
return 2
repo = manifest[key]["repo"]
print(f"{key}: the page-history boundary ({mark_note(mark)}; dates UTC)")
print(
f" series side: {repo} at {pin}: the series' history of lectures/<path> up to and "
"including this commit"
)
print(
f" monorepo side: {added[0]} ({added[1]}): the commit that added {key}'s `{CUTOVER_FIELD}:` "
"line; the history of lectures/<slug>.md after it"
)
if mark.get("accepted"):
print(
f" accepted: {mark['accepted']['pin']} ({mark['accepted']['date']}): a later pin a re-run "
"of the switch accepted; the watch reads from it, and the boundary does not move"
)
return 0
# --------------------------------------------------------------------------- #
# CLI #
# --------------------------------------------------------------------------- #
def build_parser():
parser = argparse.ArgumentParser(
prog="tools/sync",
description=(
"Reconstruct the read-only mirror/ from pinned upstream SHAs. "
"With --update, re-pin each series to its current HEAD first."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="Series keys are defined in sync/manifest.yml.",
)
parser.add_argument(
"keys",
nargs="*",
metavar="SERIES",
help="series keys to operate on (default: all series in the manifest).",
)
parser.add_argument(
"--update",
action="store_true",
help="re-resolve each selected series' HEAD and re-pin its SHA "
"(only when the HEAD actually moved).",
)
parser.add_argument(
"--pin-only",
action="store_true",
help="resolve and write SHAs but skip reconstruction (no downloads).",
)
parser.add_argument(
"--boundary",
metavar="SERIES",
help="print the page-history boundary of a cut-over series (its "
"mark's pin, and the commit that added the mark), then exit.",
)
return parser
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
# Parse args (and handle -h/--help) BEFORE the git check or manifest load,
# so `tools/sync --help` works on a fresh checkout and without git present.
parser = build_parser()
args = parser.parse_args(argv)
if args.boundary and (args.keys or args.update or args.pin_only):
parser.error("--boundary takes one SERIES, and no other key or option")
if shutil.which("git") is None:
sys.stderr.write(
"error: `git` was not found on PATH. tools/sync drives git to "
"reconstruct the mirror; please install git and try again.\n"
)
return 2
if args.boundary:
return boundary(args.boundary)
manifest = load_manifest()
marks = load_marks()
valid_keys = list(manifest.keys())
if args.keys:
unknown = [k for k in args.keys if k not in valid_keys]
if unknown:
parser.error(
"unknown series key(s): "
+ ", ".join(unknown)
+ "\nvalid keys: "
+ ", ".join(valid_keys)
)
# Preserve manifest order, drop duplicates.
selected = [k for k in valid_keys if k in set(args.keys)]
else:
selected = list(valid_keys)
# --pin-only implies resolving the SHA (it just skips the download).
do_resolve = args.update or args.pin_only
do_reconstruct = not args.pin_only
state = load_state()
if not do_resolve:
# Reconstruction-only mode needs SHAs already on disk.
if not STATE_PATH.exists():
sys.stderr.write(
f"error: no pinned SHAs found — {STATE_PATH} does not exist.\n"
" Run `tools/sync --update` to resolve and pin HEADs "
"first.\n"
)
return 2
MIRROR_DIR.mkdir(parents=True, exist_ok=True)
results = [] # list of (key, ok: bool)
skipped = [] # cut-over series a run naming no keys leaves alone
for key in selected:
cfg = manifest[key]
url = repo_url(cfg["repo"])
mark = marks.get(key)
if mark is not None:
# Never re-pinned; rebuilt only when named, at its frozen pin.
if do_resolve:
print(f"[{key}] {mark_note(mark)}: not re-pinned")
if not args.keys:
if do_reconstruct:
print(f"[{key}] {mark_note(mark)}: not reconstructed (`tools/sync {key}` rebuilds it)")
skipped.append(key)
continue
try:
if do_resolve and mark is None:
new_sha = resolve_head(url, cfg["branch"])
old_sha = ((state.get(key) or {}).get("sha") or "").strip()
if new_sha != old_sha:
state[key] = {"sha": new_sha, "synced_at": now_iso()}
# Persist immediately so a later failure keeps this pin.
# Only write on real movement, so CI commits track genuine
# upstream changes rather than timestamp churn.
write_state(state, valid_keys)
print(
f"[{key}] pinned {cfg['repo']}@{new_sha[:12]} "
f"({cfg['branch']})"
)
else:
print(f"[{key}] unchanged @ {new_sha[:12]} ({cfg['branch']})")
sha = new_sha
else:
sha = ((state.get(key) or {}).get("sha") or "").strip()
if not sha and mark is not None:
raise SyncError(
f"no pinned SHA for '{key}' in {STATE_PATH.name}, and it is cut over, so "
"`--update` never pins it: restore its pin from git history."
)
if not sha:
raise SyncError(
f"no pinned SHA for '{key}' in {STATE_PATH.name} — run "
f"`tools/sync --update {key}` to pin it first."
)
if do_reconstruct:
print(f"[{key}] reconstructing mirror/{key}/ @ {sha[:12]} …")
reconstruct(key, url, sha, cfg["paths"])
print(f"[{key}] done -> {MIRROR_DIR / key}")
results.append((key, True))
except SyncError as exc:
sys.stderr.write(f"[{key}] FAILED: {exc}\n")
results.append((key, False))
except Exception as exc: # never let one series abort the rest
sys.stderr.write(f"[{key}] FAILED (unexpected): {exc}\n")
results.append((key, False))
# ----------------------------------------------------------------------- #
# Summary #
# ----------------------------------------------------------------------- #
failed = [key for key, ok in results if not ok]
passed = [key for key, ok in results if ok]
print("\n" + "─" * 60)
mode = (
"pin-only (resolve, no download)"
if args.pin_only
else ("update + reconstruct" if args.update else "reconstruct")
)
print(
f"summary [{mode}]: {len(passed)} ok, {len(failed)} failed"
+ (f", {len(skipped)} cut over (left alone)" if skipped else "")
)
if passed:
print(" PASS: " + ", ".join(passed))
if skipped:
print(" CUT OVER: " + ", ".join(skipped))
if failed:
print(" FAIL: " + ", ".join(failed))
print("─" * 60)
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())