# Merge, rebase, squash: combining work, and fixing conflicts

The four ways to bring a branch into main, the history each leaves behind, and when teams use each. How to read and resolve a conflict calmly, and copy one commit with cherry-pick.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 6. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/git/06-merge-strategies

## What you will learn

- Tell a fast-forward from a merge commit, and force either one
- Rebase a branch onto main, and know the one rule that keeps rebasing safe
- Squash a branch into one commit, and know what it costs
- Read conflict markers, resolve them, and finish or abort a merge or rebase
- Copy a single commit to another branch with cherry-pick
- Choose a strategy for a team and match GitHub's merge button to it

## Four ways to combine a branch

**Why this is worth a whole lesson.** Merging looks like a solved problem: you finish a branch and
it goes into `main`. But six months later, production breaks and you open the history to find the
commit that caused it. In one team the log is a tangle: 40 merge bubbles, "wip" and "fix typo"
commits everywhere, and the real change buried in the middle. In another team, every line in the log
is one complete, described change, and the culprit takes a minute to find. Same code, same tools.
The difference is how branches were combined.

Every method below ends with the same files on `main`. What differs is the **history** left behind,
and history is what you read when something breaks:

> **Figure.** The same feature branch with commits A and B, started from main at commit 1, while main gained commit 2, combined four ways. Merge commit: A and B stay, joined to main by a merge commit M with two parents. Rebase then fast-forward: A and B are replayed after 2 as new commits A-prime and B-prime, giving a straight line. Squash: A and B become one new commit S after 2. Fast-forward only: possible when main has not moved, main just moves to B.
>
> Same code on main every time. Different history: a graph, a straight line, or one commit per change.

| Method                        | History on main                             | Use when                                                         |
| ----------------------------- | ------------------------------------------- | ---------------------------------------------------------------- |
| **Merge commit**              | every branch commit, plus a merge commit    | you want the true record of how work happened                    |
| **Rebase, then fast-forward** | branch commits, replayed in a straight line | each commit is meaningful and you want a linear log              |
| **Squash**                    | one commit per branch                       | branches are messy; main should read one change per pull request |
| **Fast-forward**              | branch commits, no extra commit             | main hadn't moved                                                |

## Fast-forward or merge commit

You saw both in the _Branches_ lesson. Two options control them:

```sh
$ git merge --no-ff feature/x     # always make a merge commit, even when a fast-forward is possible
$ git merge --ff-only feature/x   # only fast-forward; refuse if a merge commit would be needed
```

A quick reminder of the difference. A **fast-forward** happens when `main` hasn't moved since you
branched: Git simply slides the `main` label forward to your last commit. No new commit is made, and
the history looks as if you'd worked on `main` all along. A **merge commit** is a new commit with
two parents, one from each side, that records "these two lines of work were joined here".

`--no-ff` forces a merge commit even when a fast-forward was possible. You get a visible "this
feature was merged here" commit, and you can revert the whole feature in one step by reverting
that commit. `--ff-only` does the opposite: it only ever fast-forwards and refuses otherwise. That
makes it a safe default for updating your local `main` from GitHub, because it never creates
surprise merge commits.

