THREE-WAY MERGE – THE 30-SECOND STORY
- Take the common ancestor (A) of the two branches.
- Take the current tip of each branch (B and C).
- Line-by-line, ask:
• Did only one side change it? → keep that change.
• Did both sides change it to the same thing? → keep it once.
• Did both sides change it to different things? → conflict – a human must decide.
Below is a tiny, self-contained example that you can literally type into three files and run through git merge to see every step.
THE PLAYERS
Ancestor (A) – the file as it existed when the two branches forked.
# calculator.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
Branch feature-logging (B) – Alice adds logging to both functions.
# calculator.py
import logging
def add(a, b):
logging.info(f"add({a}, {b})")
return a + b
def sub(a, b):
logging.info(f"sub({a}, {b})")
return a - b
Branch feature-negative (C) – Bob decides subtraction should return the absolute value.
# calculator.py
def add(a, b):
return a + b
def sub(a, b):
return abs(a - b) # Bob's new idea
STEP-BY-STEP MERGE
- Git finds the common ancestor (A).
- Git compares A→B and A→C.
| Line range | A (ancestor) | B (feature-logging) | C (feature-negative) | 3-way merge decision |
|---|
| Top | (none) | import logging | (none) | Only B touched it → keep B’s line. |
add body | return a+b | add logging line | unchanged | Only B touched it → keep B’s change. |
sub body | return a-b | add logging line | return abs(a-b) | Both sides changed differently → CONFLICT. |
Git stops and drops this into the working tree:
<<<<<<< HEAD (feature-logging)
logging.info(f"sub({a}, {b})")
return a - b
=======
return abs(a - b)
>>>>>>> feature-negative
HOW A HUMAN RESOLVES IT
Alice and Bob talk, decide they want both logging and the absolute-value behavior.
They edit the file to:
def sub(a, b):
logging.info(f"sub({a}, {b})")
return abs(a - b)
Then:
git add calculator.py
git commit # creates the merge commit
WHY CONFLICTS HAPPEN & HOW TO REDUCE THEM
-
Touch the same lines – unavoidable if intent overlaps.
Mitigation: smaller commits, smaller functions, clear ownership.
-
Refactor early – if Bob had extracted a helper def _sub_raw(a,b): return a-b and only changed that helper, Alice’s logging in sub would have auto-merged.
-
Communicate – “I’m about to change the return value of sub” prevents surprises.
-
Rebase or merge frequently – the shorter the diff A→B and A→C, the fewer collisions.
ONE-MINUTE REPLAY
Ancestor
├── Alice adds logging → branch B
└── Bob changes return value → branch C
Merge = “What did Alice do since ancestor? What did Bob do since ancestor?
If they stepped on each other, shout for help.”