I've been writing a small script that cleans up old git worktrees and their branches, and the one question it has to answer before it runs git branch -D is whether everything on the branch is already on main. For a branch that was merged with a merge commit that's easy, but most of my pull requests are rebase-merged or squash-merged, and for those the easy answer is wrong, and the obvious fixes are wrong in more interesting ways than I expected.
Why the ancestry check isn't enough
The usual way to ask "is this merged?" is to ask whether main can reach the branch's tip:
git merge-base --is-ancestor my-branch main && echo merged
# or, the same thing counted
git rev-list --count main..my-branch # 0 means merged
Both of these compare commits, and a rebase merge (or a squash merge) puts brand new commits on main with the same content but different SHAs, so the branch's own commits are never reachable from main and every rebase-merged branch reads as unmerged. That's safe, since the script just refuses to delete anything, but it also makes the script useless for a repository where nothing is merged with merge commits, so we have to compare content instead.
git cherry and its whitespace problem
The first tool I reached for was git cherry, which compares patch-ids, a hash of each commit's diff, and prints - for every commit on the branch whose change already exists upstream:
git cherry main my-branch
# - 5f1c... already upstream
# + 9a2b... not upstream
In a scratch repo it also skips merge commits completely (a merge commit gets no line at all), so my first version used git cherry only when the branch had no merge commits in it. The bigger problem is that patch-ids ignore whitespace, which is the whole point of them (they were made to recognize the same patch after it's been re-indented or rebased), but it's exactly wrong for a "safe to delete" check:
printf 'def f():\n return 1\n' > a.py # base, 4 spaces
# branch "tab" re-indents with a tab, branch "two" with 2 spaces
git cherry tab two
# - 8507691...
git cherry says the 2-space branch is already in the tab branch, and it says the same for a trailing space vs a trailing tab. Those are different bytes, and in Python, Makefiles or YAML a whitespace change can just as well change what the file means (move a line out of a nested block, say), so a check built on git cherry would happily delete a branch whose only change was one of those.
Asking whether a merge would change anything
A better question doesn't care how the branch was merged: if we merged the branch into main right now, would main change at all? If the merge result is byte-for-byte the same tree as main, every change on the branch is already there. git merge-tree --write-tree (git 2.38+) does the merge without touching a working tree and prints the resulting tree id:
target_tree=$(git rev-parse --verify "main^{tree}")
if merged_tree=$(git merge-tree --write-tree --no-messages main my-branch) &&
[ "$merged_tree" = "$target_tree" ]; then
echo "merged content"
fi
The exit status is part of the answer, so don't pipe it through head. Exit 1 means a conflict, and a conflicted merge can still produce main's exact tree: a binary file changed on both sides conflicts, and git's built-in binary driver leaves main's version in the result, so comparing trees alone would call that branch merged. Anything other than a clean exit is "not merged".
This covers rebase merges, squash merges, and branches that contain merge commits carrying their own edits. I also considered a simpler "entry equality" check (does every path the branch touched have the same blob on main?), but that blocks a merged branch whenever main later edited a file the branch had touched, and the merge question handles that, since the later edit is on main's side of the merge. The one case it still gets "wrong" is a rebase-merged branch whose exact lines main later rewrote, which conflicts and stays, and that's the safe direction to be wrong in.
How merge drivers change the result
The problem with the merge question is that git merge-tree runs merge drivers, and a merge driver decides how to combine two versions of a file. If a driver resolves a file to main's side without a conflict, the branch's edit disappears from the merge result, the tree equals main's tree, and the check says "merged" for a branch that isn't.
Drivers only run when both sides changed the file (otherwise git just takes the changed side), so the probe needs main to touch the same file in a different place:
printf 'a\nb\nc\nd\ne\nf\n' > a.txt # base
# branch "edit" changes the last line, main changes the first line
echo '* merge=ours' > .gitattributes # on main
git -c merge.ours.driver=true merge-tree --write-tree main edit
# same tree as main: the branch's edit is gone
merge.ours.driver=true defines a driver called ours whose command is true, which exits 0 and leaves the "current" (main's) file as the result. That one's easy to picture, but there are more ways to get a driver in than I'd have guessed:
-
Attributes in the checkout.
merge-treereads.gitattributesfrom the working tree, not from the trees being merged, so an uncommitted file is enough. -
Config redefining a built-in name.
merge.union.driver=truewith* merge=unionreplaces git's ownuniondriver. -
A default driver.
merge.defaultpicks a driver for every path that has nomergeattribute. -
A rename on the target side. If
mainrenamed a file into a path that carries amergeattribute, the merge happens on the new path, which the branch never touched, so checking only the branch's paths misses it. -
The environment.
GIT_CONFIG_COUNT,GIT_CONFIG_KEY_0andGIT_CONFIG_VALUE_0inject config without touching any file:
GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=merge.ours.driver GIT_CONFIG_VALUE_0=true \
git merge-tree --write-tree main edit
# same tree as main again
I tried closing these one at a time, first with an empty --attr-source and then with a guard that read the merge attributes of every changed path, and every patch left the next one open, which is usually a sign that you're guarding the wrong layer.
Running the merge where no driver can exist
What worked was to stop filtering drivers and run the merge somewhere they can't be defined. A driver needs config to exist, so we create a throwaway bare repository with no config of its own, point its objects/info/alternates at the real repository's object store so it can read every commit and tree, and run every git call under env -i with no system or global config:
repo=/path/to/repo
target=refs/heads/main
branch=refs/heads/my-branch
scratch=$(mktemp -d) || exit 2
trap 'rm -rf "$scratch"' EXIT
mkdir "$scratch/home" || exit 2
clean_git() {
env -i PATH="$PATH" HOME="$scratch/home" GIT_CONFIG_NOSYSTEM=1 \
git -c core.commitGraph=false "$@"
}
# resolve the names in the real repository, then leave it
target_commit=$(clean_git -C "$repo" rev-parse --verify --quiet "$target^{commit}") || exit 2
rev_commit=$(clean_git -C "$repo" rev-parse --verify --quiet "$branch^{commit}") || exit 2
common_dir=$(clean_git -C "$repo" rev-parse --path-format=absolute --git-common-dir) || exit 2
format=$(clean_git -C "$repo" rev-parse --show-object-format) || exit 2
# the sealed repository borrows the objects and nothing else
sealed="$scratch/sealed.git"
clean_git init -q --bare --object-format="$format" "$sealed" || exit 2
printf '%s\n' "$common_dir/objects" > "$sealed/objects/info/alternates" || exit 2
if clean_git -C "$sealed" merge-base --is-ancestor "$rev_commit" "$target_commit"; then
echo "merged ancestry"; exit 0
fi
target_tree=$(clean_git -C "$sealed" rev-parse --verify --quiet "$target_commit^{tree}") || exit 2
# exit 1 is a conflict, anything else an error, and neither is "merged"
merged_tree=$(clean_git -C "$sealed" merge-tree --write-tree --no-messages "$target_commit" "$rev_commit") ||
{ echo unmerged; exit 1; }
if [ "$merged_tree" = "$target_tree" ]; then
echo "merged content"; exit 0
fi
echo unmerged; exit 1
Every step that fails exits non-zero, and nothing but a clean, matching result says "merged". With --verify --quiet a mistyped name prints nothing, and without the || exit 2 two empty strings would compare equal.
In the sealed repository the only drivers that can run are git's built-in text, binary and union, which keep both sides or report a conflict, so the branch's edit can't be dropped without the exit status saying so. env -i removes GIT_CONFIG_COUNT and friends, and HOME pointing at an empty folder hides the global config. The bare repository has no checkout, so there's no .gitattributes for merge-tree to read. Each of the cases above now either keeps the branch's edit, which gives a tree that differs from main's, or conflicts, and the check reports the branch as unmerged.
The ancestry check runs in the sealed repository too, because the real one can have replace refs (refs/replace/) or an info/grafts file (deprecated, but git still reads it), and both can stitch history together so that main seems to reach a branch it never merged. Alternates share more than the packs, though, and a commit-graph file in the borrowed objects/info/ is trusted for parent links when git loads it, so a forged one can do the same stitching, which is what -c core.commitGraph=false is for. Only the name lookups run in the real repository, after which everything works on raw commit ids, and the names are passed in full (refs/heads/main) because a tag with the same name as a branch wins the lookup. Once the seal existed, the empty --attr-source from earlier no longer caught anything the seal didn't, so it went.
Summary
For a merge commit, git merge-base --is-ancestor is the right check, but for rebase and squash merges we have to compare content, and both obvious tools can call a real change merged: git cherry because patch-ids ignore whitespace, and git merge-tree because it runs whatever merge driver the repository or the environment defines, and because a conflict can still leave main's tree behind. When the answer decides whether a branch gets deleted, I'd run the merge in a sealed bare repository that borrows the objects through alternates, under env -i with no system or global config and with the commit-graph off, do the ancestry check there too, and treat anything other than a clean merge that equals main's tree as unmerged, since a list of guarded cases is never finished and the seal doesn't need one. The only inputs it still trusts are the git binary on your PATH and the objects, which are addressed by their content.
Top comments (0)