import functools import os import pathlib import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from branch_chunks.fixes import blamed, fixing_changes, removed, with_fixes from branch_chunks.cut import Branch, BranchChunk, chunk_log, Commit, landing, shipped from branch_chunks.read import branch_chunks, traced_to from failure import Failure from git_repo import git from test_env import isolated_env from todo_table import Item HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n" WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n" FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 10 | 6 | 7 | 1 | 9.0 |" SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |" FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |" def todo(*rows: str, header: str = HEADER) -> str: return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows) def item(id_: int, exempt: str = "") -> Item: return Item(id_, (0, 1, 0), exempt, f"**Item {id_}.**", {}, (), ()) def chunk(label: str, shipped: tuple[Item, ...] = ()) -> BranchChunk: return BranchChunk(f"{label}-before", f"{label}-tip", label, "merge", "2026-10-13T10:00:00Z", (), shipped, ()) def commit(hash_: str, committed: int, authored: int, *parents: str, title: str = "") -> Commit: return Commit(hash_, hash_, committed, authored, parents, title, ()) def cut(*line: Commit) -> list[tuple[str, str, int, str]]: """Each chunk chunk_log cuts the first-parent line into: its oldest and newest commit, its commit time and how it landed.""" return [(run[-1].hash, run[0].hash, run[0].committed, landing(run)) for run in chunk_log(list(line))] class Shipped(unittest.TestCase): def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self): self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4]) self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 10, "A": 6, "G": 7}) def test_lists_the_shipped_items_by_id(self): self.assertEqual([found.id for found in shipped(todo(SECOND, FIRST), todo())], [4, 5]) def test_reads_a_table_from_before_c_joined_it(self): older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |" self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7}) def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self): self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), []) self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), []) class ChunkLog(unittest.TestCase): def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self): self.assertEqual(cut(commit("m", 100, 100, "a", "b"), commit("c", 100, 100, "a")), [("m", "m", 100, "merge"), ("c", "c", 100, "push")]) def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self): self.assertEqual(cut(commit("c2", 200, 150, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")]) def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self): self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "push")]) def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self): self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")]) def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self): self.assertEqual(cut(commit("c2", 200, 100, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "rebase")]) def test_a_commit_at_another_time_starts_a_new_chunk(self): self.assertEqual(cut(commit("c2", 300, 300, "c1"), commit("c1", 200, 200, "r")), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")]) class FixingChanges(unittest.TestCase): def test_takes_the_whole_change_of_each_chunk_that_ships_a_defect_or_a_security_item(self): branch = Branch({}, [chunk("d", (item(9, "security"),)), chunk("c", (item(8),)), chunk("b", (item(6, "defect"), item(7))), chunk("a")], {}) self.assertEqual(fixing_changes(branch), [(0, "d-before", "d-tip"), (2, "b-before", "b-tip")]) def test_takes_each_round_commit_whose_title_counts_both_a_red_and_a_misread_finding(self): titles = { "r1": "Answer stability round 1: 1 🔴, 0 🟡 (1 misread); keep y's caller", "r2": "Answer stability round 2: 1 🔴, 0 🟡 (0 misread); fix", "r3": "Answer prose round 1: 0 🔴, 1 🟡 (1 misread); fix", "r4": "Answer principles round 1: 1 🔴, 0 🟡; fix", "r5": "Do the work", } commits = {name: commit(name, 100, 100, f"{name}-parent", title=title) for name, title in titles.items()} branch = Branch(commits, [chunk("b"), chunk("a")], {"r1": 1, "r2": 0, "r3": 0, "r4": 0, "r5": 0}) self.assertEqual(fixing_changes(branch), [(1, "r1-parent", "r1")]) class WithFixes(unittest.TestCase): def test_names_each_later_chunk_once_against_each_chunk_whose_commits_its_fixes_traced_to_newest_first(self): branch = Branch({}, [chunk("d"), chunk("c"), chunk("b"), chunk("a")], {"a1": 3, "a2": 3, "b1": 2, "c1": 1, "d1": 0}) found = with_fixes(branch, [(1, {"a1", "a2"}), (0, {"a1", "b1", "c1"}), (1, {"a2"}), (0, {"a2"})]) self.assertEqual([found.fixed_by for found in found], [(), ("d",), ("d",), ("d", "c")]) def test_counts_no_fix_of_its_own_chunks_commit_a_newer_chunks_or_one_no_chunk_brought(self): branch = Branch({}, [chunk("b"), chunk("a")], {"b1": 0, "a1": 1}) self.assertEqual([found.fixed_by for found in with_fixes(branch, [(1, {"a1", "b1", "elsewhere"})])], [(), ()]) class Removed(unittest.TestCase): def test_reads_the_old_lines_each_hunk_removes_or_rewrites_by_the_path_they_had(self): diff = "\n".join([ "diff --git a/a.py b/a.py", "--- a/a.py", "+++ b/a.py", "@@ -2 +2 @@ def f():", "-x", "+y", "@@ -5,3 +4,0 @@", "@@ -9,0 +8,2 @@", "diff --git a/old.py b/new.py", "--- a/old.py", "+++ b/new.py", "@@ -1,2 +1,2 @@", "diff --git a/gone.py b/gone.py", "--- a/gone.py", "+++ /dev/null", "@@ -1,4 +0,0 @@", "diff --git a/born.py b/born.py", "--- /dev/null", "+++ b/born.py", "@@ -0,0 +1,3 @@", "diff --git \"a/tab\\there.py\" \"b/tab\\there.py\"", "--- \"a/tab\\there.py\"", "+++ \"b/tab\\there.py\"", "@@ -1 +1 @@", "diff --git a/my file.py b/my file.py", "--- a/my file.py\t", "+++ b/my file.py\t", "@@ -7,2 +7 @@", ]) self.assertEqual(removed(diff), {"a.py": [(2, 1), (5, 3)], "old.py": [(1, 2)], "gone.py": [(1, 4)], "my file.py": [(7, 2)]}) def test_reads_a_hunk_line_inside_the_changed_text_as_text(self): diff = "--- a/a.md\n+++ b/a.md\n@@ -3 +3 @@\n---- a/quoted\n+text\n" self.assertEqual(removed(diff), {"a.md": [(3, 1)]}) class Blamed(unittest.TestCase): def test_reads_the_commit_of_each_line_from_porcelain_output(self): first, second = "a" * 40, "b" * 40 porcelain = f"{first} 2 2 1\nauthor t\nfilename a.py\n\tx\n{second} 5 5 2\nauthor t\n\ty\n{second} 6 6\n\t{first} 1 1 1\n" self.assertEqual(blamed(porcelain), {first, second}) class TracedTo(unittest.TestCase): DIFF = "--- a/a.py\n+++ b/a.py\n@@ -2 +2 @@\n-x\n+y\n--- a/todo.md\n+++ b/todo.md\n@@ -5 +4,0 @@\n-| 6 |\n--- a/docs/reading-cost.md\n+++ b/docs/reading-cost.md\n@@ -1 +1 @@\n-a\n+b\n" def test_blames_the_lines_a_change_removes_before_it_leaving_out_the_plan_and_the_records(self): blames = [] def run(*args): if args[0] == "diff": return self.DIFF blames.append(args) return f"{'a' * 40} 2 2 1\n\tx\n" self.assertEqual(traced_to("before", "tip", run), {"a" * 40}) self.assertEqual([(args[-1], "-L2,+1" in args, "before" in args) for args in blames], [("a.py", True, True)]) def test_fails_where_git_cannot_blame(self): self.assertEqual(traced_to("before", "tip", lambda *args: self.DIFF if args[0] == "diff" else Failure("no blame")), Failure("no blame")) class BranchChunks(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.checkout = pathlib.Path(os.path.realpath(temp.name)) self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.checkout)} self.git("init", "-q", "-b", "main") self.commit("Start", {"todo.md": todo(FIRST, SECOND, FIX), "a.py": "1\n"}) def git(self, *args): return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout def commit(self, title, files): for name, text in files.items(): (self.checkout / name).write_text(text) self.git("add", name) self.git("commit", "-q", "-m", title) def merge(self, branch, title, files, at): """Merges a branch holding one commit, at the given time, and returns the merge commit's short hash.""" self.git("switch", "-q", "-c", branch) self.commit(title, files) self.git("switch", "-q", "main") self.env.update({"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at}) self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch) for name in ("GIT_COMMITTER_DATE", "GIT_AUTHOR_DATE"): self.env.pop(name) return self.git("rev-parse", "--short", "HEAD").strip() def test_reads_each_chunk_with_the_items_it_shipped_and_the_later_chunks_that_fixed_it(self): shipped = self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z") fixed = self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z") found = branch_chunks("main", functools.partial(git, cwd=str(self.checkout))) self.assertNotIsInstance(found, Failure) self.assertEqual([(found.label, found.landed, found.merged, [item.id for item in found.shipped], found.fixed_by) for found in found[:2]], [(fixed, "merge", "2026-10-14T10:00:00Z", [6], ()), (shipped, "merge", "2026-10-13T10:00:00Z", [4], (fixed,))]) self.assertEqual(sorted(found[1].titles), ["Do four", "Merge four"]) self.assertEqual((found[1].tip, found[2].tip), (self.git("rev-parse", "HEAD^").strip(), self.git("rev-parse", "HEAD^^").strip())) self.assertEqual((found[1].before, found[2].before), (found[2].tip, None)) def test_fails_where_git_cannot_read_the_branch(self): self.assertEqual(branch_chunks("main", lambda *args: Failure("no log")), Failure("no log")) if __name__ == "__main__": unittest.main()