Git: Testing Patches in Pieces

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, -p or --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.

Normally 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.

Advertisements

3 thoughts on “Git: Testing Patches in Pieces

    1. Surprisingly, no. I used to use Magit and I very often recommend it to people, but I feel more comfortable working with Git outside of Emacs. Sometimes I use some of the built-in VC Mode commands, but that’s about it.

Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s