'Applying patch doesn't create newly created files in Git

I have created a new file called ABC.txt in branch x. I didn't commit the changes.

Then I wanted to move these changes into a new branch called y. So I followed these steps:

  1. $ git diff > mypatch.diff

  2. $ git clean -fd

  3. $ git checkout y

  4. $ git apply myPatch.diff error: ABC.txt: No such file or directory

Why git can't simply create my new ABC.txt file in the current branch I'm in?



Solution 1:[1]

That is because git diff only lists changes of files that are part of the repository, and your newly created file is not.

The easiest solution is to add the file to the index:

$ git add ABC.txt

And then use the --cached option when creating the patch:

$ git diff --cached > mypatch.diff

However if the error happens when you apply the diff, it may be caused because the file does not exist in the target branch, so git does not know where to apply those changes.

You can see if the diff file contains changes to an formerly existing file, or a newly created file, by looking at the chunk header:

If you see:

--- a/ABC.txt
+++ b/ABC.txt

Then there are changes to an existing file. Applying this patch will not create a new file from void.

But if you see:

--- /dev/null
+++ b/ABC.txt

Then it is a newly created file and applying this patch will create a new file with these contents.

Solution 2:[2]

When I followed these steps:

git add ABC.txt
git diff --cached > mypatch.diff

mypatch.diff contained my new files, but none of my edited files.

Here's what worked for me:

git add -N ABC.txt
git diff > mypatch.diff

Solution 3:[3]

Try to use

$git am foo.patch

reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 KaseyMK
Solution 3 Shao