How to merge a specific commit in Git

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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.

I want to merge it only without previous commits. What I should do? I have known how to merge all commits:

git branch -b a-good-feature git pull repository master git checkout master git merge a-good-feature git commit -a git push 

回答1:

'git cherry-pick' should be your answer here.

Apply the change introduced by an existing commit.

Do not forget to read bdonlan's answer about the consequence of cherry-picking in this post:
"Pull all commits from a branch, push specified commits to another", where:

A-----B------C  \   \    D 

becomes:

A-----B------C  \   \    D-----C' 

The problem with this commits is that git considers commits to include all history before them

Where C' has a different SHA-1 ID.
Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.

This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).
More importantly though, it ignores functional dependencies - if C actually used a function defined in B, you'll never know.



回答2:

You can use git cherry-pick to apply a single commit by itself to your current branch.

Example: git cherry-pick d42c389f



回答3:

Let's try to take an example and understand:

I have a branch, say master, pointing to X , and I have a new branch pointing to Y .

Where Y = branch commits - few commits

Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:

Step 1:

git checkout -b local origin/new 

where local is the branch name. Any name can be given.

Step 2:

  git merge origin/master --no-ff --stat -v --log=300 

Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most actual commits that are being merged.

For more information and parameters about Git merge, please refer to:

git merge --help 

Also if you need to merge a specific commit, then you can use:

git cherry-pick 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!