timakro timakro - 12 days ago 5
Git Question

Prevent git apply from deleting old files

I have two files

a
and
b
, each containing their name. I create a patch like this:

git diff a b > test.patch


Now when applying the patch, file
a
is deleted:

git apply test.patch


Is there a way to prevent git from deleting the file when creating or applying the patch?

Answer

The syntax for your usage of git diff is

git diff [--no-index] <path> <path>

In your case, the --no-index is assumed implicitly. Therefore, the command

git diff a b

assumes that b is a newer version of the file a. Running your commands produces a patch that looks like this:

$ git diff --no-index 123.txt 456.txt
diff --git a/123.txt b/456.txt
index 97f93f4..9fa0bac 100644
--- a/123.txt
+++ b/456.txt
@@ -1 +1 @@
-123.txt
+456.txt

If you try to do this with more than 2 files, there is an error:

$ git diff -- 123.txt 456.txt 789.txt
Not a git repository
To compare two paths outside a working tree:
usage: git diff [--no-index] <path> <path>

$ git diff --no-index 123.txt 456.txt 789.txt
usage: git diff --no-index <path> <path>

One workaround (assuming you want to create a patch with both a and b added) would be to create a new git repo in a temporary directory. You can create an initial commit with no files using

git commit --allow-empty -m "Initial"

and copy the files a and b in.

After running git add --all, git diff --staged > test.patch will create a proper patch, like this:

diff --git a/123.txt b/123.txt
new file mode 100644
index 0000000..97f93f4
--- /dev/null
+++ b/123.txt
@@ -0,0 +1 @@
+123.txt
diff --git a/456.txt b/456.txt
new file mode 100644
index 0000000..9fa0bac
--- /dev/null
+++ b/456.txt
@@ -0,0 +1 @@
+456.txt
diff --git a/789.txt b/789.txt
new file mode 100644
index 0000000..a25ef22
--- /dev/null
+++ b/789.txt
@@ -0,0 +1 @@
+789.txt