cherry-pick

在正常迭代中或多或少遇到过需要将当前迭代的某一功能提前发布的需求(点名批评产品~),要是按功能建的分支的话直接 merge 或 rebase 就可以了,若分支管理不规范或者真的只需要当前分支的部分代码时 cherry-pick 就派上用场了

cherry-pick usage

git cherry-pick

将指定的 commit 应用于当前分支,并在当前分支产生新的 commit 且生成新的 commit hash

Eg:

代码仓库模型:master 和 feature

a - b - c - d   Master
\
e - f - g Feature

现在将 Feature 分支的 commit f 提取到 master 分支

git cherry-pick f

Result:

a - b - c - d - f   Master
\
e - f - g Feature

如何在 Master 分支拿到 Feature 分支的 commitHash 呢?小 Tips:

# target 一般为 origin
git log target/Feature

git cherry-pick

提取 Feature 分支的最近一次 commit 到当前分支

git cherry-pick feature

一次提取多个 commit

git cherry-pick <HashA> <HashB>

从其他分支提取 A 和 B 两个 commit,应用到当前分支并生成两个对应的新提交。

转移连续多个提交

git cherry-pick A..B 

上面的命令可以转移 A(不包含)到 B 的所有提交。若 commit 的顺序不为有序则 pick 失败

包含A

git cherry-pick A^..B 

webStorm - 2022.3 EAP with newUI

找到 Feature 分支需要的 commit 复制 Hash 值,再右键 cherry-pick 即可

shift 选择多个分支(所选即所得)

其他配置项

git cherry-pick命令的常用配置项如下。

  • -e--edit
    打开外部编辑器,编辑提交信息
  • -n--no-commit
    不产生新的提交,只更新工作区和暂存区
  • -x
    在提交信息的末尾追加一行(cherry picked from commit ...),方便以后查到这个提交是如何产生的
  • -s--signoff
    在提交信息的末尾追加一行操作者的签名,表示是谁进行了这个操作。
  • -m parent-number--mainline parent-number
    如果原始提交是一个合并节点,来自于两个分支的合并,那么 Cherry pick 默认将失败,因为它不知道应该采用哪个分支的代码变动。
    -m配置项告诉 Git,应该采用哪个分支的变动。它的参数parent-number是一个从1开始的整数,代表原始提交的父分支编号。
git cherry-pick -m 1 <commitHash>

git cherry-pick 教程