如何将Git仓库指定目录迁移/复制/同步到新仓库并保留提交历史
方案说明
所有方案均使用Git原生功能实现,无需编写自定义脚本,可完整保留目标目录的提交历史。
场景1:剪切迁移(将目标目录从原仓库删除,完全移动到新仓库)
操作步骤:
- 克隆原仓库到本地:
git clone https://github.com/username/existing_repo.git - 进入本地仓库目录:
cd existing_repo - 提取目标目录的提交历史,并调整路径到根目录:
git filter-repo --path blah1/blah2/DirectoryOfInterest/ --path-rename blah1/blah2/DirectoryOfInterest/:DirectoryOfInterest/
提示:如果执行
git filter-repo提示命令不存在,可通过包管理器安装:Ubuntu/Debian执行sudo apt install git-filter-repo,Mac执行brew install git-filter-repo,Windows最新版Git for Windows已默认自带
- 绑定新仓库的远程地址:
git remote add new-origin https://github.com/username/new_repo.git - 推送到新仓库(如果你的默认分支是master,把main替换为master即可):
git push new-origin main - 回到原仓库的完整本地备份目录,删除目标目录并提交变更:
git rm -r blah1/blah2/DirectoryOfInterestgit commit -m "迁移DirectoryOfInterest到独立新仓库"git push origin main
场景2:独立复制(两个仓库的目标目录后续无需同步,各自独立更新)
操作步骤和场景1基本一致,仅需要注意操作时不要修改原仓库的本地拷贝即可:
- 新建临时文件夹,克隆原仓库到临时目录:
git clone https://github.com/username/existing_repo.git temp_repo - 进入临时目录:
cd temp_repo - 提取目标目录的提交历史并调整路径:
git filter-repo --path blah1/blah2/DirectoryOfInterest/ --path-rename blah1/blah2/DirectoryOfInterest/:DirectoryOfInterest/ - 绑定新仓库远程地址并推送:
git remote add new-origin https://github.com/username/new_repo.gitgit push new-origin main - 操作完成后删除临时目录即可,原仓库不受任何影响,两个仓库后续的更新完全独立。
场景3:双向同步(两个仓库的目标目录可实时同步更新)
使用Git原生子模块功能实现,无需手动来回拷贝文件:
- 先按照场景2的步骤,将目标目录的内容推送到new_repo中,确保new_repo根目录就是DirectoryOfInterest的内容。
- 回到原仓库的本地目录,删除原有的目标目录:
git rm -r blah1/blah2/DirectoryOfInterest - 将新仓库添加为原仓库的子模块,路径对应原目录的位置:
git submodule add https://github.com/username/new_repo.git blah1/blah2/DirectoryOfInterest - 提交变更到原仓库:
git commit -m "将DirectoryOfInterest替换为独立仓库子模块"git push origin main
同步操作方法:
- 新仓库更新后,在原仓库目录执行
git submodule update --remote即可拉取最新内容到原仓库对应目录 - 在原仓库的目标目录中修改内容后,直接在该目录内执行commit、push操作,就会直接提交到新仓库,其他使用原仓库的用户更新子模块即可拿到最新修改
内容的提问来源于stack exchange,提问作者BadmanSkinny
相关产品推荐
相关产品推荐

