Using `git add -p` to cleanup your commits
Git Logo from https://git-scm.com/downloads/logos
As a developer, I don’t find it natural for me to do just one thing to my code base between commits. I end up cleaning up a couple things as I’m working on a new feature or bug ticket or even lump together two tickets that touch the same module. To this end, some of my commits ended up looking like this:
Eventually, I (or even worse someone else) would try to figure out what happened in that commit and have no idea because of the shitty commit message. That all changed the day I learned about git add -p
.
Git add -p
is the “interactive add” feature in Git so instead of adding an entire file I can just add a single changed section or several sections from a file.
As an example, I have the diff below. The original intention was to add the getVariable()/setVariable() functions but in working on that change I realized I misspelled “Something”. I could commit these in a single commit but then the reasoning might get lost (just imagine it’s a more complicated change :-) ).
To do this I’m going to use git add -p
start the interactive add:
Git then shows me the first hunk I have to make a decision on. The options below are not all self explanitory so you can press ? to display more information:
In this case I’m going to press “y” because I do want to stage this hunk.
Then it’s going to display the next hunk which I will say no to:
After this, I can do a quick git status
to make sure everything makes sense. In this case we see something interesting which is the fact that test.php is both staged and not staged because we’re only committing part of the file.
Finally I can commit the change with a useful commit message.
Then I can commit the remainder of the change.
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows