... unless you did it with --fixup and --autosquash
The most important thing first: Of course you never change commits in branches that you share with others like develop
, master
or whatever you call your "main" git branches. If you encounter an error there, just fix it with a new commit.
When you're working on a branch on your own like a feature branch or local branch there's a more elegant way to fix commits.
Take a look at the following git log:
8680a59d This is the 3rd commit
7e866455 This is the 2nd commit
a069e42a This is the 1st commit of my feature branch
0e2977b5 Previous commit that is already integrated in master
Imagine you want to fix an error in the 2nd commit.
Make the file changes to fix the problem and add the changes to the stage, e.g. with git add --all
.
git commit --fixup 7e866455
Notice the commit hash 7e866455
is the one from the commit that contained the error. Now your git log looks something like this:
335ca372 fixup! This is the 2nd commit
8680a59d This is the 3rd commit
7e866455 This is the 2nd commit
a069e42a This is the 1st commit of my feature branch
0e2977b5 Previous commit that is already integrated in master
The new commit has the commit message from the 2nd commit, but prefixed with fixup!
.
You can do this multiple times for the same or for different commits in your branch. When your branch is ready to be merged (or reviewed) you'll want to clean things up. Just run:
git rebase -i --autosquash 0e2977b5
The commit hash 0e2977b5
is the one your feature branch is based on ("previous commit").
This will apply your fixup commits directly to the commits they belong to and you will get a clean git log with all errors fixed.
26fe362d This is the 3rd commit
5db42a3d This is the 2nd commit
a069e42a This is the 1st commit of my feature branch
0e2977b5 Previous commit that is already integrated in master
✨✨✨
Top comments (2)
Nice write-up! Wasn't familiar with 'fixup'.
Not a fan of squashing everything for the sake of it, but commits should preferably contain a logical unit of work. And getting those 'fixed a typo/forgot a file' commits out of the history is a good thing imo.
I needed this all my career, thanks! <3