import typing from branch_chunks.fixes import blamed, fixing_changes, removed, with_fixes from branch_chunks.cut import BranchChunk, cut_branch, LOG, NOT_WORK, plan_revisions, with_shipped from failure import Failure # Runs git with the given arguments in the checkout's top: blame and a pathspec read a path from the current directory, and the diff names each from the top. Run = typing.Callable[..., str | Failure] def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure: """Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.""" # The -- keeps a file named like the branch from making it ambiguous. log = run(*LOG, default, "--") if isinstance(log, Failure): return log branch = cut_branch(log) plans = plans_at(plan_revisions(branch), run) if isinstance(plans, Failure): return plans branch = with_shipped(branch, plans) traced = traces(fixing_changes(branch), run) return traced if isinstance(traced, Failure) else with_fixes(branch, traced) def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure: """todo.md's text at each revision, empty where the revision holds none.""" plans = {} for revision in revisions: listed = run("ls-tree", "--name-only", revision, "--", "todo.md") if isinstance(listed, Failure): return listed plan = run("show", f"{revision}:todo.md") if listed.strip() else "" if isinstance(plan, Failure): return plan plans[revision] = plan return plans def traces(changes: list[tuple[int, str, str]], run: Run) -> list[tuple[int, set[str]]] | Failure: """The commits each change traced_to traces, paired with the change's chunk's index.""" found = [] for index, before, tip in changes: traced = traced_to(before, tip, run) if isinstance(traced, Failure): return traced found.append((index, traced)) return found def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure: """The commits that last changed each line the change from before to tip removes or rewrites, outside the plan and the records.""" # The prefixes and options keep the checkout's diff config out of the output. diff = run("diff", "-U0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip) if isinstance(diff, Failure): return diff traced: set[str] = set() for path, spans in removed(diff).items(): if path in NOT_WORK: continue # An empty --ignore-revs-file drops a configured one, which blame fails on where the file is missing. blame = run("blame", "--porcelain", "--no-textconv", "--ignore-revs-file=", *(f"-L{start},+{count}" for start, count in spans), before, "--", path) if isinstance(blame, Failure): return blame traced |= blamed(blame) return traced