How can I selectively merge or pick changes from another branch in Git?

前端 未结 25 1945
慢半拍i
慢半拍i 2020-11-22 02:53

I\'m using Git on a new project that has two parallel -- but currently experimental -- development branches:

  • master: import of existing codebase pl
25条回答
  •  醉梦人生
    2020-11-22 03:15

    It's strange that Git still does not have such a convenient tool "out of the box".

    I use it heavily when updating some old version branch (which still has a lot of software users) by just some bugfixes from the current version branch. In this case, it is often needed to quickly get just some lines of code from the file in trunk, ignoring a lot of other changes (that are not supposed to go into the old version)...

    And of course interactive three-way merge is needed in this case. git checkout --patch is not usable for this selective merge purpose.

    You can do it easily:

    Just add this line to [alias] section in your global .gitconfig or local .git/config file:

    [alias]
        mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; /C/BCompare3/BCompare.exe $2.theirs $2 $2.base $2; rm -f $2.theirs; rm -f $2.base;' -"
    

    It implies you use Beyond Compare. Just change to the software of your choice if needed. Or you can change it to three-way auto-merge if you don't need the interactive selective merging:

    [alias]
        mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs; git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base; git merge-file $2 $2.base $2.theirs; rm -f $2.theirs; rm -f $2.base;' -"
    

    Then use it like this:

    git mergetool-file  
    

    This will give you the true selective tree-way merge opportunity of just any file in the other branch.

提交回复
热议问题