7

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?

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
  • For future reference, what you were trying to do can be done with `git stash`. Or, in most cases, you could just do the checkout while keeping the change in your work tree and/or index (and git would warn you if this was going to be a problem). – Mark Adelsberger Sep 07 '18 at 13:08

3 Answers3

7

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.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • When I look at `mypatch.diff` file I can see that the newly created file content is also there. – Jude Niroshan Sep 07 '18 at 11:39
  • @JudeNiroshan: Ah, but then it is probably not a new file. I mean the diff includes only a few changes in the file because that file already existed, but it does not exist in branch `y` so there is nowhere to apply those changes. – rodrigo Sep 07 '18 at 11:50
  • @JudeNiroshan: If that is the case, either you need to do `git diff `, being `` a commit before the file was created or just copy `ABC.txt` file manually. – rodrigo Sep 07 '18 at 11:52
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
KaseyMK
  • 23
  • 6
0

Try to use

$git am foo.patch

reference

Shao
  • 11
  • 5