How can I rename a git stash?

I have a stash with an incorrect name. I would like to fix the name so it's accurate.

How can I rename a stash?


Solution 1:

Let's assume your stash list looks like this:

$ git stash list
stash@{0}: WIP on master: Add some very important feature 
stash@{1}: WIP on master: Fix some silly bug

First, you must remove stash entry which you want to rename:

$ git stash drop stash@{1}
Dropped stash@{1} (af8fdeee49a03d1b4609f294635e7f0d622e03db)

Now just add it again with new message using sha of commit returned after dropping:

$ git stash store -m "Very descriptive message" af8fdeee49a03d1b4609f294635e7f0d622e03db

And that's it:

$ git stash list
stash@{0}: Very descriptive message
stash@{1}: WIP on master: Add some very important feature

This solution requires git 1.8.4 or later, and yes, it works with dirty working directory too.

Solution 2:

Unless you do it manually or contribute an improvement to Git, you can use an alias:

git config --global alias.stash-rename '!_() { rev=$(git rev-parse $1) && git stash drop $1 || exit 1 ; git diff-index --quiet HEAD; s=$?; [ $s != 0 ] && git stash save "tmp stash from stash-rename"; git stash apply $rev && shift && git stash save "$@" && [ $s != 0 ] && git stash pop stash@{1}; }; _'

Usage: "git stash-rename <stash> [save options] [<message>]"

With [save options] any option of git stash save: [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet] [-u|--include-untracked] [-a|--all]

Example:

$ git stash list
stash@{0}: On master: Pep8 format
stash@{1}: On master: co other than master with local changes
stash@{2}: On master: tests with deployAtEnd

# Let's say I want to rename the stash@{2} adding an issue reference:
$ git stash-rename stash@{2} NXP-13971-deployAtEnd

$ git stash list
stash@{0}: On master: NXP-13971-deployAtEnd
stash@{1}: On master: Pep8 format
stash@{2}: On master: co other than master with local changes

That will work even if you have local unstaged changes :)

EDIT 2016/02/22

Simplified script, credits to qzb, https://stackoverflow.com/a/35549615/515973

git config --global alias.stash-rename '!_() { rev=$(git rev-parse $1) && git stash drop $1 || exit 1 ; git stash store -m "$2" $rev; }; _'

Usage: "git stash-rename <stash> [<message>]"

Solution 3:

It's very simple. First, undo the last stash with:

git stash pop

After this, yo can save the stash with a customized name in this way:

git stash save "your explanatory name"

I hope it useful for you. :)