8. Rewriting history
Author: Ángel Fernández Caravaca
Date: August 15, 2026
Chapter 7 hit the same wall twice. Keeping a branch up to date while its pull request waited, and turning a messy sequence of commits into something a reviewer could read, both pointed to an operation we kept putting off, and both came with a warning about rewriting history. This chapter is that operation. We will learn what git rebase really does to your commits, why the result is never the same objects you started with, how an interactive rebase lets you rewrite your latest commits before anyone sees them and the one rule about when you must not do any of this.
What rebase does¶
For once, the name is a good description. To rebase is to change the base of a branch, that is, to take the commits that are yours and apply them again as if you had started from a different commit.
The situation is the fork from Chapter 4: you created your branch from main, made three commits and, in the meantime, main moved forward with commits of its own. Chapter 4 offered one answer, that is, integrating the two lines and recording the join. Rebase offers the other:
Mechanically, Git does three things, all of them using ideas you already have:
- It finds the merge base, that is, the commit where the two branches diverged, exactly as in Chapter 4.
- It works out what each of your commits changed, that is, it turns each commit on
featuresince that base into a patch. - It applies those patches one by one on top of
main's tip, creating a new commit for each, and finally movesfeature's pointer to the last of them.
The result is a straight line: your work now comes after everything on main, as if you had created the branch this morning instead of last week. There is no merge commit, no fork is drawn in the graph and git log reads as a single sequence.
The third step hides the most important fact in this chapter. Those are new commits, not the ones you wrote:
The reason goes back to Chapter 1, where we said a commit's hash is computed from its content plus its parent's hash. A replayed commit has a different parent, so it necessarily has a different hash, even if the change it carries is identical down to the last byte. Its message, author and date are copied, so it looks like the same commit and reads the same in the log, but for Git it is a new object and the old one still exists, now unreferenced.
Important
This is the whole of Chapter 8 in one sentence: rebase doesn't move commits, it replaces them with copies. Everything that follows, that is, why the golden rule exists, why you have to force-push afterwards and why the reflog can rescue you, is a consequence of that single fact.
Rebase versus merge¶
Both commands answer the same question, that is, how do I bring one branch's work into another?, and they answer it differently. Neither is the right one in general:
git merge main |
git rebase main |
|
|---|---|---|
| What it creates | A merge commit with two parents | A new commit for each commit on your branch |
| Existing commits | Untouched | Replaced by copies with new hashes |
| Resulting shape | A fork and a join, that is, a graph | A straight line |
| Records that the work was parallel | Yes, and permanently | No, that information is discarded |
| Conflicts | Resolved once, in a single operation | Possibly once per replayed commit |
| Safe on a published branch | Always | No, see the next section |
The trade-off is honest and worth stating clearly. A merge is truthful, that is, it records what actually happened, including the fact that two people worked in parallel for a week, and it never touches a commit that already exists. A rebase is readable, that is, it produces the history you would have written if you had known the final answer from the start, at the cost of pretending the parallel work never happened.
For example: a three-commit branch, two of which are fix typo and actually fix the test, tells the reviewer nothing about the change and a lot about your afternoon. Rebase lets you present the version worth reading. Conversely, a release branch merged into main after two months is a real event in the life of the project, and flattening it into a line hides something people will want to find later.
The rule of thumb most teams end up agreeing on:
- Rebase your own unpublished branch, that is, to keep it up to date and to tidy it up before review.
- Merge to integrate, that is, when the branch finally joins
main, whether by hand or with the button from Chapter 7.
Note
Rebase is not a way to avoid conflicts, and it is worth dropping that expectation early. The same overlapping edits from Chapter 5 disagree in exactly the same way in either case. What changes is when they show up, that is, a merge asks you once with the two final states in front of you, whereas a rebase may ask you once per commit, since each replayed patch meets the new base in turn.
The golden rule¶
There is exactly one strict rule in this chapter, and it is worth memorising in its usual form:
Never rebase commits that exist in a repository someone else may have pulled from.
The reason follows directly from the fact that rebase creates copies. Suppose you pushed your branch, a colleague fetched it, and then you rebase and force-push. Their repository still has the original commits, since nothing can reach into it and delete them, while yours now has the copies. Both sets carry the same changes with different hashes, so when they next pull, Git will see two unrelated lines of history and try to merge them, that is, your colleague ends up with every commit duplicated and a conflict on each one. Untangling that is genuinely unpleasant, and it is caused entirely by rewriting something that had already been shared.
The practical version of the rule is easier to apply than the formal one:
- Your own feature branch, which only you have pushed: rebase freely. The
--force-with-leasefrom Chapter 6 exists precisely for this, and pull requests handle it without trouble. - A branch someone else is working on with you: talk to them first, or don't rebase.
main, or any long-lived shared branch: never. Not withrebase, not withcommit --amend, not with theresetfrom Chapter 2 followed by a force-push.
Caution
Notice that the rule talks about shared, not pushed. A branch pushed to your own fork that nobody has ever looked at is still yours to rewrite, whereas a branch that three people have already based work on is off-limits even if it was pushed ten minutes ago. When you're not sure which of the two cases you're in, merge, since merging is never the wrong answer in the sense that it can never damage someone else's clone.
Rebase in practice, conflicts included¶
A rebase that finds no overlaps finishes on its own and prints nothing interesting. When one of the replayed patches meets a line the new base changed, it stops exactly as Chapter 5 described, that is, with markers in the file and the conflicting paths under Unmerged paths:
The resolution cycle is the one you already know, that is, edit the file, remove the markers and git add, with a different command to carry on:
Three details are worth pointing out, since this is where a rebase feels different from a merge:
- It can stop more than once. Each commit is replayed in turn, so a five-commit branch can present five conflicts. This is the cost the table above mentioned, and it is the strongest argument for rebasing often, that is, against a base that has barely moved.
- You are on a detached
HEADwhile it runs. The state from Chapter 2, andgit statussays so. The branch pointer only moves at the very end, which is what allows--abortto restore everything. --oursand--theirsswap. This is the trap Chapter 5 promised to warn about again, and it deserves its own warning.
Warning
During a rebase, --ours is the branch you are replaying onto and --theirs is your own commit being replayed. It is the opposite of what the words suggest and the opposite of the merge case, and it is not a bug: Git is consistent, since --ours always means the side that is already in place and during a rebase that side is main, while your commit is the incoming one. Read them as the base and the commit being applied and you will never get it wrong. When in doubt, git status names both branches explicitly.
There is also a version of the command for performing surgery on the branch's starting point:
Read it as take the commits on feature that are not on old-base and put them on top of main. It is the tool for the branch you accidentally created from the wrong place, or for the branch built on another branch that has just been merged.
Tip
Before any rebase, run git status and make sure the working directory is clean, and
note down where you are with git log --oneline -1. The former avoids the refusal
Git will issue anyway, and the latter gives you something to compare against
afterwards. As always in this course, only what has been committed is safe.
Interactive rebase: rewriting your own commits¶
The command's second use has nothing to do with changing base, and it is the one you will use most. Interactive rebase replays your commits onto their own base, that is, it changes nothing by itself, but it stops first and lets you edit the list of commits it is about to replay:
Your editor opens with a plain text file, one line per commit, from oldest to newest:
That file is a script, and Git runs it from top to bottom as soon as you save and close it. Changing the word at the start of a line changes what happens to that commit, and reordering the lines reorders the commits:
| Word | Short form | What it does |
|---|---|---|
pick |
p |
Keeps the commit as it is |
reword |
r |
Keeps the changes and opens the editor to rewrite the message |
edit |
e |
Stops at this commit so you can modify its content |
squash |
s |
Melds it into the previous commit, combining both messages |
fixup |
f |
The same, but discarding this commit's message |
drop |
d |
Removes the commit entirely, that is, its changes disappear |
exec |
x |
Runs a shell command at this point, e.g. the test suite |
break |
b |
Stops here and hands control back to you; --continue resumes it |
The five commits above become a reviewable branch by changing three words and deleting nothing:
Saving that produces two commits, that is, Add the parser and Add tests for the parser, each with the fixes that belonged to it. This is exactly the tidy-up Chapter 7 asked for before opening a pull request, and it is why the intermediate mess on your branch is nothing to be ashamed of: it is working material, and this command is where it gets cleaned up.
The word edit is the one that needs a second sentence, since it stops the rebase at that commit and leaves you there with the working directory as it was. From that point you make your changes, amend the commit and carry on:
Important
Deleting a line from that file is the same as writing drop, and it deletes the commit's changes, not just its entry in the log. It is the only truly destructive thing in the interactive editor, and it is easy to do by accident when what you meant was to reorder. If you save something wrong, git rebase --abort during the operation and git reflog afterwards can undo it, as the last section shows.
Smaller rewrites: amend and autosquash¶
Not everything needs the interactive editor. By far the most frequent rewrite is fixing the commit you have just made, and it has its own flag:
--amend is a one-commit rebase with a friendlier name, so the same rule applies: it replaces the last commit with a new one, hash included, and is therefore safe exactly as long as that commit hasn't been shared.
For example: you made a commit and then realised you forgot to stage a file. Instead of writing a second commit called forgot a file, you add it and amend:
When the commit you want to fix isn't the latest one, there is a pair of commands that automates the interactive rebase for you:
--fixup writes a normal commit whose message is a marker, and --autosquash reads those markers and prepares the script from the previous section on its own, so all you have to do is save and close. It is the tidy way to work while a review is in progress, that is, each remark becomes a --fixup commit the reviewer can see, and the branch is only flattened at the end.
Cherry-pick: copying a single commit¶
A command that fits here because it works the same way, that is, by replaying a patch as a new commit:
Whereas rebase replays your whole branch onto a new base, cherry-pick replays one chosen commit anywhere. The typical use is a fix that was written on a feature branch and is needed on main right now, without dragging the rest of the branch along.
It can produce conflicts like anything else, and the controls are the same three:
Note
The copy is a truly independent commit, so the change now exists twice in the project, once on each branch. That is fine and usually what you want, but it means the branches will later meet with the same change on both sides, which normally integrates without trouble and occasionally produces a conflict that looks absurd. -x is worth it precisely for this, since that way the message says where the commit came from.
Publishing a rewritten branch¶
After any of the operations above, your local branch and its remote counterpart have diverged in the strict sense of Chapter 6: the remote has the originals, you have the copies, and neither is an ancestor of the other. So a normal git push is rejected, and rightly so, since accepting it would discard the old commits.
The right way to publish is the flag we introduced in Chapter 6:
--force-with-lease compares the remote's current position with your remote-tracking branch, that is, with what your last fetch recorded, and refuses if someone pushed in the meantime. That is precisely the case in which forcing would destroy work, so the flag turns the dangerous command into a safe one at no cost.
The same reasoning explains the Chapter 6 option we left pending:
Read it now with this chapter in hand: instead of merging origin/main into your branch and recording a merge commit for a sync nobody cares about, it rebases your unpushed commits onto it. Those commits are yours and unpublished by definition, so the golden rule is respected, which is why many teams make it the default:
The safety net: reflog¶
Everything in this chapter replaces commits, and the natural question is what happens to the originals. The answer is reassuring: they are still there. Nothing deleted them; they simply stopped being reachable from any branch, and Git keeps a record of every position HEAD has occupied:
The HEAD@{4} line is where the branch was before the rebase started, and the commits it names are the originals. Going back is the reset from Chapter 2 pointed at that entry:
This is what makes rebase far less scary than its reputation suggests. A rebase you regret is undone with a single command as long as you haven't deleted the repository, and the reflog keeps its entries for ninety days by default.
Important
The reflog is local and personal. It records the movements of your HEAD in your clone, so it can't rescue a colleague whose repository you damaged with a force-push, and it doesn't exist in a fresh clone. It is a safety net for your own mistakes, and one more reason why the golden rule is about other people's repositories and not yours.
Summary¶
| Command | What it does |
|---|---|
git rebase <branch> |
Replays the current branch's commits on top of that one |
git rebase --onto <new> <old> <branch> |
Replays only the commits on <branch> that are not on <old>, onto <new> |
git rebase --continue |
Carries on after resolving a conflict |
git rebase --skip |
Drops the commit being replayed and carries on |
git rebase --abort |
Cancels the rebase and restores the branch |
git rebase -i <base> |
Opens the list to reorder, meld, reword or drop commits |
git rebase -i --autosquash <base> |
The same, with the --fixup commits already in place |
pick / reword / edit |
Keep a commit / rewrite its message / stop to modify it |
squash / fixup / drop |
Meld it into the previous one / the same discarding the message / remove it |
git commit --amend |
Replaces the last commit, e.g. to fix its message |
git commit --amend --no-edit |
The same keeping the message, e.g. to add a forgotten file |
git commit --fixup <hash> |
Records a commit marked as a fix for an earlier one |
git cherry-pick <hash> |
Copies a single commit on top of the current branch |
git cherry-pick -x <hash> |
The same, noting the original hash in the message |
git pull --rebase |
Fetches and replays your local commits instead of merging |
git push --force-with-lease |
Publishes a rewritten branch, refusing if the remote has moved |
git reflog |
Lists every position HEAD has occupied, including unreferenced ones |
git reset --hard HEAD@{n} |
Puts the branch back at one of those positions |
git reset --hard ORIG_HEAD |
Goes back to the position saved before the last big operation |
git config --global rebase.autosquash true |
Makes --autosquash the default behaviour |
git config --global pull.rebase true |
Makes git pull rebase instead of merge |
History is no longer something that only grows. You can now reshape a branch before showing it to anyone, keep it up to date without a trail of sync merges, copy a single commit wherever it is needed and undo any of these from the reflog, with a single rule that limits it all to work that hasn't been shared yet. What we have never covered is how teams agree on which branches exist in the first place, and how a specific state of main is marked as the version that reached users. That is Chapter 9: the branching models teams actually use, that is, Git Flow versus trunk-based development, and how git tag turns a commit into a release.