160 lines
7.7 KiB
Python
160 lines
7.7 KiB
Python
"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker reads them rather than finding them.
|
|
|
|
usage: chunk-preflight
|
|
|
|
Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's
|
|
first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It
|
|
fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
|
|
local main or master, as larv-review does. It fast-forwards the checkout to that branch where the
|
|
checkout is on it, behind it and holds no uncommitted change; else it says why not. It then reads
|
|
the checkout's own todo.md, the file loop-claude routes on, and prints:
|
|
|
|
- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md
|
|
holds under ## Unreleased, or else how many commits followed the tag;
|
|
- the next release in todo.md, and that release's first item that does not wait, the item
|
|
loop-claude routes on, with its L and E + I;
|
|
- the item's worktree: a sibling of the checkout named <checkout>-item-<ID>, on the branch
|
|
item-<ID>. It continues a worktree already on that branch; else it adds one on the local branch,
|
|
else on a new branch tracking origin's, else on a new branch off the default branch;
|
|
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists
|
|
them on a github.com origin, and else as tea does. No title reaches the output: on a public forge,
|
|
anyone may open a pull request, and its title would reach the worker's prompt;
|
|
- the items of that release that a chunk taking the item may take too: none is a question, and no
|
|
item outside them and the item blocks one;
|
|
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
|
|
file's lines or a folder's files, and the item's tagline and detail;
|
|
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <ID>`, `reading-cost` and
|
|
`larv-review places` print in the worktree, each with its exit code. reading-cost appends to the
|
|
worktree's docs/reading-cost.md, for the chunk to commit.
|
|
|
|
A fact it cannot find it says it cannot, and why, and goes on. A tool or forge CLI still running
|
|
after TIMEOUT seconds is stopped. With no item, it makes no worktree and runs none of those four
|
|
tools.
|
|
|
|
Exit 1, saying why, on any argument, or when git cannot start or finds no checkout.
|
|
"""
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
|
|
from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top
|
|
from failure import Failure
|
|
from chunk_preflight.gathered import Forge, forge_of, Gathered, held_back, ItemFacts, named_paths, NamedPath, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on
|
|
from chunk_preflight.facts import render
|
|
|
|
BIN = pathlib.Path(__file__).resolve().parents[1]
|
|
# Each tool run in the item's worktree, {item} standing for the item's ID.
|
|
TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places"))
|
|
# Seconds before a tool or forge CLI is stopped, so a hung one leaves the facts the others find.
|
|
TIMEOUT = 60
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
if argv in (["-h"], ["--help"]):
|
|
print(__doc__.strip())
|
|
return 0
|
|
if argv:
|
|
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr)
|
|
return 1
|
|
root = top()
|
|
if isinstance(root, Failure):
|
|
print(root.reason, file=sys.stderr)
|
|
return 1
|
|
print("\n".join(preflight(pathlib.Path(root))))
|
|
return 0
|
|
|
|
|
|
def preflight(root: pathlib.Path) -> list[str]:
|
|
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them."""
|
|
default = default_branch(stale_ok=True)
|
|
if isinstance(default, Failure):
|
|
return [f"- No default branch: {default.reason}"]
|
|
ref, note = default
|
|
# First, so the plan read next is the fast-forwarded checkout's.
|
|
kept_as_is = fast_forward(ref)
|
|
plan = planned(text_of(root / "todo.md"))
|
|
item = plan if isinstance(plan, str) else item_facts(root, ref, plan)
|
|
return render(Gathered(ref, note, kept_as_is, release(ref), item))
|
|
|
|
|
|
def fast_forward(default: str) -> str | None:
|
|
"""Fast-forwards the checkout to default unless held_back says why not; None once it has."""
|
|
held = held_back(default, git("symbolic-ref", "--quiet", "--short", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("rev-list", "--count", f"HEAD..{default}"))
|
|
if held is not None:
|
|
return held
|
|
merged = git("merge", "--ff-only", "--quiet", default)
|
|
return merged.reason if isinstance(merged, Failure) else None
|
|
|
|
|
|
def release(default: str) -> Release:
|
|
tag = newest_release_tag(default)
|
|
commits = git("rev-list", "--count", f"{tag}..{default}" if isinstance(tag, str) else default)
|
|
return Release(tag, file_at(default, "CHANGELOG.md"), commits if isinstance(commits, Failure) else int(commits))
|
|
|
|
|
|
def item_facts(root: pathlib.Path, default: str, plan: Plan) -> ItemFacts:
|
|
worktree = item_worktree(root, plan.branch, default)
|
|
made = worktree.path if isinstance(worktree, Worktree) else None
|
|
return ItemFacts(plan, worktree, pull_listing(root, plan.branch), named_files(plan.text, made or root), tools_run(plan.first.id, made) if made else [])
|
|
|
|
|
|
def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure:
|
|
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else."""
|
|
held = git("worktree", "list", "--porcelain")
|
|
if isinstance(held, Failure):
|
|
return held
|
|
if (path := worktree_on(held, branch)) is not None:
|
|
return Worktree(path, f"on the branch {branch}, which it already held.")
|
|
path = root.parent / f"{root.name}-{branch}"
|
|
if path.exists():
|
|
return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}")
|
|
args, how = worktree_add(branch, path, default, commit_exists(f"refs/heads/{branch}"), commit_exists(f"refs/remotes/origin/{branch}"))
|
|
added = git(*args)
|
|
return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how)
|
|
|
|
|
|
def pull_listing(root: pathlib.Path, branch: str) -> tuple[Forge, Ran | Failure] | None:
|
|
url = git("remote", "get-url", "origin")
|
|
if isinstance(url, Failure):
|
|
return None
|
|
forge = forge_of(url)
|
|
return forge, ran(pulls_command(forge, branch), root)
|
|
|
|
|
|
def named_files(text: str, base: pathlib.Path) -> list[NamedPath] | Failure:
|
|
tracked = git("-C", str(base), "ls-files")
|
|
if isinstance(tracked, Failure):
|
|
return tracked
|
|
return [NamedPath(span, files, line_count(base / span)) for span, files in named_paths(text, tracked.splitlines())]
|
|
|
|
|
|
def line_count(path: pathlib.Path) -> int | Failure | None:
|
|
"""A file's lines, or why they cannot be read; None for a folder."""
|
|
if not path.is_file():
|
|
return None
|
|
text = text_of(path)
|
|
return text if isinstance(text, Failure) else len(text.splitlines())
|
|
|
|
|
|
def tools_run(item_id: int, worktree: pathlib.Path) -> list[tuple[str, Ran | Failure]]:
|
|
commands = [[part.format(item=item_id) for part in tool] for tool in TOOLS]
|
|
return [(" ".join(command), ran([sys.executable, str(BIN / command[0]), *command[1:]], worktree)) for command in commands]
|
|
|
|
|
|
def text_of(path: pathlib.Path) -> str | Failure:
|
|
"""A file's text; empty where there is no such file."""
|
|
try:
|
|
return path.read_text(encoding="utf-8")
|
|
except FileNotFoundError:
|
|
return ""
|
|
except (OSError, UnicodeDecodeError) as failure:
|
|
return Failure(str(failure))
|
|
|
|
|
|
def ran(command: list[str], cwd: pathlib.Path) -> Ran | Failure:
|
|
try:
|
|
done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT)
|
|
except (OSError, subprocess.TimeoutExpired) as failure:
|
|
return Failure(f"could not finish: {failure}")
|
|
return Ran(done.returncode, done.stdout, done.stderr)
|