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

前端 未结 25 1574
慢半拍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:25

    Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.

    First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:

    git merge --no-ff --no-commit -s ours branchname1
    

    ... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.

    git checkout branchname1 -- file1 file2 etc.
    

    If you were merging from more than one other branch, repeat as needed.

    git checkout branchname2 -- file3 file4 etc.
    

    Now the files from the other branch are in the index, ready to be committed, with history.

    git commit
    

    And you'll have a lot of explaining to do in that commit message.

    Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.

提交回复
热议问题