You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将仓库中指定范围的Commit迁移至新仓库?

提取指定范围提交到新仓库的操作步骤

针对需要从旧仓库oldRepo(提交链:A-B-C-D-E-F-G-H-I)提取B-C-D-E-F到新仓库newRepo的需求,以下是两种可靠的操作方法:

方法一:使用 git cherry-pick 直接提取提交

这种方法简单直观,适合快速提取指定范围的提交:

    1. 创建并初始化新仓库
mkdir newRepo && cd newRepo
git init
    1. 关联旧仓库并拉取所有提交历史
# 替换为旧仓库的本地路径或远程URL
git remote add oldrepo /path/to/your/oldRepo
git fetch oldrepo
    1. 提取目标提交范围
      假设B的提交哈希为<commit-B>,F的提交哈希为<commit-F>,执行:
# 提取包含B到F的所有提交
git cherry-pick <commit-B>^..<commit-F>

说明:<commit-B>^指向B的父提交A,这个范围表示提取A之后到F的所有提交,正好覆盖B、C、D、E、F。如果只需要从C到F,去掉^即可。

    1. (可选)推送到远程新仓库
git remote add origin /path/to/your/newRepo-remote
git push -u origin main

方法二:使用 git rebase --onto 重构提交历史

如果之前用rebase报错,大概率是命令参数有误,以下是正确的重构步骤:

    1. 在旧仓库创建临时分支指向F提交
cd /path/to/your/oldRepo
git checkout -b temp-branch <commit-F>
    1. 剥离A提交的历史,重构B-F为独立提交链
git rebase --onto --root <commit-B>^

说明:--root表示将提交链重构为无父提交的根节点,<commit-B>^指定以A为分界点,最终得到的临时分支只包含B到F的提交,且无A的历史。

    1. 将重构后的分支同步到新仓库
cd /path/to/newRepo
# 拉取临时分支内容到新仓库的主分支
git pull /path/to/your/oldRepo temp-branch:main

冲突处理说明

无论使用哪种方法,若遇到提交冲突:

  1. 手动修改冲突文件,解决后执行git add <冲突文件>
  2. 继续执行操作:
    • cherry-pick冲突:git cherry-pick --continue
    • rebase冲突:git rebase --continue
  3. 若需跳过冲突提交:git cherry-pick --skip 或 git rebase --skip
  4. 放弃操作回到初始状态:git cherry-pick --abort 或 git rebase --abort

内容的提问来源于stack exchange,提问作者MobxLimited

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 02:50:41