Skip to content

Lesson 2 of 28Git in a team

Rebase, Merge and Squash

What merge, rebase and squash really do to the commit graph, how to rewrite your branch safely, and how team merge policies affect bisect, revert and blame.

13 min read0/5 questions

Your PR has been open for two days. main has moved on, the PR page says "This branch is out of date", and a reviewer has asked you to "clean up the history before merging". A teammate says to rebase. Another says never rebase. The merge button offers three options with no explanation. These are everyday decisions on a team, and getting them wrong ranges from mildly annoying (a messy history nobody can bisect) to genuinely costly (a force-push that deletes a colleague's work). This lesson gives you the model behind all three operations so you can choose on purpose.

One history, three ways to combine it

Start with the situation from Git Basics. main has commits A and B. You branched at B and made D and E on feature. Meanwhile a teammate's commit C landed on main. You can combine the two lines of work in three ways, and each one leaves a different graph behind.

Merge commit

git merge: join the lines with a merge commit
ABCmainDEfeatureM

currentwaitingdone

The starting point. main is at C, feature is at E, and both descend from B, the merge base.

1/3

Rebase

git rebase: replay your commits on the new main
ABCmainDEfeatureD'E'

currentwaitingdone

Same start. On feature, you run git rebase main.

1/4

Squash merge

Squash and merge: one new commit on main
ABCmainDEfeatureS

currentwaitingdone

Same start again. You click Squash and merge on the PR (locally, git merge --squash feature then git commit).

1/3

What a rebase actually does

git rebase main is not magic. Underneath it does roughly this:

  1. Find the merge base of your branch and main.
  2. List the commits on your branch after that point, skipping any whose exact change is already on main (for example, a fix that was cherry-picked).
  3. Check out main's tip.
  4. Apply each listed commit in order, creating a new commit each time. Each one can stop with a conflict.
  5. Move your branch label to the last new commit.

Step 4 is why the hashes change. A commit's hash covers its content, its message, its author and timestamps, and its parent's hash. Change the parent and you get a different commit, even when the change it makes is identical:

Python
import hashlib def commit_id(tree, parent, message): # A real commit also hashes author, committer and timestamps. body = f"tree {tree}\nparent {parent}\n\n{message}\n" return hashlib.sha1(body.encode()).hexdigest()[:7] B = "66bad6a" # where your branch startedC = "a8564b3" # the commit main has moved on to # Your two commits, built on Bd = commit_id("tree-with-d", B, "Add d")e = commit_id("tree-with-d-e", d, "Add e")print("before rebase:", d, e) # Rebase replays the same changes on C. Same messages, new parents.d2 = commit_id("tree-with-c-d", C, "Add d")e2 = commit_id("tree-with-c-d-e", d2, "Add e")print("after rebase: ", d2, e2)print("same commits? ", (d, e) == (d2, e2))
Output
Press Run (⌘ Enter) to see what happens.

In a real repo it looks like this:

git log --oneline -2# a2970f3 E: add e# 12010fe D: add dgit rebase main# Successfully rebased and updated refs/heads/feature.git log --oneline -2# 271e680 E: add e# 3976a36 D: add d

Before a rebase, Git saves where your branch was in ORIG_HEAD, and the reflog records every position, so a rebase you regret is a git reset --hard ORIG_HEAD away (as long as you have not done anything else since). Git archaeology: bisect, blame and reflog covers recovery in depth.

The golden rule

Because rebasing replaces commits with new ones, never rebase commits that other people have based work on. If a teammate has pulled your D and E and committed on top, and you rebase and force-push, their history and yours now contain two copies of the same work with different hashes. Their next pull either duplicates the commits or produces confusing conflicts, and if they force-push to "fix" it, your new commits vanish.

In practice the rule becomes:

  • Your own unpushed commits: rebase freely.
  • Your own PR branch that only you work on: rebasing is normal on most teams, followed by a careful force-push. Some teams prefer you do not rewrite during review because it breaks "changes since last review" views. Follow the team.
  • Shared branches (main, develop, release/*, a branch two people commit to): never rewrite. Use merge, or git revert to undo something.
Quick check
Which of these is a safe time to rebase?
Need a nudge? A hint rules out a wrong answer.

Keeping your branch up to date

When main moves, you have two ways to bring your branch forward. Merging main into your branch is always safe but adds a merge commit each time. Rebasing gives a clean line and tests your commits against the real current main.

git fetch origingit rebase origin/main          # replay your work on the latest main# resolve any conflicts, run the testsgit push --force-with-lease --force-if-includes

git pull is git fetch plus an integration step, and current Git refuses to guess when your branch and its upstream have both moved:

hint: You have divergent branches and need to specify how to reconcile them.
...
fatal: Need to specify how to reconcile divergent branches.

Pick a default once. Many engineers set rebase, so pulling never creates "Merge branch 'main' of github.com..." commits:

git config --global pull.rebase truegit config --global rebase.autoStash true    # stash local edits around the rebase

Pushing rewritten history safely

After a rebase your local branch and the remote copy have diverged, so a normal push is rejected. A plain git push --force overwrites the remote unconditionally, including any commits a teammate pushed in the meantime. --force-with-lease adds a check: only overwrite if the remote branch is still where your remote-tracking ref (origin/feat) says it is.

$ git push --force-with-lease
 ! [rejected]        feat -> feat (stale info)

That rejection is the lease saving you: someone pushed since you last fetched. But there is a trap. If anything runs git fetch in the background (many editors and Git GUIs do), origin/feat gets updated to include the teammate's commit without you ever looking at it, and the bare lease then succeeds and deletes their work. --force-if-includes (Git 2.30 and later) closes the gap: it also checks that the remote tip is actually part of your local branch's history, meaning you integrated it.

$ git fetch                                          # a background fetch, in effect
$ git push --force-with-lease --force-if-includes
 ! [rejected]        feat -> feat (remote ref updated since checkout)

Make it the default with an alias, and never force-push a shared branch at all:

git config --global alias.pushf "push --force-with-lease --force-if-includes"
Put it in order5 steps

Your PR branch is behind main and the team rebases PR branches. Put the steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Interactive rebase: editing your own history

Your branch has the commits you actually made, including "fix typo" and "wip". Before review, an interactive rebase lets you turn them into a story a reviewer can follow. git rebase -i main opens a todo list of your commits, oldest first:

pick a84dbba # Add refund model
pick 1cf47a8 # Add refund endpoint
pick 1945a72 # fixup! Add refund model
pick 62bfbf0 # Add debug logging
pick 062f418 # Add endpoint tests

You edit the verb on each line and reorder lines, then save and close. The main verbs:

  • pick: keep the commit as it is.
  • reword: keep it, but edit the message.
  • edit: stop after applying it so you can amend or split it.
  • squash: meld into the commit on the line above and combine both messages.
  • fixup: meld into the line above and keep only the line above's message (fixup -C keeps this one's instead).
  • drop: remove the commit (deleting the line does the same).
  • exec: run a shell command at that point, for example exec npm test after every pick to prove each commit builds.

The best habit is to create fix-ups as you go. When a reviewer spots a bug in an earlier commit, commit the fix with git commit --fixup <sha>. Git names it fixup! <subject>, and git rebase -i --autosquash main moves it under its target and marks it fixup automatically. Set rebase.autoSquash to true and you never have to remember the flag.

Predict the output

You save this todo list for git rebase -i main. What does git log --format=%s main..HEAD print afterwards (newest first)?

pick a84dbba # Add refund model
fixup 1945a72 # fixup! Add refund model
pick 1cf47a8 # Add refund endpoint
drop 62bfbf0 # Add debug logging
squash 062f418 # Add endpoint tests
Need a nudge? Hints walk you through it.

Team merge policies

The merge button on GitHub offers Create a merge commit, Squash and merge and Rebase and merge, and repo admins choose which are allowed. Each changes what the history of main is good for later.

  • Squash and merge gives one commit per PR. main reads like a changelog, git revert of a whole feature is one commit, and messy branch commits never matter. You lose the individual commits, so a careful sequence like "refactor, then change behaviour" becomes one blob for git blame and git bisect. It also makes the PR title the commit message that lives forever.
  • Rebase and merge replays each commit onto main with no merge commit. History is linear and granular, so bisect can point to a small commit, but only if every commit builds and passes tests. A branch full of "wip" commits pollutes main.
  • Merge commits keep everything, including when work happened in parallel. Revert a whole PR with git revert -m 1 <merge-sha>, and use git log --first-parent main to see one line per PR. The graph gets noisy, and bisect may land inside a branch's half-finished commits unless you start it with git bisect start --first-parent.

Many teams squash by default because it is forgiving. Teams that care about atomic commits often rebase-merge and require clean history in review. Neither is wrong; consistency is what makes the history useful.

Match the pairs0/4 matched

Match each merge policy to its main consequence.

Choose an item, then its match on the other side.

Squash merges and stacked branches

Squash merging has a sharp edge when branches are stacked. Say ui was built on api, and api was squash-merged into main. If you now run git rebase main on ui, Git tries to replay api's original commits too, because as far as it can tell they are not on main. They conflict with the squashed copy:

$ git rebase main
CONFLICT (add/add): Merge conflict in api
error: could not apply f3127c0... api 1

Abort, and tell Git exactly which commits to move: everything after the old api branch, placed onto main.

git rebase --abortgit rebase --onto main api ui    # replay only ui's own commits onto main

Before anything is merged, --update-refs keeps a stack aligned. Run from the top branch, it rebases the whole stack and moves every branch label in it:

$ git switch ui
$ git rebase --update-refs main
Successfully rebased and updated refs/heads/ui.
Updated the following refs with --update-refs:
	refs/heads/api

Remembering conflict resolutions with rerere

If you rebase a long branch several times, you may resolve the same conflict again and again. rerere ("reuse recorded resolution") remembers how you resolved a conflict and replays it next time the identical conflict appears:

git config --global rerere.enabled true

The first time, Git prints Recorded resolution for 'config.py'. The next time, Resolved 'config.py' using previous resolution. It still leaves the file for you to check and git add, which is the right default: always look before you trust it. Resolving Conflicts with Confidence covers the resolution itself.

Quick check
You rebased your PR branch. Your editor fetches in the background, and it has just fetched a commit your teammate pushed to your branch. Which push protects their commit?
Need a nudge? A hint rules out a wrong answer.
Key terms
merge base
The most recent commit two branches have in common; where they diverged.
rebase
Replaying a branch's commits on a new base, creating new commits with new hashes.
fast-forward
Moving a branch label forward along existing commits when no merge commit is needed.
squash merge
Combining a branch's whole diff into one new commit on the target, with no link back to the branch.
interactive rebase
A rebase driven by an editable todo list: pick, reword, edit, squash, fixup, drop, exec.
force-with-lease
A force-push that fails if the remote branch moved since your last fetch; pair it with --force-if-includes.
rerere
Git's option to record conflict resolutions and reuse them when the same conflict reappears.