Lesson 4 of 6 in this module

4/13 in track

Merge conflicts

python14 min

Overview

Two people edited the same lines of ingest.py. git pull brings their commit in and stops. You edit the markers out, git add, then git commit.

On this page8 sections

The broken result

You run git pull to get your teammate's latest work. Git prints a few lines and stops halfway.

ShellGit refuses to guess (shown for reading, not run here)
$ git pull
Auto-merging ingest.py
CONFLICT (content): Merge conflict in ingest.py
Automatic merge failed; fix conflicts and then commit the result.

Open ingest.py and the file looks broken. Git has written both versions of the clashing lines into it, with marker lines around them.

Four words for this lesson.

WordWhat it means
ConflictTwo people changed the same lines in different ways, and Git cannot choose.
MergeJoining the changes of two branches into one.
MarkerThe special lines Git writes into the file to show the clash.
HEADThe commit you are standing on right now. In a conflict it labels your side.
A code file with three highlighted marker lines splitting 2 versions of the date_col line, with labels for start marker, divider and end marker
The file as Git leaves it. The red lines are Git's markers, not code.
  1. The line with seven < signs starts the clash. Below it is your version.
  2. The line of seven = signs divides the two versions.
  3. Below it is the version that came in from the other branch. The line with seven > signs ends the clash.

If you run the file like this, Python stops with a SyntaxError on the first marker.

Why this failure matters

You and your teammate both started from the same version, then each changed line 12 of ingest.py. You wanted the date column to be order_date. They wanted created_at.

Git can see that the two edits collide. It cannot know which one is right for your pipeline.

Commit A splits into commit B on their branch and commit C on your branch, which join again in a merge commit M
Two histories grow from one shared commit and meet in a merge commit.

A is the last commit you both had. B is their change and C is yours. M is the merge Git is trying to make. A conflict only happens at M, and only when B and C touched the same lines.

Git compares both sides with the shared starting point. Only the last row needs a person.

Line 12 at the startTheir branchYour branchWhat Git does
order_dateorder_dateorder_dateNobody changed it. Keep it.
order_datecreated_atorder_dateOnly they changed it. Take theirs.
order_datecreated_atorder_date_utcBoth changed it differently. Conflict.

So a conflict is not an error, and nobody did anything wrong. Git is asking a question it cannot answer.

The damage comes from answering badly. If you commit with the markers still in the file, the pipeline ships with <<<<<<< in the middle of the code and fails. If you keep only your side without reading theirs, you silently erase a teammate's work.

Watch outgit add . and git commit -a are traps here

They sweep up every file, including ones you have not opened. During a conflict, add only the file you fixed, after you have read it. Never commit while a marker is still in the file.

How to diagnose

Start with git status. During a conflict it lists the files that still need a decision.

ShellGit lists every disputed file (shown for reading, not run here)
$ git status
On branch main
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)
Unmerged paths:
  (use "git add <file>..." to mark resolution)
	both modified:   ingest.py

both modified means both branches changed the file. The git add hint matters: adding the file is how you tell Git you have dealt with it.

If you get lost, git merge --abort puts everything back the way it was before the pull. You can start again without damage.

You can also search for leftover markers yourself. On a real project that is the first command below.

ShellSearch the project for conflict markers (shown for reading, not run here)
$ grep -rn "<<<<<<<" .
./ingest.py:2:<<<<<<< HEAD

The Python below does the same on a list of lines. It counts how many conflicts are in a file by counting the lines that start with seven < signs.

PythonCount the conflicts in a file
conflicted = """def load(path):
<<<<<<< HEAD
    date_col = "order_date"
=======
    date_col = "created_at"
>>>>>>> origin/main
    return read(path, date_col)"""

def count_conflicts(lines):
    return sum(1 for line in lines if line.startswith("<<<<<<<"))

print(count_conflicts(conflicted.splitlines()))

How many conflicts do you expect? Look at the file above and count the blocks.

1

One block, so one conflict. When you have fixed the file properly, the count must be 0.

The fix

Fixing a conflict takes four moves. Each one sets up the next.

  1. git pulltheir work comes in, stops
  2. Edit the fileremove markers, decide
  1. git add ingest.pysay it is settled
  2. git commitrecord the merge

The four steps, and why the order matters.

StepWhy it sits hereWhat goes wrong if you swap it
git pullYou cannot merge what you have not fetched.Pushing first gets rejected, or overwrites their work.
Edit the fileGit needs one valid file to record.Keeping both sides blindly gives a syntax error.
git add ingest.pyMarks the conflict as settled.Committing first fails: Git says unmerged paths remain.
git commitRecords the merge.Committing with a marker left in records a broken file.

Here is the edit. First, the file with markers.

PythonBefore: markers in the file
def load(path):
<<<<<<< HEAD
    date_col = "order_date"
=======
    date_col = "created_at"
>>>>>>> origin/main
    return read(path, date_col)

After the edit, one version is kept and every marker line is gone.

PythonAfter: one line kept, markers gone
def load(path):
    date_col = "created_at"
    return read(path, date_col)
Watch outNot every conflict is yours to decide

Here the two sides disagree about which date column to read. That is a question about the business, not about typing. If you pick wrong, the daily orders report counts the wrong day. Ask the teammate.

Sometimes you need both sides. If you changed one filter line and your teammate added another next to it, delete only the three marker lines and keep both. Then check that the result still makes sense.

When the file is right, tell Git and record the merge:

ShellSettle it, then record the merge (shown for reading, not run here)
$ git add ingest.py
$ git commit -m "merge main: read created_at for order dates"
[main 8d41b07] merge main: read created_at for order dates
RememberBefore you commit

