Answer principles round 1: 0 🔴, 6 🟡; read the plan from the fetched default branch for routing and the preflight alike and drop the fast-forward, name no item where the release after the last tag has none, tell an empty items table from none, time out the fetch, return run_python's errors as exit codes, test the error paths and the gh rows, assert facts in place of sentences, keep the open-PR sentence in every fresh prompt, name the item branch in CLAUDE.md, and measure item 175 against five chunks with counter-signals

This commit is contained in:
2026-10-17 02:07:40 +02:00
parent 50541c32fd
commit 495184b9c6
21 changed files with 621 additions and 297 deletions
+14 -18
View File
@@ -1,18 +1,17 @@
"""The lines the preflight prints, stated from what it gathered."""
from todo_table import bundle_candidates, Item
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Plan, pulls_command, Ran, Release
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, PULLS_LIST, Ran, Release, version
from markdown_text import quoted, sections
def render(found: Gathered) -> list[str]:
"""One `- ` line per fact, then the item's tagline and detail, and what each tool printed."""
note = [f"- {found.note}"] if found.note else []
checkout = f"- The checkout was not fast-forwarded: {found.kept_as_is}" if found.kept_as_is else f"- The checkout was fast-forwarded to {found.default}."
head = [*note, checkout, f"- {last_release(found.default, found.release)}"]
if isinstance(found.item, str):
return [*head, f"- No plan item: {found.item}, so no worktree was made."]
return [*head, *item_lines(found.item)]
head = [*note, f"- {last_release(found.default, found.release)}"]
if isinstance(found.item, NoItem):
return [*head, f"- No plan item: {found.item.why} No worktree was made."]
return [*head, *item_lines(found.default, found.item)]
def last_release(default: str, release: Release) -> str:
@@ -22,9 +21,10 @@ def last_release(default: str, release: Release) -> str:
entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None
if entries is not None:
return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased."
commits = release.commits.reason if isinstance(release.commits, Failure) else counted(release.commits, "commit", "commits")
since = f"since {release.tag}" if release.tag else f"on {default}"
return f"{cut} Unreleased: {commits} {since}, and no ## Unreleased in CHANGELOG.md."
commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}"
changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md"
return f"{cut} Unreleased: {commits}; {changelog}."
def unreleased_entries(changelog: str) -> int | None:
@@ -33,11 +33,11 @@ def unreleased_entries(changelog: str) -> int | None:
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
def item_lines(item: ItemFacts) -> list[str]:
def item_lines(default: str, item: ItemFacts) -> list[str]:
first = item.plan.first
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
return [
f"- Next release, in the checkout's todo.md: {release_name(first)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
f"- The earliest release in {default}'s todo.md: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
*bundled(item.plan),
@@ -52,7 +52,7 @@ def pulls_text(pulls: tuple[Forge, Ran | Failure] | None, branch: str) -> str:
if pulls is None:
return "none, as the checkout has no origin remote."
forge, done = pulls
shown = " ".join(pulls_command(forge, branch)[:3])
shown = " ".join(PULLS_LIST[forge])
if isinstance(done, Failure):
return f"cannot be listed: `{shown}` {done.reason}"
if done.code:
@@ -71,9 +71,9 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
def bundled(plan: Plan) -> list[str]:
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
if not candidates:
return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, {levels(item)}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates]
return [f'- The items of release {release_name(first)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates]
return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
def named_lines(named: list[NamedPath] | Failure) -> list[str]:
@@ -104,9 +104,5 @@ def levels(item: Item) -> str:
return f"L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}"
def release_name(item: Item) -> str:
return ".".join(map(str, item.release))
def counted(count: int, one: str, many: str) -> str:
return f"{count} {one if count == 1 else many}"
+57 -37
View File
@@ -9,6 +9,11 @@ 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"]
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
# How the plan's earliest release stands to the version x.y.z the newest tag names. "next": it is x.y.z+1, x.y+1.0 or x+1.0.0, or no tag names a version. "cut": it is x.y.z or earlier.
# Else the release after the tag holds no item: "finished" where commits followed the tag, "unplanned" where none did, and "unknown" where they cannot be counted.
Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"]
@dataclasses.dataclass(frozen=True)
@@ -30,7 +35,7 @@ class Release:
@dataclasses.dataclass(frozen=True)
class Plan:
"""The checkout's todo.md items, and first, the item the next chunk takes first."""
"""The default branch's todo.md items, and first, the item the next chunk takes first."""
items: list[Item]
first: Item
# first's tagline and detail.
@@ -42,6 +47,12 @@ class Plan:
return f"item-{self.first.id}"
@dataclasses.dataclass(frozen=True)
class NoItem:
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
why: str
@dataclasses.dataclass(frozen=True)
class Worktree:
path: pathlib.Path
@@ -77,48 +88,57 @@ class Gathered:
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
# What was found or made for the plan's first item; else why the plan names none.
item: ItemFacts | NoItem
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."""
def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoItem:
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.next_item's pick, where standing finds the plan's earliest release next; else why there is none."""
where = f"{default}'s todo.md"
if isinstance(todo, Failure):
return f"the checkout's todo.md cannot be read: {todo.reason}"
return NoItem(f"{where} 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)
return NoItem(f"{where} cannot be read: {found.reason}.")
if found is None:
return NoItem(f"{where} holds no items table.")
earliest = min((item.release for item in found), default=None)
stands = standing(release, earliest)
if earliest is not None and stands == "cut":
return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {release.tag}.")
gap = f"{where} holds no item for the release after the last cut, {release.tag}, and"
if stands == "finished":
return NoItem(f"{gap} commits have landed since, so that release is finished and ready to cut, and the working loop stops here.")
if stands == "unplanned":
return NoItem(f"{gap} no commit has landed since, so that release is to be planned first.")
if stands == "unknown":
return NoItem(f"{gap} the commits since it cannot be counted.")
first = next_item(found)
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"
return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.")
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())
return Plan(found, 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.
def standing(release: Release, earliest: tuple[int, int, int] | None) -> Standing:
"""How the plan's earliest release, None where the plan holds no item, stands to the version the release's tag names, as Standing says."""
cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", release.tag) if isinstance(release.tag, str) else None
if cut is None:
return "next"
major, minor, patch = (int(part) for part in cut.groups())
if earliest in ((major, minor, patch + 1), (major, minor + 1, 0), (major + 1, 0, 0)):
return "next"
if earliest is not None and earliest <= (major, minor, patch):
return "cut"
if isinstance(release.commits, Failure):
return "unknown"
return "finished" if release.commits else "unplanned"
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 version(release: tuple[int, int, int]) -> str:
return ".".join(map(str, release))
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
@@ -133,11 +153,11 @@ def worktree_on(porcelain: str, branch: str) -> pathlib.Path | 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."
return ["worktree", "add", "--quiet", str(path), branch], f"added 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}."
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added 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}."
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
def forge_of(origin_url: str) -> Forge:
@@ -147,12 +167,12 @@ def forge_of(origin_url: str) -> Forge:
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"]
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
return [*PULLS_LIST["tea"], "--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))
spans = dict.fromkeys(span.removesuffix("/") 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]
+73 -65
View File
@@ -5,14 +5,17 @@ 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:
local main or master, as larv-review does. It leaves the checkout as it is: it reads todo.md as
that branch holds it, the plan 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 earliest 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. It names that item only where the tag names no
version x.y.z, or the release is x.y.z+1, x.y+1.0 or x+1.0.0. For a later release, or a todo.md
that holds no item, it says the release after the tag holds none: finished and ready to cut where
commits followed the tag, and else to be planned first. For x.y.z or an earlier release, it says
todo.md files items under a release already cut;
- 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;
@@ -27,84 +30,97 @@ the checkout's own todo.md, the file loop-claude routes on, and prints:
`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.
A fact it cannot find it says it cannot, and why, and goes on. A fetch, forge CLI or tool still
running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT sets, is stopped; a
stopped fetch reads origin as last fetched. 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.
Exit 1, saying why, on any argument, on a CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds
above 0, or when git cannot start or finds no checkout or no default branch.
"""
import pathlib
import re
import subprocess
import sys
import typing
from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top
from git_repo import commit_exists, commits_since, default_branch, default_branch_todo, 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.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, 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.
# Seconds before a fetch, forge CLI or tool is stopped, so a hung one leaves the facts the others find; TIMEOUT_SETTING sets others.
TIMEOUT = 60
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
def main(argv: list[str]) -> int:
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
print(__doc__.strip().format(timeout=TIMEOUT))
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)
printed = run(env.get(TIMEOUT_SETTING))
if isinstance(printed, Failure):
print(printed.reason, file=sys.stderr)
return 1
print("\n".join(preflight(pathlib.Path(root))))
print("\n".join(printed))
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)
def run(setting: str | None) -> list[str] | Failure:
"""The preflight's lines, given what TIMEOUT_SETTING holds; a Failure where that is no number of seconds, or git finds no checkout or no default branch."""
timeout = seconds(setting)
if isinstance(timeout, Failure):
return timeout
root = top()
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout)
def seconds(setting: str | None) -> float | Failure:
"""The seconds a TIMEOUT_SETTING of setting gives, TIMEOUT where it is unset; a Failure where it is no number above 0."""
if setting is None:
return TIMEOUT
if re.fullmatch(r"[0-9]+(\.[0-9]+)?", setting) and float(setting) > 0:
return float(setting)
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure:
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
default = default_branch(stale_ok=True, timeout=timeout)
if isinstance(default, Failure):
return [f"- No default branch: {default.reason}"]
return default
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))
cut = release(ref, root)
plan = planned(default_branch_todo(str(root), timeout), cut, ref)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout)
return render(Gathered(ref, note, cut, 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:
def release(default: str, root: pathlib.Path) -> 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))
commits = tag if isinstance(tag, Failure) else commits_since(tag, default)
return Release(tag, file_at(default, "CHANGELOG.md", str(root)), commits)
def item_facts(root: pathlib.Path, default: str, plan: Plan) -> ItemFacts:
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> 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 [])
path = worktree.path if isinstance(worktree, Worktree) else None
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path 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.")
listing = git("worktree", "list", "--porcelain")
if isinstance(listing, Failure):
return listing
if (path := worktree_on(listing, branch)) is not None:
return Worktree(path, f"continued, on the branch {branch}.")
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}")
@@ -113,12 +129,12 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | F
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:
def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> 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)
return forge, ran(pulls_command(forge, branch), root, timeout)
def named_files(text: str, base: pathlib.Path) -> list[NamedPath] | Failure:
@@ -132,28 +148,20 @@ 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 ""
return len(path.read_text(encoding="utf-8").splitlines())
except (OSError, UnicodeDecodeError) as failure:
return Failure(str(failure))
def ran(command: list[str], cwd: pathlib.Path) -> Ran | Failure:
def tools_run(item_id: int, worktree: pathlib.Path, timeout: float) -> 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, timeout)) for command in commands]
def ran(command: list[str], cwd: pathlib.Path, timeout: float) -> Ran | Failure:
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT)
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
except (OSError, subprocess.TimeoutExpired) as failure:
return Failure(f"could not finish: {failure}")
return Ran(done.returncode, done.stdout, done.stderr)
+281 -67
View File
@@ -9,8 +9,9 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from chunk_preflight.gathered import forge_of, Gathered, held_back, ItemFacts, NamedPath, planned, Ran, Release, Worktree, worktree_add
from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Release, standing, Worktree, worktree_add
from test_env import isolated_env
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from chunk_preflight.facts import open_pulls, render, unreleased_entries
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -44,26 +45,40 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
"""
# The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files.
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# An items table that holds no row.
EMPTY = TODO[:TODO.index("| 5 |")]
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
# What the preflight reads of the last release: tag v0.1.0, two entries under ## Unreleased, and 4 commits since the tag.
CUT = Release("v0.1.0", CHANGELOG, 4)
# Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1.
FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n"
# Item 3's open pull request, as `gh pr list` prints it through the preflight's template; any other arguments exit 1.
FAKE_GH = """#!PYTHON
import sys
if sys.argv[1:] != ["pr", "list", "--head", "item-3", "--json", "number,url", "--template", "{{range .}}{{.number}}\\t{{.url}}\\n{{end}}"]:
sys.exit(1)
print("12\\thttps://github.com/o/r/pull/12")
""".replace("PYTHON", sys.executable)
class Repo:
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea on PATH."""
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea and gh on PATH."""
def __init__(self, test, todo=TODO):
def __init__(self, test, todo=TODO, origin="origin.git"):
temp = tempfile.TemporaryDirectory()
test.addCleanup(temp.cleanup)
self.temp = pathlib.Path(os.path.realpath(temp.name))
self.origin = self.temp / "origin.git"
self.origin = self.temp / origin
self.root = self.temp / "proj"
fake = self.temp / "fake-bin"
fake.mkdir()
(fake / "tea").write_text(FAKE_TEA)
(fake / "tea").chmod(0o755)
(fake / "git").symlink_to(shutil.which("git"))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
self.fake = self.temp / "fake-bin"
self.fake.mkdir()
for name, script in (("gh", FAKE_GH), ("tea", FAKE_TEA)):
(self.fake / name).write_text(script)
(self.fake / name).chmod(0o755)
(self.fake / "git").symlink_to(shutil.which("git"))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root))
self.write(self.root, "README.md", README)
@@ -95,24 +110,34 @@ class Repo:
self.commit(other, "elsewhere")
self.git(other, "push", "--quiet", "origin", "main")
def preflight(self):
return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env=self.env, text=True, timeout=120)
def stub_git(self, arm):
"""Puts a git on PATH that runs arm, a shell case arm, on its arguments, and the real git on any others."""
stub = self.fake / "git"
stub.unlink()
stub.write_text(f'#!/bin/sh\ncase "$*" in\n{arm}\nesac\nexec {shutil.which("git")} "$@"\n')
stub.chmod(0o755)
def preflight(self, **env):
return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120)
class ChunkPreflightTool(unittest.TestCase):
def test_fast_forwards_the_checkout_reads_its_plan_and_makes_the_items_worktree_off_the_fetched_default_branch(self):
def test_reads_the_fetched_default_branchs_plan_and_makes_the_items_worktree_off_it_leaving_the_checkout_as_it_was(self):
repo = Repo(self)
repo.push_from_elsewhere("todo.md", SHIPPED)
# Claude Code rewrites tracked files, such as settings.json, so a checkout behind origin often holds changes.
repo.write(repo.root, "todo.md", TODO + "\nA change of the checkout's own.\n")
head = repo.git(repo.root, "rev-parse", "HEAD")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main"))
self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), head)
worktree = repo.temp / "proj-item-7"
self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-7")
self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main"))
for fact in (
"fast-forwarded to origin/main",
"item 7, L 1, E + I 2",
f"{worktree}, on the new branch item-7, made off origin/main.",
str(worktree),
"item-7, made off origin/main",
"#12 https://forge/pulls/12",
"`src/app.py`: 3 lines",
"`src`: 1 file",
@@ -120,9 +145,10 @@ class ChunkPreflightTool(unittest.TestCase):
"`larv-review needs-scoring-run 7` exited 0",
"`reading-cost` exited 0",
"`larv-review places` exited 0",
f"to {worktree}/docs/reading-cost.md",
f"{worktree}/docs/reading-cost.md",
):
self.assertIn(fact, done.stdout)
with self.subTest(fact=fact):
self.assertIn(fact, done.stdout)
self.assertNotIn("#13", done.stdout)
self.assertNotIn("`gone.py`:", done.stdout)
@@ -130,31 +156,87 @@ class ChunkPreflightTool(unittest.TestCase):
repo = Repo(self)
repo.preflight()
worktree = repo.temp / "proj-item-3"
self.assertIn(f"Worktree: {worktree}, on the branch item-3, which it already held.", repo.preflight().stdout)
continued = repo.preflight().stdout
self.assertIn(str(worktree), continued)
self.assertIn("continued", continued)
(worktree / "work.txt").write_text("work\n")
repo.git(worktree, "add", "work.txt")
repo.git(worktree, "commit", "--quiet", "-m", "work")
repo.git(worktree, "push", "--quiet", "origin", "item-3")
repo.git(repo.root, "worktree", "remove", "--force", str(worktree))
repo.git(repo.root, "branch", "--quiet", "-D", "item-3")
self.assertIn(f"Worktree: {worktree}, on the new branch item-3, made off origin/item-3.", repo.preflight().stdout)
pushed = repo.preflight().stdout
self.assertIn(str(worktree), pushed)
self.assertIn("made off origin/item-3", pushed)
self.assertTrue((worktree / "work.txt").exists())
def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self):
repo = Repo(self)
(repo.temp / "proj-item-3").mkdir()
done = repo.preflight()
self.assertIn(f"Worktree: none made, since {repo.temp / 'proj-item-3'} exists", done.stdout)
self.assertIn(f"none made, since {repo.temp / 'proj-item-3'} exists", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_add_it(self):
repo = Repo(self)
repo.temp.chmod(0o555)
self.addCleanup(repo.temp.chmod, 0o755)
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("Worktree: none made: git worktree add", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_list_the_worktrees(self):
repo = Repo(self)
repo.stub_git('"worktree list --porcelain") echo "listing broke" >&2; exit 1;;')
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("listing broke", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self):
repo = Repo(self)
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;')
done = repo.preflight(CHUNK_PREFLIGHT_TIMEOUT="1")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("as last fetched", done.stdout)
self.assertIn("item 3, L 4, E + I 5", done.stdout)
self.assertIn("`reading-cost` exited 0", done.stdout)
def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self):
repo = Repo(self, origin="github.com/o/r.git")
self.assertIn("#12 https://github.com/o/r/pull/12", repo.preflight().stdout)
def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self):
repo = Repo(self, todo="")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("Last version cut: v0.1.0.", done.stdout)
self.assertIn("No plan item: the checkout holds no todo.md items table, so no worktree was made.", done.stdout)
self.assertIn("v0.1.0", done.stdout)
self.assertIn("no items table", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_states_its_timeout_in_its_help(self):
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight"), "--help"], capture_output=True, env=isolated_env(), text=True)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(f"after {TIMEOUT} seconds", done.stdout)
def test_exits_1_on_a_timeout_setting_that_is_no_number_of_seconds(self):
done = Repo(self).preflight(CHUNK_PREFLIGHT_TIMEOUT="soon")
self.assertEqual(done.returncode, 1)
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", done.stderr)
self.assertEqual(done.stdout, "")
def test_exits_1_without_a_default_branch(self):
with tempfile.TemporaryDirectory() as temp:
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
subprocess.run(["git", "init", "--quiet", "--initial-branch=trunk", temp], check=True, env=env)
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env=env, text=True)
self.assertEqual(done.returncode, 1)
self.assertIn("main or master", done.stderr)
self.assertEqual(done.stdout, "")
def test_exits_1_outside_a_checkout(self):
with tempfile.TemporaryDirectory() as temp:
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True)
@@ -162,52 +244,98 @@ class ChunkPreflightTool(unittest.TestCase):
self.assertIn("git rev-parse --show-toplevel", done.stderr)
def item_facts(**fields):
"""Item 3's facts, its worktree made, with fields given replacing the rest."""
plan = planned(TODO)
return ItemFacts(**{"plan": plan, "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields})
def item_facts(todo=TODO, **fields):
"""The facts of todo's next item, its worktree made, with fields given replacing the rest."""
return ItemFacts(**{"plan": planned(todo, CUT, "origin/main"), "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "added on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields})
def rendered(item, release=Release("v0.1.0", CHANGELOG, 4), kept_as_is=None):
return "\n".join(render(Gathered("origin/main", None, kept_as_is, release, item)))
def rendered(item, release=CUT, note=None):
return "\n".join(render(Gathered("origin/main", note, release, item)))
class Render(unittest.TestCase):
def test_states_the_next_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
said = rendered(item_facts())
self.assertIn("0.2.0", said)
self.assertIn("origin/main's todo.md: 0.2.0", said)
self.assertIn("item 3, L 4, E + I 5", said)
self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said)
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
self.assertNotIn("item 8,", said)
def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self):
self.assertIn("v0.1.0. Unreleased: 2 entries", rendered("no item"))
self.assertIn("v0.1.0. Unreleased: 4 commits since v0.1.0", rendered("no item", Release("v0.1.0", "# Changelog\n", 4)))
self.assertIn("none. Unreleased: 1 commit on origin/main", rendered("no item", Release(None, "", 1)))
def test_states_the_items_worktree_or_why_none_was_made(self):
self.assertIn("/c/proj-item-3", rendered(item_facts()))
self.assertIn("none made: path taken", rendered(item_facts(worktree=Failure("none made: path taken"))))
def test_states_whether_the_checkout_was_fast_forwarded_and_why_there_is_no_plan_item(self):
self.assertIn("The checkout was fast-forwarded to origin/main.", rendered("every item waits"))
said = rendered("every item waits", kept_as_is="it holds uncommitted changes")
self.assertIn("The checkout was not fast-forwarded: it holds uncommitted changes", said)
self.assertIn("No plan item: every item waits, so no worktree was made.", said)
def test_states_that_no_other_item_may_join_the_chunk(self):
said = rendered(item_facts(TODO.replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | 5 |")))
self.assertIn("No other item", said)
self.assertNotIn("item 7,", said)
def test_states_an_unscored_level_as_unscored(self):
unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 4 | 2 | 3 | 7 | 3 |", "| 7 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
self.assertIn("item 3, L unscored, E + I unscored", rendered(item_facts(unscored)))
def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self):
self.assertIn("v0.1.0. Unreleased: 2 entries", rendered(NoItem("x.")))
self.assertIn("1 entry", rendered(NoItem("x."), Release("v0.1.0", "## Unreleased\n\n- One.\n", 4)))
without = rendered(NoItem("x."), Release("v0.1.0", "# Changelog\n", 4))
self.assertIn("4 commits since v0.1.0", without)
self.assertIn("no ## Unreleased", without)
untagged = rendered(NoItem("x."), Release(None, "", 1))
self.assertIn("cut: none", untagged)
self.assertIn("1 commit on origin/main", untagged)
def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self):
said = rendered(NoItem("x."), Release("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable")))
self.assertIn("changelog unreadable", said)
self.assertIn("cannot be counted: count unreadable", said)
self.assertNotIn("no ## Unreleased", said)
def test_states_why_origin_reads_as_last_fetched_and_nothing_after_a_fetch(self):
self.assertIn("- reading origin as last fetched: fetch stalled", rendered(NoItem("x."), note="reading origin as last fetched: fetch stalled"))
fetched = rendered(NoItem("x."))
self.assertNotIn("last fetched", fetched)
self.assertNotIn("None", fetched)
def test_states_why_there_is_no_plan_item(self):
said = rendered(NoItem("every item waits."))
self.assertIn("every item waits.", said)
self.assertNotIn("Worktree", said)
def test_states_the_open_pull_requests_from_the_items_branch_or_why_none_are_listed(self):
self.assertIn("Open pull requests from item-3: #12 https://forge/pulls/12\n", rendered(item_facts(pulls=("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", "")))))
self.assertIn("Open pull requests from item-3: none.", rendered(item_facts(pulls=("gh", Ran(0, "", "")))))
self.assertIn("Open pull requests from item-3: none, as the checkout has no origin remote.", rendered(item_facts()))
self.assertIn("Open pull requests from item-3: cannot be listed: `tea pulls list` exited 1: no login", rendered(item_facts(pulls=("tea", Ran(1, "", "no login\n")))))
cases = (
(("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", "")), ("#12 https://forge/pulls/12",)),
(("gh", Ran(0, "12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "")), ("#12 https://github.com/o/r/pull/12, #14 https://github.com/o/r/pull/14",)),
(("gh", Ran(0, "", "")), ("item-3: none.",)),
(None, ("item-3: none", "no origin remote")),
(("tea", Ran(1, "", "no login\n")), ("`tea pulls list`", "exited 1", "no login")),
(("gh", Ran(1, "", "not logged in\n")), ("`gh pr list`", "exited 1", "not logged in")),
(("gh", Failure("could not finish: timed out")), ("`gh pr list`", "could not finish: timed out")),
)
for pulls, facts in cases:
with self.subTest(pulls=pulls):
said = rendered(item_facts(pulls=pulls))
for fact in facts:
self.assertIn(fact, said)
def test_states_each_named_files_lines_and_each_named_folders_files(self):
said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8"))]))
said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8")), NamedPath("one.py", 1, 1), NamedPath("docs", 1, None)]))
self.assertIn("`src/app.py`: 3 lines", said)
self.assertIn("`src`: 2 files", said)
self.assertIn("`bad.py`: cannot be read: not UTF-8", said)
self.assertIn("`one.py`: 1 line\n", said)
self.assertIn("`docs`: 1 file\n", said)
def test_states_that_the_item_names_no_tracked_file_or_why_they_cannot_be_listed(self):
self.assertIn("no file", rendered(item_facts(named=[])))
self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke"))))
def test_states_what_each_tool_printed_and_its_exit_code(self):
said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review places", Failure("could not finish: timed out"))]))
self.assertIn("`rank_todo.py --check todo.md` exited 0, printing:\n\n> ranked", said)
self.assertIn("`reading-cost` exited 1, printing nothing.", said)
said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))]))
self.assertIn("`rank_todo.py --check todo.md` exited 0", said)
self.assertIn("> ranked", said)
self.assertIn("`reading-cost` exited 1, printing nothing", said)
self.assertIn("> out\n> err", said)
self.assertIn("`larv-review places` could not finish: timed out", said)
@@ -217,18 +345,88 @@ class OpenPulls(unittest.TestCase):
self.assertEqual(open_pulls("index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n13\tother\thttps://forge/pulls/13\n", "tea", "item-3"), ["#12 https://forge/pulls/12"])
class Plans(unittest.TestCase):
def test_picks_the_earliest_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self):
self.assertEqual(planned(TODO, CUT, "origin/main").first.id, 3)
waits = planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |"), CUT, "origin/main")
self.assertIn("waits", waits.why)
self.assertIn("0.2.0", waits.why)
self.assertIn("Permission denied", planned(Failure("Permission denied"), CUT, "origin/main").why)
self.assertIn("L 'x'", planned(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), CUT, "origin/main").why)
self.assertIn("details cannot be read", planned(TODO + "```\n", CUT, "origin/main").text)
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
without = planned("", CUT, "origin/main").why
self.assertIn("origin/main", without)
self.assertIn("no items table", without)
empty = planned(EMPTY, Release(None, "", 4), "origin/main").why
self.assertIn("holds no item", empty)
self.assertNotIn("no items table", empty)
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
cases = (
(LATER, 4, "finished and ready to cut"),
(LATER, 0, "planned first"),
(EMPTY, 4, "finished and ready to cut"),
(EMPTY, 0, "planned first"),
(LATER, Failure("count unreadable"), "cannot be counted"),
)
for todo, commits, fact in cases:
with self.subTest(todo=todo, commits=commits):
why = planned(todo, Release("v0.1.0", "", commits), "origin/main").why
self.assertIn(fact, why)
self.assertIn("v0.1.0", why)
def test_says_the_plan_files_items_under_a_release_already_cut(self):
why = planned(TODO, Release("v0.2.0", "", 4), "origin/main").why
self.assertIn("release 0.2.0", why)
self.assertIn("v0.2.0", why)
self.assertIn("not after", why)
def test_takes_an_item_without_a_detail_as_its_tagline_alone(self):
self.assertEqual(planned(TODO[:TODO.index("## Details")], CUT, "origin/main").text, "**Do the next thing.**")
class Standing(unittest.TestCase):
def test_takes_the_earliest_release_where_it_is_the_next_patch_minor_or_major_or_no_tag_names_a_version(self):
cases = (
(Release("v1.2.3", "", 4), (1, 2, 4), "next"),
(Release("v1.2.3", "", 4), (1, 3, 0), "next"),
(Release("v1.2.3", "", 4), (2, 0, 0), "next"),
(Release(None, "", 4), (0, 2, 0), "next"),
(Release(None, "", 4), None, "next"),
(Release("v1.2.3-rc.1", "", 4), (1, 2, 3), "next"),
(Release(Failure("tags unreadable"), "", 4), (0, 2, 0), "next"),
(Release("v1.2.3", "", 4), (1, 2, 3), "cut"),
(Release("v1.2.3", "", 4), (1, 2, 2), "cut"),
(Release("v1.2.3", "", 4), (1, 2, 5), "finished"),
(Release("v1.2.3", "", 4), (1, 3, 1), "finished"),
(Release("v1.2.3", "", 4), (2, 0, 1), "finished"),
(Release("v1.2.3", "", 4), None, "finished"),
(Release("v1.2.3", "", 0), (1, 4, 0), "unplanned"),
(Release("v1.2.3", "", 0), None, "unplanned"),
(Release("v1.2.3", "", Failure("count unreadable")), (1, 4, 0), "unknown"),
)
for release, earliest, stands in cases:
with self.subTest(release=release, earliest=earliest):
self.assertEqual(standing(release, earliest), stands)
class Gathering(unittest.TestCase):
def test_counts_the_top_level_entries_under_unreleased(self):
self.assertEqual(unreleased_entries(CHANGELOG), 2)
self.assertEqual(unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
self.assertIsNone(unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
def test_picks_the_next_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self):
self.assertEqual(planned(TODO).first.id, 3)
self.assertEqual(planned(""), "the checkout holds no todo.md items table")
self.assertEqual(planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |")), "every item of the checkout's next release waits")
self.assertEqual(planned(Failure("Permission denied")), "the checkout's todo.md cannot be read: Permission denied")
self.assertIn("todo.md's details cannot be read", planned(TODO + "```\n").text)
def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self):
cases = (
("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]),
("`src/`", ["src/app.py", "src/b.py"], [("src", 2)]),
("`src/app.py`, `gone.py` and `run`", ["src/app.py"], [("src/app.py", 1)]),
)
for text, tracked, named in cases:
with self.subTest(text=text):
self.assertEqual(named_paths(text, tracked), named)
def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self):
path = pathlib.Path("/c/proj-item-3")
@@ -240,19 +438,35 @@ class Gathering(unittest.TestCase):
self.assertEqual(forge_of("git@github.com:o/r.git"), "gh")
self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea")
def test_fast_forwards_only_a_clean_checkout_on_the_default_branch_that_is_behind_it(self):
cases = (
(("main", "main\n", "", "2\n"), "it has no origin remote"),
(("origin/main", Failure(""), "", "2\n"), "it is on no branch"),
(("origin/main", "item-5\n", "", "2\n"), "it is on item-5, not main"),
(("origin/main", "main\n", " M todo.md\n", "2\n"), "it holds uncommitted changes"),
(("origin/main", "main\n", "", "0\n"), "it is not behind origin/main"),
(("origin/main", "main\n", Failure("git status: broken"), "2\n"), "its status cannot be read: git status: broken"),
(("origin/main", "main\n", "", "2\n"), None),
)
for found, why in cases:
with self.subTest(found=found):
self.assertEqual(held_back(*found), why)
def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self):
self.assertEqual(seconds(None), TIMEOUT)
self.assertEqual(seconds("2.5"), 2.5)
for setting in ("soon", "0", "-1", "1e3", ""):
with self.subTest(setting=setting):
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", seconds(setting).reason)
class Running(unittest.TestCase):
def test_says_why_a_command_could_not_finish(self):
with tempfile.TemporaryDirectory() as cwd:
cases = (([str(pathlib.Path(cwd, "missing"))], 60, "missing"), ([sys.executable, "-c", "import time; time.sleep(5)"], 0.2, "0.2"))
for command, timeout, fact in cases:
with self.subTest(fact=fact):
done = ran(command, pathlib.Path(cwd), timeout)
self.assertIsInstance(done, Failure)
self.assertIn(fact, done.reason)
def test_counts_a_files_lines_says_why_they_cannot_be_read_and_counts_none_for_a_folder(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
(folder / "two.txt").write_text("a\nb\n")
(folder / "latin.txt").write_bytes(b"caf\xe9\n")
(folder / "locked.txt").write_text("a\n")
(folder / "locked.txt").chmod(0)
self.assertEqual(line_count(folder / "two.txt"), 2)
self.assertIn("utf-8", line_count(folder / "latin.txt").reason)
self.assertIn("locked.txt", line_count(folder / "locked.txt").reason)
self.assertIsNone(line_count(folder))
if __name__ == "__main__":