Search code examples
gitgit-stash

How to discard stash pop in Git without dropping my uncommitted changes?


I've made some uncommitted changes before executing git stash pop. How can I discard stash pop without dropping my uncommitted changes?

git reset --hard HEAD will reset my local changes.


Solution

  • Once you run git stash pop the changes get applied to your working tree and the stash is removed. Depending on how much has changed between the time you ran pop and now, there is a chance you could recover the stash from the commit logs (stashing does create some commit references), but it might not be easy...

    First, follow this post to try and get the hash for the stash commit you are looking to recover. Once it's found, create a branch with it (I'll call it stash_data, and assume we are starting from branch master):

    git branch stash_data [stash hash ID]
    

    That branch should now have just the content of the stash and none of the other changes. Now create a new branch to commit all of the uncommitted changes-- both the stash and non-stash (I'll call it combined_data).

    [on `master` branch, with all changes]
    git checkout -b combined_data
    git add [your files]
    git commit -m "preparing to revert a stash pop"
    

    Now there are 3 branches. One with the stash changes applied (stash_data), one with all changes applied (combined_data) and one at baseline (master). Apply the diff between stash_data and master to combined_data:

    [still on branch `combined_data`]
    git diff stash_data master | git apply
    

    combined_data should now have only those changes that were not in the stash, and stash_data should have only the change that were in the stash.