git-apply fails mysteriously, how do I troubleshoot/fix?
Try to check against your patch file - example :
git apply --reject mypatch.patch
this will show you differences if any - here is an example of how it could look like :
error: patch failed: <filename>:<linenumber>
error: while searching for :
cout << "}" << endl; // example of a line in your patch
Update:
You can use git apply -v
to see more detailed info about what's going on, git apply --check
to just verify the operation, or git apply --index
to rebuild the local index file.
Based on your comment, it seems your local index was corrupted, and so index
solved it.
I will leave my original answer and the comments mostly to give people context on what was going on, as I suspect other people would jump to the same initial conclusions I had based on the problem description.
------
Most likely nothing's wrong with the diff. Instead look at the target git repository. While you are doing git reset --hard HEAD
, nothing guarantees you that the HEAD
on that other repository is the same as the HEAD
on your.
Do git log
on the target repo and look at the commit at the top. Is it the same as the one you produced the diff from? Most likely it is not. Look down the history and check if the commit you need is there. If it is, then the target repo is ahead of yours, and you have to go back, do git pull
(or git rebase
) and produce a new diff. If it isn't, then the target repo is behind yours, and you need to do git pull
(or git rebase
) on the target repo to bring it up to speed.
Keep in mind that if you have other people committing to your "master" repo (the one where bot yours and the target repositories are pulling from), you might have to git pull
both repositories, to get them to a reasonably recent common commit.
In such cases, if you already tried all options listed below:
- Investigating potential non-printable/invisible characters in file
- Using
dos2unix
for conversion - changing the git config to adjust the way of handling line endings for eg:
git config --global core.autocrlf input
Another root of evil in such cases could be your IDE.
For example, some of the JetBrains IDEs like PHPStorm has following option:
After spending more than 4 bloody hours today on a weird patching issue ending up with following error:
git apply < my.git.patch --verbose
...
error: patch failed: plugins/some/file.php:74
I realized that I was victim of my editor (I am not sure if this was the default behavior).
I was using PHPStorm to check the patch file and it was silently removing a single whitespace from the patch file which literally exist on the target file that needs to be patched.
This was super sneaky and I ended up with setting Strip trailing spaces on Save for
option to None
to never hit such issue again.
Also keep in mind that platform related differences like case-sensitivity of the underlying filesystem (MacOS/Linux for eg) may also be the suspect.