Why does `git stash -p` sometimes fail?

This happens for me any time I try to split a hunk into smaller hunks that are too close together (less than 3 lines between changes). The short explanation is that the patch has context lines in it that conflict with your local changes. More complete explanation below.


Suppose I have a git repo with these uncommitted changes:

--- a/pangram
+++ b/pangram
@@ -1,8 +1,8 @@
 The
-quick
+relatively quick
 brown
 fox
-jumps
+walks
 over
 the
 lazy

If I stash the first change, I get:

--- a/pangram
+++ b/pangram
@@ -1,5 +1,5 @@
 The
-quick
+relatively quick
 brown
 fox
 jumps

The git stash command actually does succeed in saving the patch (check git stash list), but then git uses that patch in reverse to remove the stashed changes from my working dir. The context after the hunk has “jumps”, which doesn’t match the “walks” still in my working dir. So git bails out with

error: patch failed: pangram:1
error: pangram: patch does not apply
Cannot remove worktree changes

and leaves all the changes in my working dir, and the stash becomes pretty much worthless.


I would call this a bug in git’s hunk splitting support. If it knows it’s splitting the changes too close, it could shave off a few lines of context from the patch, or jimmy the patch to have the modified context lines instead of the pristine ones. Alternatively, if splitting hunks this close is officially unsupported, it should actually refuse to split hunks that close.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)