Search code examples
gitgithubgit-stash

git stash apply recovered only unstaged files


I have some 24 files changed on branch A. None of these are committed. Some of these files with changes, say 18 are unstaged. And other 6 files are staged. I had to checkout to other branch B because of some other work. I stashed these changes while on branch A, checked out to branch B, did my work and later checked back to branch A. I now did git stash apply. I can only see changes that are unstaged are recovered, but there is no sign of file changes that are changed and staged.

Can anyone help how I can get these staged but uncommitted changes back?


Solution

  • You can :

    • discard your current changes (for example : git checkout .),
    • run git stash apply --index

    When you create a stash (using git stash), git stores two snapshots of your repo : your current index (the state of the files that are currently staged) , and your current worktree (the state of the files on disk).

    When you run git stash apply, it restores only the state of your worktree ; when you run git stash apply --index, it restores both the index (as it was when you stahed your changes) and the worktree.

    In the situation you describe in your question : you stashed from branch A, and you returned to exactly that state before running git stash apply. You have therefore a 100% guarantee that no conflict will occur when applying your stash.

    The small twist to the --index option is the following : if conflicts get in the way when running git stash apply --index, since git uses the index to store (and let you solve) conflicts, you won't really know if the conflicts come from the "index" part or the "worktree" part. Again : this doesn't apply to the situation you describe in your question.