tags:

views:

2313

answers:

5

I am trying to apply changes I stashed earlier with git stash pop and get the message:

Cannot apply to a dirty working tree, please stage your changes

Any suggestion on how to deal with that?

+5  A: 

Either clean your working directory with git reset, commit the changes, or, if you want to stash the current changes, try:

$ git stash save "description of current changes"
$ git stash pop stash@{1}

This will stash the current changes, and then pop the second stash from the stash stack.

William Pursell
+1  A: 

You have files that have been modified but not committed. Either:

git reset --hard HEAD (to bring everything back to HEAD)

or, if you want to save your changes:

git checkout -b new_branch
git add ...
git commit
git checkout -b old_branch
git stash pop
brool
+3  A: 

You can do this without having to stash your current changes by exporting the stash you want as a patch file and manually applying it.

For example, say you want to apply stash@{0} to a dirty tree:

  1. Export stash@{0} as a patch:

    git stash show -p stash@{0} > Stash0.patch

  2. Manually apply the changes:

    git apply Stash0.patch

If the second step fails, you will have to edit the Stash0.patch file to fix any errors and then try git apply again.

Ishan
This is practical and workable for the case that, I made refactoring on a dir (removed it, and created a symlink with its name). Git couldn't tell what were my working copy changes.
yclian
This worked great. I wasn't able to apply a stash even though I'm pretty sure my working tree is clean.
Shiki
+9  A: 

When I have to apply stashed changes to a dirty working copy, e.g. pop more than one changeset from the stash, I use the following:

$ git stash show -p | git apply && git stash drop

Basically it creates a patch, pipes that to the apply command and if that succeeds without conflicts it drops the just applied stash item...

I wonder why there is no -f (force) option for git stash pop which should exactly behave like the one-liner above.

Mathias Leppich
+1 works great. Exactly the kind of behaviour I was looking for (some pop --force of sorts). I too wonder why it isn't there as an option.
lkraider
A: 

None of these answers actually work if you find yourself in this situation as I did today. Regardless of how many git reset --hard's I did, it got me nowhere. My answer (not official by any means was):

  1. Figure out the stash's hash use git reflog --all
  2. Merge that hash with the branch you're interested in
Yar