Search code examples
gitgit-addgit-patch

"error: ... patch does not apply" when editing hunk with "git add -p"


tldr: why am I getting error: ... patch does not apply when editing a hunk and removing a line, even though it looks like it should work?

I'm editing a hunk while doing git add -p, where I want to only add new line 1 (and not add new line 2):

# Manual hunk edit mode -- see bottom for a quick guide
@@ -1 +1,3 @@
 first line
+new line 1
+new line 2
# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.

I changed the + to a space for new line 2:

# Manual hunk edit mode -- see bottom for a quick guide
@@ -1 +1,3 @@
 first line
+new line 1
 new line 2
# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.

but that gives the error:

error: patch failed: myfile:1
error: myfile: patch does not apply
Your edited hunk does not apply. Edit again (saying "no" discards!) [y/n]? 

What is the problem?


Solution

  • Delete the line instead.

    Changing the + to a space is not the correct action.
    Per the directions given by git (# To remove '+' lines, delete them. ), what is needed is to delete new line 2:

    # Manual hunk edit mode -- see bottom for a quick guide
    @@ -1 +1,3 @@
     first line
    +new line 1
    # (^^^ note that "new line 2" has been deleted ^^^)
    # ---
    # To remove '-' lines, make them ' ' lines (context).
    # To remove '+' lines, delete them.
    # Lines starting with # will be removed.