Skip to content

livery.workshop._sweep

livery.workshop._sweep

What the workshop leaves in the runner's directories, and the sweep that bounds it.

The runner's data directory holds the workshop's durable state: the issue worktrees under worktrees/<repo>/ and the loop's workspace. footman's collector never touches it, by design. This module is the workshop's sweeper, registered under footman's footman.sweepers entry point and run by fm janitor, by the daily collector child, and, for the worktrees alone, by every fm start. It also runs the state store's own janitor over every series the workshop keeps (livery.workshop._series), in the scope the run has: the checkout's local series on a machine, the remote series too inside CI.

The rules, each saying what went or why it stayed:

  • A worktree whose linked git directory is gone (its checkout was deleted) goes. This rule is quick and offline: no forge is asked.
  • A worktree whose issue is closed, or whose branch's pull request merged, goes when the branch holds nothing that exists nowhere else, decided by the one keep-or-drop rule fm issue.close uses (livery.workshop._submit.only_local_work): a tree whose tip the merge took holds nothing only there, whatever a squash did to the ancestry. A tree with uncommitted changes or commits past the merge stays and is named, and so is a tree whose issue is open or whose forge cannot be asked. A closed issue's tree also stays while its branch heads an open pull request, as fm issue.close leaves it, since that pull request still needs the branch. A tree whose name carries no issue number is judged by its branch's pull request alone. This rule asks the forge, since asking is what proves the removal safe.
  • A local branch of the checkout whose pull request merged and took its tip goes by the same rule; the branch a linked worktree holds belongs to the worktree rule, and the branch the checkout stands on is named for fm sync to step off. On demand only, like the rule above.
  • Every declared series of the state store is bounded, windows, ages, and orphans, as livery.git.sweep says.
  • The config directory is reported, never touched: anything beside the user's config, tasks file, and shared env file is named. The loop's workspace is reported by size and kept.

Functions:

Name Description
sweep

The workshop's sweep, footman's sweeper contract; the lines to print.

finish_worktree

Remove linked worktree tree and its local branch when its work landed.

sweep_worktrees

Sweep every <repo>/<number>-<slug> worktree under home; the lines.

sweep_branches

Drop the checkout's local branches whose pull request merged and took their tip.

finish_branch

Drop branch when its pull request merged and took its tip; whether it went.

finish_flow

Clean up finished work: one branch/worktree, or every landed one with all_.

sweep_store

Bound every declared series of the state store in the run's scope; the lines.

report_config

Name what sits in the config directory beside the user's own files.

report_loop

The loop's workspace by size, kept: fm ci.e2e reuses it.

Attributes:

Name Type Description
WORKTREES
LOOP
CONFIG_OWN
sweep_branch

WORKTREES module-attribute

WORKTREES = 'worktrees'

LOOP module-attribute

LOOP = 'workshop-e2e'

CONFIG_OWN module-attribute

CONFIG_OWN = ('config.toml', '.repo.shared.env', '__pycache__')

sweep_branch module-attribute

sweep_branch = finish_branch

sweep

sweep(*, data_dir: Path, config_dir: Path, dry_run: bool, now: datetime, **facts: Any) -> list[str]

The workshop's sweep, footman's sweeper contract; the lines to print.

The state store's series are the checkout's: the one above the working directory, or the root among facts when one is given, None for no checkout at all.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def sweep(
    *, data_dir: Path, config_dir: Path, dry_run: bool, now: datetime, **facts: Any
) -> list[str]:
    """The workshop's sweep, footman's sweeper contract; the lines to print.

    The state store's series are the checkout's: the one above the
    working directory, or the ``root`` among *facts* when one is
    given, ``None`` for no checkout at all.
    """
    from livery.workshop._extensions import workspace_root

    root = facts["root"] if "root" in facts else workspace_root()
    lines = sweep_worktrees(data_dir / WORKTREES, dry_run=dry_run)
    lines += sweep_branches(root, dry_run=dry_run)
    lines += sweep_store(root, dry_run=dry_run, now=now)
    lines += report_config(config_dir)
    lines += report_loop(data_dir / LOOP)
    return lines

finish_worktree

finish_worktree(tree: Path, *, name: str = '', dry_run: bool = False, allow_chdir: bool = False) -> tuple[bool, str]

Remove linked worktree tree and its local branch when its work landed.

