Branches and Merging
The bakery site is live and working. You want to try a whole new menu layout, which will take a few days, but tomorrow the owner may ask you to fix a typo in the opening hours. You cannot leave a half-finished layout on the live site. Branches let both lines of work exist side by side.
The rule
Branch to experiment safely; merge to bring the work home.
A branch is simply a movable name pointing at a commit. The default branch is usually called main. When you commit on a branch, its name moves forward to the new commit; other branches stay where they were.
git switch -c new-menu-layout # create a branch and move onto it
# ...edit, add, commit as usual...
git switch main # back to main; files return to main's version
git merge new-menu-layout # bring the branch's commits into main
git branch -d new-menu-layout # delete the branch name once merged(Older tutorials use git checkout -b instead of git switch -c; both work.)
Two kinds of merge.
- Fast-forward: if
mainhas not moved since you branched, Git just slides themainname forward to your latest commit. No new commit is needed. - Merge commit: if both branches gained commits, Git combines them and records a new commit with two parents.
Conflicts. If both branches changed the same lines of the same file, Git cannot know which version you want. It pauses and marks the file:
<<<<<<< HEAD
<p>Open 7am to 3pm</p>
=======
<p>Open 8am to 4pm</p>
>>>>>>> new-menu-layoutThe top part is what your current branch has; the bottom part is what the incoming branch has. You edit the file to the correct final text, delete the marker lines, then git add the file and git commit to finish the merge. A conflict is not an error; it is Git asking a question only you can answer.
The shortcut
Before merging, ask "Has the branch I am merging into moved since I branched?" No: expect a fast-forward. Yes: expect a merge commit, and if both sides touched the same lines, expect a conflict to resolve by hand.
Branch off
From
main,git switch -c new-menu-layout. Two commits of layout work follow.
The trap is doing new, unrelated work straight on main. Keep main in a state you would happily put live, and do everything else on branches.
Drills
Answer fast — trust the rule.
What is a Git branch?
You branched from main, made three commits, and nobody changed main. What does git merge on main do?
When does a merge conflict happen?
After editing a conflicted file to its final text and removing the markers, what do you do next?
Remember
- Branch to experiment safely; merge to bring the work home.
- Has the target moved? No: fast-forward. Yes: merge commit, maybe a conflict.
- Trap: working directly on
main; keep it ready to go live.
