"""What the preflight gathers, and the pure choices its steps act on; facts.render states it.""" import dataclasses import pathlib import re import typing from failure import Failure from todo_table import Item, item_details, items, next_item # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. Forge = typing.Literal["gh", "tea"] @dataclasses.dataclass(frozen=True) class Ran: """A command that ran to its end: its exit code and what it printed.""" code: int stdout: str stderr: str @dataclasses.dataclass(frozen=True) class Release: """What the last release fact rests on, each read from the default branch.""" tag: str | None | Failure changelog: str | Failure # How many commits follow the tag, or make up the branch where it has none. commits: int | Failure @dataclasses.dataclass(frozen=True) class Plan: """The checkout's todo.md items, and first, the item the next chunk takes first.""" items: list[Item] first: Item # first's tagline and detail. text: str @property def branch(self) -> str: """The branch first's worktree is on.""" return f"item-{self.first.id}" @dataclasses.dataclass(frozen=True) class Worktree: path: pathlib.Path # How it came to be, as the worker reads it. how: str @dataclasses.dataclass(frozen=True) class NamedPath: """A tracked file or folder the item names, with how many tracked files it holds.""" span: str files: int # A file's lines, or why they cannot be read; None for a folder. lines: int | Failure | None @dataclasses.dataclass(frozen=True) class ItemFacts: """What the preflight found or made for the plan's first item.""" plan: Plan worktree: Worktree | Failure # The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote. pulls: tuple[Forge, Ran | Failure] | None named: list[NamedPath] | Failure # Each tool run in the worktree, by its command line, and how it ran; none without a worktree. tools: list[tuple[str, Ran | Failure]] @dataclasses.dataclass(frozen=True) class Gathered: """Everything the preflight read and ran, for facts.render to state.""" # The default branch's ref, such as origin/main. default: str # Why origin reads as last fetched; None after a fetch. note: str | None # Why the checkout was not fast-forwarded to default; None once it was. kept_as_is: str | None release: Release # The plan's first item and what was found or made for it; else why there is none. item: ItemFacts | str def planned(todo: str | Failure) -> Plan | str: """The checkout's plan and its first item, as todo_table.next_item picks it; else why there is none.""" if isinstance(todo, Failure): return f"the checkout's todo.md cannot be read: {todo.reason}" found = items(todo) if isinstance(found, Failure): return f"the checkout's todo.md cannot be read: {found.reason}" listed = found or [] first = next_item(listed) if first is None: return "every item of the checkout's next release waits" if listed else "the checkout holds no todo.md items table" details = item_details(todo) detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" return Plan(listed, first, f"{first.tagline}\n\n{detail}".strip()) def held_back(default: str, head: str | Failure, status: str | Failure, behind: str | Failure) -> str | None: """Why the checkout is not fast-forwarded to default, from its branch, its tracked changes and how many commits it is behind; None where nothing holds it back. A dirty checkout is never fast-forwarded, as `~/.claude/CLAUDE.md` → "Working with the codebase" asks: its changes are for the human to see, never to carry along. """ branch = default.removeprefix("origin/") if branch == default: return "it has no origin remote" if isinstance(head, Failure): return "it is on no branch" if head.strip() != branch: return f"it is on {head.strip()}, not {branch}" if isinstance(status, Failure): return f"its status cannot be read: {status.reason}" if status.strip(): return "it holds uncommitted changes" if isinstance(behind, Failure): return f"how far it is behind {default} cannot be read: {behind.reason}" return f"it is not behind {default}" if int(behind) == 0 else None def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: """The worktree on branch, in what `git worktree list --porcelain` printed; None where none is.""" for block in porcelain.split("\n\n"): fields = dict(line.partition(" ")[::2] for line in block.splitlines()) if fields.get("branch") == f"refs/heads/{branch}": return pathlib.Path(fields["worktree"]) return None def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]: """The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default.""" if local: return ["worktree", "add", "--quiet", str(path), branch], f"on the branch {branch}, which existed already." if pushed: return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"on the new branch {branch}, made off origin/{branch}." # --no-track: tracking the default branch would point a bare `git push` at it. return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"on the new branch {branch}, made off {default}." def forge_of(origin_url: str) -> Forge: return "gh" if "github.com" in origin_url else "tea" def pulls_command(forge: Forge, branch: str) -> list[str]: """The command that lists open pull requests, by number, head and URL. gh lists only branch's; tea lists every one, for facts.open_pulls to pick branch's.""" if forge == "gh": return ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] return ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"] def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]: """Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file.""" spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text)) held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans) return [(span, count) for span, count in held if count]