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.