Run git status, then search for <<<<<<<. If either one still points at the file, you are not done.

Conflicts happen to everyone. They are rarer if you pull often, commit small changes, and do not let two people sit on the same file for a week.

When a reviewer writes "please fix conflicts", it means these four steps. It never means pushing over your teammate's commit with --force.

Going further: merge or rebase?

There are two ways to bring branches together. A merge makes one extra commit that joins both histories. A rebase takes your commits and replays them on top of the latest main, giving one straight line of history.

ShellReplay your branch on top of main (shown for reading, not run here)
$ git switch feature/order-metrics
$ git fetch origin
$ git rebase origin/main

If a rebase hits a conflict, you fix the file, run git add, then git rebase --continue. The safe rule: only rebase your own private branch. Never rebase commits other people have already pulled.

Before you open a pull request, git rebase -i HEAD~4 lets you tidy up messy commits such as wip or fix typo. For each commit you choose what to do:

  • pick: keep it as it is.
  • squash: merge it into the commit before it, and join the messages.
  • fixup: merge it into the commit before it, and drop its message.
  • reword: keep it, but change its message.
  • drop: throw it away.

Common beginner questions

Why does Git not just pick the newer change?

Newer does not mean right. Both edits might be needed, or one might break the other. Git compares text, not meaning, so it hands the decision to you.

What if I make it worse halfway through?

Before you commit, run git merge --abort. It returns your branch to how it was before the pull. After you have committed, git revert can cancel the merge with a new commit.

Can I avoid conflicts completely?

No, but you can make them rarer. Pull before you start, commit small changes, and split big files so people rarely edit the same lines.

The pull that stopped halfway
  1. git pull brings in a teammate's work and stops with a CONFLICT in ingest.py.

    1. git pull
    2. CONFLICT
  2. Both branches changed line 12 in different ways. Git cannot know which one is right.

    1. same line
    2. two answers
  3. Git writes both versions into the file between the marker lines, so the file is no longer valid code.

    1. markers
    2. broken file
  4. git status lists the file as both modified. Searching for the seven-sign marker finds any that are left.

    1. git status
    2. search markers
  5. Edit the file until it is normal code, then git add, then git commit.

    1. edit
    2. add
    3. commit
  6. Committing too early records the markers as code. If you get lost, git merge --abort starts you over.

    1. order matters
    2. merge --abort

What comes next

You can now save your work and join it with someone else's. Next we go from Git to the command line itself: how the shell finds a program, how to chain commands, and what an exit code tells a script.

Practice

You are given a file as a list of lines, with conflict markers in it.

Write count_conflicts(lines) to count how many conflicts you must resolve. Store the number in result and print it.

Going further: reading a conflict, backing out, and choosing a side

A conflict is git saying 'both of you changed the same lines and I will not guess'. It is not an error in your work. You can look at it, back out of the merge completely, or pick one side. Predict what the file looks like in the middle of a conflict.

ShellCreate a conflict, abort, then resolve it (illustration, not run here)
git init -q
printf 'timeout=10\nretries=3\n' > config.txt && git add config.txt && git commit -qm "base"
git switch -q -c feature
printf 'timeout=60\nretries=3\n' > config.txt && git commit -qam "feature: timeout 60"
git switch -q main
printf 'timeout=30\nretries=3\n' > config.txt && git commit -qam "main: timeout 30"
git merge feature 2>&1 | tail -2
cat config.txt
git merge --abort
git status --short
echo "-- after abort: $(head -1 config.txt)"
git merge -q feature 2>&1 | tail -1
git checkout --theirs config.txt
git add config.txt
git commit -qm "merge feature, keep timeout 60"
cat config.txt
CONFLICT (content): Merge conflict in config.txt
Automatic merge failed; fix conflicts and then commit the result.
<<<<<<< HEAD
timeout=30
=======
timeout=60
>>>>>>> feature
retries=3
-- after abort: timeout=30
Automatic merge failed; fix conflicts and then commit the result.
Updated 1 path from the index
timeout=60
retries=3

Between <<<<<<< and ======= is our side (main, timeout=30). Between ======= and >>>>>>> is the incoming side (feature, timeout=60). The line retries=3 was changed by neither, so it is outside the markers. git merge --abort put everything back, and the status is clean.

The second attempt was resolved by taking the incoming side with --theirs, then git add and commit finished the merge.

OptionMeansCareful
--oursThe branch you are onIn a rebase the meaning flips, so check which side is which
--theirsThe branch you are merging inSame warning
Edit the file by handKeep parts of bothRemove every marker line, then run the tests
git merge --abortForget the merge attemptSafe: you lose nothing that was committed

Two practical rules. Always run the tests after resolving, because a file can merge cleanly and still be wrong. And for generated files such as lock files, do not edit the markers by hand: take one side, then regenerate the file with the tool that owns it.

Try a new scenario

You and a teammate both changed the same SQL file. After you resolve the conflict, the file looks fine but the query returns different numbers. What happened and what do you do?

Work it out, then open the answer

A conflict resolution is a code change nobody reviewed. You may have kept your filter and their column rename but lost one dependent change. Re-run the query and compare it with the result on main and on the teammate's branch, and ask the teammate to look at the resolved file. Resolving the markers is not the same as being correct.

Why do conflicts happen?

Git can combine changes automatically when they touch different lines. When two branches change the same lines differently, it cannot tell which is right, so it stops and asks you.

Close the lesson and explain it

Without scrolling up, explain how to read the markers in a conflict and how to back out of a merge.

Practicals · load into the editor

After you read the theory, run these in the pane on the right. They execute in this tab, no cluster.

Finished this lesson?

Mark it as read when you could explain it to someone else.

Rate:
Was this useful?