Cleaning up Git commit history before a review
Rework local commits with reset, amend, and interactive rebase. Protect a remote branch with force-with-lease and recover commits with reflog.
Several checkpoints make sense while I’m building a feature. Before review, I group them into commits with a clear purpose, then use Git’s lease and recovery tools if I need to update a published feature branch.
The commands use Git 2.30 or later.
--force-if-includesbecame available in Git 2.30.
Start with the three states Git tracks
Labels like wip and fix typo may be fine during implementation, but in review I want each commit to explain a change and ideally build on its own. That helps if I later need to bisect a regression or selectively revert a change. For a small pull request that will be squash-merged, the additional cleanup may offer little value.
Git tracks the current commit through HEAD, the staged snapshot in the index, and the editable files in the working tree. The three common commit-level reset modes differ in which states Git updates.
| Mode | HEAD | Index | Working tree | Use |
|---|---|---|---|---|
--soft | Moves | Preserved | Preserved | Combine commits or rebuild their messages |
--mixed, the default | Moves | Reset | Preserved | Stage files and hunks again in separate groups |
--hard | Moves | Reset | Reset | Restore a specific snapshot and discard tracked edits |
Check git status before rewriting, especially before a hard reset. Commit or stash independent edits first. If the branch is important, a temporary backup branch keeps the old commit reachable while you compare the rewrite.
Amend one commit or rebuild a group
If I missed a file or mistyped the latest commit message, I use git commit --amend. The two examples below illustrate adding a staged file while retaining the old message and replacing the message.
1
2
3
4
5
6
# Stage a missing file and amend without changing the message
git add src/main/kotlin/com/example/auth/TokenValidator.kt
git commit --amend --no-edit
# Replace the latest commit message
git commit --amend -m "feat: validate JWT expiration"
Amend creates a replacement commit and moves the branch tip. Staging content, editing the commit message, or changing its metadata changes the commit object ID. If the old commit is already on the remote, a normal push may be rejected as non-fast-forward.
For a stack of temporary commits, I sometimes reset to the feature’s base and rebuild the stack. git reset --soft main works for this when the local main is an appropriate base, such as when it still points at the commit I branched from. If main has moved independently, first identify the intended base so the new commits don’t inadvertently undo unrelated changes.
1
2
3
4
5
6
7
8
9
10
11
# 1. Move back to main and keep all changes staged
git reset --soft main
# 2. Unstage and commit each logical change
git reset
git add src/main/kotlin/com/example/auth/
git commit -m "feat: issue and validate auth tokens"
# 3. Select hunks when one file contains several changes
git add -p src/main/kotlin/com/example/user/UserService.kt
git commit -m "refactor: simplify user lookup dependencies"
After the soft reset, git reset with no arguments resets the index to HEAD and leaves the working tree intact. I can stage a whole directory for one change and use git add -p for selected hunks in a file with mixed changes. Check git diff --cached before each commit.
Use interactive rebase for a narrower edit
If only a few middle commits need updating, I use interactive rebase.
1
git rebase -i HEAD~4
Use pick to retain a commit, reword to change its message, squash or fixup to combine it with the preceding commit, and drop to omit it. Git reapplies the results in the order shown. If the original patches are tightly tangled and replay keeps conflicting, rebuilding the staged diff from the base can be simpler. Review the final diff and run the test suite before replacing a remote tip.
Publish rewritten work with a lease
A rewritten tip and its previous remote history have diverged. An unconditional force push can erase commits someone else has added. --force-with-lease protects an expected remote value. It lets Git replace the remote reference when the current tip matches the expected value and rejects the push otherwise.
flowchart TD
A["Push with a lease"] --> B["Compare expected and actual tips"]
B -->|"Match"| C["Update remote branch"]
B -->|"Mismatch"| D["Reject stale lease"]
D --> E["Fetch and integrate changes"]
A colleague’s update to the remote feature branch can produce this result.
1
2
3
4
$ git push --force-with-lease origin feat/auth
To github.com:example/backend-api.git
! [rejected] feat/auth -> feat/auth (stale info)
error: failed to push some refs to 'github.com:example/backend-api.git'
The implicit lease often uses the local remote-tracking reference as its expectation. An IDE’s background fetch may update that reference to a commit you haven’t integrated. --force-if-includes adds a check for that implicit lease and requires evidence in the local branch reflog that the remote-tracking tip was integrated. You can also pin the explicit expected object ID when you want the lease to protect a known snapshot.
1
git config --global alias.pushf "push --force-with-lease --force-if-includes"
On a shared branch such as main or develop, I use a revert commit instead of rewriting history. Prefer protected branch settings where several contributors share the same base.
Recover an old tip from reflog
A hard reset or a mistaken rebase can make a commit disappear from the ordinary log while the commit object still exists. The reflog records local reference updates. By default, Git expires reachable reflog entries after 90 days and unreachable ones after 30 days, subject to repository settings and cleanup.
1
2
3
4
5
6
$ git reflog -n 5
3ec7167 (HEAD -> feat/login) HEAD@{0}: commit: feat: add login flow
4e692b9 (main) HEAD@{1}: reset: moving to main
2b09b38 HEAD@{2}: commit (amend): fix typo
2b09b38 HEAD@{3}: commit: fix typo
acf8597 HEAD@{4}: commit: wip
Find the entry before the mistake and note its object ID. Reflog positions shift as new updates occur. Starting a recovery branch lets you confirm the proposed restoration before overwriting the working tree. The two commands below illustrate alternative recovery operations.
1
2
3
4
5
# Option 1: Reset directly to the prior tip
git reset --hard HEAD@{2}
# Option 2: Inspect the prior tip on a recovery branch
git switch -c recovery/login HEAD@{2}
Reflog entries can help with committed work. They cannot restore arbitrary edits Git never recorded, so either commit or stash local changes you need before a destructive reset.
Preserve history that others depend on
A revert adds the inverse change while keeping the shared commits available. Reverting a merge requires the number of the parent that should remain the mainline.
1
2
3
git revert <commit-to-revert>
# For a merge, select the mainline parent (parent 1 here)
git revert -m 1 <merge-commit>
Before publishing a rewrite, check the base and the resulting diff, preserve a backup tip, run tests, and use a lease only on the branch you own. If the lease rejects the update, inspect and integrate the remote change before trying again.