diff --git a/docs/concepts.md b/docs/concepts.md index 3bf0977..f02e7f8 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -13,9 +13,27 @@ because fetching writes to the repository and needs the network. Squash and rebase merges inflate this count. When a branch is squash-merged on the host, its original commits stay unreachable from any remote ref, so a local copy of that branch still counts as unique even though its changes shipped. -Check such a branch with `git cherry -v `: lines starting -with `-` are already upstream by patch content. Delete the branch once you have -confirmed that; repo-ledger does not do patch-id matching yet. + +## Already landed + +So each branch also gets **unlanded commits**: its unique commits whose change +is not already on a remote's default branch (the remote's `HEAD`, else `main`, +else `master`). A commit has landed when `git cherry` finds a commit with the +same patch there, which covers rebase and cherry-pick merges. The whole branch +has landed when one commit there has the same patch as the branch's full diff +from its merge base, which covers a squash merge. + +A branch with unique commits and no unlanded ones is listed under +**branches already landed**. Its commits are still counted as unique and the +repository is still at risk, because the match is by patch text, not identity: +confirm with `git cherry -v ` before you delete it. The +check misses a squash that also changed other files, and one whose context +lines changed because the default branch edited the same files first. A local +merge commit never counts as landed. + +The check reads each remote's default branch once, back to the common ancestor +of the local branches, so a repository with hundreds of local-only branches and +a long history takes a few times longer to inventory than it did before. ## Privacy of a receipt diff --git a/schemas/inventory.schema.json b/schemas/inventory.schema.json index be21ea6..5627ca3 100644 --- a/schemas/inventory.schema.json +++ b/schemas/inventory.schema.json @@ -142,6 +142,10 @@ "unique_commits": { "type": "integer", "minimum": 0 + }, + "unlanded_commits": { + "type": "integer", + "minimum": 0 } }, "required": [ @@ -150,6 +154,7 @@ "commit", "name", "unique_commits", + "unlanded_commits", "upstream", "upstream_gone" ], @@ -288,10 +293,17 @@ "unreadable_worktrees": { "type": "integer", "minimum": 0 + }, + "branches_already_landed": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ "at_risk", + "branches_already_landed", "branches_with_unique_commits", "dirty_paths", "missing_worktrees", diff --git a/tools/repo-ledger/README.md b/tools/repo-ledger/README.md index 58406b3..f12c79e 100644 --- a/tools/repo-ledger/README.md +++ b/tools/repo-ledger/README.md @@ -28,6 +28,10 @@ For each repository it reports: - **unique commits**: commits reachable from a local branch but from no remote-tracking ref. These are lost if the disk is. - **branches with unique commits**, by name, including branches with no upstream. +- **branches already landed**: of those, the ones whose changes are already on a + remote's default branch by patch content, as after a squash or rebase merge. + Each branch's **unlanded commits** counts what has not landed. See + [Concepts](../../docs/concepts.md#already-landed). - **stashes** and **dirty paths** (staged, unstaged, untracked, conflicted), counted in the main worktree and in every linked worktree. - **worktrees**, including ones whose directory is gone. diff --git a/tools/repo-ledger/src/repo_ledger/gitcmd.py b/tools/repo-ledger/src/repo_ledger/gitcmd.py index 3404b59..1fc38c5 100644 --- a/tools/repo-ledger/src/repo_ledger/gitcmd.py +++ b/tools/repo-ledger/src/repo_ledger/gitcmd.py @@ -4,6 +4,7 @@ import os import subprocess +import tempfile from pathlib import Path # A repository's own config can name an fsmonitor command that `git status` @@ -35,12 +36,13 @@ def __init__(self, stderr: str, returncode: int): self.returncode = returncode -def run(repo: Path, *args: str, check: bool = True) -> str: +def run(repo: Path, *args: str, check: bool = True, stdin: str | None = None) -> str: proc = subprocess.run( ["git", *SAFE_CONFIG, "-C", str(repo), *args], capture_output=True, env=git_env(), - stdin=subprocess.DEVNULL, + **({"input": stdin.encode(errors="surrogateescape")} if stdin is not None + else {"stdin": subprocess.DEVNULL}), timeout=120, ) if check and proc.returncode != 0: @@ -48,6 +50,30 @@ def run(repo: Path, *args: str, check: bool = True) -> str: return proc.stdout.decode(errors="surrogateescape") +def piped(repo: Path, first: tuple[str, ...], second: tuple[str, ...]) -> str: + """``git | git ``, streamed so a long first output is never held.""" + with tempfile.TemporaryFile() as err: + head = subprocess.Popen(["git", *SAFE_CONFIG, "-C", str(repo), *first], + stdout=subprocess.PIPE, stderr=err, stdin=subprocess.DEVNULL, + env=git_env()) + try: + tail = subprocess.run(["git", *SAFE_CONFIG, "-C", str(repo), *second], + stdin=head.stdout, capture_output=True, env=git_env(), + timeout=600) + except BaseException: + head.kill() + raise + finally: + head.stdout.close() + code = head.wait() + if tail.returncode != 0: + raise GitError(tail.stderr.decode(errors="replace"), tail.returncode) + if code != 0: + err.seek(0) + raise GitError(err.read().decode(errors="replace"), code) + return tail.stdout.decode(errors="surrogateescape") + + def ok(repo: Path, *args: str) -> bool: try: run(repo, *args) diff --git a/tools/repo-ledger/src/repo_ledger/inventory.py b/tools/repo-ledger/src/repo_ledger/inventory.py index 60777e7..553cedd 100644 --- a/tools/repo-ledger/src/repo_ledger/inventory.py +++ b/tools/repo-ledger/src/repo_ledger/inventory.py @@ -70,10 +70,106 @@ def _worktrees(repo: Path) -> list[dict]: return trees +# Patch text must come from git's own diff: a repository's config can name an +# external diff, a textconv filter or a signature check, and each runs a command. +_DIFF = ("--no-ext-diff", "--no-textconv", "--no-color") + + +def _default_targets(repo: Path) -> list[str]: + """Each remote's default branch: its HEAD, else ``main``, else ``master``.""" + out = gitcmd.run(repo, "for-each-ref", "--format=%(refname)%00%(symref)", "refs/remotes") + refs: dict[str, set[str]] = {} + heads: dict[str, str] = {} + for line in out.splitlines(): + ref, _, symref = line.partition("\0") + remote, _, branch = ref.removeprefix("refs/remotes/").rpartition("/") + if branch == "HEAD": + heads[remote] = symref + else: + refs.setdefault(remote, set()).add(ref) + targets = [] + for remote, names in sorted(refs.items()): + options = [heads.get(remote)] + [f"refs/remotes/{remote}/{b}" for b in ("main", "master")] + pick = next((o for o in options if o in names), None) + if pick: + targets.append(pick) + return targets + + +_LOG_PATCH = ("log", "-p", *_DIFF, "--no-renames", "--no-show-signature", "--no-merges", + "--format=commit %H") + + +def _patch_ids(repo: Path, *log_args: str) -> dict[str, str]: + """commit -> patch id, for each non-merge commit ``git log `` lists.""" + out = gitcmd.piped(repo, (*_LOG_PATCH, *log_args), ("patch-id", "--stable")) + return {commit: pid for pid, commit in (line.split() for line in out.splitlines() if line)} + + +def _file_sets(repo: Path, *log_args: str) -> set[frozenset[str]]: + """The set of paths each non-merge commit ``git log `` lists changes.""" + out = gitcmd.run(repo, "log", "--no-merges", "--no-renames", "--format=commit %H", + "--name-only", *log_args) + sets: set[frozenset[str]] = set() + for chunk in out.split("commit ")[1:]: + sets.add(frozenset(line for line in chunk.splitlines()[1:] if line)) + return sets + + +def _squash_ids(repo: Path, target: str, tips: list[str]) -> dict[str, str]: + """branch tip -> patch id of its whole diff from its merge base with ``target``.""" + text = "".join(f"commit {tip}\n" + gitcmd.run(repo, "diff", *_DIFF, "--no-renames", + f"{target}...{tip}") + for tip in tips) + out = gitcmd.run(repo, "patch-id", "--stable", stdin=text) if text else "" + return {commit: pid for pid, commit in (line.split() for line in out.splitlines() if line)} + + +def _mark_landed(repo: Path, branches: list[dict], unique: dict[str, list[str]]) -> None: + """Set each branch's ``unlanded_commits``: unique commits with no patch on a default branch. + + A commit has landed when a default branch has a commit with the same patch + (a rebase or cherry-pick merge). A whole branch has landed when one commit + there has the patch of the branch's full diff from its merge base (a squash + merge). Each default branch is read once, back to the common ancestor of every + branch, and a branch's full diff is built only when its changed files match + the files of some commit there, so the cost stays near one history pass. + """ + for branch in branches: + branch["unlanded_commits"] = len(unique[branch["commit"]]) + left = {b["commit"]: set(unique[b["commit"]]) for b in branches if b["unlanded_commits"]} + if not left: + return + own = _patch_ids(repo, "--branches", "--not", "--remotes") + for target in _default_targets(repo): + oldest = gitcmd.run(repo, "merge-base", "--octopus", target, *sorted(left), + check=False).strip() + since = ["--not", oldest] if oldest else [] + landed = set(_patch_ids(repo, target, *since).values()) + for commits in left.values(): + commits -= {c for c in commits if own.get(c) in landed} + shapes = _file_sets(repo, target, *since) + candidates = [] + for tip, commits in left.items(): + if not commits: + continue + names = gitcmd.run(repo, "diff", "--no-renames", "--name-only", f"{target}...{tip}", + check=False).splitlines() + if names and frozenset(n for n in names if n) in shapes: + candidates.append(tip) + for tip, pid in _squash_ids(repo, target, candidates).items(): + if pid in landed: + left[tip] = set() + for branch in branches: + if branch["commit"] in left: + branch["unlanded_commits"] = len(left[branch["commit"]]) + + def _branches(repo: Path) -> list[dict]: fmt = "%(refname:short)%00%(objectname)%00%(upstream:short)%00%(upstream:track,nobracket)" out = gitcmd.run(repo, "for-each-ref", f"--format={fmt}", "refs/heads") branches = [] + unique: dict[str, list[str]] = {} for line in out.splitlines(): name, sha, upstream, track = (line.split("\0") + ["", "", ""])[:4] ahead = behind = 0 @@ -83,7 +179,7 @@ def _branches(repo: Path) -> list[dict]: ahead = int(number) elif word == "behind": behind = int(number) - unique = int(gitcmd.run(repo, "rev-list", "--count", sha, "--not", "--remotes").strip() or 0) + unique[sha] = gitcmd.run(repo, "rev-list", sha, "--not", "--remotes").split() branches.append({ "name": name, "commit": sha, @@ -91,8 +187,9 @@ def _branches(repo: Path) -> list[dict]: "upstream_gone": track.strip() == "gone", "ahead": ahead, "behind": behind, - "unique_commits": unique, + "unique_commits": len(unique[sha]), }) + _mark_landed(repo, branches, unique) return branches @@ -180,6 +277,8 @@ def inspect(path: Path, name: str | None = None, worktree_status: bool = True) - entry["summary"] = { "unique_commits": unique_total, "branches_with_unique_commits": local_only, + "branches_already_landed": [b["name"] for b in entry["branches"] + if b["unique_commits"] and not b["unlanded_commits"]], "stashes": entry["stashes"], "dirty_paths": dirty_total, "missing_worktrees": sum(1 for t in trees if not t["exists"]), diff --git a/tools/repo-ledger/src/repo_ledger/render.py b/tools/repo-ledger/src/repo_ledger/render.py index ab1b7ac..30b6795 100644 --- a/tools/repo-ledger/src/repo_ledger/render.py +++ b/tools/repo-ledger/src/repo_ledger/render.py @@ -32,5 +32,9 @@ def inventory_markdown(receipt: dict) -> str: if repo["state"] == "ok" and repo["summary"]["branches_with_unique_commits"]: names = ", ".join(repo["summary"]["branches_with_unique_commits"]) lines.append(f"- {_cell(repo['name'])}: branches with commits on no remote: {names}") + if repo["state"] == "ok" and repo["summary"]["branches_already_landed"]: + names = ", ".join(repo["summary"]["branches_already_landed"]) + lines.append(f"- {_cell(repo['name'])}: of those, already on a remote default branch " + f"by patch content: {names}") lines.append("Remote refs are as of each repo's last fetch; nothing was fetched.") return "\n".join(lines) + "\n" diff --git a/tools/repo-ledger/tests/conftest.py b/tools/repo-ledger/tests/conftest.py index 8c42b2c..4855e0b 100644 --- a/tools/repo-ledger/tests/conftest.py +++ b/tools/repo-ledger/tests/conftest.py @@ -21,8 +21,10 @@ def isolated_git(tmp_path, monkeypatch): def git(cwd: Path, *args: str) -> str: - return subprocess.run(["git", "-C", str(cwd), *args], check=True, - capture_output=True, text=True).stdout + proc = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, text=True) + if proc.returncode: + raise AssertionError(f"git {' '.join(args)} failed: {proc.stderr.strip()}") + return proc.stdout def commit(repo: Path, name: str = "file.txt", text: str = "x\n") -> str: diff --git a/tools/repo-ledger/tests/test_inventory.py b/tools/repo-ledger/tests/test_inventory.py index 7dfa875..e81f6fb 100644 --- a/tools/repo-ledger/tests/test_inventory.py +++ b/tools/repo-ledger/tests/test_inventory.py @@ -29,7 +29,8 @@ def test_clean_pushed_repo_is_not_at_risk(make_repo, capsys): assert entry["head"]["branch"] == "main" assert entry["branches"][0]["upstream"] == "origin/main" assert entry["summary"] == { - "unique_commits": 0, "branches_with_unique_commits": [], "stashes": 0, + "unique_commits": 0, "branches_with_unique_commits": [], "branches_already_landed": [], + "stashes": 0, "dirty_paths": 0, "missing_worktrees": 0, "unreadable_worktrees": 0, "at_risk": False, } @@ -53,9 +54,70 @@ def test_unpushed_and_local_only_branches_are_counted(make_repo, capsys): assert by_name["local-only"]["unique_commits"] == 2 assert entry["summary"]["unique_commits"] == 2 # union, not a sum assert entry["summary"]["branches_with_unique_commits"] == ["local-only", "main"] + assert by_name["local-only"]["unlanded_commits"] == 2 + assert entry["summary"]["branches_already_landed"] == [] assert entry["summary"]["at_risk"] is True +def _landed(make_repo, tmp_path, how): + """A local branch `done` whose change reached origin/main by squash or cherry-pick.""" + repo = make_repo() + git(repo, "switch", "-q", "-c", "done") + commit(repo, "a.txt", "a\n") + commit(repo, "b.txt", "b\n") + git(repo, "switch", "-q", "main") + commit(repo, "other.txt") # main moves on, so nothing is a fast-forward + if how == "squash": + git(repo, "merge", "-q", "--squash", "done") + git(repo, "commit", "-q", "-m", "squash done") + else: + git(repo, "cherry-pick", "done~1", "done") + git(repo, "update-ref", "refs/remotes/origin/main", "main") # as a fetch would leave it + return repo + + +@pytest.mark.parametrize("how", ["squash", "cherry-pick"]) +def test_branch_whose_changes_already_landed_is_named(make_repo, tmp_path, capsys, how): + repo = _landed(make_repo, tmp_path, how) + git(repo, "switch", "-q", "-c", "open") + commit(repo, "open.txt") + git(repo, "switch", "-q", "main") + _, data = receipt(capsys, str(repo)) + entry = data["repos"][0] + by_name = {b["name"]: b for b in entry["branches"]} + assert by_name["done"]["unique_commits"] == 2 + assert by_name["done"]["unlanded_commits"] == 0 + assert by_name["open"]["unlanded_commits"] == 1 + assert entry["summary"]["branches_already_landed"] == ["done"] + assert entry["summary"]["at_risk"] is True # the commits themselves are still local-only + + +def test_partly_landed_branch_counts_only_the_rest(make_repo, capsys): + repo = make_repo() + git(repo, "switch", "-q", "-c", "half") + commit(repo, "a.txt", "a\n") + commit(repo, "b.txt", "b\n") + git(repo, "switch", "-q", "main") + commit(repo, "other.txt") # else the pick can recreate the same commit hash + git(repo, "cherry-pick", "half~1") + git(repo, "update-ref", "refs/remotes/origin/main", "main") + _, data = receipt(capsys, str(repo)) + entry = data["repos"][0] + half = next(b for b in entry["branches"] if b["name"] == "half") + assert (half["unique_commits"], half["unlanded_commits"]) == (2, 1) + assert entry["summary"]["branches_already_landed"] == [] + + +def test_landed_check_uses_the_remote_head(make_repo, capsys): + repo = _landed(make_repo, None, "squash") + git(repo, "update-ref", "refs/remotes/origin/trunk", "main") + git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk") + git(repo, "branch", "-q", "--unset-upstream", "main") + git(repo, "update-ref", "-d", "refs/remotes/origin/main") + _, data = receipt(capsys, str(repo)) + assert data["repos"][0]["summary"]["branches_already_landed"] == ["done"] + + def test_repo_without_remote_counts_every_commit(make_repo, capsys): repo = make_repo(pushed=False) _, data = receipt(capsys, str(repo)) @@ -251,6 +313,30 @@ def test_repository_config_cannot_run_a_command(make_repo, tmp_path, capsys): assert not marker.exists() +def test_landed_check_cannot_run_a_diff_driver(make_repo, tmp_path, capsys): + repo = _landed(make_repo, tmp_path, "squash") + marker = tmp_path / "ran" + tool = tmp_path / "driver.sh" + tool.write_text(f"#!/bin/sh\ntouch '{marker}'\ncat \"$1\"\n") + tool.chmod(0o755) + (repo / ".gitattributes").write_text("*.txt diff=evil\n") + git(repo, "config", "diff.external", str(tool)) + git(repo, "config", "diff.evil.command", str(tool)) + git(repo, "config", "diff.evil.textconv", str(tool)) + git(repo, "config", "log.showSignature", "true") + git(repo, "config", "gpg.program", str(tool)) + _, data = receipt(capsys, str(repo)) + assert data["repos"][0]["summary"]["branches_already_landed"] == ["done"] + assert not marker.exists() + + +def test_markdown_lists_landed_branches(make_repo, tmp_path, capsys): + repo = _landed(make_repo, tmp_path, "squash") + assert cli.main(["inventory", str(repo)]) == 0 + out = capsys.readouterr().out + assert "already on a remote default branch by patch content: done" in out + + def test_markdown_table_names_risky_branches(make_repo, capsys): repo = make_repo("pipe|name") git(repo, "switch", "-q", "-c", "keep-me")