Rebasing

Advanced

Introduction

Merging records exactly what happened, including every branch and merge. Many teams prefer a cleaner, linear history, where each feature appears as a neat sequence of commits on top of main. Rebasing produces that, and an interactive rebase lets you polish your commits before others see them: fix messages, combine "oops" commits, drop experiments.

How it works

git rebase main, run on feature, does three things:

  1. finds the commits on feature that are not on main: those reachable from feature but not from main;
  2. moves to the tip of main;
  3. replays each of those commits in order, applying the same change and creating a new commit with a new id and a new parent.

The branch then points to the last new commit. The old commits still exist (the reflog remembers them) but are no longer on the branch. The result looks as if the feature had been started from the current main, and main can now fast-forward to it.

If a replayed change conflicts with what is already on main, the rebase stops at that commit. You resolve the conflict, git add the file and git rebase --continue; or git rebase --abort to go back. During a rebase, "ours" is the branch being built on (main) and "theirs" is your commit being replayed, the opposite of a merge.

Interactive rebase (git rebase -i main) opens a to-do list, one line per commit, oldest first:

pick f1a2b3c Add search box
squash 4d5e6f7 Fix typo in search box
reword 8a9b0c1 Search results
drop 2c3d4e5 Experiment

pick keeps a commit; reword keeps it with a new message; squash melds it into the previous commit and combines the messages; fixup melds it and keeps only the previous message; drop removes it; reordering lines reorders the commits.

The golden rule: rebase only commits that nobody else has. Rebasing creates new ids; anyone who built on the old ones now has diverged history to untangle.

git switch feature
git rebase main               # replay feature onto main
git rebase -i HEAD~4          # tidy the last four commits
git rebase --continue         # after resolving a conflict
git pull --rebase             # fetch, then rebase local commits on top

Example

commits = {
    "a": (None, "Start"),
    "b": ("a", "Add page"),
    "m1": ("b", "Fix footer on main"),
    "f1": ("b", "Add search box"),
    "f2": ("f1", "Search results"),
}
main, feature = "m1", "f2"


def ancestors(oid):
    out = set()
    while oid:
        out.add(oid)
        oid = commits[oid][0]
    return out


on_main = ancestors(main)
to_replay, oid = [], feature
while oid not in on_main:
    to_replay.append(oid)
    oid = commits[oid][0]
to_replay.reverse()
print("commits to replay:", to_replay)
base = main
for number, old in enumerate(to_replay, start=1):
    new = f"{old}'"
    commits[new] = (base, commits[old][1])
    print(f"replayed {old} as {new} on top of {base}: {commits[old][1]}")
    base = new
feature = base
line, oid = [], feature
while oid:
    line.append(oid)
    oid = commits[oid][0]
print("feature history is now linear:", " <- ".join(line))
Open in compiler

Line by line

  1. main and feature diverged at b: main has m1, feature has f1 and f2.
  2. The commits to replay are those on feature that main cannot reach, oldest first.
  3. Each is replayed on top of the new base and gets a new id, written here with a prime.
  4. After the rebase, feature's history runs through main's tip m1: it is linear.
  5. The original f1 and f2 are no longer on any branch, but still exist until Git cleans up.

Expected result

commits to replay: ['f1', 'f2']
replayed f1 as f1' on top of m1: Add search box
replayed f2 as f2' on top of f1': Search results
feature history is now linear: f2' <- f1' <- m1 <- b <- a

In the real world

Many projects ask contributors to rebase their pull requests on the latest main before merging, and GitHub offers a "Rebase and merge" button. Interactive rebase is used daily to clean up local work. The Linux kernel and many open-source projects require a tidy series of commits, each building and passing tests on its own, which interactive rebase makes possible.

Common mistakes

  • Rebasing a branch others are using, forcing them to repair their history.
  • Forgetting to force-push carefully after rebasing your own pushed branch; use git push --force-with-lease.
  • Mixing up ours and theirs while resolving rebase conflicts.
  • Squashing away meaningful history that reviewers wanted to see.

Best practices

  • Rebase your own feature branch onto main before opening or updating a pull request.
  • Use fixup commits while working, then tidy them with an interactive rebase.
  • If a rebase goes wrong, git rebase --abort, or find the old tip in the reflog.

Summary

A rebase replays the commits reachable from your branch but not from the upstream on top of the upstream, giving new commits and a linear history. Interactive rebase lets you pick, reword, squash, fix up, drop and reorder commits. Conflicts are resolved commit by commit, and the golden rule is never to rebase history others depend on.

Quick check

1. What happens to commit ids when you rebase?
2. Which commits does git rebase main replay?
3. What does fixup do in an interactive rebase?
4. What is the golden rule of rebasing?

Key takeaways

  • A rebase copies your commits onto the new base; the copies have new ids and the originals are abandoned.
  • The commits replayed are those reachable from your branch but not from the upstream.
  • Rebase only private branches; rebasing shared history forces everyone else to repair theirs.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.