Study notes · 11% of the exam

Rebasing and Rewriting History

Rebase, amend, cherry-pick and history-rewriting tools all create new commits with new IDs. Use them freely on private work, carefully on anything shared, and force-push with a lease that actually protects others' commits.

Key points

  1. 1

    Rebase replays the commits in upstream..branch onto a new base; each replayed commit gets a new ID, and the old tip is kept in ORIG_HEAD and the reflog.

  2. 2

    git rebase --onto <newbase> <upstream> <branch> transplants just the commits in upstream..branch, which is how you move a branch off a rewritten or unwanted base.

  3. 3

    Interactive rebase lists commits oldest first: pick, reword, edit, squash (keep both messages), fixup (drop this message), fixup -C (use this message), drop or a deleted line, and exec.

  4. 4

    During a rebase, "ours" is the branch you are rebasing onto and "theirs" is your commit being replayed: the reverse of a merge.

  5. 5

    Rebase skips commits whose patch is already upstream, flattens merge commits unless you pass --rebase-merges, and moves stacked branch refs only with --update-refs.

  6. 6

    Cherry-pick ranges exclude the start (A..B); use -x to record the source, and -m 1 to pick a merge commit relative to its first parent.

  7. 7

    Prefer --force-with-lease plus --force-if-includes over --force; a background fetch can silently satisfy a plain lease.

Common traps

  • A background git fetch updates your remote-tracking ref, so --force-with-lease can still overwrite a teammate's commit you never saw.

  • git checkout --ours/--theirs mean the opposite sides during a rebase compared with a merge.

  • Rewriting history and force-pushing doesn't remove a leaked secret from clones, forks or caches: rotate the secret first.

Test yourself on Rebasing and Rewriting History

Ten questions, with the answer and explanation after each one.