The one keep-or-drop rule shared by fm finish, fm janitor, and fm start: queries the owning checkout's forge contract (_forge_root), verifies the issue closed or PR merged with no open PR remaining, and confirms only_local_work is empty before touching anything. When allow_chdir is set and the process stands inside tree, moves to the owning checkout first and prints the cd hint.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def finish_worktree(
    tree: Path,
    *,
    name: str = "",
    dry_run: bool = False,
    allow_chdir: bool = False,
) -> tuple[bool, str]:
    """Remove linked worktree *tree* and its local branch when its work landed.

    The one keep-or-drop rule shared by ``fm finish``, ``fm janitor``,
    and ``fm start``: queries the owning checkout's forge contract
    (`_forge_root`), verifies the issue closed or PR merged with no
    open PR remaining, and confirms `only_local_work` is empty before
    touching anything. When *allow_chdir* is set and the process stands
    inside *tree*, moves to the owning checkout first and prints the
    ``cd`` hint.
    """
    from livery.workshop._submit import only_local_work

    label = name or f"{tree.parent.name}/{tree.name}"
    verb = "would remove" if dry_run else "removed"
    gitdir = _gitdir(tree)
    if gitdir is None:
        return False, f"worktree {label}: not a linked worktree; kept"
    if not gitdir.exists():
        if not dry_run:
            _remove_worktree(tree, None)
        return True, f"worktree {label}: its checkout is gone; {verb}"
    head, _, _rest = tree.name.partition("-")
    number = int(head) if head.isdigit() else None
    try:
        branch = git.current_branch(tree)
    except git.GitError as error:
        return False, f"worktree {label}: git could not answer ({error}); kept"
    done, why, merged_head = _done(_forge_root(tree, gitdir), number, branch, tree)
    if not done:
        return False, f"worktree {label}: {why}; kept"
    try:
        only_local = only_local_work(tree, branch, merged_head=merged_head)
    except git.GitError as error:
        return False, f"worktree {label}: git could not answer ({error}); kept"
    if only_local:
        return False, f"worktree {label}: {why}, but it holds {only_local}; kept"
    try:
        standing_here = _in_tree(Path.cwd(), tree)
    except OSError:
        standing_here = False
    if standing_here and not allow_chdir:
        return (
            False,
            f"worktree {label}: {why}, but this process stands inside it;"
            f" `{footman.prog()} finish` removes it",
        )
    if not dry_run:
        checkout = gitdir.parent.parent.parent
        moved = False
        if standing_here:
            os.chdir(checkout)
            moved = True
        _remove_worktree(tree, gitdir)
        if branch and branch != "main" and git.local_branch_exists(checkout, branch):
            git.delete_branch(checkout, branch)
        if moved:
            print(f"  this shell's directory is gone: cd {checkout}")
    return True, f"worktree {label}: {why}, nothing only here; {verb}"

sweep_worktrees

sweep_worktrees(home: Path, *, dry_run: bool) -> list[str]

Sweep every <repo>/<number>-<slug> worktree under home; the lines.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def sweep_worktrees(home: Path, *, dry_run: bool) -> list[str]:
    """Sweep every ``<repo>/<number>-<slug>`` worktree under *home*; the lines."""
    lines: list[str] = []
    if not home.is_dir():
        return lines
    for repo_dir in sorted(p for p in home.iterdir() if p.is_dir()):
        for tree in sorted(p for p in repo_dir.iterdir() if p.is_dir()):
            _went, line = finish_worktree(
                tree, name=f"{repo_dir.name}/{tree.name}", dry_run=dry_run
            )
            lines.append(line)
    return lines

sweep_branches

sweep_branches(root: Path | None, *, dry_run: bool, allow_switch: bool = False) -> list[str]

Drop the checkout's local branches whose pull request merged and took their tip.

