1"""What the workshop leaves in the runner's directories, and the sweep that bounds it.
3The runner's data directory holds the workshop's durable state: the
4issue worktrees under ``worktrees/<repo>/`` and the loop's workspace.
5footman's collector never touches it, by design. This module is the
6workshop's sweeper, registered under footman's ``footman.sweepers``
7entry point and run by ``fm janitor``, by the daily collector child,
8and, for the worktrees alone, by every ``fm start``.
9It also runs the state store's own janitor over every series the
10workshop keeps ([livery.workshop._series][]), in the scope the run
11has: the checkout's local series on a machine, the remote series too
12inside CI.
14The rules, each saying what went or why it stayed:
16- A worktree whose linked git directory is gone (its checkout was
17 deleted) goes. This rule is quick and offline: no forge is asked.
18- A worktree whose issue is closed, or whose branch's pull request
19 merged, goes when the branch holds nothing that exists nowhere else,
20 decided by the one keep-or-drop rule ``fm issue.close`` uses
21 ([livery.workshop._submit.only_local_work][]): a tree whose tip the
22 merge took holds nothing only there, whatever a squash did to the
23 ancestry. A tree with uncommitted changes or commits past the merge
24 stays and is named, and so is a tree whose issue is open or whose
25 forge cannot be asked. A closed issue's tree also stays while its
26 branch heads an open pull request, as ``fm issue.close`` leaves it,
27 since that pull request still needs the branch. A tree whose name
28 carries no issue number is judged by its branch's pull request
29 alone. This rule asks the forge, since asking is what proves the
30 removal safe.
31- A local branch of the checkout whose pull request merged and took
32 its tip goes by the same rule; the branch a linked worktree holds
33 belongs to the worktree rule, and the branch the checkout stands on
34 is named for ``fm sync`` to step off. On demand only, like the rule
35 above.
36- Every declared series of the state store is bounded, windows,
37 ages, and orphans, as [livery.git.sweep][] says.
38- The config directory is reported, never touched: anything beside the
39 user's config, tasks file, and shared env file is named. The loop's
40 workspace is reported by size and kept.
41"""
43from __future__ import annotations
45import os
46import shutil
47from datetime import datetime
48from pathlib import Path
49from typing import Any
51import livery.footman as footman
52from livery import git
54#: The workshop's homes under the data directory.
55WORKTREES = "worktrees"
56LOOP = "workshop-e2e"
58#: What the config directory is for; anything else is reported.
59CONFIG_OWN = ("config.toml", ".repo.shared.env", "__pycache__")
62def sweep(
63 *, data_dir: Path, config_dir: Path, dry_run: bool, now: datetime, **facts: Any
64) -> list[str]:
65 """The workshop's sweep, footman's sweeper contract; the lines to print.
67 The state store's series are the checkout's: the one above the
68 working directory, or the ``root`` among *facts* when one is
69 given, ``None`` for no checkout at all.
70 """
71 from livery.workshop._extensions import workspace_root
73 root = facts["root"] if "root" in facts else workspace_root()
74 lines = sweep_worktrees(data_dir / WORKTREES, dry_run=dry_run)
75 lines += sweep_branches(root, dry_run=dry_run)
76 lines += sweep_store(root, dry_run=dry_run, now=now)
77 lines += report_config(config_dir)
78 lines += report_loop(data_dir / LOOP)
79 return lines
82# --- the worktrees -------------------------------------------------------------
85def _gitdir(tree: Path) -> Path | None:
86 """The linked git directory a worktree's ``.git`` file names, or None."""
87 marker = tree / ".git"
88 if not marker.is_file():
89 return None
90 text = marker.read_text("utf-8").strip()
91 if not text.startswith("gitdir:"):91 ↛ 92line 91 didn't jump to line 92 because the condition on line 91 was never true
92 return None
93 return Path(text[len("gitdir:") :].strip())
96def _remove_worktree(tree: Path, gitdir: Path | None) -> None:
97 """Remove *tree* through its checkout's git when that checkout exists."""
98 if gitdir is not None and gitdir.exists():
99 # <checkout>/.git/worktrees/<name>: the checkout is three up.
100 checkout = gitdir.parent.parent.parent
101 try:
102 git.run(checkout, "worktree", "remove", "--force", str(tree))
103 return
104 except git.GitError:
105 pass
106 shutil.rmtree(tree, ignore_errors=True)
107 if gitdir is not None and gitdir.exists():107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true
108 with _quiet():
109 git.run(gitdir.parent.parent.parent, "worktree", "prune")
112class _quiet:
113 def __enter__(self) -> None:
114 return None
116 def __exit__(self, *exc: object) -> bool:
117 return True
120def _forge_root(tree: Path, gitdir: Path) -> Path:
121 """The checkout whose forge contract answers for *tree*.
123 A linked worktree's own ``workshop.toml`` may predate a repository
124 move (such as an organisation rename), while its owning checkout
125 holds the current contract; fall back to *tree* when the owning
126 checkout has none.
127 """
128 checkout = gitdir.parent.parent.parent
129 return checkout if (checkout / "workshop.toml").is_file() else tree
132def _repository(tree: Path) -> Any:
133 from livery.workshop._forge_lane import this_repository
135 return this_repository(tree)
138def _done(
139 forge_root: Path, number: int | None, branch: str, tree: Path
140) -> tuple[bool, str, str]:
141 """Whether the work landed, why or why not, and the merged pull request's head.
143 Landed is the issue closed or the branch's pull request merged; a
144 tree named after no issue has only the pull request to answer.
145 A closed issue whose branch still heads an open pull request has
146 not landed: the tree stays for that pull request, as
147 ``fm issue.close`` leaves it. The merged head is ``""`` when no
148 pull request merged.
149 """
150 from livery.workshop._submit import merged_pull_request
152 try:
153 repo = _repository(forge_root)
154 pull = merged_pull_request(repo, tree, branch)
155 head = pull.head_sha if pull is not None else ""
156 if number is not None:
157 work = repo.issue.get(number)
158 if work is not None and work.state == "closed":
159 live = repo.pr.find_by_head(branch) if pull is None else None
160 if live is not None and live.state == "open":
161 return (
162 False,
163 f"issue #{number} is closed, but PR #{live.number}"
164 " is open from its branch",
165 "",
166 )
167 return True, f"issue #{number} is closed", head
168 if pull is not None:
169 return True, f"PR #{pull.number} merged", head
170 except Exception as error:
171 return False, f"the forge could not be asked ({error})", ""
172 if number is None:
173 return False, "no merged pull request", ""
174 return False, f"issue #{number} is open", ""
177def _in_tree(path: Path, tree: Path) -> bool:
178 """Whether *path* is *tree* or lies inside it."""
179 try:
180 path.resolve().relative_to(tree.resolve())
181 except (OSError, ValueError):
182 return False
183 return True
186def finish_worktree(
187 tree: Path,
188 *,
189 name: str = "",
190 dry_run: bool = False,
191 allow_chdir: bool = False,
192) -> tuple[bool, str]:
193 """Remove linked worktree *tree* and its local branch when its work landed.
195 The one keep-or-drop rule shared by ``fm finish``, ``fm janitor``,
196 and ``fm start``: queries the owning checkout's forge contract
197 (`_forge_root`), verifies the issue closed or PR merged with no
198 open PR remaining, and confirms `only_local_work` is empty before
199 touching anything. When *allow_chdir* is set and the process stands
200 inside *tree*, moves to the owning checkout first and prints the
201 ``cd`` hint.
202 """
203 from livery.workshop._submit import only_local_work
205 label = name or f"{tree.parent.name}/{tree.name}"
206 verb = "would remove" if dry_run else "removed"
207 gitdir = _gitdir(tree)
208 if gitdir is None:
209 return False, f"worktree {label}: not a linked worktree; kept"
210 if not gitdir.exists():
211 if not dry_run:211 ↛ 213line 211 didn't jump to line 213 because the condition on line 211 was always true
212 _remove_worktree(tree, None)
213 return True, f"worktree {label}: its checkout is gone; {verb}"
214 head, _, _rest = tree.name.partition("-")
215 number = int(head) if head.isdigit() else None
216 try:
217 branch = git.current_branch(tree)
218 except git.GitError as error:
219 return False, f"worktree {label}: git could not answer ({error}); kept"
220 done, why, merged_head = _done(_forge_root(tree, gitdir), number, branch, tree)
221 if not done:
222 return False, f"worktree {label}: {why}; kept"
223 try:
224 only_local = only_local_work(tree, branch, merged_head=merged_head)
225 except git.GitError as error:
226 return False, f"worktree {label}: git could not answer ({error}); kept"
227 if only_local:
228 return False, f"worktree {label}: {why}, but it holds {only_local}; kept"
229 try:
230 standing_here = _in_tree(Path.cwd(), tree)
231 except OSError:
232 standing_here = False
233 if standing_here and not allow_chdir:
234 return (
235 False,
236 f"worktree {label}: {why}, but this process stands inside it;"
237 f" `{footman.prog()} finish` removes it",
238 )
239 if not dry_run:
240 checkout = gitdir.parent.parent.parent
241 moved = False
242 if standing_here:
243 os.chdir(checkout)
244 moved = True
245 _remove_worktree(tree, gitdir)
246 if branch and branch != "main" and git.local_branch_exists(checkout, branch):246 ↛ 248line 246 didn't jump to line 248 because the condition on line 246 was always true
247 git.delete_branch(checkout, branch)
248 if moved:
249 print(f" this shell's directory is gone: cd {checkout}")
250 return True, f"worktree {label}: {why}, nothing only here; {verb}"
253def sweep_worktrees(home: Path, *, dry_run: bool) -> list[str]:
254 """Sweep every ``<repo>/<number>-<slug>`` worktree under *home*; the lines."""
255 lines: list[str] = []
256 if not home.is_dir():
257 return lines
258 for repo_dir in sorted(p for p in home.iterdir() if p.is_dir()):
259 for tree in sorted(p for p in repo_dir.iterdir() if p.is_dir()):
260 _went, line = finish_worktree(
261 tree, name=f"{repo_dir.name}/{tree.name}", dry_run=dry_run
262 )
263 lines.append(line)
264 return lines
267def sweep_branches(
268 root: Path | None, *, dry_run: bool, allow_switch: bool = False
269) -> list[str]:
270 """Drop the checkout's local branches whose pull request merged and took their tip.
272 A branch a linked worktree holds is the worktree rule's; the base
273 branch is never touched; the branch the checkout stands on is
274 named when *allow_switch* is False, since a sweep never moves a
275 person's HEAD. Asks the forge, since asking is what proves the
276 removal safe. The lines say what went and why the rest stayed.
277 """
278 if root is None:
279 return []
280 from livery.workshop._submit import worktree_for
282 try:
283 current = git.current_branch(root)
284 branches = git.local_branches(root, "")
285 except git.GitError as error:
286 return [f"branches: git could not answer ({error}); kept"]
287 lines: list[str] = []
288 for branch in branches:
289 if branch == "main" or worktree_for(root, branch):
290 continue
291 _went, line = finish_branch(
292 root,
293 branch,
294 current=current,
295 dry_run=dry_run,
296 allow_switch=allow_switch,
297 )
298 lines.append(line)
299 return lines
302def finish_branch(
303 root: Path,
304 branch: str,
305 *,
306 current: str,
307 dry_run: bool,
308 allow_switch: bool = False,
309 repo: Any = None,
310) -> tuple[bool, str]:
311 """Drop *branch* when its pull request merged and took its tip; whether it went.
313 The one branch cleanup rule shared by ``fm finish``, ``fm janitor``,
314 ``fm sync``, and ``fm start``. When *branch* is checked out
315 (*current*), *allow_switch* steps onto an up-to-date ``main`` and
316 deletes it through ``teardown_branch``; without *allow_switch*, the
317 branch stays and is named for ``fm sync`` to step off. *repo* is the
318 forge's repository, asked for when absent. The line says what went,
319 or why it stayed.
320 """
321 from livery.workshop._submit import (
322 merged_pull_request,
323 only_local_work,
324 teardown_branch,
325 )
327 try:
328 resolved = repo if repo is not None else _repository(root)
329 found = merged_pull_request(resolved, root, branch)
330 except Exception as error:
331 return False, f"branch {branch}: the forge could not be asked ({error}); kept"
332 if found is None:
333 return False, f"branch {branch}: no merged pull request; kept"
334 only_local = only_local_work(root, branch, merged_head=found.head_sha)
335 if only_local:
336 return False, (
337 f"branch {branch}: PR #{found.number} merged, but it holds"
338 f" {only_local}; kept"
339 )
340 if branch == current:
341 if not allow_switch:
342 return False, (
343 f"branch {branch}: PR #{found.number} merged, but the checkout"
344 f" stands on it; `{footman.prog()} sync` steps off it"
345 )
346 if dry_run:
347 return (
348 True,
349 f"branch {branch}: PR #{found.number} merged, nothing only here;"
350 " would step off onto main and remove",
351 )
352 teardown_branch(resolved, root, branch, "main")
353 return (
354 True,
355 f"branch {branch}: PR #{found.number} merged, nothing only here;"
356 " stepped off onto main and removed",
357 )
358 if not dry_run:
359 git.delete_branch(root, branch)
360 verb = "would remove" if dry_run else "removed"
361 return (
362 True,
363 f"branch {branch}: PR #{found.number} merged, nothing only here; {verb}",
364 )
367sweep_branch = finish_branch
370def _is_linked_worktree(root: Path) -> bool:
371 """Whether *root* is a linked worktree rather than the main checkout."""
372 try:
373 git_dir = git.run(root, "rev-parse", "--git-dir").strip()
374 common_dir = git.run(root, "rev-parse", "--git-common-dir").strip()
375 except git.GitError:
376 return False
377 return git_dir != common_dir
380def _matching_worktree(home: Path, ref: str, number: int | None) -> Path | None:
381 """The linked worktree under *home* matching *ref* or issue/PR *number*."""
382 if not home.is_dir():
383 return None
384 for tree in sorted(p for p in home.iterdir() if p.is_dir()):
385 if tree.name == ref:385 ↛ 386line 385 didn't jump to line 386 because the condition on line 385 was never true
386 return tree
387 if number is not None and tree.name.startswith(f"{number}-"):
388 return tree
389 try:
390 if git.current_branch(tree) == ref:390 ↛ 391line 390 didn't jump to line 391 because the condition on line 390 was never true
391 return tree
392 except git.GitError:
393 continue
394 return None
397def _matching_branch(root: Path, ref: str, number: int | None) -> str:
398 """The local branch in *root* matching *ref* or issue/PR *number*, or empty."""
399 branches = git.local_branches(root, "")
400 if ref in branches:
401 return ref
402 if number is not None:402 ↛ 407line 402 didn't jump to line 407 because the condition on line 402 was always true
403 needle = f"/{number}-"
404 for branch in branches:
405 if needle in branch:405 ↛ 406line 405 didn't jump to line 406 because the condition on line 405 was never true
406 return branch
407 return ""
410def finish_flow(
411 root: Path,
412 ref: str = "",
413 *,
414 all_: bool = False,
415 dry_run: bool = False,
416) -> None:
417 """Clean up finished work: one branch/worktree, or every landed one with *all_*."""
418 from livery.footman import fail
419 from livery.workshop._issue_tasks import worktree_home
420 from livery.workshop._submit import parse_number
422 if ref and all_:
423 fail("name a branch or issue, or pass --all, not both")
424 linked = _is_linked_worktree(root)
425 main_root = git.main_checkout(root) if linked else root
426 home = worktree_home(main_root)
428 if all_:
429 lines: list[str] = []
430 if home.is_dir():430 ↛ 440line 430 didn't jump to line 440 because the condition on line 430 was always true
431 for tree in sorted(p for p in home.iterdir() if p.is_dir()):
432 if linked and tree.resolve() == root.resolve():432 ↛ 433line 432 didn't jump to line 433 because the condition on line 432 was never true
433 continue
434 _went, line = finish_worktree(
435 tree,
436 name=f"{home.name}/{tree.name}",
437 dry_run=dry_run,
438 )
439 lines.append(line)
440 if linked:440 ↛ 441line 440 didn't jump to line 441 because the condition on line 440 was never true
441 _went, line = finish_worktree(
442 root,
443 name=f"{root.parent.name}/{root.name}",
444 dry_run=dry_run,
445 allow_chdir=True,
446 )
447 lines.append(line)
448 lines.extend(
449 sweep_branches(main_root, dry_run=dry_run, allow_switch=not linked)
450 )
451 if not lines:451 ↛ 452line 451 didn't jump to line 452 because the condition on line 451 was never true
452 print(" nothing finished to clean up")
453 return
454 for line in lines:
455 print(f" {line}")
456 return
458 if ref:
459 number = parse_number(ref)
460 matched_tree = _matching_worktree(home, ref, number)
461 if matched_tree is not None:
462 went, line = finish_worktree(
463 matched_tree,
464 name=f"{matched_tree.parent.name}/{matched_tree.name}",
465 dry_run=dry_run,
466 allow_chdir=linked and matched_tree.resolve() == root.resolve(),
467 )
468 if not went:468 ↛ 469line 468 didn't jump to line 469 because the condition on line 468 was never true
469 fail(line)
470 print(f" {line}")
471 return
472 branch = _matching_branch(main_root, ref, number)
473 if branch:
474 current = git.current_branch(main_root)
475 went, line = finish_branch(
476 main_root,
477 branch,
478 current=current,
479 dry_run=dry_run,
480 allow_switch=not linked,
481 )
482 if not went:482 ↛ 483line 482 didn't jump to line 483 because the condition on line 482 was never true
483 fail(line)
484 print(f" {line}")
485 return
486 fail(f"no worktree or local branch matches {ref!r}")
488 if linked:
489 went, line = finish_worktree(
490 root,
491 name=f"{root.parent.name}/{root.name}",
492 dry_run=dry_run,
493 allow_chdir=True,
494 )
495 if not went:495 ↛ 496line 495 didn't jump to line 496 because the condition on line 495 was never true
496 fail(line)
497 print(f" {line}")
498 return
500 current = git.current_branch(root)
501 if not current or current == "main":
502 fail("already on main: name a branch or issue, or pass --all")
503 went, line = finish_branch(
504 root, current, current=current, dry_run=dry_run, allow_switch=True
505 )
506 if not went:506 ↛ 507line 506 didn't jump to line 507 because the condition on line 506 was never true
507 fail(line)
508 print(f" {line}")
511# --- the rest of the data directory --------------------------------------------
514def sweep_store(root: Path | None, *, dry_run: bool, now: datetime) -> list[str]:
515 """Bound every declared series of the state store in the run's scope; the lines."""
516 from contextlib import nullcontext
518 from livery.git import remote_snapshot
519 from livery.git import sweep as sweep_series
520 from livery.workshop._ci_context import run_context, state_store
521 from livery.workshop._proved import sweep_proved_store
522 from livery.workshop._series import declared
524 if root is None:
525 return ["state store: no checkout here; nothing swept"]
526 remote = run_context() is not None
527 # One listing of the remote namespace; each sweep fetches only the refs it
528 # actually inspects instead of pulling every proved-parts blob upfront.
529 scope = remote_snapshot(state_store(root)) if remote else nullcontext()
530 with scope:
531 lines = sweep_series(
532 state_store(root), declared(root), remote=remote, dry_run=dry_run, now=now
533 )
534 if remote:534 ↛ 535line 534 didn't jump to line 535 because the condition on line 534 was never true
535 lines += sweep_proved_store(root, dry_run=dry_run, now=now)
536 return [f"state store: {line.strip()}" for line in lines]
539def report_config(config_dir: Path) -> list[str]:
540 """Name what sits in the config directory beside the user's own files."""
541 from livery.footman import tasks_file_name
543 if not config_dir.is_dir():
544 return []
545 own = {*CONFIG_OWN, tasks_file_name()}
546 foreign = sorted(p.name for p in config_dir.iterdir() if p.name not in own)
547 if not foreign:547 ↛ 548line 547 didn't jump to line 548 because the condition on line 547 was never true
548 return []
549 return [
550 f"config: {name} is not the config, the tasks file, or the shared env;"
551 " yours to remove"
552 for name in foreign
553 ]
556def report_loop(home: Path) -> list[str]:
557 """The loop's workspace by size, kept: `fm ci.e2e` reuses it."""
558 if not home.is_dir():
559 return []
560 total = sum(p.stat().st_size for p in home.rglob("*") if p.is_file())
561 import livery.footman as footman
563 return [
564 f"loop workspace: {total / 1e6:.0f} MB at {home};"
565 f" kept for `{footman.prog()} ci.e2e`"
566 ]