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.

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.

sweep_branch

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

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

WORKTREES module-attribute

WORKTREES = 'worktrees'

LOOP module-attribute

LOOP = 'workshop-e2e'

CONFIG_OWN module-attribute

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

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

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."""
    from livery.workshop._submit import only_local_work

    lines: list[str] = []
    if not home.is_dir():
        return lines
    verb = "would remove" if dry_run else "removed"
    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()):
            name = f"{repo_dir.name}/{tree.name}"
            gitdir = _gitdir(tree)
            if gitdir is None:
                lines.append(f"worktree {name}: not a linked worktree; kept")
                continue
            if not gitdir.exists():
                lines.append(f"worktree {name}: its checkout is gone; {verb}")
                if not dry_run:
                    _remove_worktree(tree, None)
                continue
            head, _, _rest = tree.name.partition("-")
            number = int(head) if head.isdigit() else None
            try:
                branch = git.current_branch(tree)
            except git.GitError as error:
                lines.append(f"worktree {name}: git could not answer ({error}); kept")
                continue
            done, why, merged_head = _done(tree, number, branch, tree)
            if not done:
                lines.append(f"worktree {name}: {why}; kept")
                continue
            try:
                only_local = only_local_work(tree, branch, merged_head=merged_head)
            except git.GitError as error:
                lines.append(f"worktree {name}: git could not answer ({error}); kept")
                continue
            if only_local:
                lines.append(f"worktree {name}: {why}, but it holds {only_local}; kept")
                continue
            lines.append(f"worktree {name}: {why}, nothing only here; {verb}")
            if not dry_run:
                _remove_worktree(tree, gitdir)
    return lines

sweep_branches

sweep_branches(root: Path | None, *, dry_run: bool) -> 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, 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) -> 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, 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 = sweep_branch(root, branch, current=current, dry_run=dry_run)
        lines.append(line)
    return lines

sweep_branch

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

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

The rule sweep_branches applies to each of the checkout's branches, for one. fm start asks it before it re-enters a branch that has no worktree, since a merged branch is finished work and a start begins fresh. The branch the checkout stands on (current) stays, named for fm sync to step off, and so does one whose forge cannot be asked. 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 sweep_branch(
    root: Path,
    branch: str,
    *,
    current: str,
    dry_run: bool,
    repo: Any = None,
) -> tuple[bool, str]:
    """Drop *branch* when its pull request merged and took its tip; whether it went.

    The rule `sweep_branches` applies to each of the checkout's
    branches, for one. ``fm start`` asks it before it re-enters a
    branch that has no worktree, since a merged branch is finished work
    and a start begins fresh. The branch the checkout stands on
    (*current*) stays, named for ``fm sync`` to step off, and so does
    one whose forge cannot be asked. *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

    try:
        found = merged_pull_request(
            repo if repo is not None else _repository(root), 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:
        return False, (
            f"branch {branch}: PR #{found.number} merged, but the checkout"
            f" stands on it; `{footman.prog()} sync` steps off it"
        )
    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}",
    )

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 WHOLE, remote_snapshot
    from livery.git import sweep as sweep_series
    from livery.workshop._ci_context import run_context, state_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
    # The remote sweep reads every series: one listing and one fetch.
    scope = remote_snapshot(state_store(root), fetch=WHOLE) if remote else nullcontext()
    with scope:
        lines = sweep_series(
            state_store(root), declared(root), remote=remote, 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`"
    ]