Key idea
A branch is a name that points at a commit and moves forward as you commit on it. You branch to work on one change without disturbing main, then merge to bring that work back. Most merges are automatic; a conflict is Git asking you to decide.
Make a branch
git switch -c add-due-dates # create a branch and move onto it
# edit, git add, git commit as usual
git switch main # back to main; your files change to match it
Branches are cheap: making one copies nothing. Use one per change, and give it a name that says what the change is.
Merge it back
From the branch you want to bring work into, name the branch to bring in:
git switch main
git merge add-due-dates
What Git does next depends on what happened to main while you worked.
Nothing happened on main: a fast-forward. Your branch is just main plus some commits, so Git slides the main name forward to your last commit. No new commit is made.
Updating 24acd58..ec4c514
Fast-forward
Main moved on too: a merge commit. Both sides have commits the other lacks. Git combines them and records a new commit with two parents, one from each side. It opens your editor for the message; git merge --no-edit add-due-dates accepts the default message instead. Landed in Vim? Type :wq and press Enter.
Merge made by the 'ort' strategy.
Read a merge
git log --oneline --graph
* 1ad8e56 Merge branch 'add-c'
|\
| * fc8cd16 Add c
* | 39011c8 Edit a
|/
* ec4c514 Add b
Read it bottom up. The lines split where the branch started, each side has its own commits, and they join at the merge commit. A fast-forward leaves a single straight line.
When both sides change the same lines
Git merges changes to different files, or different parts of one file, on its own. If both branches changed the same lines, it can't know which you want, so it stops:
CONFLICT (content): Merge conflict in greeting.js
Automatic merge failed; fix conflicts and then commit the result.
A conflict isn't an error, and nothing is lost. Git has written both versions into the file, between markers, and waits for you to choose. The next lesson walks through one.
Keep branches short
The longer a branch lives, the further main moves away from it, and the more lines both sides touch. A branch merged the same day rarely conflicts; one left for a month almost always does. Small branches, merged often, keep merges boring.
Rebase, and what happens to a branch after a merge
Rebase is the other way to combine branches: it replays your commits on top of the latest main, so the history stays one straight line. It rewrites your commits, so only rebase a branch nobody else has built on. Module 7 shows how hosted repositories offer merge, squash or rebase as a button.
After a merge the branch has done its job. git branch -d add-due-dates deletes the name; the commits stay in main's history.
Check yourself