Can Git remind me about or auto-apply a stash when switching back into the corresponding branch?

Viewed 1293

I often start working on a certain branch (e.g. new-feature) and get interrupted by something with a higher priority (e.g. high-prio). Most of the time, my changes on new-feature are incomplete and therefore I don't want to do a full commit¹, so I git stash them before checking out a new high-prio branch. This creates a new stash which is associated with new-feature:

stash@{0}: WIP on new-feature: <sha1 and message of previous commit>

Now, I can complete my work on high-prio. After I'm done with that I checkout new-feature again and (since it has been a while) often forget that there was a stash associated with this branch. This creates problems as I might re-do work I already completed on the stash or I have to merge / rebase those changes later.

Is there a configuration setting which reminds me about the existing stash or, even better, automatically pops the stash back into my working tree after checking out new-feature again?

¹ Doing a "WIP"-Commit and later squashing the changes is not a good solution because I want to always keep origin/new-feature in sync with my local new-feature.

2 Answers

You can use the git post-checkout hook like so:

Add the following text to .git/hooks/post-checkout

#!/bin/bash
echo "Don't forget to git stash pop the following:"
git stash list

or

#!/bin/bash
branch=$(git branch | sed -n '/\* /s///p')
last_stash_on_branch=$(git stash list --grep="WIP on ${branch}:" | head -1 | cut -d: -f1)
if [[ -n "${last_stash_on_branch}" ]]; then
    git stash pop --index ${last_stash_on_branch}
fi

Make it executable

chmod +x .git/hooks/post-checkout

Now when you checkout any branch your post-checkout script will hopefully remind you check your stashes

Here is a trick I use:

In general, prefer to commit over stashing in your case:

git checkout -b new-feature

// now instead of stash, commit:

git commit -am "Started implementation"

// now move to high priority branch and do the high priority task
 ... 
// done high priority task

git checkout new-feature 
// now this is the important command: it saves your work in index, removes the commit 
from the branch but all the files are preserved  
git reset --soft HEAD~1

// now to see the outcome, execute
git status

Bottom line, git reset --soft HEAD~1 is your friend here

Related