Chapter 2 · Git and GitHub
Branches, Merging and Merge Conflicts
- Page 8 of 22
- 17 min read
So far every commit went straight onto main. That works until you want to try something risky (a new labelling rule, a different model, a prompt rewrite) while main keeps working, or until two people change the project at the same time. Branches solve both: each line of work gets its own branch, you commit there freely, and when it is good you merge it back.
In Git, branches are cheap and fast; professional teams create several a day. This page shows what a branch really is, the two kinds of merge, and how to resolve a merge conflict calmly when two branches changed the same line.
What you will learn
- What a branch is (a movable pointer to a commit) and what
HEADis. - Creating, listing and switching branches with
git switch -c,git branchandgit switch. - Fast-forward merges and three-way merges, and how to read them in
git log --graph. - Creating a real merge conflict, reading the conflict markers and resolving it.
- Deleting branches safely with
git branch -d, and throwing away experiments with-D.
Set up the example project
The review analyser once more, with one commit on main:
mkdir -p ~/projects/review-analyser
cd ~/projects/review-analyser
git init -q
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love"}
NEGATIVE = {"bad", "slow", "broken", "late"}
EOF
cat > analyse.py <<'EOF'
"""Label product reviews as positive, negative or neutral."""
import csv
from words import NEGATIVE, POSITIVE
def label(text):
words = text.lower().split()
score = sum(w in POSITIVE for w in words) - sum(w in NEGATIVE for w in words)
return "positive" if score > 0 else "negative" if score < 0 else "neutral"
if __name__ == "__main__":
with open("reviews.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(label(row["text"]), "|", row["text"])
EOF
cat > reviews.csv <<'EOF'
id,text
1,great phone and fast delivery
2,battery is bad and the box was broken
3,it works
EOF
git add .
git commit -q -m "Add keyword review analyser"
git log --oneline7f5e38e Add keyword review analyserWhat a branch really is
A branch is not a copy of your files. It is a name that points at one commit, stored in a tiny file inside .git. When you commit on a branch, Git creates the new commit and moves the branch name forward to it. HEAD is Git's "you are here" marker: it points at the branch you are on.
git branch
git log --oneline --decorate
git rev-parse main* main
7f5e38e (HEAD -> main) Add keyword review analyser
7f5e38e11b46dd79dfd7f805148d947b79a782a8git branch lists branches and stars the current one. (HEAD -> main) says "HEAD is on main, and main points here". git rev-parse shows the full hash the name points to: that is all a branch is. Creating one costs a 41-byte file (with Git's default storage), which is why you should never hesitate to make one.
Creating and switching branches
Nadia wants to add more sample reviews without touching main until she is happy. git switch -c NAME creates a branch at the current commit and switches to it:
git switch -c feature/more-reviews
cat >> reviews.csv <<'EOF'
4,not good at all
5,love the camera
EOF
git commit -q -am "Add two more sample reviews"
git log --oneline --graph --all --decorateSwitched to a new branch 'feature/more-reviews'
* 331faf2 (HEAD -> feature/more-reviews) Add two more sample reviews
* 7f5e38e (main) Add keyword review analyser--all shows every branch, not just the current one, and --decorate labels commits with the branch names that point at them (in a terminal Git usually does this even without the option). feature/more-reviews has moved one commit ahead; main still points at the first commit. Switching branches changes the files in your folder to match the branch's commit:
git switch main
wc -l reviews.csv
git switch feature/more-reviews
wc -l reviews.csvSwitched to branch 'main'
4 reviews.csv
Switched to branch 'feature/more-reviews'
6 reviews.csvSame folder, same file name, different content: Git rewrote reviews.csv each time you switched. (A slash in a branch name is just a naming convention; feature/…, fix/… and exp/… keep a long branch list readable.)
Fast-forward merge
The new reviews are fine, so they go into main. You always merge into the branch you are on: switch to the receiving branch, then name the branch to bring in.
git switch main
git merge feature/more-reviewsSwitched to branch 'main'
Updating 7f5e38e..331faf2
Fast-forward
reviews.csv | 2 ++
1 file changed, 2 insertions(+)Fast-forward means main had no new commits of its own since the branch started, so Git did not need to combine anything: it just slid the main pointer forward to the branch's commit. No new commit was created.
before: A <- main
\
B <- feature/more-reviews
after: A --- B <- main, feature/more-reviewsRun the analyser on the new data and you find a real bug:
python analyse.pypositive | great phone and fast delivery
negative | battery is bad and the box was broken
neutral | it works
positive | not good at all
positive | love the camera"not good at all" is labelled positive, because the analyser only counts words and ignores the "not". That is the next branch's job.
Three-way merge
Nadia starts a branch for negation handling and rewrites label() so that a word right after "not" counts the opposite way:
git switch -c feature/negation
cat > analyse.py <<'EOF'
"""Label product reviews as positive, negative or neutral."""
import csv
from words import NEGATIVE, POSITIVE
def label(text):
words = text.lower().split()
score = 0
for i, w in enumerate(words):
sign = -1 if i > 0 and words[i - 1] == "not" else 1
score += sign * ((w in POSITIVE) - (w in NEGATIVE))
return "positive" if score > 0 else "negative" if score < 0 else "neutral"
if __name__ == "__main__":
with open("reviews.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(label(row["text"]), "|", row["text"])
EOF
git commit -q -am "Handle negation: not good is negative"Meanwhile main moves on too: a README is added there (in a team, this would be a colleague's work merged while you were busy):
git switch main
echo "# Review analyser" > README.md
git add README.md
git commit -q -m "Add README"
git log --oneline --graph --all --decorateSwitched to branch 'main'
* 5fdf51b (feature/negation) Handle negation: not good is negative
| * b6e78ff (HEAD -> main) Add README
|/
* 331faf2 (feature/more-reviews) Add two more sample reviews
* 7f5e38e Add keyword review analyserThe history has diverged: both branches have a commit the other lacks. A fast-forward is impossible, so Git does a three-way merge: it compares both branch tips with their common ancestor (the "merge base", here the "Add two more sample reviews" commit), combines the changes, and records the result in a new merge commit that has two parents.
git merge --no-edit feature/negationMerge made by the 'ort' strategy.
analyse.py | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)ort is the name of Git's default merge strategy. Without --no-edit, Git opens your editor with the message Merge branch 'feature/negation'; save and close it to finish the merge. Now look at the graph and the result:
git log --oneline --graph --all --decorate
python analyse.py* a67180e (HEAD -> main) Merge branch 'feature/negation'
|\
| * 5fdf51b (feature/negation) Handle negation: not good is negative
* | b6e78ff Add README
|/
* 331faf2 (feature/more-reviews) Add two more sample reviews
* 7f5e38e Add keyword review analyser
positive | great phone and fast delivery
negative | battery is bad and the box was broken
neutral | it works
negative | not good at all
positive | love the cameraThe two lines of work join at the merge commit, main has both the README and the negation fix, and "not good at all" is negative. In the graph, * is a commit, and |, \ and / connect commits to their parents.
C <- feature/negation C
/ / \
A --- B A --- B M <- main
\ \ /
D <- main DTeams sometimes want a merge commit even when a fast-forward is possible, so that the history shows where a feature began and ended. git merge --no-ff BRANCH does that; GitHub's default "Merge pull request" button behaves the same way, as you will see on the pull-request page.
Cleaning up merged branches
Once a branch is merged, its commits are part of main and the name is no longer needed. git branch --merged lists the branches whose commits are all in the current branch; git branch -d deletes them:
git branch --merged
git branch -d feature/more-reviews feature/negation
git branch feature/more-reviews
feature/negation
* main
Deleted branch feature/more-reviews (was 331faf2).
Deleted branch feature/negation (was 5fdf51b).
* mainDeleting a branch deletes only the name; the commits stay in main's history. -d is the safe form: it refuses to delete a branch whose commits are not merged anywhere, and tells you to use -D if you really mean it. That is exactly what you want for a failed experiment:
git switch -q -c exp/remove-stopwords
echo "STOPWORDS = {\"the\", \"and\", \"is\"}" >> words.py
git commit -q -am "Experiment: stopword list"
git switch -q main
git branch -D exp/remove-stopwordsDeleted branch exp/remove-stopwords (was 937aec5).(-q keeps git switch quiet.) The experiment's commit is no longer on any branch; for a few weeks the reflog from the previous page could still find it.
Merge conflicts
Git merges changes to different lines, or different files, automatically. When both branches changed the same line in different ways, Git cannot know which version is right, so it stops and asks you. That is a merge conflict. It is normal, not an error, and fixing it takes a minute once you can read the markers.
Let's make one. On a branch, Nadia adds "excellent" to the positive words. On main, a teammate adds "perfect" to the same line:
git switch -c feature/more-positive
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late"}
EOF
git commit -q -am "Add excellent to positive words"
git switch main
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect"}
NEGATIVE = {"bad", "slow", "broken", "late"}
EOF
git commit -q -am "Add perfect to positive words"Switching with uncommitted changes
Before merging, one thing to know about git switch. Uncommitted edits travel with you when you switch, as long as the other branch has the same version of that file. If switching would overwrite them, Git refuses rather than lose your work:
echo "# TODO: more words" >> words.py
git switch feature/more-positiveerror: Your local changes to the following files would be overwritten by checkout:
words.py
Please commit your changes or stash them before you switch branches.
AbortingCommit the edit, or discard it as here with git restore (or put it aside with git stash, covered in the advanced tutorial):
git restore words.pyThe conflict
git merge feature/more-positiveAuto-merging words.py
CONFLICT (content): Merge conflict in words.py
Automatic merge failed; fix conflicts and then commit the result.The merge stopped halfway. git status tells you where you are and what to do:
git statusOn 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: words.py
no changes added to commit (use "git add" and/or "git commit -a")Git has written both versions into the file, between conflict markers:
cat words.py<<<<<<< HEAD
POSITIVE = {"good", "great", "fast", "love", "perfect"}
=======
POSITIVE = {"good", "great", "fast", "love", "excellent"}
>>>>>>> feature/more-positive
NEGATIVE = {"bad", "slow", "broken", "late"}| Marker | Meaning |
|---|---|
<<<<<<< HEAD | Start of your side: the branch you are on and merging into (main) |
======= | Divider between the two sides |
>>>>>>> feature/more-positive | End of their side: the branch being merged in |
Only the conflicting lines are marked; the NEGATIVE line, which neither side changed, is left as it was. To resolve, edit the file so it says what the project should say, and delete all three marker lines. Here both words are wanted. In your editor, make words.py look like this (we write it with cat so you can copy the step):
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late"}
EOF
grep -c '<<<<<<<\|>>>>>>>' words.py
python -c "import words; print(sorted(words.POSITIVE))"0
['excellent', 'fast', 'good', 'great', 'love', 'perfect']No markers left (count 0) and the file is valid Python again. Always run the code or the tests after resolving: a resolution can be free of markers and still wrong. Then mark the file as resolved by staging it, and finish the merge with a commit:
git add words.py
git commit --no-edit
git log --oneline --graph --decorate -5[main 9e4c744] Merge branch 'feature/more-positive'
* 9e4c744 (HEAD -> main) Merge branch 'feature/more-positive'
|\
| * 5290990 (feature/more-positive) Add excellent to positive words
* | 95e91ff Add perfect to positive words
|/
* a67180e Merge branch 'feature/negation'
|\
| * 5fdf51b Handle negation: not good is negativeEditors help a lot here. VS Code, PyCharm and others highlight conflicts and offer buttons such as Accept Current Change (your side, HEAD), Accept Incoming Change (their side) and Accept Both Changes; you still check the result. If a merge goes wrong and you want to start over, git merge --abort puts everything back exactly as it was before git merge.
Keeping conflicts small
- Merge
maininto long-lived branches often (or keep branches short-lived), so they never drift far apart. - Keep commits and branches focused on one thing; a branch that reformats every file will conflict with everyone.
- Agree on a formatter (for Python, Ruff or Black) so that whitespace and quote styles never cause conflicts.
- Notebooks (
.ipynb) are JSON with outputs embedded and conflict badly; keep logic in.pyfiles and clear outputs before committing notebooks.
Where this shows up in real AI work
- Experiment branches:
exp/bigger-context,exp/new-prompt-v3: try an idea without breakingmain, merge it if the evaluation improves, delete it with-Dif not. - Feature branches and pull requests: nearly every team works on short-lived branches and merges them into
mainthrough a pull request (two pages from now), somainis always deployable. - Hotfixes: when the deployed model API breaks, a
fix/…branch frommaincarries the small fix while bigger features stay in progress on their own branches. - Prompt and config files are a common conflict spot in LLM apps because everyone tunes them. Small, focused changes and frequent merges keep conflicts rare.
Common mistakes
- Merging in the wrong direction.
git merge mainwhile on the feature branch bringsmaininto the feature, not the other way. Fix:git switch mainfirst, thengit merge feature/…; check withgit branchwhich branch has the star. - Committing a file that still contains conflict markers. The code breaks for everyone. Fix: search for
<<<<<<<beforegit add, and run the program or tests. - Resolving by deleting the other side without reading it. You silently undo a teammate's work. Fix: understand both changes; often the right answer combines them, as here.
- Working for weeks on one branch. The further it drifts from
main, the bigger and harder the final merge. Fix: small branches, merged within days; mergemainin regularly. - Using
-Dby habit. It deletes unmerged work without asking. Fix: use-d; reach for-Donly for experiments you have decided to throw away.
Try it yourself
Continue in the same repository, in order.
- Easy: Create a branch
fix/readme, add a lineLabels reviews as positive, negative or neutral.toREADME.md, commit, then merge it intomain. Which kind of merge happens, and why? Delete the branch. - Medium: Create two branches from
main:feature/neg-wordsadds"terrible"toNEGATIVE, andfeature/sampleappends a review6,terrible batterytoreviews.csv. Merge both intomain(the second merge needs a merge commit) and show the graph. - Hard: Create a conflict on purpose: a branch
feature/strong-negchanges theNEGATIVEline to add"awful", whilemainadds"poor"to the same line. Merge, resolve so both words are kept, check that no markers remain, and finish the merge.
Answers
# Easy
git switch -c fix/readme
echo "Labels reviews as positive, negative or neutral." >> README.md
git commit -q -am "Describe the project in the README"
git switch main
git merge fix/readme
git branch -d fix/readmeSwitched to a new branch 'fix/readme'
Switched to branch 'main'
Updating 9e4c744..74fad10
Fast-forward
README.md | 1 +
1 file changed, 1 insertion(+)
Deleted branch fix/readme (was 74fad10).A fast-forward: main had no new commits since the branch was created, so Git only moved the pointer.
# Medium
git switch -q -c feature/neg-words
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late", "terrible"}
EOF
git commit -q -am "Add terrible to negative words"
git switch -q main
git switch -q -c feature/sample
echo "6,terrible battery" >> reviews.csv
git commit -q -am "Add a terrible battery review"
git switch -q main
git merge -q feature/neg-words
git merge -q --no-edit feature/sample
git log --oneline --graph --decorate -4
python analyse.py | tail -n 1* 11e6553 (HEAD -> main) Merge branch 'feature/sample'
|\
| * bb5b471 (feature/sample) Add a terrible battery review
* | 468c878 (feature/neg-words) Add terrible to negative words
|/
* 74fad10 Describe the project in the README
negative | terrible batteryThe first merge was a fast-forward; the second needed a merge commit, because by then main had moved past the point where feature/sample started.
# Hard
git switch -q -c feature/strong-neg
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late", "terrible", "awful"}
EOF
git commit -q -am "Add awful to negative words"
git switch -q main
cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late", "terrible", "poor"}
EOF
git commit -q -am "Add poor to negative words"
git merge feature/strong-negAuto-merging words.py
CONFLICT (content): Merge conflict in words.py
Automatic merge failed; fix conflicts and then commit the result.cat > words.py <<'EOF'
POSITIVE = {"good", "great", "fast", "love", "perfect", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late", "terrible", "poor", "awful"}
EOF
grep -c '<<<<<<<' words.py
git add words.py
git commit -q --no-edit
git branch -d feature/strong-neg feature/neg-words feature/sample feature/more-positive
git log --oneline -10
Deleted branch feature/strong-neg (was c9e3323).
Deleted branch feature/neg-words (was 468c878).
Deleted branch feature/sample (was bb5b471).
Deleted branch feature/more-positive (was 5290990).
0b814d7 Merge branch 'feature/strong-neg'Summary
- A branch is a movable name for a commit;
HEADmarks the branch you are on. Branches are cheap: use one for every feature, fix and experiment. git switch -c NAMEcreates and switches;git switch NAMEswitches;git branchlists;git log --oneline --graph --allshows the picture.- Merge into the branch you are on. If it has not moved, the merge is a fast-forward; if both sides have new commits, Git makes a three-way merge commit with two parents.
- A conflict means both sides changed the same lines. Edit the file to the right result, remove the markers, run the code,
git add,git commit; orgit merge --abortto start over. git branch -ddeletes merged branches safely;-Dforce-deletes unmerged experiments.
Next: GitHub: Remotes, push, pull and clone. Your branches and commits are still only on your laptop. Next you will connect the repository to a remote, push it, clone it somewhere else, and keep two copies in sync.

