Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions docs/concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <upstream> <branch>`: 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 <default> <branch>` 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

Expand Down
12 changes: 12 additions & 0 deletions schemas/inventory.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@
"unique_commits": {
"type": "integer",
"minimum": 0
},
"unlanded_commits": {
"type": "integer",
"minimum": 0
}
},
"required": [
Expand All @@ -150,6 +154,7 @@
"commit",
"name",
"unique_commits",
"unlanded_commits",
"upstream",
"upstream_gone"
],
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions tools/repo-ledger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 28 additions & 2 deletions tools/repo-ledger/src/repo_ledger/gitcmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -35,19 +36,44 @@ 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:
raise GitError(proc.stderr.decode(errors="replace"), proc.returncode)
return proc.stdout.decode(errors="surrogateescape")


def piped(repo: Path, first: tuple[str, ...], second: tuple[str, ...]) -> str:
"""``git <first> | git <second>``, 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)
Expand Down
103 changes: 101 additions & 2 deletions tools/repo-ledger/src/repo_ledger/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <log_args>`` 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 <log_args>`` 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
Expand All @@ -83,16 +179,17 @@ 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,
"upstream": upstream or None,
"upstream_gone": track.strip() == "gone",
"ahead": ahead,
"behind": behind,
"unique_commits": unique,
"unique_commits": len(unique[sha]),
})
_mark_landed(repo, branches, unique)
return branches


Expand Down Expand Up @@ -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"]),
Expand Down
4 changes: 4 additions & 0 deletions tools/repo-ledger/src/repo_ledger/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
6 changes: 4 additions & 2 deletions tools/repo-ledger/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading