如何使用Git正确应用移动/重命名文件的补丁

11

我正在尝试使用Git正确创建和应用补丁:

  1. 我创建了一个新的Git项目,其中包含两个文件:first.txtsecond.txt
  2. 我创建了一个分支
  3. 在这个新的分支中,我修改了两个文件的内容并进行了提交
  4. 我将文件second.txt移动到folder\second_moved.txt并提交

现在我使用git format-patch master --stdout > changes.patch创建了一个补丁。

这是changes.patch的内容:

From cb2a85ff9a0bc36d4f04fbe72068ae9ec3a9bcb0 Mon Sep 17 00:00:00 2001
From: 
Date: Mon, 29 Sep 2014 20:46:18 -0400
Subject: [PATCH 1/2] changes

---
 fist.txt   | 2 +-
 second.txt | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/fist.txt b/fist.txt
index d4b4f36..b5d9ba4 100644
--- a/fist.txt
+++ b/fist.txt
@@ -1 +1 @@
-first file
\ No newline at end of file
+first file foobar
\ No newline at end of file
diff --git a/second.txt b/second.txt
index 0f8bbfe..54e687e 100644
--- a/second.txt
+++ b/second.txt
@@ -1 +1 @@
-second file
\ No newline at end of file
+second file barfoo
\ No newline at end of file
-- 
1.8.4.msysgit.0


From 09c868828cf30fba36ba04cbd476dfcb0f68f79c Mon Sep 17 00:00:00 2001
From: 
Date: Mon, 29 Sep 2014 20:47:15 -0400
Subject: [PATCH 2/2] moved

---
 folder/second_moved.txt | 1 +
 second.txt              | 1 -
 2 files changed, 1 insertion(+), 1 deletion(-)
 create mode 100644 folder/second_moved.txt
 delete mode 100644 second.txt

diff --git a/folder/second_moved.txt b/folder/second_moved.txt
new file mode 100644
index 0000000..54e687e
--- /dev/null
+++ b/folder/second_moved.txt
@@ -0,0 +1 @@
+second file barfoo
\ No newline at end of file
diff --git a/second.txt b/second.txt
deleted file mode 100644
index 54e687e..0000000
--- a/second.txt
+++ /dev/null
@@ -1 +0,0 @@
-second file barfoo
\ No newline at end of file
-- 
1.8.4.msysgit.0

现在,我回到我的主分支,并使用 git apply changes.patch 命令应用补丁。没有错误。

下面是 git status 命令的结果:

# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   fist.txt
#       modified:   second.txt
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       changes.patch
#       folder/
no changes added to commit (use "git add" and/or "git commit -a")

如您所见,我仍然拥有文件second.txt。我并不希望这样,因为它已经被移动到了folder中。在folder中,我实际上得到了文件second_moved.txt。这两个文件的内容都已经被正确地修改了。

由于我期望使用git生成和应用补丁到将会被大规模重构的代码分支中,我无法手动跟踪和删除所有已更改、移动或重命名的文件。那么,我该如何避免这种情况呢?

1个回答

8

尝试使用

git am changes.patch

使用git-am(1)代替git apply来创建由git-format-patch(1)生成的补丁文件。

根据Git 2.1.1版本测试,我看到了与你相同的应用程序行为,但am的工作正常。


1
同意。而且 git apply 可以应用使用 git diff 或 shell 命令 diff 创建的补丁。git am 在幕后使用 git apply,但它做得更多。 - Landys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接