git merge-base Command: Find Common Ancestor in CI
git merge-base finds the commit where two branches diverged, their best common ancestor.
Change-aware CI needs to diff a PR against the point it branched from, not against the tip of the target branch. merge-base computes exactly that fork point.
Common flags
<a> <b>- print the best common ancestor of two commits--fork-point <ref>- find where the current branch forked, using reflog data--is-ancestor <a> <b>- exit zero if A is an ancestor of B (a test, no output)--all- print all best common ancestors when several exist--octopus- common ancestor for more than two commits
Example
shell
# Diff a PR against the point it diverged from main
BASE="$(git merge-base origin/main HEAD)"
git diff --name-only "${BASE}...HEAD"In CI
Computing the merge-base is the correct way to scope a PR diff; using origin/main directly includes unrelated commits merged after the branch was cut. This requires enough history to reach the fork point, so use fetch-depth: 0 (or a deepened fetch) on PR builds.
Key takeaways
- git merge-base finds the true PR fork point for accurate changed-files diffs.
- --is-ancestor is a clean boolean test for "is this commit reachable".
- It needs history back to the divergence, so PR builds want fetch-depth 0.
Related guides
git diff Command: Detect Changes in CIgit diff shows changes between commits or the working tree. Reference for --name-only, --stat, and --exit-cod…
git rev-list Command: Count Commits in CIgit rev-list lists commit objects in reverse chronological order. Reference for --count to derive monotonic b…
git cherry-pick Command in CIgit cherry-pick applies the changes of specific commits onto the current branch. Reference for -x, --no-commi…
git fetch Command: Update Refs in CIgit fetch downloads objects and refs from a remote without merging. Reference for --depth, --unshallow, --tag…