在 Github 会用到多分支开发代码,随着时间的推迟,两个分支的差距可能越来越大,这时候一个 commit 要提交多个分支会比较麻烦。下面介绍如何通过 git cherry pick 将一个 commit 提交到其他分支。
介绍
git cherry-pick 在 gerrit 中经常使用,能够自动获取一个提交的变动替代码(选出最佳代码)
使用
# 单个提交
git cherry-pick <commitHash>
# 两个提交
git cherry-pick <HashA> <HashB>
# 多个提交,从 A 到 B 的所有提交
git cherry-pick A..B
# 从 A (不包括A)到 B 的所有提交
git cherry-pick A^..B
Demo
假如一个项目两个分支,分别是 main 和 feature_xxx,假如我们在 feature_xxx 中有一个提交:
commit da286e72e88cba9e599420b9cf3c17447abb43dd
Author: xiexianbin <me@xiexianbin.cn>
Date: Sat Aug 28 06:42:49 2021 +0800
minor: page opti
需要 merge 到 main 分支,但在 github 页面提交 pr 时发现有数十个 commit 会同时提交过去,我们可以通过 git cherry-pick check 出指定的 commit:
# 切换到指定分支,并查看日志
$ git checkout main
$ git log
commit 281567be9e4c4dfc056916eb73814c441b238781 (HEAD -> main, origin/main, origin/HEAD)
Author: xiexianbin <me@xiexianbin.cn>
Date: Sat Sep 11 10:06:25 2021 +0800
feature: xxx
# check 指定 commit 代码
$ git cherry-pick da286e72e88cba9e599420b9cf3c17447abb43dd
# 查看 da286e72e88cba9e599420b9cf3c17447abb43dd 修改的内容
$ git diff 281567be9e4c4dfc056916eb73814c441b238781
# 提交
git push
pr 方式提交
如果需要通过 br 方式提交,我们可以基于 main 新建一个分支,然后 cherry-pick 代码,提交后再在 github 页面提交:
# 新建分支
git checkout main
git checkout -b patch1
# check 指定 commit 代码,并 push
git cherry-pick da286e72e88cba9e599420b9cf3c17447abb43dd
git push origin patch1
# 删除本地分支
git checkout main
git branch -D patch1