Git:将提交的一部分应用到另一个分支

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6618730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 05:39:42  来源:igfitidea点击:

Git: Apply part of a commit to another branch

git

提问by Abhi

How can I apply partof a commit from one branch to another? I understand that I can cherry-pick a commit, but I need to go one step further and "cherry pick" some of the changes introduced by that commit and apply them to another (target) branch.

如何将一部分提交从一个分支应用到另一个分支?我知道我可以挑选提交,但我需要更进一步,“挑选”该提交引入的一些更改并将它们应用到另一个(目标)分支。

Is there a clean way to do this, or should I just apply the entire commit, manually undo some hunks, and remember to create more atomic commits in the future?

有没有一种干净的方法来做到这一点,或者我应该只应用整个提交,手动撤消一些大块头,并记住将来创建更多的原子提交?

回答by dahlbyk

git cherry-pick -n <SHA>will stage the changes but not commit them. You can then use git reset -pto unstage the bits you don't want, or git reset HEADand git add -Apto stage only the changes you want.

git cherry-pick -n <SHA>将暂存更改但不提交它们。然后,您可以使用git reset -p到unstage你不想要,还是位git reset HEADgit add -Ap台数只有你想要的变化。

回答by Alex

If the parts you want to apply can be specified by path (i.e., you do not wish to specify hunks within one file) another solution is possible.

如果可以通过路径指定要应用的部分(即,您不希望在一个文件中指定大块),则可以使用另一种解决方案。

One approach is to form a patch from the commit, and apply it to your branch.

一种方法是从提交中形成补丁,并将其应用到您的分支。

With the branch you wish to modify checked out:

签出您要修改的分支:

git show <SHA> -- <relevant paths> | git apply

Will apply any changes in commit SHA, in paths relevant pathsto your current working copy.

将在relevant paths当前工作副本的路径中应用提交 SHA 中的任何更改。