Search code examples
gitgit-stash

Applying a git stash created with --all


I accidentally created a git stash with the --all option, which, according to the docs,

If the --all option is used instead then the ignored files are stashed and cleaned in addition to the untracked files.

So now restoring my changes with git stash pop fails:

some/ignored/file already exists, no checkout
Could not restore untracked files from stash

(What I actually should have done is use --include-untracked)

git stash show -p still lists my changes, without any ignored files. How can I apply my stash without git trying to restore ignored files?

Edit: I just created a test repository and did a git stash --all. Ignored files were stashed and removed from the file system. My problem is that in my case above, they were stashed, but not removed from the file system, so that seems to be the cause for the problem.


Solution

  • Use log to find the commit hash of your stash

    $ git log --graph --all --decorate --oneline
    

    All is important because it also shows stashes

    It should look similar to this

    *-.   cd5e9ae (refs/stash) WIP on master: cd48088 Fixed GET chats output
    |\ \  
    | | * e48d0d7 untracked files on master: cd48088 Fixed GET chats output
    | * 1a3bf97 index on master: cd48088 Fixed GET chats output
    |/  
    * cd48088 (HEAD, origin/master, master) Fixed GET chats output
    

    Now, you want to checkout the top of the stash (here, it's cd5e9ae)

    $ git checkout cd5e9ae
    

    You will be in a detached HEAD state
    reset it one step back, keeping the changes

    $ git reset HEAD~1
    

    and now stash it like you meant to

    $ git stash --include-untracked
    

    Now you can go back to master or wherever you were working and apply that new correct stash

    $ git checkout master
    $ git stash pop
    

    Inspired by this blog post

    I just tested it and it worked in my project with my ignored files, it should work for you as well.