> **Video.** [Git Tutorial #11: How to Merge Branches and Resolve Conflicts | Learn Git with GitKraken](https://www.youtube.com/watch?v=mS8oUqqc2G8) (GitKraken)

## Rebase: replay your commits

> **Figure.** Animated. feature has commits A and B, started from commit 1, while main has moved on to commit 2. git rebase main replays A and B on top of 2 as new commits A-prime and B-prime; the old A and B fade, no longer on any branch, and feature points to B-prime. git merge --ff-only feature then moves main forward to B-prime: a straight line with no merge commit.
>
> A and B are replayed after 2 as new commits A′ and B′; then main fast-forwards. Same changes, new IDs.

**Why rebase?** You branched from `main` on Monday. By Thursday, five teammates have merged their
work into `main`, so your branch starts from an old version of the code. You could merge `main` into
your branch, but that adds a merge commit every time you catch up. Rebase gives a different result:
it makes your branch look as if you'd started it _today_, on top of the latest `main`.

Here's what it does. `git rebase main` takes the commits on your branch that aren't on `main`, sets
them aside, moves your branch to the tip of `main`, and replays them one by one:

```sh
$ git log --oneline --graph --all
* fbf0837 wip
* 2022fd0 Return an empty list from search
* 0d86374 Add search stub
| * d45f583 Add VERSION
|/
*   18269df Merge branch 'feature/discount'
$ git rebase main
Successfully rebased and updated refs/heads/feature/search.
$ git log --oneline --graph -4
* 735332d wip
* fa49403 Return an empty list from search
* d9fd28b Add search stub
* d45f583 Add VERSION
```

The branch now starts after `Add VERSION`, and merging it into main would be a fast-forward. Look at
the IDs: `0d86374` became `d9fd28b`. **Rebase creates new commits.** The old ones still exist for a
while, but your branch no longer points at them.

> **The golden rule.** Only rebase commits that nobody else has. Rebasing your own branch before opening a pull request is fine. Rebasing `main`, or a branch a teammate has pulled, rewrites commits under their feet, and their next pull turns into a mess. If you must update a pushed branch after a rebase, push with `--force-with-lease` (the *Rewriting history* lesson) and tell the people on it.

> **Video.** [Git Tutorial #23: Rebasing in GitKraken vs CLI (Part 1) | Learn Git with GitKraken](https://www.youtube.com/watch?v=xKanizFigpk) (GitKraken)

## Squash: one commit per change

A branch often ends with commits like "wip", "fix typo", "address review". `--squash` brings in all
the changes but none of those commits, so you write one good commit:

```sh
$ git switch main
$ git merge --squash feature/search
Squash commit -- not updating HEAD
 search.py | 2 ++
 1 file changed, 2 insertions(+)
$ git status --short             # the changes are staged, nothing is committed yet
A  search.py
$ git commit -m "Add search"
```

On GitHub you rarely type this: the pull request's **Squash and merge** button does it. The cost is
that main loses the branch's individual commits, so `git bisect` (the _History_ lesson) can only narrow
a bug down to the whole pull request. Small pull requests make that cost tiny.

## Handling conflicts

A **conflict** happens when both sides changed the same lines and Git can't know which is right. It
stops and asks you:

```sh
$ git merge feature/discount
Auto-merging config.py
CONFLICT (content): Merge conflict in config.py
Automatic merge failed; fix conflicts and then commit the result.
$ git status --short
UU config.py
$ cat config.py
<<<<<<< HEAD
PRICE = 120
=======
PRICE = 90
>>>>>>> feature/discount
TAX = 0.18
```

> **Figure.** Anatomy of a conflict in config.py. The block from <<<<<<< HEAD to ======= is your current branch's version, PRICE = 120. The block from ======= to >>>>>>> feature/discount is the incoming branch's version, PRICE = 90. Lines outside the markers, like TAX = 0.18, merged cleanly. To resolve: edit the file to the correct final content, delete all three marker lines, then git add the file and git commit, or git merge --abort to go back.
>
> Yours above the line, theirs below. You write the final version and delete the markers.

Resolving is always the same four steps:

1. **Understand both changes.** Here main raised the price and the branch lowered it. Ask whoever
   made them if the right answer isn't obvious; never just pick a side to make the conflict go away.
2. **Edit the file** to what it should finally say, and **delete all three marker lines**.
3. **Mark it resolved:** `git add config.py`.
4. **Finish:** `git commit` for a merge, `git rebase --continue` for a rebase.

```sh
$ git diff                       # during a conflict: both sides, side by side
$ git merge --abort              # changed your mind: back to before the merge
$ git rebase --abort             # same, for a rebase
$ git checkout --ours config.py  # take your side for this whole file
$ git checkout --theirs config.py
```

During a **rebase** "ours" and "theirs" swap places: Git is replaying _your_ commits onto _their_
branch, so `HEAD` is main. It confuses everyone once.

Two settings make conflicts easier:

```sh
$ git config --global merge.conflictStyle zdiff3   # also show the original lines both sides changed
$ git config --global rerere.enabled true          # remember how you resolved a conflict and reuse it
```

With `zdiff3` a third block, starting `|||||||` and the ID of the common ancestor commit, shows what the line was before either change: `PRICE =
100`. Seeing that both sides moved away from 100 makes the right answer much easier to work out. In VS
Code, the merge editor shows the same three panes.

> **Video.** [Git Tutorial #27: What Is a Merge Conflict and How to Resolve It | Learn Git with GitKraken](https://www.youtube.com/watch?v=MzpW-k66XE8) (GitKraken)

## Cherry-pick: one commit

`cherry-pick` copies the change from one commit onto your current branch, as a new commit. The classic
use: a fix landed on main, and a release branch needs only that fix:

```sh
$ git switch release/1.0
$ git cherry-pick 2cb5a0e
[release/1.0 ec15333] Add search
 1 file changed, 2 insertions(+)
$ git cherry-pick -x 2cb5a0e     # -x adds "(cherry picked from commit …)" to the message
```

Use it for single commits. If you find yourself cherry-picking ten commits, the branches are set up
wrong; a merge is probably what you need.

**When not to:** cherry-picking creates a _copy_ with a new ID, so Git doesn't know the two commits
are the same change. If both branches are later merged together, the same change appears twice, and
if one copy was edited afterwards you can get a confusing conflict. Keep cherry-picks for small,
self-contained fixes going into release branches, and add `-x` so the message records where the copy
came from.

> **Pick one strategy as a team.** Mixing styles makes history hard to read. A common setup: squash-merge pull requests into main, keep feature branches short, and rebase your own branch on main before asking for review. Enforce it in the repository settings by enabling only the merge buttons you want (*Settings → General → Pull Requests*).

> **Video.** [Git CHERRY PICK Tutorial](https://www.youtube.com/watch?v=i657Bg_HAWI) (The Modern Coder)

## Mission: Resolve a real conflict, then land a clean branch

Two branches change the same price on main. Merge them, resolve the conflict to the price the business agreed (110), and verify. Then rebase a second feature branch onto the updated main and squash it into a single commit.

- You need: Any empty folder
- You'll have: main with the agreed price and one 'Add search' commit

```sh
$ git init shop && cd shop
$ printf 'PRICE = 100\nTAX = 0.18\n' > config.py && git add . && git commit -m "Add pricing config"
$ git switch -c feature/discount && sed -i 's/PRICE = 100/PRICE = 90/' config.py && git commit -am "Lower the price to 90"
$ git switch main && sed -i 's/PRICE = 100/PRICE = 120/' config.py && git commit -am "Raise the price to 120"
$ git merge feature/discount                       # CONFLICT
$ printf 'PRICE = 110\nTAX = 0.18\n' > config.py   # the agreed price, no markers
$ git add config.py && git commit --no-edit
$ git switch -c feature/search
$ echo "def search(q): return []" > search.py && git add . && git commit -m "Add search stub"
$ echo "# TODO: real search" >> search.py && git commit -am "wip"
$ git rebase main                                  # already on main's tip: nothing to replay over
$ git switch main && git merge --squash feature/search && git commit -m "Add search"
$ git branch -D feature/search feature/discount
$ git log --oneline --graph
* 728e61d Add search
*   2278f46 Merge branch 'feature/discount'
|\
| * 6286003 Lower the price to 90
* | f3a8a78 Raise the price to 120
|/
* 48f3407 Add pricing config
$ grep -c '<<<<<<<' config.py                     # 0: no markers left behind
0
```

`git branch -D` is needed for `feature/search` because a squash merge copies the changes without
recording the branch's commits as merged. Your commit IDs will differ from these.

## Try it

- Make a conflict on purpose (change the same line on two branches), merge, and read `git status`.
- Resolve it, then run `git log --oneline --graph` and find the merge commit.
- Rebase a branch with three commits onto an updated main, and compare its commit IDs before and after.
- Merge a branch with `git merge --squash` and read what `git status` shows before you commit.
- Cherry-pick one commit from main onto a release branch.
- Set `git config --global merge.conflictStyle zdiff3` and make another conflict to see the difference.

## Quiz

1. When does git merge create a fast-forward instead of a merge commit?
   - Always
   - **When the current branch has no new commits since the other branch started from it** (answer)
   - When there are conflicts
   - Only with --squash
   Why: There is nothing to combine, so Git just moves the pointer. --no-ff forces a merge commit anyway; --ff-only refuses anything but a fast-forward.

2. What is the golden rule of rebasing?
   - Rebase only on Fridays
   - **Never rebase commits that others have already pulled; rebase only your own unshared work** (answer)
   - Always rebase main onto your branch
   - Rebase only after merging
   Why: Rebase replaces commits with new ones (new IDs). Anyone who built on the old ones now has diverged history to untangle.

3. What does a conflict block between <<<<<<< HEAD and ======= contain?
   - The other branch's version
   - **Your current branch's version (during a merge)** (answer)
   - The original version before both changes
   - A Git error message
   Why: HEAD is the branch you are on. The part after ======= up to >>>>>>> is the incoming branch. During a rebase the sides swap, because Git is replaying your commits onto the other branch.

4. What do you lose with a squash merge?
   - Nothing
   - **The individual commits of the branch; main gets one commit with all the changes** (answer)
   - The changes themselves
   - The branch name only
   Why: That is the point: a tidy main with one commit per pull request. The detailed commits stay visible in the closed pull request.

5. A bug fix is on main, and the release/1.0 branch needs it too, without everything else on main. What do you use?
   - git merge main
   - **git cherry-pick <commit>** (answer)
   - git rebase main
   - git revert
   Why: cherry-pick copies one commit's change as a new commit on your current branch.

## Resources

- [Pro Git: rebasing](https://git-scm.com/book/en/v2/Git-Branching-Rebasing) (Pro Git)
- [Pro Git: advanced merging](https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging) (Pro Git)
- [GitHub Docs: about merge methods on GitHub](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/about-merge-methods-on-github) (GitHub Docs)
- [GitHub Docs: resolving a merge conflict using the command line](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-using-the-command-line) (GitHub Docs)
- [git-cherry-pick documentation](https://git-scm.com/docs/git-cherry-pick) (Git)
