Branching and Merging
Work in parallel, merge, resolve conflicts and rebase.
What you will learn
- Create and switch branches
- Resolve a merge conflict
- Choose merge vs rebase
A branch is an independent line of development. Branches let you build a feature or fix a bug without disturbing the stable code, then combine the work when it is ready. In Git, branches are extremely cheap: just a movable pointer to a commit.
git branch # list branches
git switch -c feature/login # create AND switch to a new branch
# ...edit, commit...
git switch main # go back
git branch -d feature/login # delete a merged branchHEAD is Git's name for "where you are now". Committing moves the current branch forward.
git switch main
git merge feature/login- Fast-forward: if main has not moved, Git just slides its pointer forward.
- Merge commit: if both branches have new commits, Git creates a commit with two parents that joins them.
Merge conflicts
A conflict occurs when both branches changed the same lines. Git stops and marks the file:
<<<<<<< HEAD
const title = "Welcome";
=======
const title = "Hello there";
>>>>>>> feature/loginTo resolve: open the file, choose or combine the correct code, delete the three marker lines, then finish.
git add src/app.js
git commit # completes the merge
# changed your mind? git merge --abortConflicts are normal in team work. Small, frequent merges and pulling often keep them small.
Rebase
git rebase main replays your branch's commits on top of the latest main, producing a straight, linear history instead of a merge commit.
git switch feature/login
git rebase main # re-apply my commits on top of main
git switch main
git merge feature/login # now a clean fast-forwardNever rebase commits that others have already pulled. Rebase rewrites history, which causes chaos for anyone who has the old version. Rebase your own local work freely.
Naming and habits
- Prefix names by intent:
feature/,fix/,chore/. - Keep branches short-lived: days, not months.
- Keep
mainalways working.
Try it yourself
Create a branch, change the same line of a file on both the branch and main, merge, then resolve the conflict by keeping both changes.
Show solution
echo "hi" > f.txt && git add f.txt && git commit -m "init"
git switch -c feature
echo "from feature" > f.txt && git commit -am "feature edit"
git switch main
echo "from main" > f.txt && git commit -am "main edit"
git merge feature # CONFLICT
# edit f.txt to contain both lines, remove markers
git add f.txt && git commit