# Rewriting history: amend, interactive rebase and safe force-pushes

Clean a messy branch before review: fix the last commit with amend, squash and reword with interactive rebase, fold in fixups, and force-push without destroying anyone's work.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 10. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/git/10-rewriting-history

## What you will learn

- Fix the last commit's message or contents with git commit --amend
- Squash, reword, reorder and drop commits with git rebase -i
- Use fixup commits and --autosquash to fold review fixes into the right commit
- Explain why rewritten commits need a force-push, and when that's acceptable
- Force-push safely with --force-with-lease and --force-if-includes
- Recover when a rebase goes wrong

## Why rewrite at all?

While you work, commits record how you got there: "wip", "fix typo", "actually fix it", "try other
approach", "revert that". That's normal, and committing often is a good habit. But it's a diary, not a
record anyone else can use. Reviewers and future readers want what you did: a few commits, each one a
complete, working step with a clear message. Someone running `git bisect` next year needs every
commit to build and pass its tests, which "wip" commits often don't.

Rewriting turns the diary into the record **before** anyone depends on it. You keep the freedom to
commit messily while you work, and the team gets a clean history.

> **The rule.** Rewrite your own commits freely until you share them. Once others have pulled them (main, release branches, a branch a teammate works on), add new commits instead. Rewriting shared history forces everyone to repair their clones, and can silently delete work.

## Amend: fix the last commit

The most common "oops" in Git happens seconds after a commit: you notice a typo in the message, or
you forgot to `git add` one file. Making a second commit called "forgot a file" works, but it clutters
history with a commit that means nothing on its own. `--amend` folds the fix into the commit you just
made, as if you'd got it right the first time.

```sh
$ git add forgot.txt
$ git commit --amend --no-edit                 # add it to the last commit, keep the message
$ git commit --amend -m "Add session handling and the forgotten file"   # change the message
$ git commit --amend --reset-author --no-edit  # after fixing user.email: fix the author too
```

Amend doesn't edit a commit; it **replaces** it with a new one (new ID). If the old one was pushed, the
new one needs a force-push, so it's at its best before you push.

## Interactive rebase: edit a whole branch

`git rebase -i main` lists every commit on your branch since main and lets you decide what happens to
each one:

> **Figure.** An interactive rebase todo list, oldest commit at the top. Before: pick Add login form, pick fix typo, pick wip, pick session stuff. Edited: pick Add login form, fixup fix typo, fixup wip, reword session stuff. After: two clean commits, Add login form with the typo fix and wip folded in, and Add session handling with a better message. All commits after the first changed have new IDs. The commands: pick keeps, reword changes the message, edit stops to change contents, squash merges and combines messages, fixup merges and drops the message, drop deletes; reordering lines reorders commits.
>
> Edit the list, save, close. Git replays the branch the way you described.

```sh
$ git log --oneline main..
a09931b Add session handling
263b2c6 wip
ceeb08b fix typo
e9160ce Add login form
$ git rebase -i main
```

Your editor opens with the oldest commit first. This is the real screen from Git 2.53, on a branch
with four commits:

> **Figure.** A real git rebase -i main session in vim. Four lines at the top, oldest first: pick c8f55e5 # Add search stub, pick 4ac0ae5 # fix typo, pick 52fedda # wip, pick d9cddf0 # rank search results. Below them, comment lines Git adds: Rebase b9cb4db..d9cddf0 onto b9cb4db (4 commands), then the list of commands with p pick, r reword, e edit, s squash and f fixup explained.
>
> Every line starts with pick. Only the first word matters to you: the ID says which commit, and the text after # is just a reminder of its message.

For the login branch, change the first word of each line so it reads:

```text
pick e9160ce # Add login form
fixup ceeb08b # fix typo
fixup 263b2c6 # wip
pick a09931b # Add session handling
```

Change the words, save and close. Git replays the commits in order:

```sh
Successfully rebased and updated refs/heads/feature/login.
$ git log --oneline main..
86eda3b Add session handling and the forgotten file
af9a5c4 Add login form
```

