Today’s tip is pretty simple. I’m going to show you how you can break up a commit into multiple, smaller commits after you’ve already committed everything to your local repo.
I’m a big advocate of peer reviews. I always try to think about the
poor sap lucky soul that gets to review my changes. I’ll try to structure my commit so that the intent of the changes are clear, and any noise is isolated in separate commits for easier review. For example, if I’m going to do a noisy refactoring, such as a rename on a frequently-used class or method, I will commit the changes caused by the refactoring separately, that way the reviewer can very quickly scan that change without missing any of the meaning of what I actually did.
Other times, I might inadvertently let some scope creep in while working on a story. When I catch this, I’ll try to push that off to a separate commit so that it can be reviewed separately from the originally-planned changes.
But what happens when I don’t realize I’ve made a mess of my commit until the end? In that case, I’ll use git to break my commit up. A ‘soft reset’ will undo the commit without actually losing any of my changes. My changes will once again appear as staged changes, ready to be commited back to the repo. For example, let’s say I have this commit:
And what I want to do is commit the two files, File1 and File2, separately. Easy enough:
git reset --soft HEAD~1
#Commit is now undone, but files are still staged.
git reset .\File2.txt
git commit -m "Added some content to File1"
#Now stage and commit File2.txt
git add File2.txt
git commit -m "Added some content to File2"
With that, my commit history looks like this:
And my actual commits look like:
You can actually get even fancier with this approach. You can actually break up changes within the same file into more than one commit. Do a soft reset, then stage and commit the changes within the file piecemeal.
It’s a simple command, but ‘git reset –soft’ is quite useful.