Skip to content

Lesson 3 of 28Git in a team

Resolving Conflicts with Confidence

Read conflicts with the base version, keep ours and theirs straight during a rebase, handle lockfiles and migrations, and catch the conflicts Git cannot see.

14 min read0/5 questions

You rebase your branch before review and Git stops: CONFLICT (content): Merge conflict in billing/service.py. Two screens of markers, code you did not write on one side, and a deploy waiting on your PR. This is where people make their worst Git mistakes: clicking "accept incoming" on everything, deleting a teammate's fix without noticing, or running --skip and losing their own commit. Conflicts are routine on any active team. What separates a confident engineer is a method: see what each side changed, decide what the code should do now, and prove it with tests. Git Basics showed you the markers; this lesson is the method.

Why conflicts happen

Git merges with a three-way merge. It compares three versions of each file: the base (the merge base, the last commit both sides share), ours and theirs. For each region of the file:

  • If only one side changed it, take that side.
  • If both made the same change, take it once.
  • If both changed it differently, stop and ask you. That is a conflict.

The rule is mechanical and does not understand code. A toy version on four config lines:

Python
# A toy three-way merge. Real Git aligns changed regions (hunks) with a# diff algorithm; here every version has the same number of lines.base = ["host='db.internal'", "timeout=30", "retries=3", "pool=10"]ours = ["host='db.internal'", "timeout=60", "retries=4", "pool=20"]theirs = ["host='db.prod'", "timeout=30", "retries=5", "pool=20"] def merge3(base, ours, theirs): result, conflicts = [], 0 for b, o, t in zip(base, ours, theirs): if o == t: # both sides agree (changed or not) result.append(o) elif o == b: # only theirs changed this line result.append(t) elif t == b: # only ours changed this line result.append(o) else: # both changed it, differently conflicts += 1 result += ["<<<<<<< ours", o, "||||||| base", b, "=======", t, ">>>>>>> theirs"] return result, conflicts merged, n = merge3(base, ours, theirs)print("\n".join(merged))print(f"\n{n} conflict(s)")
Output
Press Run (⌘ Enter) to see what happens.

Notice that the base is what makes the decisions possible. Without it, host would look like a disagreement; with it, Git can see only one side touched that line.

Real Git differs from the toy in one way that surprises people: it works on hunks, not single lines. If you change line 2 and a teammate changes line 3, Git treats that as one overlapping region and reports a conflict, even though no single line was edited twice. Leave one unchanged line between the edits and it merges cleanly. Conflicts also come from the file level:

  • modify/delete: one side edited a file, the other deleted it. Git keeps the edited version in your folder and asks whether it should exist.
  • add/add: both sides created a file at the same path with different content.
  • renames: Git detects renames by content similarity, so if one side renamed util.py to helpers.py and the other edited util.py, the edit usually lands in helpers.py without a conflict. Renaming and heavily editing a file in one commit can defeat the detection.

Turn on the base: zdiff3

By default Git shows you only two of the three versions:

<<<<<<< HEAD
        timeout=30,  # seconds
        retries=5,
=======
        timeout=60,
        retries=3,
>>>>>>> main

Which side changed retries? Which changed timeout? You cannot tell, so you guess, and guessing is how fixes get lost. One setting changes this (it needs Git 2.35 or later):

git config --global merge.conflictStyle zdiff3

Now the same conflict shows the base between ||||||| and =======:

<<<<<<< HEAD
        timeout=30,  # seconds
        retries=5,
||||||| 55ddfb2
        timeout=30,
        retries=3,
=======
        timeout=60,
        retries=3,
>>>>>>> main

Read it as two diffs against the base. Your side (HEAD) added a comment to timeout and raised retries to 5. Main doubled timeout to 60 and left retries alone. Neither side disagreed about anything; they just edited neighbouring lines. The right answer keeps both intentions:

        timeout=60,  # seconds
        retries=5,

That is the whole technique: for each side, work out what it was trying to do relative to the base, then write code that does both, or decide consciously that one intention wins. The "z" in zdiff3 means it also trims lines that are identical on both sides out of the conflict, so the markers wrap only what really differs.

