Files
claude-config/bin/chunk_preflight/test_chunk_preflight.py
T

260 lines
14 KiB
Python

import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
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 test_env import isolated_env
from chunk_preflight.facts import open_pulls, render, unreleased_entries
BIN = pathlib.Path(__file__).resolve().parents[1]
README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
TODO = """# todo
## Scoring
`Score = 100 * V / (2**S + 8)`
`Bar = 0.1`
`Next ID = 10`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |
| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
## Details
### 3. Do the next thing.
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.")
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
# 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"
class Repo:
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea on PATH."""
def __init__(self, test, todo=TODO):
temp = tempfile.TemporaryDirectory()
test.addCleanup(temp.cleanup)
self.temp = pathlib.Path(os.path.realpath(temp.name))
self.origin = self.temp / "origin.git"
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.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)
self.write(self.root, "src/app.py", "def run():\n\treturn 1\n\n")
self.commit(self.root, "start")
self.git(self.root, "tag", "v0.1.0")
self.write(self.root, "CHANGELOG.md", CHANGELOG)
if todo:
self.write(self.root, "todo.md", todo)
self.commit(self.root, "plan")
self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0")
def git(self, cwd, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
def write(self, root, path, text):
(root / path).parent.mkdir(parents=True, exist_ok=True)
(root / path).write_text(text)
def commit(self, root, title):
self.git(root, "add", "-A")
self.git(root, "commit", "--quiet", "-m", title)
def push_from_elsewhere(self, path, text):
"""Pushes a change to path from another clone, leaving the checkout behind origin."""
other = self.temp / "other"
self.git(self.temp, "clone", "--quiet", str(self.origin), str(other))
self.write(other, path, text)
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)
class ChunkPreflightTool(unittest.TestCase):
def test_fast_forwards_the_checkout_reads_its_plan_and_makes_the_items_worktree_off_the_fetched_default_branch(self):
repo = Repo(self)
repo.push_from_elsewhere("todo.md", SHIPPED)
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"))
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.",
"#12 https://forge/pulls/12",
"`src/app.py`: 3 lines",
"`src`: 1 file",
"`rank_todo.py --check todo.md` exited 0",
"`larv-review needs-scoring-run 7` exited 0",
"`reading-cost` exited 0",
"`larv-review places` exited 0",
f"to {worktree}/docs/reading-cost.md",
):
self.assertIn(fact, done.stdout)
self.assertNotIn("#13", done.stdout)
self.assertNotIn("`gone.py`:", done.stdout)
def test_continues_the_items_worktree_and_else_its_pushed_branch(self):
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)
(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)
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.assertNotIn("`reading-cost`", done.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.assertFalse((repo.temp / "proj-item-3").exists())
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)
self.assertEqual(done.returncode, 1)
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 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)))
class Render(unittest.TestCase):
def test_states_the_next_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("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_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_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")))))
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"))]))
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)
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)
self.assertIn("`larv-review places` could not finish: timed out", said)
class OpenPulls(unittest.TestCase):
def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self):
self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"])
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 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_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")
self.assertEqual(worktree_add("item-3", path, "origin/main", True, True)[0], ["worktree", "add", "--quiet", "/c/proj-item-3", "item-3"])
self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"])
self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"])
def test_lists_pull_requests_with_gh_on_a_github_origin_and_with_tea_elsewhere(self):
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)
if __name__ == "__main__":
unittest.main()