Skip to content
Engineering Bible
Git

Git on merging and rebasing

A merge joins two lines of history

  • git merge search brings the commits of search into the branch you are on.
  • If your branch has no commits of its own, Git only moves the pointer: a fast-forward.
  • Otherwise Git adds a merge commit with two parents. No existing commit changes.

A rebase replays your commits on a new base

  • git rebase main reapplies your branch's commits on top of main, one at a time.
  • The result is a straight line, as if you had started from the latest main.
  • The replayed commits are new commits with new IDs. The old ones are left behind.

Never rewrite history that other people have

  • Rebase and amend replace commits. Anyone who built on the old ones has to redo work.
  • Rewrite your own branch as much as you like. Leave main and shared branches alone.
  • To push a rewritten branch, use git push --force-with-lease, not --force.
  • It refuses if the remote branch has moved since you last fetched it.

A conflict means Git needs you to choose

  • It happens when both sides changed the same lines. Git stops and marks the file.
  • Edit the file to what it should be, delete the markers, then git add it.
  • Finish with git merge --continue or git rebase --continue.
  • git merge --abort or git rebase --abort puts everything back as it was before.
<<<<<<< HEAD
const timeout = 30;
=======
const timeout = 60;
>>>>>>> search
During a merge, the top half is the branch you are on and the bottom half is the one coming in.

A pull request can merge in three ways

  • GitHub offers a merge commit, squash and merge, or rebase and merge.
  • Squash suits short-lived branches: main gets one commit per pull request.
  • After a squash or rebase merge, main holds new commits, not the ones on your branch.
  • So delete the branch once it is merged, and start the next one from main.
MethodWhat lands on the base branchResult
Merge commitEvery commit, plus a merge commitFull history, with the join shown
Squash and mergeOne new commit with all the changesOne commit per pull request
Rebase and mergeEvery commit, copied with a new IDStraight line, no merge commit

Keep your branch close to main

  • git pull stops if you and the remote both have new commits and no rule is set.
  • git pull --rebase replays your local commits on top of the remote's.
  • Make that the rule with git config --global pull.rebase true.
  • Bring main into a long-lived branch often, so each conflict stays small.
Git in four pages3 / 4