Computing Foundations › Git and GitHub › Day 31
Day 31: Branching and Merging
After this lesson you will be able to create and switch branches, merge them, resolve a merge conflict calmly, and explain when to merge versus rebase — the everyday loop for working on anything in parallel without breaking the version that works.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-031-branching-and-merging
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/computing-foundations/day-031-branching-and-merging - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Explain what a branch is — a movable pointer to a commit — and why creating one in Git costs almost nothing
- Create and switch between branches with git branch and git switch (and the classic git checkout equivalents)
- Distinguish a fast-forward merge from a three-way merge and identify which occurred from the history graph
- Produce, read, and resolve a merge conflict: interpret the <<<<<<< / ======= / >>>>>>> markers, edit the file, and complete the merge with git add and git commit
- Explain rebasing at an intuitive level, compare it with merging, and state the golden rule of never rebasing shared history
- Apply branch hygiene — short, focused, short-lived branches deleted after merging — and read branch history with git log --graph
Prerequisites
- Day 30 (Git Fundamentals): comfortable with git init, git add, git commit, and git log
- A terminal with git installed (git --version prints a version)
Why this matters
-
Branching is what makes experiments safe. An abandoned idea costs nothing and leaves the main line untouched.
-
Every AI project runs parallel experiments, and a branch per experiment is the simplest way to keep them apart.
-
Merge conflicts are not errors. They are Git refusing to guess, and knowing that removes most of the fear.
-
The rebase rule has real consequences for other people, and it is the one Git rule worth memorising verbatim.
-
Cheap branching changed how software is written, because it made trying things free.
The idea in plain language
-
A branch is a pointer to a commit, and nothing more. Creating one is instant because it writes a single line.
-
HEAD marks which branch you are on. Committing moves the branch pointer and HEAD forward together.
-
Switching branches re-aims HEAD and refreshes your working files. Nothing else moves.
-
Merging combines two lines, usually automatically, sometimes with a question for you.
-
A conflict means both sides changed the same lines differently, and Git will not pick a winner.
Historical background
-
Branching was expensive before Git, because centralised systems copied whole directory trees on the server.
-
So branches were rare and heavyweight — used for releases, not for a day’s work.
-
Git made a branch a pointer, which is why creating one is instantaneous and why the whole culture of software changed around it.
-
The pull-request workflow followed, and is entirely built on branches being cheap enough to make casually.
-
git switchandgit restorearrived in 2019 to split upcheckout, which had accumulated too many unrelated jobs. -
The old spellings still work, and you will see both in every tutorial you read.
What it is — and what it is not
A branch is:
- A movable pointer to one commit in the graph.
- Cheap to create, cheap to abandon.
- The unit of parallel work, and of review.
It is not:
-
Not a copy of your files. Nothing is duplicated; only a pointer is written.
-
Not a folder. Switching branches changes the files in place, in the same directory.
-
Not permanent. Deleting a merged branch loses nothing; the commits live on in the history.
-
Not isolated from your working directory. Uncommitted changes come with you when you switch, which surprises people once.
Why it was created and what problems it solves
-
Isolation. Work in progress does not disturb the main line, so main stays releasable.
-
Parallelism. Several people, or several ideas, can proceed at once.
-
Reviewability. A branch is a coherent unit someone else can read and comment on.
-
Safe experimentation. Abandoning a branch costs nothing, which is what makes trying things cheap.
-
Deliberate integration. Merging is a decision you make at a moment you choose, rather than a continuous scramble.
How it works
The model
-
Every commit points to its parent, so history is a graph.
-
A branch is a pointer to one commit in that graph; HEAD marks which branch you are on.
-
Committing creates a commit whose parent is the current one, then slides the branch pointer and HEAD forward. Nothing else moves.
-
Read the diagram left to right. The dark line is
main(C1, C2, C3). At C2 afeaturebranch was created and given two commits (F1, F2) without disturbing main. -
M is the merge commit — a commit with two parents, C3 and F2. That two-parent commit is the visible signature of a merge.
Creating and switching
| Task | Modern | Classic |
|---|---|---|
| List branches | git branch | git branch |
| Create, stay put | git branch feature-x | git branch feature-x |
| Create and move onto it | git switch -c feature-x | git checkout -b feature-x |
| Move to an existing branch | git switch feature-x | git checkout feature-x |
| Merge into the current branch | git merge feature-x | git merge feature-x |
| Delete a merged branch | git branch -d feature-x | git branch -d feature-x |
- Prefer
switchfor new habits. It exists precisely becausecheckoutdid too many unrelated jobs.
Fast-forward and three-way merges
-
Git first finds the merge base — the most recent commit both branches share.
-
If the target has not advanced since the split, there is nothing to combine. Git slides the pointer forward: a fast-forward, with no merge commit, and the history stays a straight line.
-
If both branches advanced, Git performs a three-way merge: the merge base plus the two branch tips, working out what each side changed relative to the base.
-
Most of the time this is automatic and silent.
Conflicts
- A conflict arises only when both sides changed the same lines differently.
- Git combines edits to different parts of a file with no trouble at all.
<<<<<<< HEAD
milk: 1 cup buttermilk
=======
milk: 2 cups
>>>>>>> feature
-
Read it as three parts. Between
<<<<<<<and=======is your current branch (“ours”). Between=======and>>>>>>>is the incoming branch (“theirs”). -
To resolve it, edit the file to read how you want — keep one side, the other, or blend them — and delete all three marker lines.
-
It is resolved only when no markers remain.
-
Then
git addthe file (telling Git it is handled) andgit commit. That commit is the merge commit. -
git merge --abortbacks out entirely, returning everything to the state before you started.
Rebase, and the one rule
-
A rebase replays your commits on top of another branch, one at a time, as if you had started from its latest commit all along.
-
The result is linear — no merge commit, and a tidy sequence.
-
It does not preserve the original commits. It creates new ones with the same changes and different identities, rewriting that slice of history.
-
That rewriting is both the appeal and the danger.
-
The golden rule: never rebase commits you have already shared. Rebase your private work to tidy it; merge anything public.
-
If you rebase commits others have built on, you replace the commits they were working against, and your repositories disagree about what history is.
| Aspect | Merge | Rebase |
|---|---|---|
| What it does | Combines with a merge commit | Replays your commits elsewhere |
| History shape | Preserves the branch structure | Rewrites into a straight line |
| Merge commit? | Yes, for a three-way | No |
| Original commits kept? | Yes | No — new ones replace them |
| Safe on shared history? | Always | Never |
| Best for | Finished work; anything public | Tidying your own private branch |
Branch hygiene
-
Short, descriptive names.
fix-login-bug, notstuff. -
One task per branch, so it merges cleanly and reviews easily.
-
Keep it short-lived. The longer a branch lives, the further main drifts and the harder the merge.
-
Delete it once merged. Fifty stale branches is a desk buried in old drafts.
An everyday analogy
Two cooks adapting the same recipe.
| The kitchen | Branching |
|---|---|
| The original recipe card | main |
| Your copy, being adapted | A feature branch |
| Their copy, also being adapted | Another branch |
| Combining both sets of notes | A merge |
| Both changed the same ingredient | A conflict |
| Deciding which amount to use | Resolving it |
| Rewriting your notes as if you had started from theirs | A rebase |
-
Different sections combine effortlessly. Your change to the method and their change to the oven temperature do not collide.
-
The same line, changed twice, needs a person. No system should silently pick one cook’s buttermilk over the other’s.
-
Rewriting your notes is fine while they are yours. Do it after someone has copied them and their copy no longer matches anything.
Examples in practice
-
A fast-forward merge on a short branch nobody else touched — no merge commit, because none was needed.
-
A three-way merge producing a two-parent commit, which is what a diamond in the history graph is.
-
A conflict in a lock file, which is the most common conflict in practice and usually resolved by regenerating rather than editing.
-
A rebased branch that broke a colleague’s work, because it had already been pushed.
-
A branch six weeks old whose merge took longer than the original work.
Implications: security, privacy, performance, scalability, and cost
-
Security: a merge can silently reintroduce removed code, including a vulnerability someone deleted on another branch. Review the merged result, not only the diff of your own changes.
-
Resolving a conflict is a code change, made under time pressure and rarely reviewed. That is a real place bugs enter.
-
Performance: branching is free, because it writes one pointer. There is no reason to hesitate.
-
Merging is expensive in proportion to divergence. The cost is not in the command; it is in how far apart the branches drifted.
-
Cost: a long-lived branch is a debt accruing interest. Every day main advances, the eventual merge gets harder.
-
Cost of the rebase rule broken: hours of confusion for everyone downstream, and it is entirely avoidable.
Alternatives: free, open source, and commercial
| Approach | Type | Where it fits |
|---|---|---|
git merge | Free, built in | Combining finished work; anything already shared |
git rebase | Free, built in | Tidying your own private branch before sharing |
git rebase -i | Free, built in | Squashing and reordering your own commits |
git cherry-pick | Free, built in | Taking one commit from another branch |
| Trunk-based development | A practice | Very short branches, merged daily; avoids drift entirely |
Merge tools (meld, editor UIs) | Free | Three-way conflict resolution, side by side |
-
Configure a merge tool before you need one. Resolving a conflict in a three-pane view is far easier than reading markers in a plain file.
-
Trunk-based development is worth knowing about. Much of merge pain is a symptom of branches living too long, and the cure is merging more often rather than merging better.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Branch | A movable pointer to a commit |
| HEAD | Which branch, and therefore which commit, you are on |
| Merge base | The most recent common ancestor of two branches |
| Fast-forward | Sliding a pointer forward; no merge commit needed |
| Three-way merge | Combining two tips relative to their base |
| Conflict | Both sides changed the same lines differently |
| Rebase | Replaying commits elsewhere as new commits |
When to use it — and when not to
- Branch for anything you might abandon, which is most experiments.
- Branch per task, not per day and not per person.
- Merge main into your branch regularly while working, so the final merge is small.
- Rebase your own unshared commits to tidy them before opening them for review.
- Never rebase anything you have pushed and someone else may have.
- Do not let a branch live for weeks. If it must, merge main into it often.
- Do not resolve a conflict by taking one side blindly. Read both; the point of the pause is that a person must decide.
The AI connection
-
A branch per experiment keeps a promising direction and a failed one clearly separate, with commit hashes to cite for each.
-
Config changes belong on the branch with the code, so a result maps to one reproducible state.
-
Notebook conflicts are painful because the file format is JSON with embedded output — another argument for stripping outputs before committing.
-
Long-running training branches drift badly. Merge main in weekly, or the eventual integration costs more than the experiment did.
-
Abandoning a branch is a result too. “This did not work” is worth recording, and a deleted branch with a note in the log preserves that.
Knowledge check
quiz:
question: "A developer rebases a feature branch that they had pushed two days earlier, then force-pushes it. A colleague who had already based work on that branch is now in difficulty. Why?"
options:
- "Rebasing replaced the shared commits with new ones, so the colleague's work is based on commits that no longer exist upstream"
- "Force-pushing deleted the colleague's commits from the remote repository"
- "Rebasing removed the merge base, so no future merge between the branches is possible"
- "The colleague's local branch was automatically reset to match the rewritten history"
answer_index: 0
explanation: "A rebase does not move commits; it creates new ones with the same changes and different identities. The colleague's work still points at the originals, which are no longer on the branch upstream, so the two histories now disagree about what happened."
Hands-on exercise
Create a conflict deliberately and resolve it. Worked through fully in the Day 31 lab directory.
| What you are doing | Command |
|---|---|
| Create and move onto a branch | git switch -c feature-x |
| Commit there | edit, git add, git commit |
| Return to main and commit differently | git switch main, edit the same line, commit |
| Merge and hit the conflict | git merge feature-x |
| See the markers | open the file |
| Resolve and complete | edit, git add <file>, git commit |
| Read the shape | git log --oneline --graph --all |
| Tidy up | git branch -d feature-x |
Expected output
Auto-merging recipe.md
CONFLICT (content): Merge conflict in recipe.md
Automatic merge failed; fix conflicts and then commit the result.
* 9a3f1c2 Merge branch 'feature-x'
|\
| * 4b2e7d1 Use two cups of milk
* | 7c5a0f3 Use buttermilk
|/
* 1d0c8b4 Add recipe
- The
*with two lines below it is the merge commit — the two-parent shape. - The diverging and rejoining lines are the branch, drawn exactly as in the diagram.
Validate your work
-
You produced a fast-forward merge and a three-way merge, and can tell which was which from the log
-
You created a conflict deliberately and resolved it by editing
-
You removed all three marker lines before staging
-
You used
git merge --abortonce, to see that it works -
You deleted a merged branch
-
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
git commitrefuses after resolving. You did notgit addthe resolved file. -
Markers still in the committed file. You missed one. Search for
<<<<<<<before staging. -
git branch -drefuses. The branch is not merged. Check, then use-Donly if you genuinely mean to discard it. -
Switching branches complains about local changes. Commit them, or stash them — uncommitted work follows you across branches.
Common mistakes
- Resolving a conflict by keeping whichever side is longer.
- Committing the marker lines.
- Rebasing a branch that has been pushed.
- Letting a branch live long enough that main becomes unrecognisable.
Practice assignment
-
Create three branches from one starting point, make conflicting changes on each, and merge them one at a time, resolving as you go.
-
Produce a fast-forward and a three-way merge deliberately, and describe from the log alone which happened.
-
Rebase a private branch onto an advanced main, and compare the resulting history with the same work merged instead.
-
Configure a three-way merge tool and resolve one conflict with it rather than by editing markers.
Extension challenge
-
Recover from a bad merge. Complete a merge, decide it was wrong, and undo it — first with the merge still local, then after it has been committed. The two cases need different tools.
-
Use
git rebase -ito squash five messy commits into two coherent ones on a private branch, and read the resulting history. -
Simulate the rebase rule being broken with two clones of the same repository, and work out how you would recover.
-
Measure merge cost against divergence. Merge a one-day-old branch and a four-week-old one, and time the conflict resolution for each.
Quiz
Q1. In Git, what is a branch?
- A complete copy of every file in the project, stored in a new folder
- A permanent record that can never be deleted once created
- A backup of the repository kept on a separate server
- A movable pointer to a commit, naming the latest commit on a line of work
Show answer
Answer: D. A movable pointer to a commit, naming the latest commit on a line of work
A branch is just a small movable pointer to a commit — a few dozen bytes on disk — which is why creating one is instant and does not copy any files.
Q2. Which command creates a new branch AND moves you onto it in one step?
- git switch -c feature-x
- git merge feature-x
- git branch feature-x
- git log --graph feature-x
Show answer
Answer: A. git switch -c feature-x
git switch -c NAME creates the branch and switches to it. Plain git branch NAME creates the branch but leaves you where you are; the classic equivalent of switch -c is git checkout -b NAME.
Q3. When does Git perform a fast-forward merge instead of a three-way merge?
- Whenever the two branches changed the same lines
- The target has not advanced, so its pointer can slide forward
- Only when you explicitly pass the --no-ff option
- When the branch being merged has more commits than the target
Show answer
Answer: B. The target has not advanced, so its pointer can slide forward
If the target branch has not moved since the split, there is nothing to combine and Git just slides its pointer forward — a fast-forward, with no merge commit. A three-way merge happens when both branches advanced.
Q4. A merge conflict occurs when:
- You forget to write a commit message
- A branch has been left un-deleted for too long
- Two branches changed the same lines differently
- Two branches have the same name
Show answer
Answer: C. Two branches changed the same lines differently
Git combines non-overlapping changes automatically. It only stops and asks for a conflict resolution when both sides changed the same lines differently — it refuses to guess which version you meant.
Q5. In a conflict block, which part is the version from your current branch (HEAD)?
- The text below ======= and above >>>>>>>
- None of it — HEAD is never shown in a conflict
- The ======= line itself
- The text between <<<<<<< HEAD and =======
Show answer
Answer: D. The text between <<<<<<< HEAD and =======
The region between <<<<<<< HEAD and ======= is "ours" — the version on your current branch. The region between ======= and >>>>>>> is "theirs", from the branch being merged.
Q6. What must be true of a file before you commit it to resolve a conflict?
- No conflict markers may remain, and you must git add the file
- It must contain all three marker lines so Git can track the history
- It must be renamed to avoid the conflict
- It must be identical to the version on main
Show answer
Answer: A. No conflict markers may remain, and you must git add the file
Resolving means editing the file to the version you want, deleting all three marker lines, then staging it with git add and running git commit. Leftover markers would be committed as literal text.
Q7. How does rebasing differ from merging?
- Rebasing deletes the branch, while merging keeps it
- Rebasing replays your commits as new ones, keeping history linear
- Rebasing only works on the main branch
- There is no difference; they are two names for the same operation
Show answer
Answer: B. Rebasing replays your commits as new ones, keeping history linear
A merge combines branches with a two-parent merge commit and preserves the branch shape; a rebase replays your commits on top of another branch as new commits, rewriting them into a straight line with no merge commit.
Q8. What is the golden rule of rebasing?
- Always rebase before every commit
- Only rebase on Fridays
- Never rebase commits you have already shared with others
- Rebase only branches that have merge conflicts
Show answer
Answer: C. Never rebase commits you have already shared with others
Rebasing rewrites commits into new ones. Doing that to commits others have already based work on makes their history and yours disagree — so you rebase only your own private, un-shared work and merge anything public.
Glossary
- branch
- A separate line of development, represented in Git as a movable pointer to a commit; creating one is instant because it copies nothing, only writes a small pointer.
- HEAD
- A special reference marking the branch (and commit) you are currently on — "you are here." It moves to the new commit each time you commit.
- checkout
- The classic Git command for switching branches (git checkout NAME) or creating and switching (git checkout -b NAME); it also does other jobs, which is why git switch was later split out of it.
- switch
- The modern Git command (added in version 2.23) for moving between branches: git switch NAME to switch, git switch -c NAME to create and switch.
- merge
- Combining the commits of one branch into another so the target contains both lines of work; a three-way merge creates a new merge commit with two parents.
- fast-forward
- A merge in which the target branch has not advanced since the split, so Git simply slides its pointer forward to the other branch tip — no merge commit is created and history stays linear.
- three-way merge
- A merge that combines two diverged branches using their common ancestor (the merge base) plus both branch tips, producing a merge commit with two parents.
- merge conflict
- The situation where two branches changed the same lines differently, so Git stops the merge and asks you to choose, marking the disputed region with conflict markers.
- rebase
- Replaying a branch's commits on top of another branch as new commits, producing a straight linear history with no merge commit; it rewrites the commits, so it must never be used on shared history.
- main
- The conventional name of the default branch that holds the primary, shippable line of a project's history (older projects often call it master).
- feature branch
- A short-lived branch created to hold one distinct piece of work — a feature, fix, or experiment — kept isolated from main until it is ready to merge and then deleted.
- merge base
- The most recent commit two branches share — their common ancestor — which Git uses as the reference point when performing a three-way merge.
- conflict markers
- The <<<<<<<, =======, and >>>>>>> lines Git inserts around a conflicting region to show both competing versions; a conflict is resolved only once all three are removed.
Sources and further reading
- Git Branching — Branches in a Nutshell (Pro Git) — Chacon & Straub / Pro Git (accessed 2026-07-12) — How Git models a branch as a movable pointer to a commit.
- Git Branching — Basic Branching and Merging (Pro Git) — Chacon & Straub / Pro Git (accessed 2026-07-12) — Worked examples of fast-forward merges, three-way merges, and resolving conflicts.
- git-merge Documentation — Git (accessed 2026-07-12)
- git-rebase Documentation — Git (accessed 2026-07-12)
- Merge vs Rebase — Atlassian (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.