November 16, 2011

Git: Stashing

There have been a lot of times when I’m caught in middle of getting ‘er done on some fix or feature and need to update the branch I’m working on with someone else’s work. I usually try to¬†git pull origin whatever and then I’m rudely reminded as the merge fails that I have one or more dirty, dirty files with uncommitted changes. I hastily commit my halfassed, partially-finished work with a message all like “incomplete work-in-progress” just so I can have a clean working tree to complete the merge.

Part of the reason I love the Git workflow is that it forces me to think critically about my process and to break tasks down into discernible goals so that I’m committing workable, finished code, no matter how tiny the chunks are. If every commit represents a discrete addition to the feature or project, I’m doing a good job of breaking larger features down into measurable tasks. Committing a bunch of half-finished stuff doesn’t fit well into this approach.

Enter the stash. Stashing sounds cool and basically just sets everything you’re working on aside for the moment. When you create a stash, you’re taking all of the work you’ve done since the last commit, setting it aside and reverting the working tree back to your HEAD. You’re saving your changes without committing them so you can do things like pull and merge into a clean working tree, and then apply your changes back to the working tree when you’re done.

Let’s say you want to pull changes into your local branch but you’re halfway done with a feature. All you have to do is stash your changes, pull from the remote, and then apply the stashed changes.

git stash save "work in progress"
git pull origin master
git stash apply

Assuming that there weren’t any conflicts, your local working copy should now be synced with the remote and your work-in-progress should be intact and ready for you to continue right where you left off.