Introduction
Branches are only useful if their work can be brought back together. git merge does this, and most of the time it needs no help at all. Knowing how it decides, by comparing both sides with the point where they diverged, tells you when a merge will be automatic, what a fast-forward is, and why conflicts happen where they do.
How it works
Running git merge feature while on main has three possible outcomes:
- Already up to date:
feature's tip is already reachable frommain; there is nothing to do. - Fast-forward:
main's tip is an ancestor offeature's tip, somainhad nothing new. Git just movesmainforward tofeature's tip. No new commit is made. - True merge: both sides have new commits. Git creates a merge commit with two parents.
For a true merge Git finds the merge base: the best common ancestor, a commit that both histories contain and that is not an ancestor of another common ancestor. It is the point where the branches diverged.
Then it does a three-way merge, comparing base (B), ours (O) and theirs (T) for each file (and, inside files, for each region of lines):
- if O and T are the same, use it;
- if only theirs changed (O equals B), take T;
- if only ours changed (T equals B), keep O;
- if both changed differently, it is a conflict.
Deletions count as changes: a file deleted on one side and unchanged on the other is deleted. A file deleted on one side and modified on the other is a modify/delete conflict; a file added on both sides with different contents is an add/add conflict; overlapping edits inside a file are a content conflict.
git switch main
git merge feature # fast-forward or merge commit
git merge --no-ff feature # always create a merge commit
git merge-base main feature # print the merge base
git merge --abort # give up a conflicted merge
Example
parents = {"a": [], "b": ["a"], "c": ["b"], "f": ["b"], "g": ["f"]}
def ancestors(oid):
seen, stack = set(), [oid]
while stack:
x = stack.pop()
if x not in seen:
seen.add(x)
stack.extend(parents[x])
return seen
def merge_base(x, y):
common = ancestors(x) & ancestors(y)
return sorted(c for c in common if not any(c in ancestors(o) and c != o for o in common))
print("merge base of main (c) and feature (g):", merge_base("c", "g"))
base = {"app.py": "v1", "README.md": "v1", "old.txt": "v1"}
ours = {"app.py": "v2", "README.md": "v1", "old.txt": "v1"}
theirs = {"app.py": "v1", "README.md": "v2", "new.txt": "v1"}
result = {}
for path in sorted(set(base) | set(ours) | set(theirs)):
b, o, t = base.get(path), ours.get(path), theirs.get(path)
if o == t:
chosen = o
elif o == b:
chosen = t
elif t == b:
chosen = o
else:
print("CONFLICT in", path)
continue
print(f"{path:10} base={b} ours={o} theirs={t} -> {chosen}")
if chosen is not None:
result[path] = chosen
print("merged snapshot:", result)Line by line
ancestorscollects every commit reachable from a commit; the merge base is a common ancestor that no other common ancestor descends from.- For main at
cand feature atg, the merge base isb, where the branches split. - app.py changed only on our side, so our version is kept.
- README.md changed only on their side, so theirs is taken; old.txt was deleted by them and untouched by us, so it is deleted.
- new.txt was added only by them, so it appears in the merged snapshot.
Expected result
merge base of main (c) and feature (g): ['b']
README.md base=v1 ours=v1 theirs=v2 -> v2
app.py base=v1 ours=v2 theirs=v1 -> v2
new.txt base=None ours=None theirs=v1 -> v1
old.txt base=v1 ours=v1 theirs=None -> None
merged snapshot: {'README.md': 'v2', 'app.py': 'v2', 'new.txt': 'v1'}
In the real world
Most merges in active projects are automatic because people change different files or different parts of files. Git's default strategy, "ort", handles renames and repeated merges efficiently. Teams choose between merge commits, which preserve the branch structure, and fast-forward-only or squash merges, which keep a straight history; pull request settings on GitHub enforce the choice.
Common mistakes
- Merging the wrong way round:
git merge featurebrings feature into the current branch. - Panicking at a conflict:
git merge --abortreturns to the state before the merge. - Expecting a merge commit after a fast-forward; use
--no-ffif you want one. - Merging with uncommitted changes, which can make a failed merge harder to undo.
Best practices
- Commit or stash your work before merging.
- Merge
maininto long-running branches regularly so conflicts stay small. - Read the merge result with
git log --graphand run the tests before pushing.
Summary
A merge is up to date, a fast-forward, or a true merge with a merge commit. A true merge compares both sides with their merge base: whichever side changed something wins, and both sides changing it differently is a conflict, reported as content, add/add or modify/delete.
Quick check
Key takeaways
- If the other branch is ahead of yours with nothing new on your side, Git just fast-forwards.
- A three-way merge keeps whichever side changed something compared with the merge base.
- When both sides changed the same thing differently, Git stops and asks you to resolve the conflict.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.