咱们在开发中有时会遇到,须要将另一个分支局部批改同步到以后分支。
如下图,想把 devA 分支中 commit E 和 F,同步到上面绿色的 devB 分支中。

这时候就能够应用 git cherry-pick 来实现这项工作。
(cherry-pick 有筛选、精选的意思)

一、根本用法

转移单个提交

git cherry-pick <commitHash>
# 切换到 devB 分支$ git checkout devB# Cherry pick 操作$ git cherry-pick <HashE>

解决抵触后,commit 即可

二、转移多个提交

如果我有一堆间断的 commit 都想同步过来,那么能够用上面的语法:
上面的命令能够转移从 E 到 F 的所有 commit。 留神按程序写:提交 E 必须早于提交 F

git cherry-pick <HashE>..<HashF>

还要留神下面命令是左闭右开的,即不蕴含 commit_E,如果须要两边都包含,用上面的语法:

git cherry-pick <HashE>^..<HashF>

如果是离开的几个 commit,能够这样写:

git cherry-pick <HashE> <HashG>

三、参数

文档中是这样写的:

usage: git cherry-pick [<options>] <commit-ish>...   or: git cherry-pick <subcommand>    --quit                end revert or cherry-pick sequence    --continue            resume revert or cherry-pick sequence    --abort               cancel revert or cherry-pick sequence    --skip                skip current commit and continue    --cleanup <mode>      how to strip spaces and #comments from message    -n, --no-commit       don't automatically commit    -e, --edit            edit the commit message    -s, --signoff         add a Signed-off-by trailer    -m, --mainline <parent-number>                          select mainline parent    --rerere-autoupdate   update the index with reused conflict resolution if possible    --strategy <strategy>                          merge strategy    -X, --strategy-option <option>                          option for merge strategy    -S, --gpg-sign[=<key-id>]                          GPG sign commit    -x                    append commit name    --ff                  allow fast-forward    --allow-empty         preserve initially empty commits    --allow-empty-message                          allow commits with empty messages    --keep-redundant-commits                          keep redundant, empty commits

提几个会用失去的:
1)-n 如果你想转移多个 commit 并在新分支中只想有一个 commit,那就能够增加 -n 参数,不主动提交代码,都转移后一次性手动提交。(留神如果有 conflict 状况就不是很好用)(为了分辨是从其余分支转移过去的,能够新开一个分支同步这些 commit,而后再 merge 到指标分支)

    -n, --no-commit       don't automatically commit

2)-x 在提交信息的开端追加一行(cherry picked from commit ...),不便当前查到这个提交是如何产生的。

    -x                    append commit name

3)不倡议同步「合并(merge)节点」,失去的后果应该不是你想要的(有趣味能够本人尝试)。

四、代码抵触

1)--continue
同步代码不可避免遇到抵触状况,解决抵触后,将批改的文件重新加入暂存区 git add .,而后应用上面命令持续:

git cherry-pick --continue

2)--abort
处理过程中可能有误操作,那么能够放弃合并,回到操作前的样子。

git cherry-pick --abort

(3)--quit
产生代码抵触后,退出 cherry pick,然而不回到操作前的样子。

git cherry-pick --quit