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

发布于:2025-07-03 ⋅ 阅读:(20) ⋅ 点赞:(0)

如何使用 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,它是目前最强大、最安全的拆库工具。


网站公告

今日签到

点亮在社区的每一天
去签到