6. 如何使用git挑选其它分支上面的commit?--"git cherry-pick"

作者:jicanmeng

时间:2015年03月19日


<<git权威指南>>上面是这样描述"git cherry-pick"命令的:

拣选指令----git cherry-pick,其含义是从众多的提交中挑选出一个提交应用在当前的工作分支中。该命令需要提供一个提交ID作为参数,操作过程相当于将该提交导出为补丁文件,然后在当前HEAD上重放,形成无论内容还是提交说明都一致的提交。

看下面一个例子:将master分支上面的两次提交使用"cherry-pick"命令应用到bugFix分支上面。

[jicanmeng@andy git-patch]$ git branch
			* bugFix
			  master
			[jicanmeng@andy git-patch]$ git log master --oneline
				ca1f1f3 3 master
				b0d7869 2 master
				0a2109f 1 master
				5c47112 initial commit
			[jicanmeng@andy git-patch]$ git log bugFix --oneline
				5c47112 initial commit
			[jicanmeng@andy git-patch]$ git cherry-pick 0a2109f
				Finished one cherry-pick.
				[bugFix bfba5f2] 1 master
				 1 files changed, 1 insertions(+), 0 deletions(-)
			[jicanmeng@andy git-patch]$ git log --oneline
				bfba5f2 1 master
				5c47112 initial commit
			[jicanmeng@andy git-patch]$ git cherry-pick ca1f1f3
				Automatic cherry-pick failed.  After resolving the conflicts,
				mark the corrected paths with 'git add <paths>' or 'git rm <paths>'
				and commit the result with:

				         git commit -c ca1f1f3

			[jicanmeng@andy git-patch]$ git status
				# On branch bugFix
				# Unmerged paths:
				#    (use "git reset HEAD ..." to unstage)
				#    (use "git add/rm ..." as appropriate to mark resolution)
				#
				#    both modified:      a.c
				#
				no changes added to commit (use "git add" and/or "git commit -a")
			[jicanmeng@andy git-patch]$ vim a.c
			[jicanmeng@andy git-patch]$ git add a.c
				bfba5f2 1 master
				5c47112 initial commit
			[jicanmeng@andy git-patch]$ git commit -c ca1f1f3
				[bugFix 804c79e] 3 master
				 1 files changed, 2 insertions(+), 0 deletions(-)
			[jicanmeng@andy git-patch]$ git log --oneline
				804c79e 3 master
				bfba5f2 1 master
				5c47112 initial commit
			[jicanmeng@andy git-patch]$ 

第一次执行"cherry-pick"命令后,命令执行成功,会在当前分支中生成一个新的提交。第二次执行"cherry-pick"命令后,命令执行失败,需要我们手动进行冲突文件的合并,然后再添加到暂存区,再提交到git库中。

参考资料

  1. git权威指南