How to merge a specific commit in Git

后端 未结 7 1316
攒了一身酷
攒了一身酷 2020-11-22 01:41

I have forked a branch from a repository in GitHub and committed something specific to me. Now I found the original repository had a good feature which was at HEAD

相关标签:
7条回答
  • 2020-11-22 02:17

    I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

    One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

    Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

    The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

    The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

    Here is how that would be done:

    1. Find the common ancestor between the master and a-good-feature branches.
    2. Create a new branch from that ancestor, we'll call this new branch patch.
    3. Cherry pick one or more commits into this new patch branch.
    4. Merge the patch branch into both the master and a-good-feature branches.
    5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

    Here is an example of those commands:

    git checkout master...a-good-feature  [checkout the common ancestor]
    git checkout -b patch
    git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
    git checkout master
    git merge patch
    git checkout a-good-feature
    git merge -s ours patch
    

    It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

    The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

    0 讨论(0)
提交回复
热议问题