Branches and Merging
You are halfway through adding search to notes-api when an urgent bug report arrives. Your half-finished work must not ship, but the fix must ship today. Branches let both lines of work exist side by side and meet again only when each is ready.
The rule
A branch is a movable label on a commit; merge joins two histories.
A branch is not a copy of your files. It is a tiny label that points at a commit and moves forward every time you commit on it. HEAD marks the branch you are on.
git switch -c feature/search # create a branch here and move onto it
# ... commit your work ...
git switch main # go back; your files change to main's version
git switch -c fix/login-timeout # branch for the urgent fix
# ... commit the fix ...
git switch main
git merge fix/login-timeoutWhen you merge, Git does one of two things:
- Fast-forward: if
mainhas not moved since you branched, Git simply slides themainlabel forward to your latest commit. No new commit is needed. - Merge commit: if both branches have new commits, Git creates a commit with two parents that combines them.
If both branches changed the same lines, Git cannot choose, so it stops with a conflict and marks the file:
<<<<<<< HEAD
timeout: 30
=======
timeout: 60
>>>>>>> fix/login-timeoutThe top part is your current branch, the bottom part is the branch being merged. You edit the file to the correct final text, delete the markers, then git add the file and git commit to finish.
The shortcut
Before merging, draw the two labels in your head and ask: has the target moved since I branched? No means fast-forward, nothing to decide. Yes means a merge commit, and possibly conflicts only where both sides touched the same lines.
Branch from main
git switch -c fix/login-timeoutfrommain. The search work stays safe on its own branch.
The trap: resolving a conflict by blindly keeping "ours" or "theirs". Read both sides; the right answer is sometimes a mix.
Drills
Answer fast — trust the rule.
What is a Git branch, underneath?
You merge fix into main, and main has no new commits since fix was created. What happens?
In a conflict, which part is the current branch's version?
After editing a conflicted file to its correct content, what finishes the merge?
Remember
- A branch is a movable label on a commit; merge joins two histories.
- Shortcut: has the target moved? No means fast-forward; yes means a merge commit.
- Trap: resolving conflicts without reading both sides.
