Coverage for packages/workshop/src/livery/workshop/_sync.py: 92%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/agents/tests/test_agents.py ran.

1"""``fm sync``: deliver every mounted extension's content to the repository.
2
3Walked in composition order, the base first, and the instance always
4wins last: the files each extension ships under ``content/``, composed
5by the fragment engine, where an extension takes another's file only
6by declaring it, and the files each extension's code writes from its
7``[fragments]`` renders ([livery.workshop._shipped_files][]). A file
8that belongs to this checkout alone goes through the materialiser: a
9link where it can, a copy where not, and an edited copy kept and named.
10
11Idempotent: a second run changes nothing and says nothing.
12"""
13
14from __future__ import annotations
15
16import os
17from pathlib import Path
18from typing import TYPE_CHECKING, Annotated, Any, NamedTuple
19
20import livery.footman as footman
21from livery import git
22from livery.footman import Failed, Forward, doc, fail, step, task
23from livery.workshop import _stack
24from livery.workshop._ci_context import state_store
25
26if TYPE_CHECKING:
27 from livery.git import Fetched
28
29from livery.workshop._extensions import (
30 workspace_root,
31)
32
33
34def sync_workspace(root: Path, *, local_only: bool = False) -> list[str]:
35 """Deliver every extension's content into *root*; the summary lines.
36
37 The engine behind ``fm sync``, separated so tests drive it against
38 temporary trees. *local_only* writes no file a commit holds: the
39 local outputs alone.
40 """
41 from livery.workshop._shipped_files import deliver
42
43 return deliver(root, local_only=local_only)
44
45
46def _foreign_authors(root: Path, since: str) -> set[str]:
47 """Author emails of the commits after *since* a rebase would rewrite; never mine."""
48 me = git.author_email(root)
49 authors = git.run(root, "log", "--format=%ae", f"{since}..HEAD").strip()
50 return {email for email in authors.splitlines() if email and email != me}
51
52
53def _rebase_args(onto: str, upstream: str) -> tuple[str, ...]:
54 """The rebase's arguments: onto *onto*, the commits after *upstream* when given."""
55 return ("--onto", onto, upstream) if upstream else (onto,)
56
57
58def resolve_receipts(root: Path) -> bool:
59 """Resolve a stopped merge or rebase whose every conflict is a render receipt.
60
61 Returns whether it did. Each conflicted receipt file is merged key
62 by key ([livery.workshop._fragment_engine.merge_receipts][]), with
63 the files beside it as the conflict left them, and staged. A
64 conflict in any other file leaves everything as it is, for the
65 caller's own path.
66 """
67 from pathlib import PurePosixPath
68
69 from livery.workshop._fragment_engine import (
70 RENDERED_MANIFEST,
71 merge_receipts,
72 receipts_from,
73 write_rendered,
74 )
75
76 unmerged = git.unmerged_paths(root)
77 if not unmerged or any(
78 PurePosixPath(path).name != RENDERED_MANIFEST for path in unmerged
79 ):
80 return False
81 for path in unmerged:
82 directory = (root / path).parent
83 merged = merge_receipts(
84 *(receipts_from(git.staged_text(root, path, stage)) for stage in (1, 2, 3)),
85 beside=directory,
86 )
87 write_rendered(directory, merged)
88 git.add(root, path)
89 print(f" {path}: the two sides' receipts merged, file by file")
90 return True
91
92
93def _try_rebase(root: Path, onto: str, upstream: str = "") -> tuple[str, str]:
94 """Attempt a rebase onto *onto*; how it ended and, when it failed, git's words.
95
96 The outcome is ``clean``, ``conflict`` or ``failed``.
97
98 With *upstream*, only the commits after it move. A stop whose
99 conflicts are all render receipts resolves them and goes on
100 ([livery.workshop._sync.resolve_receipts][]). Any other stop is
101 aborted, so the branch is exactly as it was: the caller decides
102 whether a person resolves it. It stopped on a conflict when paths
103 are left unmerged. Anything else that stops it, a commit the signer
104 refused or a hook, is ``failed`` with git's own words: each needs
105 another next act, and only git's words say which.
106 """
107 try:
108 git.run(root, "rebase", *_rebase_args(onto, upstream))
109 return "clean", ""
110 except git.GitError as error:
111 stopped = error
112 while resolve_receipts(root):
113 try:
114 # Continuing an automated receipt merge must never open a
115 # person's editor or fail under an ambient GIT_EDITOR=false.
116 git.run(
117 root,
118 "rebase",
119 "--continue",
120 env={**os.environ, "GIT_EDITOR": "true"},
121 )
122 except git.GitError as error:
123 stopped = error
124 continue
125 return "clean", ""
126 unmerged = git.unmerged_paths(root)
127 git.run(root, "rebase", "--abort")
128 return ("conflict", "") if unmerged else ("failed", str(stopped))
129
130
131def _rebase_step(
132 root: Path, onto: str, *, interactive: bool, upstream: str = ""
133) -> bool:
134 """One rebase of the current branch onto *onto*; whether it landed.
135
136 With *upstream*, only the commits after it move: a stacked branch's
137 own. Foreign-authored commits gate the rebase: rewriting them
138 orphans every other copy of the branch, so the shared-branch case
139 goes through ``fm integrate`` (a merge) unless a person says
140 otherwise. A conflicted rebase is never entered silently: an
141 interactive run may choose to resolve it now, everything else
142 parks with the teaching. A rebase stopped by anything other than a
143 conflict leaves the branch as it was and prints git's words.
144 """
145 import livery.footman as footman
146
147 branch = git.current_branch(root)
148 foreign = _foreign_authors(root, upstream or onto)
149 if foreign:
150 listed = ", ".join(sorted(foreign))
151 if not (151 ↛ 164line 151 didn't jump to line 164 because the condition on line 151 was always true
152 interactive
153 and footman.confirm(
154 f"rebasing {branch} onto {onto} rewrites commits by"
155 f" {listed}; their copies would be orphaned. Rebase anyway?"
156 )
157 ):
158 print(
159 f" left {branch} behind {onto}: it carries commits by"
160 f" {listed}, and rewriting them orphans every other copy."
161 f" Bring the base in by merge instead: `{footman.prog()} integrate`."
162 )
163 return False
164 outcome, said = _try_rebase(root, onto, upstream)
165 if outcome == "clean":
166 print(f" rebased {branch} onto {onto}")
167 return True
168 if outcome == "failed":
169 print(
170 f" left {branch} behind {onto}: the rebase stopped, and not on a"
171 " conflict. git said:"
172 )
173 for line in said.splitlines():
174 print(f" {line}")
175 print(f" Fix what git names, then run `{footman.prog()} sync` again.")
176 return False
177 if interactive and footman.confirm(177 ↛ 181line 177 didn't jump to line 181 because the condition on line 177 was never true
178 f"rebasing {branch} onto {onto} hits conflicts. Start the rebase"
179 " and resolve them now?"
180 ):
181 import contextlib
182
183 with contextlib.suppress(git.GitError):
184 git.run(root, "rebase", *_rebase_args(onto, upstream))
185 raise SystemExit(
186 " the rebase is started and waiting on you: resolve the"
187 f" conflicts, `git rebase --continue`, then run `{footman.prog()} sync`"
188 " again."
189 )
190 print(
191 f" left {branch} behind {onto}: the rebase has conflicts. Run"
192 f" `{footman.prog()} sync` interactively to resolve them, or bring the base in"
193 f" by merge with `{footman.prog()} integrate`."
194 )
195 return False
196
197
198def restack(
199 root: Path,
200 branch: str,
201 *,
202 interactive: bool,
203 stack: tuple[str, str] | None = None,
204) -> bool | None:
205 """Move a stacked branch's own commits onto its parent, or onto main once it merged.
206
207 A branch ``fm start --from`` began carries its parent's commits
208 under its own. The ones after the recorded start commit are the
209 branch's own whatever the parent became since, so they move alone:
210 onto the parent's new tip when the parent moved, onto
211 ``origin/main`` once the parent merged and origin deleted it. A
212 parent squashed from several commits then moves nothing it
213 carried, where a plain rebase replays those commits against their
214 squash and conflicts. A branch started before the start commit was
215 recorded, or moved by hand off it since, falls back on git's own
216 matching, which drops a parent that landed as one commit. A branch
217 whose parent is still open and unchanged is left where it is: main
218 reaches it through the parent.
219
220 Returns whether the branch moved; None when it was left behind; a
221 branch that is not stacked returns False. *stack* is the branch's
222 stack when the caller read it already; read here otherwise.
223 """
224 parent, tip = stack if stack is not None else _stack.stack(root, branch)
225 if not parent:225 ↛ 226line 225 didn't jump to line 226 because the condition on line 225 was never true
226 return False
227 if tip and not git.is_ancestor(root, tip, "HEAD"):227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 tip = "" # moved by hand since: its history no longer holds the start
229 merged = parent not in git.remote_branches(root, parent)
230 onto = "origin/main" if merged else f"origin/{parent}"
231 if not merged:
232 target = git.sha_of(root, onto)
233 if tip == target or (not tip and git.is_ancestor(root, target, "HEAD")):
234 if not tip:234 ↛ 235line 234 didn't jump to line 235 because the condition on line 234 was never true
235 _stack.record_stack(root, branch, parent, target)
236 return False
237 if not _rebase_step(root, onto, interactive=interactive, upstream=tip):
238 return None
239 if merged:
240 _stack.forget_stack(root, branch)
241 print(f" {parent} has merged: {branch} stands on main now")
242 else:
243 _stack.record_stack(root, branch, parent, git.sha_of(root, onto))
244 return True
245
246
247def _repository(root: Path) -> Any:
248 from livery.workshop._forge_lane import this_repository
249
250 return this_repository(root)
251
252
253def _leave_merged_branch(
254 root: Path,
255 branch: str,
256 *,
257 reserved: bool = False,
258) -> bool:
259 """Step off *branch* when its pull request merged; True when handled.
260
261 Shared by reserved ``workflow/`` branches and ordinary feature
262 branches. In the main checkout, delegates to ``finish_branch``
263 (switching back to an up-to-date ``main`` and deleting the local
264 branch) when ``only_local_work`` is empty. In a linked worktree,
265 skips rebasing a merged branch and points to ``fm finish`` so
266 ``fm sync`` never yanks a shell's working directory out from under
267 it. A reserved branch whose pull request has not merged stays owned
268 by the workflow engine (returns True); an unmerged feature branch
269 returns False so normal sync continues.
270 """
271 from livery.workshop._submit import merged_pull_request, only_local_work
272 from livery.workshop._sweep import _is_linked_worktree, finish_branch
273
274 try:
275 repo = _repository(root)
276 pull = merged_pull_request(repo, root, branch)
277 except Exception:
278 repo = None
279 pull = None
280 if repo is None or pull is None:
281 if reserved:
282 print(
283 f" {branch}: a reserved branch; the engine owns it until its pull"
284 " request merges"
285 )
286 return True
287 return False
288 why = only_local_work(root, branch, merged_head=pull.head_sha)
289 if why:
290 print(f" {branch}: PR #{pull.number} merged, but the branch holds {why}; kept")
291 return True
292 if not reserved and _is_linked_worktree(root):
293 print(
294 f" {branch}: PR #{pull.number} merged; run `{footman.prog()} finish`"
295 " to remove this worktree"
296 )
297 return True
298 print(f" {branch}: PR #{pull.number} merged; stepping off")
299 finish_branch(
300 root, branch, current=branch, dry_run=False, allow_switch=True, repo=repo
301 )
302 return True
303
304
305_leave_merged_reserved = _leave_merged_branch
306
307
308def continue_on_moved_code(
309 root: Path, before: str, after: str, *, verb: str = "sync"
310) -> bool:
311 """Hand the command to a fresh process when the checkout moved under it.
312
313 The modules this process imported are the checkout's old code;
314 what follows a move reads the new source, and a mixed process
315 fails on the first changed signature. The handoff re-runs the
316 same command through uv on the code now on disk; *verb* names it
317 in the line. Returns False when nothing moved; when the re-run
318 cannot start it is named and the command continues on the loaded
319 code, which returns True.
320 """
321 if after == before:
322 return False
323 from livery.workshop import _reconcile
324
325 print(
326 f" the checkout moved from {before[:12]} to {after[:12]}; the {verb}"
327 " continues on that code"
328 )
329 _reconcile._reexec(root, _reconcile.MOVED) # pyright: ignore[reportPrivateUsage]
330 return True
331
332
333def continue_on_moved_extensions(root: Path, moved: tuple[str, ...]) -> None:
334 """Hand the sync to a fresh process when its install moved a mounted extension.
335
336 *moved* names the base and the extensions whose distribution the
337 sync's ``uv sync`` moved or removed; when it names none, nothing
338 happens. This process found each extension's directory as it
339 mounted it, and reads its declaration, its shipped files and its
340 code from there; it reads the base's own files, its contract, its
341 seeds and its fragments, from the directory it imported the base
342 from.
343 An install that replaces an index's wheel with an editable member
344 at another path removes that directory, and the member's path joins
345 ``sys.path`` only when a process starts; an install from another
346 editable tree leaves the old one on disk, no longer installed. The
347 fresh process re-runs the command and mounts what the environment
348 installs now; an extension the install removed is then one the
349 mount finds missing, and the fresh process installs it or refuses,
350 naming it. This process does not read a moved extension again,
351 because it imported that extension's modules from the old place
352 already.
353
354 Raises:
355 Failed: when the fresh process cannot start, or the command
356 already re-ran once for a moved extension. Nothing was
357 delivered after the install then.
358 """
359 if not moved:
360 return
361 from livery.workshop import _reconcile
362
363 names = ", ".join(moved)
364 print(
365 f" the install moved or removed {names}; the sync continues in a fresh"
366 " process, which mounts what is installed now"
367 )
368 _reconcile._reexec(root, _reconcile.RELOCATED) # pyright: ignore[reportPrivateUsage]
369 fail(
370 f"the install moved or removed {names}, and this process cannot mount"
371 f" what is installed now: run `{footman.prog()} sync` again. Nothing was"
372 " delivered after the install"
373 )
374
375
376def require_mounted(
377 root: Path, flags: tuple[str, ...] = (), *, install: bool = True
378) -> None:
379 """Refuse to render or lock while an extension of the installed set is unmounted.
380
381 The extensions mount when the command starts. One the installed set
382 holds and no installed distribution declared then (a commit the sync
383 moved onto lists it, or a person just listed it, in the root's list
384 or a package's) registered nothing, and a render or a lock without
385 it would remove its files and its tools as withdrawn. When the
386 environment holds it now, or holds it once ``uv sync`` ran with
387 *flags*, the sync hands itself to a fresh process, which mounts it.
388
389 A newly listed extension is in no lock yet, so that ``uv sync``
390 cannot install it. With *install*, it is installed the way the
391 workspace resolves it: the project file alone is written again,
392 and its dev group names the extension's distribution, then ``uv
393 sync`` locks and installs through the file's ``[tool.uv.sources]``
394 and indexes. An extension the workspace sources from a path or
395 from git installs from there. That write reads the contracts
396 without judging their keys: a key of an extension no installed
397 distribution declares yet, such as the root's ``[python]`` table
398 before python is installed, has no declaration to be judged by
399 until the install. The fresh process then judges every contract
400 over the installed declarations and renders every file with the
401 extension mounted.
402
403 One no distribution declares even then refuses, naming it and the
404 list that brings it, and so does a handoff that cannot start. Each
405 refusal, and an install that fails, first puts back the project
406 file, its receipt and ``uv.lock`` as they were before the install,
407 so nothing is rendered or locked.
408
409 Raises:
410 Failed: when a listed extension cannot be mounted in this process,
411 or the install fails.
412 """
413 from livery.workshop import _reconcile
414 from livery.workshop._extensions import (
415 declared_now,
416 stale_declarations,
417 unmounted,
418 where_listed,
419 )
420 from livery.workshop._uv import run_uv
421
422 missing = unmounted(root)
423 if not missing:
424 return
425 installed = declared_now(missing)
426 # An environment from before the checkout's declares an extension
427 # by an entry point whose package ships no declaration file: its
428 # metadata is what `uv sync` brings current. When a local extension
429 # member was renamed or removed, that first `uv sync` fails against
430 # the stale pyproject.toml; with *install*, fall through to
431 # `_install_listed`, which rewrites the project file first.
432 sync_failed = False
433 if installed != missing or stale_declarations(root):433 ↛ 442line 433 didn't jump to line 442 because the condition on line 433 was always true
434 try:
435 run_uv("sync", *flags, root=root)
436 except Failed:
437 if not install:
438 raise
439 sync_failed = True
440 else:
441 installed = declared_now(missing)
442 absent = [name for name in missing if name not in installed]
443 held: dict[str, bytes | None] = {}
444 if (absent or sync_failed) and install:
445 held = _install_listed(root, flags)
446 installed = declared_now(missing)
447 absent = [name for name in missing if name not in installed]
448 if absent:
449 _put_back(root, held)
450 why = (
451 "and installing it found no distribution declaring it"
452 if install
453 else f"and a sync with {' '.join(flags)} installs nothing outside the lock"
454 )
455 where = where_listed(root)
456 named = ", ".join(
457 f"{name} ({where[name]})" if name in where else name for name in absent
458 )
459 fail(
460 f"no installed distribution declares {named}, {why}: install the"
461 " distribution that ships each, or remove the entry. Nothing was"
462 " rendered or locked"
463 )
464 print(
465 f" extensions installed by this sync: {', '.join(installed)}; the sync"
466 " continues with them mounted"
467 )
468 _reconcile._reexec(root, _reconcile.INSTALLED) # pyright: ignore[reportPrivateUsage]
469 _put_back(root, held)
470 fail(
471 f"{', '.join(installed)} installed, and this process cannot mount"
472 f" them: run `{footman.prog()} sync` again. Nothing was rendered or locked"
473 )
474
475
476def _install_listed(root: Path, flags: tuple[str, ...]) -> dict[str, bytes | None]:
477 """Install the missing listed extensions the way the workspace resolves them.
478
479 Writes the project file alone, whose dev group names each listed
480 extension's distribution, then runs ``uv sync`` with *flags*, which
481 locks first. Besides the environment, the install writes three
482 files: the project file, its receipt and ``uv.lock``. An install
483 that fails puts them back before the failure goes on.
484
485 Returns:
486 What each of the three files held before, None for one that was
487 not there, for a refusal that puts them back.
488 """
489 from livery.workshop._contract import unjudged
490 from livery.workshop._fragment_engine import RENDERED_MANIFEST
491 from livery.workshop._shipped_files import PROJECT_FILE, deliver_project_file
492 from livery.workshop._uv import run_uv
493
494 held = {
495 name: (root / name).read_bytes() if (root / name).is_file() else None
496 for name in (PROJECT_FILE, RENDERED_MANIFEST, "uv.lock")
497 }
498 try:
499 with unjudged():
500 for line in deliver_project_file(root):
501 print(line)
502 run_uv("sync", *flags, root=root)
503 except BaseException:
504 _put_back(root, held)
505 raise
506 return held
507
508
509def _put_back(root: Path, held: dict[str, bytes | None]) -> None:
510 """Write back each file of *held* that moved, or remove one that was not there."""
511 moved: list[str] = []
512 for name, body in held.items():
513 path = root / name
514 now = path.read_bytes() if path.is_file() else None
515 if now == body:
516 continue
517 moved.append(name)
518 if body is None:518 ↛ 519line 518 didn't jump to line 519 because the condition on line 518 was never true
519 path.unlink()
520 else:
521 path.write_bytes(body)
522 if moved:
523 print(f" put back as they were before the install: {', '.join(moved)}")
524
525
526def bring_current(root: Path, *, interactive: bool, fetched: bool = False) -> None:
527 """Bring the current checkout up to date; the one-stop's first act.
528
529 ``main`` only ever fast-forwards. A reserved ``workflow/`` branch
530 belongs to the engine until its pull request merges, after which
531 the checkout steps off it; a detached HEAD names no branch, a
532 clone with no ``origin`` has nothing to follow, and a dirty tree
533 is never moved: each skips with its note. A feature
534 branch fast-forwards onto its moved remote, rebases onto it when
535 diverged, then rebases onto the base; a stacked branch follows its
536 parent instead ([livery.workshop._sync.restack][]). A rebase of a
537 pushed branch finishes the job with the leased force-push, because
538 rebased-locally with a stale remote is the worst state. *fetched*
539 says origin's heads are not to be fetched here: the one fetch that
540 also mirrors the state store brought them already, or the sync is
541 offline and the remote-tracking refs the last fetch left stand.
542 """
543 _ = root
544 branch = git.current_branch(root)
545 if not branch:
546 print(" detached HEAD: nothing to bring current")
547 return
548 if not git.has_remote(root, "origin"):
549 print(" no origin remote: nothing to bring current")
550 return
551 if not fetched:
552 git.fetch(root)
553 if branch == "main":
554 ahead = git.run(root, "rev-list", "--count", "origin/main..main").strip()
555 if ahead != "0":
556 print(
557 " main has local commits origin does not: never rebased,"
558 " never merged here. Move them to a branch."
559 )
560 return
561 behind = git.run(root, "rev-list", "--count", "main..origin/main").strip()
562 if behind == "0":562 ↛ 563line 562 didn't jump to line 563 because the condition on line 562 was never true
563 return
564 try:
565 git.run(root, "merge", "--ff-only", "origin/main")
566 except Exception as error:
567 # The two states need different acts, so the refusal is
568 # named with git's own reason, never read as "local
569 # commits" (usually it is uncommitted changes in the way).
570 print(f" main is {behind} behind and the fast-forward was refused:")
571 print(f" {error}")
572 return
573 if branch.startswith("workflow/"):
574 _leave_merged_branch(root, branch, reserved=True)
575 return
576 if not git.is_clean(root):
577 print(" uncommitted changes: the branch stays where it is")
578 return
579 rebased = False
580 remote_exists = branch in git.remote_branches(root, "")
581 behind_base = git.run(root, "rev-list", "--count", f"{branch}..origin/main").strip()
582 if (not remote_exists or behind_base != "0") and _leave_merged_branch(root, branch):
583 return
584 if remote_exists:
585 ahead_remote = git.run(
586 root, "rev-list", "--count", f"origin/{branch}..{branch}"
587 ).strip()
588 behind_remote = git.run(
589 root, "rev-list", "--count", f"{branch}..origin/{branch}"
590 ).strip()
591 if behind_remote != "0":
592 if ahead_remote == "0":592 ↛ 595line 592 didn't jump to line 595 because the condition on line 592 was always true
593 git.run(root, "merge", "--ff-only", f"origin/{branch}")
594 print(f" fast-forwarded {branch} to origin/{branch}")
595 elif not _rebase_step(root, f"origin/{branch}", interactive=interactive):
596 return
597 else:
598 rebased = True
599 behind_base = git.run(
600 root, "rev-list", "--count", f"{branch}..origin/main"
601 ).strip()
602 stack = _stack.stack(root, branch)
603 parent, _tip = stack
604 if parent:
605 moved = restack(root, branch, interactive=interactive, stack=stack)
606 if moved is None:
607 return
608 if moved:
609 rebased = True
610 elif behind_base != "0":610 ↛ 619line 610 didn't jump to line 619 because the condition on line 610 was always true
611 print(
612 f" {branch} is stacked on {parent}: main reaches it when"
613 f" {parent} merges"
614 )
615 elif behind_base != "0":
616 if not _rebase_step(root, "origin/main", interactive=interactive):
617 return
618 rebased = True
619 if rebased and remote_exists:
620 # The same commits, rewritten: the lease guards anything a
621 # colleague pushed since the fetch above.
622 git.push_force(root, branch)
623 print(f" origin/{branch} follows (leased force-push)")
624
625
626def _uv_flags(
627 *,
628 frozen: bool = False,
629 locked: bool = False,
630 offline: bool = False,
631 upgrade: bool = False,
632) -> tuple[str, ...]:
633 """The uv flags for the options this verb was given, in uv's spelling."""
634 flags: list[str] = []
635 if frozen:
636 flags.append("--frozen")
637 if locked:
638 flags.append("--locked")
639 if offline:
640 flags.append("--offline")
641 if upgrade:641 ↛ 642line 641 didn't jump to line 642 because the condition on line 641 was never true
642 flags.append("--upgrade")
643 return tuple(flags)
644
645
646@task
647def lock(
648 upgrade: Forward[bool] = False,
649 upgrade_tool: Annotated[
650 list[str] | None, doc("move just these tools to their newest")
651 ] = None,
652 check: Forward[bool] = False,
653) -> None:
654 """Write both locks: `toolroom.lock` for the tools, `uv.lock` for the venv.
655
656 The pair to `sync`, in uv's shape: this decides what a checkout
657 installs and nothing on the machine changes, and `sync` installs
658 what these say. An entry that still satisfies its declarations
659 stands, so a newer release moves nothing until an upgrade asks.
660
661 ``--upgrade`` moves every entry of both locks to its newest eligible
662 version, and ``--check`` reports whether both locks are current and
663 writes nothing, exiting non-zero when either would move. Both mean
664 the same thing to each half, so both reach both.
665
666 A name does not. ``--upgrade-tool`` names tools and reaches the
667 tools alone, because a tool is not a package in ``uv.lock``: for one
668 package there, ``uv lock --upgrade-package`` is the verb.
669 """
670 from livery.workshop._tool_tasks import tools_lock
671 from livery.workshop._uv import run_uv
672
673 root = workspace_root()
674 if root is None:
675 fail("no workspace: no workshop.toml above the working directory")
676 tools_lock(upgrade_tool=upgrade_tool)
677 run_uv(
678 "lock",
679 *_uv_flags(upgrade=upgrade),
680 *(("--check",) if check else ()),
681 root=root,
682 )
683
684
685@task(interactive=True)
686def sync(
687 frozen: Forward[bool] = False,
688 locked: Forward[bool] = False,
689 offline: Forward[bool] = False,
690) -> bool:
691 """Bring the checkout current, materialise content, match the lock.
692
693 The one-stop: fast-forward or rebase the current branch (asking
694 before anything conflicted or shared; a branch started on another
695 with ``fm start --from`` follows its parent; a directory with no git
696 history, no repository or no commit, has nothing to follow), remove
697 what a removed package left under ``packages/``, fetch origin's
698 state store into the checkout's mirror for the gate to read, then
699 every extension's fragments, skills, and hooks, then the two locks.
700 Both halves match their lock the way uv does: `toolroom.sync` for the
701 tools, ``uv sync`` for the environment, each writing its lock when
702 there is none or the declarations have moved past it. Last, the
703 composed and generated files are written again, since both read the
704 locks. Idempotent: re-running it is the recovery procedure.
705
706 The three options are uv's and reach both halves: ``--frozen``
707 installs each lock as it is and resolves nothing, ``--locked``
708 refuses when a lock is not current, and ``--offline`` uses what the
709 machine already holds. As uv's two leave its lock unchanged, ours
710 change nothing a commit holds: the branch is not moved and no
711 tracked file is written, while the checkout's own untracked files
712 are. They differ as uv's do, in whether the locks are judged:
713 ``--locked`` refuses a stale one, so CI's setup runs it and a job
714 holds what a person's checkout holds; ``--frozen`` takes them as
715 they are, which is how the per-command hook brings a checkout
716 current before every command, running this verb's work frozen and
717 offline ([livery.workshop._reconcile.apply][]). Judging the tracked
718 files stays the drift check's.
719
720 A frozen sync reads the receipts first
721 ([livery.workshop._reconcile.current][]). When the environment, the
722 tools and the delivered files all match them, its local steps have
723 nothing to do and are skipped, and nothing is printed, so the hook
724 costs a current checkout those reads and nothing else. A plain sync
725 renders and installs again regardless, since a fragment edit is in
726 no receipt; the tools' supply alone reads its receipts in every
727 mode ([livery.workshop._tool_tasks.sync_tools][]).
728
729 A checkout the first act moved holds code this process has not
730 loaded, so the rest of the sync is handed to a fresh process on
731 that code; the handoff is named, and a process that cannot be
732 started continues on the loaded code and says so. An extension the
733 workspace lists that the command started without is mounted the
734 same way before anything renders or locks: a sync never renders
735 without one. A newly listed extension is installed first, the way
736 the workspace resolves it: the sync writes the project file alone,
737 whose dev group then names the extension's distribution, and runs
738 ``uv sync``, which locks and installs through the file's
739 ``[tool.uv.sources]`` and indexes. So an extension the workspace
740 sources from a path or from git installs from there. When no
741 installed distribution declares the extension even then, the sync
742 refuses, naming the extension and the list that brings it. Before
743 that refusal, and when the install fails, it puts the project file,
744 its receipt and ``uv.lock`` back as they were. A ``uv sync`` that
745 moves or removes the distribution of the workshop, or of an
746 extension the command mounted, hands the rest of the sync over the
747 same way, before anything reads it again: this process found it
748 where the install no longer puts it. A handoff that cannot start
749 then refuses, and the next sync completes.
750
751 Shell completion answers from a manifest this command wrote as it
752 started, from what was installed then. A sync that changed the
753 distributions the environment installs, run by a person at a
754 terminal, starts the detached rebuild of that manifest for the
755 directory the command was typed in
756 ([livery.footman.refresh_completion][]), so the next Tab there
757 offers the tasks an installed extension brings. A sync that changed
758 nothing installed starts nothing, and so does one no person is
759 there for, in CI or under `--no-input`. A rebuild that cannot
760 start leaves the sync's outcome as it is.
761
762 Returns:
763 Whether the local steps ran. A frozen sync of a current
764 checkout returns False.
765 """
766 root = workspace_root()
767 if root is None:767 ↛ 768line 767 didn't jump to line 768 because the condition on line 767 was never true
768 fail("no workspace: no workshop.toml above the working directory")
769 synced = sync_and_compare(root, frozen=frozen, locked=locked, offline=offline)
770 if synced.installs_changed:
771 footman.refresh_completion(footman.current().invoked_dir or root)
772 return synced.ran
773
774
775class Synced(NamedTuple):
776 """What one sync did, as `sync_and_compare` reports it."""
777
778 ran: bool
779 """Whether the local steps ran. A frozen sync of a current checkout runs none."""
780 installs_changed: bool
781 """Whether the installed distributions differ after the sync from before it."""
782
783
784def sync_and_compare(
785 root: Path, *, frozen: bool = False, locked: bool = False, offline: bool = False
786) -> Synced:
787 """Do the sync verb's work on *root*, comparing what is installed before and after.
788
789 `sync_checkout` does the work, and the options mean what they mean
790 there. The comparison reads every distribution's name and entry
791 points in the environment, so an editable member installed again
792 with new entry points counts as a change. A sync whose local steps
793 did not run changed nothing, and the environment is not read again.
794
795 Returns:
796 Whether the local steps ran, and whether they changed what the
797 environment installs.
798 """
799 from livery.workshop._reconcile import installed_distributions
800
801 before = installed_distributions(root)
802 ran = sync_checkout(root, frozen=frozen, locked=locked, offline=offline)
803 return Synced(ran, ran and installed_distributions(root) != before)
804
805
806def sync_checkout(
807 root: Path, *, frozen: bool = False, locked: bool = False, offline: bool = False
808) -> bool:
809 """Do the sync verb's work on the workspace at *root*; whether the local steps ran.
810
811 [livery.workshop._sync.sync][] runs it on the workspace above its
812 task's directory; the options mean what they mean there. The
813 per-command hook ([livery.workshop._reconcile.apply][]) runs it
814 frozen and offline on the root it found, as a plain call and never
815 as a call of the verb: a task called from a hook resolves its own
816 directory, which can lie outside *root*, and its row joins the
817 run's report, where its failure would fail the command the hook
818 must never stop.
819
820 Returns:
821 Whether the local steps ran. A frozen sync of a current
822 checkout returns False.
823
824 Raises:
825 Failed: naming what stopped the sync, a stale lock under
826 *locked* or a listed extension this process cannot mount.
827 RunFailed: when a command one of the steps runs exits non-zero.
828 """
829 if locked:
830 # Refused before anything runs, naming the lock and the sync that
831 # writes it: uv's own refusal would name uv's command instead.
832 problems = stale_locks(root)
833 if problems:
834 fail(
835 "--locked: "
836 + "; ".join(problems)
837 + f". `{footman.prog()} sync` writes the locks; commit them"
838 )
839 # Neither mode changes what a commit holds.
840 local_only = locked or frozen
841 # Each phase is a step: a receipt line with its duration, a row in
842 # --json, a slice in a profile, and a unit parallel() could schedule
843 # where two were independent. They are not yet: the fetch moves the
844 # checkout before anything renders, the delivery writes the conan
845 # workspace file the tools' build reads, the tools come before uv's
846 # build, and the last delivery and the generated files read the locks
847 # both halves just wrote.
848 fetched = False
849 mirrored: tuple[str, ...] | None = None
850 if not local_only and not offline and git.has_commits(root):
851 mirrored = _mirrored(root)
852 fetched = fetch_origin(root, mirrored)()
853 if not local_only and not git.has_commits(root):
854 print(" no git history here: nothing to bring current")
855 elif not local_only:
856 # Offline, the remote-tracking refs the last fetch left are what
857 # the checkout holds: the bring-current reads them and fetches nothing.
858 moved = bring_checkout_current(root, fetched=fetched or offline)()
859 if moved is not None:
860 continue_on_moved_code(root, *moved)
861 # Before anything renders or locks: a listed extension the mount
862 # found missing would count as withdrawn, and its files and its
863 # tools would go.
864 require_mounted(
865 root,
866 _uv_flags(frozen=frozen, locked=locked, offline=offline),
867 install=not local_only,
868 )
869 # Before anything discovers packages: a removed package's leftover
870 # directory refuses discovery until it goes.
871 for line in sweep_residue(root):
872 print(line)
873 # The receipts say what the machine holds against the locks and the
874 # delivery. A frozen sync matches the machine to them and nothing
875 # else, so when every receipt matches its local steps have nothing
876 # to do and are skipped, silently: the per-command hook runs this
877 # form before every command. A plain sync renders again regardless,
878 # since a fragment edit is in no receipt. A receipt that cannot be
879 # read is off: the steps rewrite it.
880 from livery.workshop._reconcile import current, record_receipt
881
882 try:
883 why = current(root)
884 except Exception as error:
885 why = f"the receipts could not be read ({error})"
886 skipped = frozen and not why
887 # Offline touches no network: the mirror the last fetch took stands.
888 if offline:
889 if not skipped:
890 print(" store: not fetched (--offline); the last snapshot stands")
891 elif mirrored is None or _mirrored(root) != mirrored:
892 # The fetch above named the series declared before the mount. An
893 # extension the mount installed keeps series that fetch could
894 # not name, so the mirror is taken again, and only then.
895 fetch_store_mirror(root)()
896 if skipped:
897 return False
898 if frozen:
899 print(f" {why}; syncing from what the machine holds")
900 sync_workspace_files(root, local_only=local_only)()
901 sync_locked_tools(root, frozen=frozen or locked, offline=offline)()
902 prepare_installs(root)()
903 shifted = uv_sync(root, _uv_flags(frozen=frozen, locked=locked, offline=offline))()
904 # Before anything reads an extension again: one the install moved is
905 # no longer where this process found it.
906 continue_on_moved_extensions(root, shifted)
907 deliver_files(root, local_only=local_only)()
908 if not local_only:
909 write_generated(root)()
910 # The receipt records this sync, so the next command's sync
911 # compares instead of syncing again.
912 record_receipt(root)
913 return True
914
915
916def stale_locks(root: Path) -> list[str]:
917 """What is not current about *root*'s locks; empty when both are.
918
919 The two locks `sync --locked` refuses on: `uv.lock` against the
920 project's declarations (``uv lock --check``) and `toolroom.lock`
921 against its sites. A workspace without a lock has nothing here to
922 judge. The installed plugins are read again first, since a sync in
923 another process may have moved them under this one.
924 """
925 import livery.toolroom.tools as tools
926 from livery.footman import rescan_entry_points
927 from livery.toolroom.store import LOCK_FILE
928 from livery.workshop._tools import lock_is_current
929
930 problems: list[str] = []
931 if (root / "uv.lock").is_file():
932 result = tools.uv.opts(cwd=root, nofail=True, recorded=False)("lock", "--check")
933 if result.code != 0:933 ↛ 951line 933 didn't jump to line 951 because the condition on line 933 was always true
934 said = [
935 line.strip()
936 for line in (result.stderr or result.stdout).splitlines()
937 if line.strip()
938 ]
939 if any("needs to be updated" in line for line in said):
940 problems.append(
941 "uv.lock is not current: the declarations moved past it"
942 )
943 else:
944 # Not a verdict on the lock: uv could not resolve to
945 # compare (no network, an index refused), in its words.
946 error = next((line for line in said if line.startswith("error")), "")
947 problems.append(
948 "uv.lock could not be checked"
949 + (f" ({error or said[-1]})" if said else "")
950 )
951 if (root / LOCK_FILE).is_file():
952 # A plugin's tools are read through its installed metadata. A
953 # member stamped to a new version and synced by any command in
954 # this checkout moves to a new dist-info directory, and an entry
955 # point scanned before the move then names no distribution, which
956 # drops its plugin's tools. The release train makes this check
957 # half an hour after its scan.
958 rescan_entry_points()
959 current, why = lock_is_current(root)
960 if not current:
961 problems.append(f"{LOCK_FILE} is not current ({why})")
962 return problems
963
964
965def sweep_residue(root: Path) -> list[str]:
966 """Remove what removed packages left under ``packages/``; the lines.
967
968 A directory under ``packages/`` without a ``workshop.toml`` goes
969 when git tracks nothing under it and every file it holds is one git
970 ignores: the leftovers of a package the checkout moved past the
971 removal of ([livery.workshop._packages.Leftover][]). A directory
972 holding a file git neither tracks nor ignores, or a machine secret,
973 is named and kept; one where git tracks a file is a package missing
974 its contract, which discovery refuses by name. Says nothing when
975 there is nothing to sweep.
976 """
977 import shutil
978
979 from livery.workshop._packages import (
980 RESIDUE,
981 SECRET,
982 UNKNOWN,
983 UNTRACKED,
984 leftover,
985 package_directories,
986 )
987
988 lines: list[str] = []
989 for directory in package_directories(root):
990 if (directory / "workshop.toml").is_file():
991 continue
992 found = leftover(root, directory)
993 name = directory.relative_to(root).as_posix()
994 shown = ", ".join(found.paths[:3]) + (
995 f" and {len(found.paths) - 3} more" if len(found.paths) > 3 else ""
996 )
997 if found.state == RESIDUE:
998 try:
999 shutil.rmtree(directory)
1000 except OSError as error:
1001 lines.append(
1002 f" {name}: what a removed package left behind could not be"
1003 f" removed ({error}); delete the directory by hand"
1004 )
1005 continue
1006 lines.append(
1007 f" {name}: removed {len(found.paths)} ignored file(s) a removed"
1008 " package left behind"
1009 )
1010 elif found.state == UNTRACKED:
1011 lines.append(
1012 f" {name}: no workshop.toml, and it holds files git neither tracks"
1013 f" nor ignores ({shown}); kept"
1014 )
1015 elif found.state == SECRET:
1016 lines.append(
1017 f" {name}: no workshop.toml, and it holds a machine secret no"
1018 f" checkout restores ({shown}); kept: move the secret out, then"
1019 " delete the directory"
1020 )
1021 elif found.state == UNKNOWN:
1022 lines.append(
1023 f" {name}: no workshop.toml, and git could not say what it holds"
1024 f" ({found.reason}); kept"
1025 )
1026 return lines
1027
1028
1029def fetch_store_lines(root: Path) -> list[str]:
1030 """Mirror the store's row series into the checkout; the line to print.
1031
1032 The mirror is what a machine's ``check`` reads
1033 ([livery.git.fetched_snapshot][]): the remote row series the
1034 workspace declares ([livery.workshop._series.mirrored_series][]),
1035 never a keyed family, so a sync or a start refreshes it while it
1036 has the network. A fetch that fails prints its reason and stops
1037 nothing: the gate falls open on a store it cannot read, and the
1038 last mirror stands.
1039 """
1040 from livery.git import fetch_store
1041 from livery.workshop._series import mirrored_prefixes
1042
1043 return store_lines(
1044 fetch_store(
1045 state_store(root),
1046 series=_mirrored(root),
1047 prefixes=mirrored_prefixes(root),
1048 )
1049 )
1050
1051
1052def _mirrored(root: Path) -> tuple[str, ...]:
1053 """The series a sync mirrors: the remote row series *root* declares now."""
1054 from livery.workshop._series import mirrored_series
1055
1056 return mirrored_series(root)
1057
1058
1059def store_lines(fetched: Fetched) -> list[str]:
1060 """The line `fetch_store`'s answer prints: what the mirror holds and what moved."""
1061 if fetched.why:
1062 return [
1063 f" store: origin's state store not fetched ({fetched.why}); the last"
1064 " snapshot stands"
1065 ]
1066 if not fetched.changed:
1067 return [" store: up to date"]
1068 return [f" store: {fetched.changed} ref(s) changed, {fetched.held} mirrored"]
1069
1070
1071def _fetch_origin(root: Path, series: tuple[str, ...]) -> bool:
1072 """One round trip: origin's heads for the bring-current, the series for the gate.
1073
1074 Mirrors *series* and prints the store's line. Returns whether the
1075 fetch succeeded, so the bring-current knows origin's heads are
1076 fresh; after a failed fetch it fetches for itself and fails in its
1077 own words.
1078 """
1079 from livery.git import fetch_store
1080 from livery.workshop._series import mirrored_prefixes
1081
1082 fetched = fetch_store(
1083 state_store(root),
1084 series=series,
1085 prefixes=mirrored_prefixes(root),
1086 branches=True,
1087 )
1088 for line in store_lines(fetched):
1089 print(line)
1090 return not fetched.why
1091
1092
1093def _bring_checkout_current(root: Path, *, fetched: bool) -> tuple[str, str]:
1094 """Bring the checkout current; HEAD before and after, for the handoff."""
1095 before = git.head_sha(root)
1096 bring_current(root, interactive=footman.attended(), fetched=fetched)
1097 return before, git.head_sha(root)
1098
1099
1100def _fetch_store_mirror(root: Path) -> None:
1101 for line in fetch_store_lines(root):1101 ↛ 1102line 1101 didn't jump to line 1102 because the loop on line 1101 never started
1102 print(line)
1103
1104
1105def _sync_workspace_files(root: Path, *, local_only: bool) -> None:
1106 for line in sync_workspace(root, local_only=local_only):1106 ↛ 1107line 1106 didn't jump to line 1107 because the loop on line 1106 never started
1107 print(line)
1108
1109
1110def _sync_locked_tools(root: Path, *, frozen: bool, offline: bool) -> None:
1111 from livery.workshop._tool_tasks import sync_tools
1112
1113 sync_tools(root, frozen=frozen, offline=offline)
1114
1115
1116def _prepare_installs(root: Path) -> None:
1117 # What a member's install needs in place first: the sync phase's
1118 # steps say what, conan's profile among them.
1119 from livery.workshop._lifecycle import sync as sync_phase
1120 from livery.workshop._packages import discover_packages
1121
1122 sync_phase(discover_packages(root), root)
1123
1124
1125def _uv_sync(root: Path, flags: tuple[str, ...]) -> tuple[str, ...]:
1126 """Run ``uv sync``; of the base and the installed set, those whose place it changed.
1127
1128 A place is where this process reads the base or an extension and
1129 where the environment installs it (`install_places` in the
1130 extensions module): one whose place differs after the install is
1131 one the install moved or removed.
1132 """
1133 from livery.footman import rescan_entry_points
1134 from livery.workshop._extensions import install_places, stack_names
1135 from livery.workshop._uv import run_uv
1136
1137 before = install_places(stack_names(root))
1138 run_uv("sync", *flags, root=root)
1139 # The install moves a member stamped to another version to a new
1140 # dist-info directory, and an entry point scanned before the move
1141 # names no distribution after it. Every reader that follows, the
1142 # deliver step first, reads the installed metadata as it now is.
1143 rescan_entry_points()
1144 after = install_places(before)
1145 return tuple(name for name, place in before.items() if after[name] != place)
1146
1147
1148def _deliver_files(root: Path, *, local_only: bool) -> None:
1149 from livery.workshop._shipped_files import deliver
1150
1151 for line in deliver(root, local_only=local_only):
1152 print(line)
1153
1154
1155def _write_generated(root: Path) -> None:
1156 from livery.workshop._templates import apply_generated
1157
1158 for path in apply_generated(root):
1159 print(f" generated: {path}")
1160
1161
1162# The sync's phases as steps, live: each prints its own lines as it goes
1163# and earns a receipt with its duration, a row in --json and a slice in a
1164# profile. A phase's title is what every one of those shows.
1165fetch_origin = step(_fetch_origin, title="fetch origin").opts(capture=False)
1166bring_checkout_current = step(_bring_checkout_current, title="bring current").opts(
1167 capture=False
1168)
1169fetch_store_mirror = step(_fetch_store_mirror, title="fetch store").opts(capture=False)
1170sync_workspace_files = step(_sync_workspace_files, title="sync workspace").opts(
1171 capture=False
1172)
1173sync_locked_tools = step(_sync_locked_tools, title="sync tools").opts(capture=False)
1174prepare_installs = step(_prepare_installs, title="prepare install").opts(capture=False)
1175uv_sync = step(_uv_sync, title="uv sync").opts(capture=False)
1176deliver_files = step(_deliver_files, title="deliver").opts(capture=False)
1177write_generated = step(_write_generated, title="generated").opts(capture=False)
1178
1179
1180def materialise_tools(root: Path, *, offline: bool = False) -> list[str]:
1181 """Supply every locked tool through the store and write the receipts; the lines.
1182
1183 The bundle the sites require, materialised as `fm sync` and
1184 `fm toolroom.sync` enter the environment, and the stubs the
1185 checkers read written after it: a checkout with no `toolroom.lock`
1186 yet has nothing to materialise and says so. *offline* supplies from
1187 the machine's store and its sources alone.
1188 """
1189 from livery.toolroom.store import LOCK_FILE
1190 from livery.workshop._tools import current_lock, materialise, stub_lines
1191
1192 if current_lock(root) is None:
1193 return [f" tools: no {LOCK_FILE}; `{footman.prog()} toolroom.lock` writes one"]
1194 done = materialise(root, strict=False, offline=offline)
1195 supplied = [m for m in done if m.receipt is not None]
1196 installed = [m.receipt.tool for m in supplied if m.installed and m.receipt]
1197 hosted = [
1198 f"{m.receipt.tool} {m.receipt.answered}".rstrip()
1199 for m in supplied
1200 if m.receipt is not None and m.receipt.source == "host"
1201 ]
1202 lines = [
1203 (
1204 f" tools: {len(supplied)} receipt(s), installed {', '.join(installed)}"
1205 if installed
1206 else " tools: up to date"
1207 )
1208 + (f", from the host: {', '.join(hosted)}" if hosted else ""),
1209 ]
1210 lines += [f" tools: {m.note}" for m in done if m.note]
1211 lines += [f" tools: could not materialise: {m.failure}" for m in done if m.failure]
1212 return lines + stub_lines(root, strict=False, offline=offline)
1213
1214
1215@task
1216def integrate() -> None:
1217 """Bring ``origin/main`` into the current branch by merge.
1218
1219 The shared-branch spelling: a merge never rewrites, so every
1220 other copy of the branch stays valid, and the squash erases the
1221 merge commit at landing. A conflict in the render's receipts alone
1222 is merged key by key and committed; any other conflict stops with
1223 git's own words: resolve, commit, and re-run.
1224 """
1225 root = workspace_root()
1226 if root is None:1226 ↛ 1227line 1226 didn't jump to line 1227 because the condition on line 1226 was never true
1227 fail("no workspace: no workshop.toml above the working directory")
1228 branch = git.current_branch(root)
1229 if not branch or branch == "main" or branch.startswith("workflow/"):1229 ↛ 1230line 1229 didn't jump to line 1230 because the condition on line 1229 was never true
1230 fail(
1231 "integrate brings origin/main into a feature branch, and"
1232 f" you are on {branch or '(detached)'!r}."
1233 )
1234 if not git.is_clean(root):1234 ↛ 1235line 1234 didn't jump to line 1235 because the condition on line 1234 was never true
1235 fail(
1236 "the working tree has uncommitted changes: commit them first,"
1237 " so the merge has one parent to speak for you."
1238 )
1239 before = git.head_sha(root)
1240 try:
1241 git.integrate(root, "main")
1242 except git.GitError as error:
1243 if not resolve_receipts(root):
1244 fail(
1245 f"the merge stopped on conflicts:\n{error}\n Resolve them,"
1246 " `git commit`, and the branch is current; re-running any verb"
1247 " is the recovery."
1248 )
1249 git.run(root, "commit", "--no-edit")
1250 if git.head_sha(root) == before:
1251 print(" already current with origin/main")
1252 return
1253 print(f" merged origin/main into {branch}")
1254 for line in sweep_residue(root):
1255 print(line)
1256 match_lock(root, since=before)
1257
1258
1259#: The files whose change across a HEAD move leaves the venv behind:
1260#: the lock, the root manifest, and every member's.
1261LOCK_FILES = ("uv.lock", "pyproject.toml", "packages/*/pyproject.toml")
1262
1263
1264def match_lock(root: Path, *, since: str) -> None:
1265 """Match the venv to the lock when HEAD moved across a change to it; say so.
1266
1267 *since* is the commit HEAD moved from. A merge that changed the
1268 lock, the root manifest, or a member's manifest leaves the venv
1269 installed from the old ones (a new entry point the venv never
1270 learned made the next gate red until a sync); the sync runs here,
1271 at the verb's end, and the receipts record it, so the next
1272 command's reconcile finds nothing to do.
1273 """
1274 from livery.workshop._reconcile import record_receipt
1275 from livery.workshop._uv import run_uv
1276
1277 changed = git.changed_between(root, since, "HEAD", LOCK_FILES)
1278 if not changed:
1279 return
1280 print(f" matching the lock: the merge changed {', '.join(changed)}")
1281 run_uv("sync", root=root)
1282 record_receipt(root)
1283 print(" matched the lock; the environment agrees with the merge")