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

时间:2014-09-30 01:07:46

标签: git patch

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

  1. 我创建了一个新的git项目,包含两个文件:first.txtsecond.txt
  2. 我创建了一个分支
  3. 在这个新分支中,我修改了两个文件的内容并提交
  4. 我将文件second.txt移至folder\second_moved.txt并提交
  5. 现在我使用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.txtgit apply已正确修改了这两个文件的内容。

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

1 个答案:

答案 0 :(得分:4)

尝试使用

git am changes.patch

而不是git apply

从手册页&#34;使用git-am(1)从git-format-patch(1)&#34;

生成的补丁创建提交

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