til / rewriting git commit history
If you want to fix a commit inside a PR you can use Git rebasing and the easiest way to do it is using an interactive rebase. Let’s say you have three commits:
- Commit A (sha: 123)
- Commit B (sha: 456)
- Commit C (sha: 789)
Now you want to change Commit B. Start by finding its SHA ID using
git log, in this example we’ve called it
git rebase -i 456^ to start an interactive rebase. Note the
^ at the end which includes the commit in question in the rebase
You’ll be presented with a Vim buffer that would look something like:
1pick 456 Commit B 2pick 789 Commit C 3 4# Commands 5# p, pick <commit> = use commit 6# e, edit <commit> = use commit, but stop for amending 7# ...
Notice the edit command, which is exactly what we want. Alter the line for Commit B with the edit command instead of the pick command.
1edit 456 Commit B 2pick 789 Commit C
After saving, you’ll be taken back in time to Commit B where you can make the changes you set out to do.
Once your done with the changes, run
git rebase --continue to take you back to the present.
If you would run
git log at this point you would notice that the commit SHAs for Commit B and Commit C have changed. This happened be we altered history using with our rebase. To update our PR we need to do a force push,
git push -f
Only do this in pull requests, don’t alter your commits on you default branch.
- Johnny Ji. (2021-06-08). Engineering Culture: Keeping a Clean Commit History. Link