Debugging with Git stash

I use git stash all the time to jump between branches or pull stuff while I’m in the middle of a project. Recently, I’ve also started using git stash --index to target specific files in my working directory that I want to tuck away for a bit. It’s a great tool to use when 1) you want to commit/push only some of the files you’ve modified in the working directory, or 2) you’ve buried a bug somewhere your working directory, but you’ve made so many changes since your last commit that you’re not quite sure where to start. It happens.

Let’s say you’ve got four tracked, modified files on your working directory: foo.js, bar.js, style.less, and module.less. You’ve made a bunch of changes to each one since your last commit, and suddenly you refresh the browser and your server crashes. You know the faulty code causing this little fiasco is probably in one of these stylesheets, but you’ve been pounding out new code for a good twenty minutes and you’re beyond the point where a little CONTROL + Z will back you up to whatever line is throwing the error.

Fear not; git-foo is with you.

First, run git reset to ensure that all four files are unstaged:

$ git reset
# Unstaged changes after reset:
# M foo.js
# M bar.js
# M style.less
# M module.less

Great. Now for some efficient debugging. We’ve got a hunch that the error might be in style.less. We can test this hypothesis by selectively stashing style.less and then restarting the server. If things run smoothly and we can’t replicate the bug, we’ve found our culprit. We need to stage style.less so that we can stash it:

$ git add style.less

Now, let’s stash style.less and leave the other three files alone:

$ git stash --keep-index
# Saved working directory and index state WIP on master: fb3b2c1 my last commit
# HEAD is now at fb3b2c1 my last commit

See what just happened? We hid style.less and now we can restart the server and see how it likes running with only foo.js, bar.js, module.less in the working directory. Happy debugging!

comments powered by Disqus