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:

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.

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications.
He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight,
where he publishes courses on everything from web applications to testing!