【问题标题】:Prevent git apply from deleting old files防止 git apply 删除旧文件
【发布时间】:2016-11-24 21:11:59
【问题描述】:

我有两个文件 ab,每个文件都包含它们的名称。我创建了一个这样的补丁:

git diff a b > test.patch

现在在应用补丁时,文件a被删除:

git apply test.patch

有没有办法防止git在创建或应用补丁时删除文件?

【问题讨论】:

  • 打补丁前后git status的输出是什么?
  • @rlee827 我不在存储库中这样做。

标签: git diff patch


【解决方案1】:

git diff 用法的语法是

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

在您的情况下,--no-index 是隐式假定的。因此,命令

git diff a b

假设b 是文件a 的更新版本。运行您的命令会生成一个如下所示的补丁:

$ 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

如果您尝试对超过 2 个文件执行此操作,则会出现错误:

$ 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>

一种解决方法(假设您要创建一个同时添加了ab 的补丁)是在一个临时目录中创建一个新的git repo。您可以使用

创建一个没有文件的初始提交
git commit --allow-empty -m "Initial"

并将文件ab 复制到。

运行git add --all 后,git diff --staged &gt; test.patch 将创建一个适当的补丁,如下所示:

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

【讨论】:

  • 这似乎是我的具体问题的正确答案,尽管未来的访问者应该考虑使用 git diff a b 创建补丁,但使用普通补丁工具来应用它:patch -p1 -f --dry-run &lt; test.patch &amp;&amp; patch -p1 -f &lt; test.patch
猜你喜欢
  • 2019-08-14
  • 2013-06-05
  • 2017-08-13
  • 2016-10-22
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
相关资源
最近更新 更多