archive2016

Git rebase or merge: the rules we use in a small team

When to rebase and when to merge in a small team, the commands I use, and the one rule that keeps shared history safe.

3 min read#dev#git#workflow

The rebase or merge question came up again in a pull request discussion, and I noticed I explain the same four rules every time. Both commands are fine. What matters is that everyone follows the same rules, so here they are, written down.

A merge joins two branches with a merge commit, and history shows what really happened, including parallel work. A rebase moves your commits so they start from the new tip of another branch. History becomes a straight line, but your commits get new IDs.

1. Never rebase commits that others have

If a commit is on a shared branch (master, develop, or a branch someone else also pulls), do not rebase it. Rebase rewrites commits. Other people still have the old ones, and their next pull gives duplicates and confusing conflicts. Rebasing your own local work, or a feature branch only you use, is safe.

2. Update your feature branch with rebase

git fetch origin
git rebase origin/master

On a conflict, fix the files and continue:

git add path/to/file
git rebase --continue

git rebase --abort takes you back to where you started.

If you already pushed the branch, you have to force-push after a rebase. Use the safe form:

git push --force-with-lease

It refuses to overwrite the remote branch if someone else pushed to it in the meantime. Plain --force does not check.

3. Clean up before review

Before opening a pull request, squash the “fix typo” and “wip” commits:

git rebase -i origin/master

In the editor, change pick to squash or fixup for commits that belong to the one above. Each commit that is left should build and have a clear message. I am not always good at this myself.

4. Merge the feature into master

git checkout master
git merge --no-ff feature/sensor-retry

--no-ff always creates a merge commit, even when a fast-forward is possible. The merge commit shows where the feature started and ended, and you can revert the whole feature with one command:

git revert -m 1 <merge-commit>

Some teams prefer a straight history with fast-forward or “squash and merge” in their Git hosting tool. That also works. Pick one and write it down.

To avoid accidental merge commits when pulling your own branch:

git config --global pull.rebase true

On one page

Situation Use
Update my feature branch from master rebase
Tidy my commits before review interactive rebase
Finish a feature into master merge (--no-ff) or squash merge
Anything already on a shared branch never rebase