| Want to…                                     | Do                                                                         |
| -------------------------------------------- | -------------------------------------------------------------------------- |
| combine "fix typo" into the commit before it | `fixup` (or `squash` to keep both messages)                                |
| fix a message                                | `reword`                                                                   |
| split a commit, or change its files          | `edit`, then `git reset HEAD~1`, commit in pieces, `git rebase --continue` |
| reorder commits                              | move the lines                                                             |
| delete a commit                              | `drop` (or delete the line)                                                |

If a step conflicts, resolve it as in the _Merge strategies_ lesson, `git add`, then
`git rebase --continue`. `git rebase --abort` puts everything back as it was before you started.

### Fixup commits: fold in review fixes

During review, make the fix as a **fixup commit** that names the commit it belongs to. Git sorts it into
place for you later:

```sh
$ git commit -a --fixup af9a5c4         # "fixup! Add login form"
$ git log --oneline main..
b57e38f fixup! Add login form
86eda3b Add session handling and the forgotten file
af9a5c4 Add login form
$ git rebase -i --autosquash main       # the fixup is already moved and marked; just save
$ git log --oneline main..
4a19ac0 Add session handling and the forgotten file
ff8fd10 Add login form
$ git config --global rebase.autoSquash true   # make --autosquash the default
```

Reviewers can read the fixups as a small diff of "what changed since my review", and you squash them just
before merging.

