Undo git stash pop that results in merge conflict

GitGit Stash

Git Problem Overview


I began making changes to my codebase, not realizing I was on an old topic branch. To transfer them, I wanted to stash them and then apply them to a new branch off of master. I used git stash pop to transfer work-in-progress changes to this new branch, forgetting that I hadn't pulled new changes into master before creating the new branch. This resulted in a bunch of merge conflicts and loss of a clean stash of my changes (since I used pop).

Once I recreate the new branch correctly, how I can I recover my stashed changes to apply them properly?

Git Solutions


Solution 1 - Git

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

Solution 2 - Git

Luckily git stash pop does not change the stash in the case of a conflict!

So nothing, to worry about, just clean up your code and try it again.

Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop again and you get the same stash, that conflicted before.

Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.

Solution 3 - Git

git reset --merge


Simplest command & works everywhere incl. git stash pop.

Careful! You'll lose all changes on untracked files.

Solution 4 - Git

Instructions here are a little complicated so I'm going to offer something more straightforward:

  1. git reset HEAD --hard Abandon all changes to the current branch

  2. ... Perform intermediary work as necessary

  3. git stash pop Re-pop the stash again at a later date when you're ready

Solution 5 - Git

git checkout -f

must work, if your previous state is clean.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionacjayView Question on Stackoverflow
Solution 1 - GitacjayView Answer on Stackoverflow
Solution 2 - GitfloriView Answer on Stackoverflow
Solution 3 - GitGabriel PeterssonView Answer on Stackoverflow
Solution 4 - GitfIwJlxSzApHEZIlView Answer on Stackoverflow
Solution 5 - GitAllahbakash.GView Answer on Stackoverflow