git合并一个或多个commit到另一个分支
2024/9/6...大约 2 分钟
git合并一个或多个commit到另一个分支
一个分支使用 git cherry-pick
要将一个分支上的一个 commit 应用与其他分支
基本用法
git cherry-pick
命令的作用,就是将指定的提交(commit)应用于其他分支。
git cherry-pick <commitHash>
上面命令就会将指定的提交commitHash
,应用于当前分支。这会在当前分支产生一个新的提交,当然它们的哈希值会不一样。
举例来说,代码仓库有master
和feature
两个分支。
a - b - c - d Master
\
e - f - g Feature
现在将提交f
应用到master
分支。
# 切换到 master 分支
$ git checkout master
# Cherry pick 操作
$ git cherry-pick f
上面的操作完成以后,代码库就变成了下面的样子。
a - b - c - d - f Master
\
e - f - g Feature
从上面可以看到,master
分支的末尾增加了一个提交f
。
git cherry-pick
命令的参数,不一定是提交的哈希值,分支名也是可以的,表示转移该分支的最新提交。
git cherry-pick feature
上面代码表示将feature
分支的最近一次提交,转移到当前分支。
合并某分支上的一些列commits
在一些特性情况下,合并单个commit并不够,你需要合并一系列相连的commits。这种情况下就不要选择cherry-pick了,rebase 更适合。使用 rebase 要谨慎,想好再使用。
因为 rebase 是变基,无法识别出历史记录
git checkout -b <newBranchName> <to-commit-id>
创建一个新的分支,指明新分支的最后一个commit
git rebase --onto <target base-commit> <commit from> [<commit to>]
变基这个新的分支到最终要合并到的分支,指明从哪个特定的commit开始
举例来说,代码仓库有master
和feature
两个分支。
a - b - c - d Master
\
e - f - g - h - i Feature
现在将提交f g
h应用到 master
分支。
# 切换到 Feature 分支
$ git checkout Feature
# 此时在 Feature_temp 分支,指明从 h commit开始
$ git rebase --onto d f^ h
上面的操作完成以后,代码库就变成了下面的样子。
a - b - c - d - f* - g* - h* Master
\
e - f - g - h - i Feature
再合并的过程中可能出现冲突,出现冲突,必须手动解决后,然后 运行git rebase --continue。
git rebase --onto
可以将 <commit from>
开始的一连串 commit 嫁接到另一个 commit (<target base-commit>
)上面。
其中:
<target base-commit>
: 作为基础的commit<commit from>
:要嫁接 commit 的起始点 (不包含此 commit)<commit to>
:要嫁接 commit 的终点(包含此commit),如果未给予,則预设为 branch 的最后一个 commit。