> **Video.** [Git Tutorial #25: What Is Interactive Rebase and How to Use It | Learn Git with GitKraken](https://www.youtube.com/watch?v=JkpYvXdbnfQ) (GitKraken)

## Force-pushing safely

**The short version:** after rewriting a branch you must force-push it, and you should always use
`git push --force-with-lease --force-if-includes`, never plain `--force`. Here's why.

A branch you rewrote no longer contains the commits the remote has, so a normal push is refused. A
force-push tells GitHub "replace your branch with mine". The danger is that a teammate may have pushed
to the same branch since you last looked, and a plain force-push would delete their work without a
warning. The safer forms check first:

| Command                                    | Overwrites the remote when…                                       |
| ------------------------------------------ | ----------------------------------------------------------------- |
| `git push --force`                         | always, even if a teammate pushed meanwhile: their commits vanish |
| `git push --force-with-lease`              | the remote still matches your `origin/branch`; refused otherwise  |
| `… --force-with-lease --force-if-includes` | as above, **and** you have integrated what you fetched            |

With a teammate's commit on the remote that you've never fetched, the lease protects you:

```text
 ! [rejected]        feature/login -> feature/login (stale info)
```

But `--force-with-lease` compares against `origin/feature/login`, which **any `git fetch` updates**,
including the background fetches many editors run. After a fetch, the lease passes and the teammate's
commit is overwritten anyway. `--force-if-includes` closes that gap by checking that their commits are
actually in your branch:

```sh
$ git fetch                                       # an editor may do this without asking
$ git push --force-with-lease --force-if-includes
 ! [rejected]        feature/login -> feature/login (remote ref updated since checkout)
$ git config --global alias.pushf "push --force-with-lease --force-if-includes"
$ git pushf                                       # use this for every force-push
```

When it's refused, `git pull --rebase` to take in their work, check the result, then `git pushf` again.

> **Guard rails.** Block force-pushes on `main` and release branches with a ruleset (the *Collaboration* lesson), so even a mistaken `--force` can't rewrite them. Before rewriting a branch someone else has touched, tell them; they should commit or push their work first.

## When it goes wrong

An interactive rebase that goes badly feels scary: commits look missing, files look wrong, and the
branch doesn't match what you expected. The good news is that a rebase never deletes the old commits.
It builds new ones and moves the branch label to them, and Git remembers where the label was before.
So you can always put it back.

The reflog (the _Undoing changes_ lesson) remembers the branch before the rebase:

```sh
$ git reflog -5                       # find the line before "rebase (start)"
$ git reset --hard feature/login@{1}  # or that commit's ID
$ git rebase --abort                  # if the rebase is still in progress
```

`ORIG_HEAD` also points at where the branch was before the last rebase or reset: `git reset --hard
ORIG_HEAD` undoes a rebase you just finished.

## Mission: Clean up a branch before review

Your feature branch has four commits: the real feature, 'fix typo', 'wip', and a second real commit with a poor message. Turn it into two clean commits with good messages, fold a later review fix into the first one with a fixup commit, and force-push safely.

- You need: Any repository with a remote (a bare repository works)
- You'll have: A branch with two commits, pushed with --force-with-lease --force-if-includes

```sh
$ git switch -c feature/login
$ echo "form" > login.py && git add . && git commit -m "Add login form"
$ echo "typo" >> login.py && git commit -am "fix typo"
$ echo "more" >> login.py && git commit -am "wip"
$ echo "s" > session.py && git add . && git commit -m "session stuff"
$ git push -u origin feature/login
$ GIT_SEQUENCE_EDITOR="sed -i -e '2s/^pick/fixup/' -e '3s/^pick/fixup/' -e '4s/^pick/reword/'" git rebase -i main
$ git log --oneline main..                      # two commits; the second has your new message
$ echo "review fix" >> login.py && git commit -a --fixup HEAD~1
$ GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash main
$ git push --force-with-lease --force-if-includes
$ git log --oneline main.. | wc -l
2
```

`GIT_SEQUENCE_EDITOR` edits the todo list with a script instead of an editor, the same change you'd make
by hand; `reword` still opens your editor for the new message ("Add session handling"). In real work,
just run `git rebase -i main` and edit the list yourself.

## Try it

- Make a commit, forget a file, then add it with `git commit --amend --no-edit`.
- Make four commits on a branch including a "wip" and a "fix typo", and squash them with `git rebase -i main`.
- Make a fix for an older commit with `git commit --fixup <id>`, then run `git rebase -i --autosquash main`.
- Set `git config --global rebase.autoSquash true` and repeat without the flag.
- Abort a rebase halfway with `git rebase --abort` and check nothing changed.
- Add an alias for safe force-pushes with `git config --global alias.pushf "push --force-with-lease --force-if-includes"`.

## Quiz

1. You committed but forgot one file, and haven't pushed. What is the cleanest fix?
   - Make a new commit called "add missing file"
   - **git add the file, then git commit --amend --no-edit** (answer)
   - git reset --hard
   - git revert HEAD
   Why: Amend replaces the last commit with a new one that includes the file. Fine before pushing; after pushing it needs a force-push.

2. In git rebase -i, what does fixup do to a commit?
   - Deletes it
   - **Melds it into the commit above it in the list and discards its message** (answer)
   - Edits its message
   - Moves it to the end
   Why: squash also melds it but lets you combine the messages. reword changes a message, edit stops to change the contents, drop removes the commit.

3. Why does a rebased branch need a force-push if it was already pushed?
   - GitHub requires it for every push
   - **The commits were replaced by new ones, so the remote branch is no longer an ancestor of yours** (answer)
   - Rebase deletes the remote branch
   - It doesn't
   Why: A normal push only adds commits. Replacing commits means discarding the old ones on the remote, which Git refuses unless you force it.

4. What does --force-with-lease protect against?
   - Nothing
   - **Overwriting commits on the remote that you haven't seen: it refuses if the remote moved since your last fetch** (answer)
   - Pushing secrets
   - Slow networks
   Why: It checks the remote still points where your origin/branch says. But a plain git fetch updates that, which is why --force-if-includes is added: it also checks you actually integrated what you fetched.

5. Which branches should you never rewrite?
   - Any branch with more than one commit
   - **Shared branches others build on, such as main and release branches** (answer)
   - Branches with tests
   - Your own feature branch before review
   Why: Rewriting main forces everyone to repair their clones. Protect it with a ruleset that blocks force-pushes. Your own branch before review is exactly where rewriting belongs.

## Resources

- [Pro Git: rewriting history](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History) (Pro Git)
- [git-rebase documentation](https://git-scm.com/docs/git-rebase) (Git)
- [git-push: --force-with-lease and --force-if-includes](https://git-scm.com/docs/git-push) (Git)
- [GitHub Docs: about Git rebase](https://docs.github.com/en/get-started/using-git/about-git-rebase) (GitHub Docs)
