Saturday, January 28, 2012

Stashing Changes in Mercurial

Stashing means setting aside changes to a working directory without commiting them.

It's useful if, for example, you're adding a feature to one of your projects when you find a bug that you want to fix immediately. You don't want to not mix the fix up with your feature code and you aren't ready to commit and start a new changeset. The solution is to stash your changes, code the bug fix and commit it and then unstash them to resume working on the feature.

Recipe

hg diff | Out-File -Encoding ascii stash.patch
hg update -C
# other stuff...
hg import --no-commit stash.patch

Explanation

Output of hg diff is a unified diff which we save to file. hg update -C, of course, removes the changes from the working directly. Be careful that you don't accidentally lose work when you're doing this! After other stuff, we use the import command to unstash the changes.

Comparison to Other Methods

There are extensions for stashing but, in my experience, they don't work very well.

mq is used for this as well but that procedure is unnecessarily complicated if you don't normally use mq.