Tonight I want to share a useful technique for Git which I forget to use too often. So in reality this article is more a reminder for myself that it is easy to test individual parts of patches before committing.
I almost always stage changes by using
git add -up. The option
-u is short for
--update and will only stage changes affecting files Git is already tracking; in other words, it will not add new files. The other option,
--patch, let’s me interactively decide the changes to put on the index for committing. By using
git add -up I often have a mixture of staged changes on the index and unstaged changes in my working directory. Before committing, however, I want to test the changes I staged and only those changes.
This is where I forget the usefulness of
git stash save --keep-index.
git stash save would hide away all of my changes, staged or not. But when I have partially staged some code I want to keep that on the index and only stash what I did not stage. And that is exactly what
--keep-index does. For example:
# Stage some of the changes I've made. $ git add -up # Hide the changes I didn't stage. $ git stash save --keep-index # Test the code I'm going to commit. $ make test # If everything looks good, make the commit. $ git commit -v # And resume work on the previously unstaged changes. $ git stash pop
One side-effect of this process is that I tend to make commits with small amounts of changes. It is easier, in my opinion, to squash commits together into larger ones than it is to split an existing commit into smaller pieces. The cycle of commands above allows me to add, test, and commit in tiny chunks when I’ve written more code than I intend to put into a single commit.
Stashing in general is useful. But for whatever reason I forget about
--keep-index until I run
git stash save and see all of my changes disappear. Now that I’ve typed this all out maybe that will etch
--keep-index into my brain. If you frequently make small, incremental commits then you will probably find this useful for testing.