将大仓库拆分为多个小仓库

如何使用 Git 拆库(将大仓库拆分为多个小仓库)

拆库是将一个大型 Git 仓库拆分成多个独立仓库的过程,通常用于提高团队协作效率、简化权限管理或分离不相关的项目。以下是几种常用的拆库方法:


方法一:使用 git filter-repo(推荐)

git filter-repo 是官方推荐的替代 git filter-branch 的工具,性能更好且更安全。

步骤

  1. 安装 git-filter-repo

    复制代码
    # 方法1:使用 pip 安装(推荐)
    pip install git-filter-repo
    
    # 方法2:手动下载
    # 从 https://github.com/newren/git-filter-repo 下载并安装
    复制代码
  2. 克隆原仓库(避免直接操作原仓库)

    复制代码
    git clone /path/to/original-repo new-repo
    cd new-repo
    复制代码
  3. 拆分子目录为独立仓库

    复制代码
    git filter-repo --path path/to/subdirectory/ --path-rename path/to/subdirectory/:
    • --path:指定要拆分的子目录
    • --path-rename:可选,用于重命名路径(如移除前缀)
  4. 推送新仓库

    复制代码
    git remote add origin https://github.com/your-username/new-repo.git
    git push -u origin main  # 或 master,取决于你的分支名
    复制代码

方法二:使用 git subtree split

适用于需要保留部分历史记录的场景。

步骤

  1. 在原仓库中创建临时分支

    复制代码
    git clone /path/to/original-repo
    cd original-repo
    git subtree split -P path/to/subdirectory/ -b split-branch
    • -P:指定要拆分的子目录
    • -b:创建临时分支
  2. 创建新仓库并推送

    复制代码
    mkdir new-repo
    cd new-repo
    git init
    git pull /path/to/original-repo split-branch
    git remote add origin https://github.com/your-username/new-repo.git
    git push -u origin main
    复制代码

方法三:手动拆分(适用于简单场景)

如果历史记录不重要,可以手动复制文件并初始化新仓库。

步骤

  1. 创建新文件夹

    复制代码
    mkdir new-repo
    cd new-repo
    git init
    复制代码
  2. 从原仓库复制文件

    复制代码
    cp -r /path/to/original-repo/path/to/subdirectory/* .
    复制代码
  3. 提交并推送

    复制代码
    git add .
    git commit -m "Initial commit from split"
    git remote add origin https://github.com/your-username/new-repo.git
    git push -u origin main
    复制代码

拆分后的处理

1. 更新原仓库(可选)

如果希望原仓库引用新拆分的仓库,可以使用 子模块(Submodule)子树(Subtree)

复制代码
# 使用子模块
git rm -r path/to/subdirectory/
git commit -m "Remove split-out subdirectory"
git submodule add https://github.com/your-username/new-repo.git path/to/subdirectory/
git commit -m "Add new-repo as submodule"

# 使用子树(更推荐)
git remote add new-repo https://github.com/your-username/new-repo.git
git fetch new-repo
git subtree add --prefix=path/to/subdirectory/ new-repo main --squash

2. 处理历史记录

  • git filter-repo 会保留完整历史记录(仅针对拆分的文件)。
  • 如果原仓库有大量无关历史,拆分后新仓库会更干净。

注意事项

  1. 备份原仓库:拆分操作会重写历史,务必先备份!

  2. 大文件处理 :如果原仓库有 git-lfs 文件,需确保新仓库也配置 git-lfs

  3. 分支和标签 :默认情况下,git filter-repo 会处理所有分支和标签。如果需要限制,可以添加 --ref 参数:

    复制代码
    git filter-repo --path path/to/subdirectory/ --ref refs/heads/main
    复制代码

总结

方法 适用场景 优点 缺点
git filter-repo 需要完整历史记录 性能好、安全 需要安装
git subtree split 保留部分历史 无需额外工具 操作稍复杂
手动拆分 简单场景 快速 无历史记录

推荐使用 git filter-repo,它是目前最强大、最安全的拆库工具。

相关推荐
CC码码9 小时前
管理你的多个 Git 密钥(多平台多账号)
git·gitlab·github
CC码码9 小时前
管理你的多个 Git 密钥(单平台多账号)
git·gitlab·github
大卫小东(Sheldon)9 小时前
GIM 1.5发布了! 支持Windows系统了
git·ai·rust
李boyang10 天前
Git(四):远程操作
git
荻野泽溪10 天前
Git新建分支并同步到远程
git
漫步企鹅10 天前
【Git】新建一个远程分支的常规操作
git·新建远程分支
潇-xiao10 天前
Linux下的版本控制器Git(15)
linux·笔记·git
@昵称不存在10 天前
Git学习
git·学习
pe7er10 天前
⛔️⛔️⛔️丢弃本地commit,强制采用远端代码
git