如何创建仅包含另一分支部分提交的新Git分支?
从Git分支挑选部分提交创建Pull Request分支
你需要从feature分支中选择部分提交,基于main创建新分支来发起Pull Request,以下是几种可行的方案:
方案1:交互式Cherry-Pick(推荐)
这是最安全直观的方式,无需修改原feature分支的历史:
- 基于
main创建用于PR的新分支:git checkout main git checkout -b pr-branch - 启动交互式Cherry-Pick,选择
feature相对于main的提交:git cherry-pick -x main..feature-x参数会在提交信息末尾添加(cherry picked from commit xxx),方便后续溯源原提交- 打开的编辑器中,将不需要的提交前的
pick改为skip,保存退出后,pr-branch就只会包含你选中的提交
方案2:交互式Rebase(正确用法)
你之前的Rebase操作错误在于直接修改了原feature分支,正确做法是在新分支上执行Rebase,保留原分支完整历史:
- 基于
feature创建PR分支:git checkout feature git checkout -b pr-branch - 以
main为基准,交互式重写PR分支的历史:git rebase -i main- 在编辑器中,删除不需要的提交行,或者将对应行的
pick改为drop(丢弃该提交) - 保存退出后,
pr-branch就仅包含你选中的提交,原feature分支完全不受影响
- 在编辑器中,删除不需要的提交行,或者将对应行的
针对你复现示例的正确操作演示
git init git commit --allow-empty -m 'First commit, only commit on main' git checkout -b feature git commit --allow-empty -m 'One' git commit --allow-empty -m 'Two' git commit --allow-empty -m 'Three' # 创建PR分支 git checkout feature git checkout -b pr-branch # 交互式Rebase到main,只保留Two提交 git rebase -i main # 编辑器中仅保留 `pick e639db2 Two` 这一行,删除其他行后保存 # 查看PR分支历史,仅包含目标提交 git log --oneline pr-branch # 输出: # 1dce690 (HEAD -> pr-branch) Two # 909d7e2 (main) First commit, only commit on main # 原feature分支历史完全不变 git log --oneline feature # 输出: # 85beaf4 (feature) Three # e639db2 Two # 156abe2 One # 909d7e2 (main) First commit, only commit on main
方案3:临时暂存+选择性提交(适用于未提交修改)
如果你的修改尚未提交,可以通过暂存部分内容来创建目标提交:
git add -p # 交互式选择要暂存的代码块 git commit -m "提交信息"
再基于这些提交创建PR分支即可,但此方案不适用于你已完成提交的场景。
你之前Rebase操作的问题分析
你直接在feature分支上执行git rebase -i pr(pr是main的分支),相当于将feature的历史完全重写到pr的基准上,编辑器中删除的提交会从feature分支中被丢弃——这就是为什么你需要通过reflog找回提交的原因。Rebase始终会修改当前分支的历史,因此必须在新分支上操作,避免破坏原开发分支。
内容的提问来源于stack exchange,提问作者user3310334
相关产品推荐
相关产品推荐