A branch a linked worktree holds is the worktree rule's; the base branch is never touched; the branch the checkout stands on is named when allow_switch is False, since a sweep never moves a person's HEAD. Asks the forge, since asking is what proves the removal safe. The lines say what went and why the rest stayed.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def sweep_branches(
    root: Path | None, *, dry_run: bool, allow_switch: bool = False
) -> list[str]:
    """Drop the checkout's local branches whose pull request merged and took their tip.

    A branch a linked worktree holds is the worktree rule's; the base
    branch is never touched; the branch the checkout stands on is
    named when *allow_switch* is False, since a sweep never moves a
    person's HEAD. Asks the forge, since asking is what proves the
    removal safe. The lines say what went and why the rest stayed.
    """
    if root is None:
        return []
    from livery.workshop._submit import worktree_for

    try:
        current = git.current_branch(root)
        branches = git.local_branches(root, "")
    except git.GitError as error:
        return [f"branches: git could not answer ({error}); kept"]
    lines: list[str] = []
    for branch in branches:
        if branch == "main" or worktree_for(root, branch):
            continue
        _went, line = finish_branch(
            root,
            branch,
            current=current,
            dry_run=dry_run,
            allow_switch=allow_switch,
        )
        lines.append(line)
    return lines

finish_branch

finish_branch(root: Path, branch: str, *, current: str, dry_run: bool, allow_switch: bool = False, repo: Any = None) -> tuple[bool, str]

Drop branch when its pull request merged and took its tip; whether it went.

The one branch cleanup rule shared by fm finish, fm janitor, fm sync, and fm start. When branch is checked out (current), allow_switch steps onto an up-to-date main and deletes it through teardown_branch; without allow_switch, the branch stays and is named for fm sync to step off. repo is the forge's repository, asked for when absent. The line says what went, or why it stayed.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def finish_branch(
    root: Path,
    branch: str,
    *,
    current: str,
    dry_run: bool,
    allow_switch: bool = False,
    repo: Any = None,
) -> tuple[bool, str]:
    """Drop *branch* when its pull request merged and took its tip; whether it went.

    The one branch cleanup rule shared by ``fm finish``, ``fm janitor``,
    ``fm sync``, and ``fm start``. When *branch* is checked out
    (*current*), *allow_switch* steps onto an up-to-date ``main`` and
    deletes it through ``teardown_branch``; without *allow_switch*, the
    branch stays and is named for ``fm sync`` to step off. *repo* is the
    forge's repository, asked for when absent. The line says what went,
    or why it stayed.
    """
    from livery.workshop._submit import (
        merged_pull_request,
        only_local_work,
        teardown_branch,
    )

    try:
        resolved = repo if repo is not None else _repository(root)
        found = merged_pull_request(resolved, root, branch)
    except Exception as error:
        return False, f"branch {branch}: the forge could not be asked ({error}); kept"
    if found is None:
        return False, f"branch {branch}: no merged pull request; kept"
    only_local = only_local_work(root, branch, merged_head=found.head_sha)
    if only_local:
        return False, (
            f"branch {branch}: PR #{found.number} merged, but it holds"
            f" {only_local}; kept"
        )
    if branch == current:
        if not allow_switch:
            return False, (
                f"branch {branch}: PR #{found.number} merged, but the checkout"
                f" stands on it; `{footman.prog()} sync` steps off it"
            )
        if dry_run:
            return (
                True,
                f"branch {branch}: PR #{found.number} merged, nothing only here;"
                " would step off onto main and remove",
            )
        teardown_branch(resolved, root, branch, "main")
        return (
            True,
            f"branch {branch}: PR #{found.number} merged, nothing only here;"
            " stepped off onto main and removed",
        )
    if not dry_run:
        git.delete_branch(root, branch)
    verb = "would remove" if dry_run else "removed"
    return (
        True,
        f"branch {branch}: PR #{found.number} merged, nothing only here; {verb}",
    )

finish_flow

finish_flow(root: Path, ref: str = '', *, all_: bool = False, dry_run: bool = False) -> None

