1. 程式人生 > >Git小技巧:如何從其他分支merge個別檔案

Git小技巧:如何從其他分支merge個別檔案

如何從其他分支merge個別檔案,git checkout是合適的工具。

git checkout source_branch <path>...
我們使用git checkout將其他分支的個別檔案新增到master分支
$ git branch
* master
  twitter_integration
$ git checkout twitter_integration app/models/avatar.rb db/migrate/20090223104419_create_avatars.rb test/unit/models/avatar_test.rb test/functional/models/avatar_test.rb
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   app/models/avatar.rb
#   new file:   db/migrate/20090223104419_create_avatars.rb
#   new file:   test/functional/models/avatar_test.rb
#   new file:   test/unit/models/avatar_test.rb
#
$ git commit -m "'Merge' avatar code from 'twitter_integration' branch"
[master]: created 4d3e37b: "'Merge' avatar code from 'twitter_integration' branch"
4 files changed, 72 insertions(+), 0 deletions(-)
create mode 100644 app/models/avatar.rb
create mode 100644 db/migrate/20090223104419_create_avatars.rb
create mode 100644 test/functional/models/avatar_test.rb
create mode 100644 test/unit/models/avatar_test.rb

翻譯自:http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/

2015.11.05更新

注意:在使用git checkout某檔案到當前分支時,會將當前分支的對應檔案強行覆蓋。

如果不確定新檔案是否能完全覆蓋master中的舊檔案,可以新建一個master分支mastertmp,將變化的檔案checkout到mastertmp,然後讓master與mastertmp進行合併。