将另一个分支上的提交应用到工作副本中:git - 将另一个分支上的提交应用到工作副本中。

206

我有一个提交记录,其中包含一个有用的代码更改,但它位于另一个分支上。

我想将这个提交记录应用到我的当前分支的工作副本中(而不是作为另一个提交)。

这是否可行?我该如何做?

我想分享一下,这与我的先前问题有关,但是针对工作副本:

git cherry picking one commit to another branch

2个回答

334

如何将所需的提交添加到不同的分支中。

git cherry-pick <SHA-1>...<SHA-1> --no-commit

应用来自主分支顶端的提交引入的更改,并使用此更改创建新的提交。

...的语法是一个提交范围。抓取从起点(不包括)到最后一个提交的所有提交。如果您只想使用单个SHA-1提交,则只需使用一个SHA-1。

enter image description here


不进行提交的cherry-pick

默认情况下,git cherry-pick提交您的更改,因此如果您希望在不提交所有更改的情况下进行 cherry-pick,只需添加-n标志。

这将使您能够查看更改并手动提交它们(如果需要),或者如果遇到太多冲突,则中止该过程。

git cherry-pick -n <hash>

cherry-pick合并提交记录

如果您需要挑选合并而不是提交记录,请使用-m标志。

#
# In this case, we select the [1] first parent in the commit
# Use git show <hash> to see a list of available parents
# 
git cherry-pick -m 1 <hash> 

阅读完整的git cherry-pick文档,了解您可以使用的所有选项


9
谢谢!感谢您提供明晰且格式良好的文本以及精美的图表。如果您出版一本书,我会买的;-) - Spike0xff
2
问题明确提到“不是另一个提交”,而您的答案明确提到“创建一个新提交以进行此更改”。我错过了什么? - Armen Michaeli
6
你缺少了“--no commit”标志。 - CodeWizard
谢谢您的回答,但是您引用“[...] creates a new commit [...]”有些误导人,因为它出现在一个包含--no-commit命令的下面,该命令会阻止默认提交的发生。 - m7913d
1
这比官方文档好。谢谢! - TBirkulosis
显示剩余3条评论

47

您仍然可以使用 git cherry-pick 命令。请参见 git cherry-pick --help

   -n, --no-commit
       Usually the command automatically creates a sequence of
       commits. This flag applies the changes necessary to
       cherry-pick each named commit to your working tree and the
       index, without making any commit. In addition, when this
       option is used, your index does not have to match the HEAD
       commit. The cherry-pick is done against the beginning state
       of your index.

所以你可以只需输入git cherry-pick -n <commitid>,就可以将更改应用于您的工作目录并缓存到索引中(类似于git -a),但不会提交。


7
我之前选择了另一个答案,主要是因为其中包含了图表和额外的信息,不过你的回答也非常有帮助。谢谢! - Oliver Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接