Clean up finished work: one branch/worktree, or every landed one with all_.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def finish_flow(
    root: Path,
    ref: str = "",
    *,
    all_: bool = False,
    dry_run: bool = False,
) -> None:
    """Clean up finished work: one branch/worktree, or every landed one with *all_*."""
    from livery.footman import fail
    from livery.workshop._issue_tasks import worktree_home
    from livery.workshop._submit import parse_number

    if ref and all_:
        fail("name a branch or issue, or pass --all, not both")
    linked = _is_linked_worktree(root)
    main_root = git.main_checkout(root) if linked else root
    home = worktree_home(main_root)

    if all_:
        lines: list[str] = []
        if home.is_dir():
            for tree in sorted(p for p in home.iterdir() if p.is_dir()):
                if linked and tree.resolve() == root.resolve():
                    continue
                _went, line = finish_worktree(
                    tree,
                    name=f"{home.name}/{tree.name}",
                    dry_run=dry_run,
                )
                lines.append(line)
        if linked:
            _went, line = finish_worktree(
                root,
                name=f"{root.parent.name}/{root.name}",
                dry_run=dry_run,
                allow_chdir=True,
            )
            lines.append(line)
        lines.extend(
            sweep_branches(main_root, dry_run=dry_run, allow_switch=not linked)
        )
        if not lines:
            print("  nothing finished to clean up")
            return
        for line in lines:
            print(f"  {line}")
        return

    if ref:
        number = parse_number(ref)
        matched_tree = _matching_worktree(home, ref, number)
        if matched_tree is not None:
            went, line = finish_worktree(
                matched_tree,
                name=f"{matched_tree.parent.name}/{matched_tree.name}",
                dry_run=dry_run,
                allow_chdir=linked and matched_tree.resolve() == root.resolve(),
            )
            if not went:
                fail(line)
            print(f"  {line}")
            return
        branch = _matching_branch(main_root, ref, number)
        if branch:
            current = git.current_branch(main_root)
            went, line = finish_branch(
                main_root,
                branch,
                current=current,
                dry_run=dry_run,
                allow_switch=not linked,
            )
            if not went:
                fail(line)
            print(f"  {line}")
            return
        fail(f"no worktree or local branch matches {ref!r}")

    if linked:
        went, line = finish_worktree(
            root,
            name=f"{root.parent.name}/{root.name}",
            dry_run=dry_run,
            allow_chdir=True,
        )
        if not went:
            fail(line)
        print(f"  {line}")
        return

    current = git.current_branch(root)
    if not current or current == "main":
        fail("already on main: name a branch or issue, or pass --all")
    went, line = finish_branch(
        root, current, current=current, dry_run=dry_run, allow_switch=True
    )
    if not went:
        fail(line)
    print(f"  {line}")

sweep_store

sweep_store(root: Path | None, *, dry_run: bool, now: datetime) -> list[str]

Bound every declared series of the state store in the run's scope; the lines.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def sweep_store(root: Path | None, *, dry_run: bool, now: datetime) -> list[str]:
    """Bound every declared series of the state store in the run's scope; the lines."""
    from contextlib import nullcontext

    from livery.git import remote_snapshot
    from livery.git import sweep as sweep_series
    from livery.workshop._ci_context import run_context, state_store
    from livery.workshop._proved import sweep_proved_store
    from livery.workshop._series import declared

    if root is None:
        return ["state store: no checkout here; nothing swept"]
    remote = run_context() is not None
    # One listing of the remote namespace; each sweep fetches only the refs it
    # actually inspects instead of pulling every proved-parts blob upfront.
    scope = remote_snapshot(state_store(root)) if remote else nullcontext()
    with scope:
        lines = sweep_series(
            state_store(root), declared(root), remote=remote, dry_run=dry_run, now=now
        )
        if remote:
            lines += sweep_proved_store(root, dry_run=dry_run, now=now)
    return [f"state store: {line.strip()}" for line in lines]

report_config

report_config(config_dir: Path) -> list[str]

Name what sits in the config directory beside the user's own files.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def report_config(config_dir: Path) -> list[str]:
    """Name what sits in the config directory beside the user's own files."""
    from livery.footman import tasks_file_name

    if not config_dir.is_dir():
        return []
    own = {*CONFIG_OWN, tasks_file_name()}
    foreign = sorted(p.name for p in config_dir.iterdir() if p.name not in own)
    if not foreign:
        return []
    return [
        f"config: {name} is not the config, the tasks file, or the shared env;"
        " yours to remove"
        for name in foreign
    ]

report_loop

report_loop(home: Path) -> list[str]

The loop's workspace by size, kept: fm ci.e2e reuses it.

Source code in packages/workshop/src/livery/workshop/_sweep.py
def report_loop(home: Path) -> list[str]:
    """The loop's workspace by size, kept: `fm ci.e2e` reuses it."""
    if not home.is_dir():
        return []
    total = sum(p.stat().st_size for p in home.rglob("*") if p.is_file())
    import livery.footman as footman

    return [
        f"loop workspace: {total / 1e6:.0f} MB at {home};"
        f" kept for `{footman.prog()} ci.e2e`"
    ]