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.
Like this post? Don't forget to follow us on Twitter and Facebook for updates.