Quick check
With zdiff3, the base says limit = 100, your side says limit = 100 with a new line offset = 0 below it, and the other side says limit = 50. What should the resolved code be?
Need a nudge? A hint rules out a wrong answer.

Ours and theirs flip during a rebase

ours and theirs are not "my code" and "their code". They mean the commit HEAD is on and the commit being brought in. In a merge that matches intuition. In a rebase it is reversed, because a rebase works by checking out the branch you are rebasing onto and replaying your commits on top of it.

Who is ours, who is theirs
BbaseCEME'

currentwaitingdone

Both lines of work start at the merge base B. C is on main; E is your commit on feature.

1/4

This matters most when you resolve a whole file to one side with git checkout --ours or --theirs (or the newer git restore --ours / --theirs). Here is a real session from the zdiff3 example, but during a rebase:

$ git rebase main
CONFLICT (content): Merge conflict in db.py
error: could not apply a5745d1... Raise retries to 5
$ git checkout --theirs db.py && grep retries db.py
        retries=5,

--theirs gave back your commit's version. Also look at the markers during a rebase: the top section is labelled HEAD but holds main's code, and the bottom is labelled with your commit's hash and message.

Predict the outputShell

Main changed the line to timeout=60,. Your branch changed it to timeout=30, # seconds. You run git rebase main, it conflicts, and you run the commands below. What does grep print?

git checkout --ours db.py
grep timeout db.py
Need a nudge? Hints walk you through it.

A calm workflow for any conflict

Whether you are merging, rebasing, cherry-picking or popping a stash, the loop is the same:

git status                               # what operation am I in? which files?git diff --name-only --diff-filter=U     # just the conflicted paths# open each file, resolve, remove every markergit diff --check                         # catches leftover markers and whitespace errorsgit add billing/service.py               # mark this file resolvednpm test                                 # or pytest: prove the result worksgit rebase --continue                    # or: git merge --continue, git cherry-pick --continue

The escape hatches matter as much as the happy path:

  • git merge --abort / git rebase --abort: put everything back exactly as it was before you started. Always safe, and the right move when the conflict is bigger than you expected and you want to talk to the other author first.
  • git checkout --conflict=zdiff3 path: you made a mess of one file; recreate its conflict markers and start that file again.
  • git rebase --skip: drop the commit currently being applied and move on. This is only right when that commit's change is already on main (a teammate merged the same fix). If you use it to "get past" a conflict, your commit is gone from the rebased branch.

A long rebase stops once per conflicting commit, so you may resolve several times. If you keep resolving the same conflict, enable rerere as described in Rebase, Merge and Squash, or consider squashing your own commits first so there is only one to replay.

Put it in order6 steps

A rebase stopped on a conflict in two files. Order the steps to finish it safely.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Tools that make it easier

  • VS Code shows conflict regions with "Accept Current", "Accept Incoming" and "Accept Both" buttons, and a Resolve in Merge Editor button that opens a three-pane view: incoming, current and the result you are writing, with the base available. The labels follow Git's ours and theirs, so "Current" is main's side during a rebase.
  • git mergetool opens each conflicted file in a configured tool. git mergetool --tool-help lists the ones Git knows about (VS Code is vscode); set one with git config --global merge.tool vscode.
  • JetBrains IDEs have a similar three-pane resolver with a "magic wand" that applies all non-conflicting changes.

Use the buttons for speed, but read the result. "Accept Both" on two versions of the same function gives you a duplicate definition, which in some languages is not even an error.

The special cases

Some files should not be resolved by hand.

Lockfiles (package-lock.json, pnpm-lock.yaml, uv.lock, poetry.lock) are generated. Hand-merging them produces something that looks valid and installs the wrong versions. Resolve the manifest (package.json, pyproject.toml) by hand first, then take main's lockfile and regenerate, so your new dependency is added on top of main's:

# during a rebase, main's version is --oursgit checkout --ours package-lock.jsonnpm install                  # or: uv lock, pnpm install, poetry lockgit add package-lock.json

