【问题标题】:How to properly apply a patch with moved/renamed files using Git如何使用 Git 正确应用带有移动/重命名文件的补丁
【发布时间】:2014-09-30 01:07:45
【问题描述】:

我正在尝试使用 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 apply正确修改了。

由于我希望使用 git 生成补丁并将补丁应用于将在很大程度上重构的代码分支,因此我无法手动跟踪和删除所有已更改、然后移动或重命名的文件。我怎样才能避免这种情况?

【问题讨论】:

    标签: git patch


    【解决方案1】:

    尝试使用

    git am changes.patch
    

    而不是git apply

    来自手册页“使用 git-am(1) 从 git-format-patch(1) 生成的补丁创建提交”

    在 Git 2.1.1 上测试。我看到你得到相同的应用行为,但工作正常。

    【讨论】:

    • 同意。而git apply 可以应用git diff 或shell 命令diff 创建的补丁。 git am在场景下使用git apply,但它的作用更多。
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多