Generated files in general (compiled CSS, API clients generated from an OpenAPI spec, snapshot files): resolve the source and rerun the generator. Never edit the output.

Database migrations conflict without a text conflict. If you and a teammate each added an Alembic migration whose down_revision is the same parent, Git merges both files cleanly but Alembic now has two heads, and alembic upgrade head fails. Check with alembic heads. Either create a merge revision with alembic merge -m "merge heads" heads, or, if your migration has not run anywhere shared yet, change its down_revision to point at your teammate's migration so the chain stays linear. Django and Rails have the same problem with their own commands.

Binary files (images, PDFs, spreadsheets) cannot be merged: Git prints warning: Cannot merge binary files and you pick one side whole with --ours or --theirs, or ask the designer for a combined file.

Delete versus modify: decide whether the file should exist. If main deleted it on purpose (it moved, or the feature was removed), your edit probably belongs somewhere else. git rm the file to accept the deletion, or git add it to keep it, then port your change.

Match the pairs0/5 matched

Match each conflict to the right way to resolve it.

Choose an item, then its match on the other side.

Semantic conflicts: clean merge, broken code

The most dangerous conflict is the one Git never reports. You rename a function and update every caller. A teammate, at the same time, adds a new call to the old name. The changes touch different lines, so the merge is clean, and the result does not work:

Python
base = '''def total_cents(items): return sum(i["price"] for i in items)''' # Branch 1 renames the function and updates every caller it knows about.branch_rename = base.replace("total_cents", "order_total_cents") # Branch 2, written at the same time, adds a new caller of the old name.branch_new_caller = base + '''def receipt(items): return f"Total: {total_cents(items)} cents"''' # The two branches touched different lines, so Git merges them cleanly:merged = branch_rename + branch_new_caller[len(base):]print(merged) scope = {}exec(merged, scope)try: print(scope["receipt"]([{"price": 250}, {"price": 100}]))except NameError as err: print("Clean merge, broken code:", err)
Output
Press Run (⌘ Enter) to see what happens.

In a typed language the compiler catches this one. It will not catch a changed default, a new required config key, a function that now returns cents instead of pounds, or two migrations that each assume they run first. Your defences are:

  • Run the tests after every resolution, and after a clean merge or rebase too.
  • CI on the merge result, not just your branch. GitHub's pull request checks run against a merge of your branch into the target, and "require branches to be up to date" plus a merge queue (from Branching Strategies Teams Use) make sure the exact combination that lands on main was tested.
  • Read what changed on main before you start: git fetch then git log --oneline HEAD..origin/main -- path/ lists the new commits on main that touched the files you changed.
Quick check
Your rebase onto main finished with no conflicts, and your branch's own tests passed yesterday. What should you do before pushing?
Need a nudge? A hint rules out a wrong answer.

Having fewer conflicts

You cannot avoid conflicts, but you can keep them small and rare:

  • Small, short-lived PRs. Branching Strategies Teams Use showed how overlap grows with the days a branch stays open.
  • Integrate often. Rebase onto or merge main daily on a long branch, so you resolve one small conflict at a time instead of ten at the end.
  • Shared formatters (Prettier, Ruff, Black) run on every commit, so nobody's editor reflows a file and turns a one-line change into a 300-line diff.
  • Separate moves from edits. Move or rename a file in one PR and change it in the next, so rename detection keeps working for everyone.
  • Talk. If you are about to refactor a hot file, say so in the team channel. A two-minute message prevents a two-hour conflict.
Key terms
three-way merge
Merging by comparing both sides with their common base, so one-sided changes apply automatically.
merge base
The most recent commit both sides share; the base version in a three-way merge.
zdiff3
A conflict style that shows the base version between the two sides, trimming lines both sides share.
ours / theirs
The version at HEAD and the version being brought in. In a rebase, ours is the branch you rebase onto.
modify/delete conflict
One side edited a file that the other side deleted; you decide whether it should exist.
semantic conflict
Changes that merge without any text conflict but break behaviour when combined.
multiple heads
Two migrations with the same parent after a merge, so the migration tool cannot pick a single latest revision.