外部仓库关联方式选型
先问两个问题:体积指「主仓库 .git 历史」还是「本地磁盘」?关联需不需要被别人 clone 后看到?
本课目录
| git submodule | git subtree | gitignore + 本地 clone | partial clone / sparse-checkout | |
|---|---|---|---|---|
| 主仓库 .git 体积 | ≈0:只存 gitlink(指向某次提交)+ .gitmodules |
增长:内容合入历史;--squash 可免带全历史,但每次更新的快照仍进历史 |
0:主仓库对此一无所知 | 不适用:这是「使用方」克隆外部仓库的方式,不动主仓库 |
| 本地磁盘占用 | init 后占工作区磁盘 | 占工作区磁盘 | 占(可放仓库外或 symlink) | 省:--filter=blob:none 按需拉 blob;sparse-checkout 只检出部分路径 |
| 关联进版本库 | 是:URL + 提交号可追溯、可 review | 是(内容本身进库) | 否:只存在你机器上,约定靠文档 | — |
| 别人 clone 主仓库后 | 默认空目录;--recurse-submodules 或 git submodule update --init 才有内容 |
内容即得,无额外步骤 | 什么都没有 | — |
| 更新外部版本 | 子目录内 checkout 新提交 → 主仓库提交「指针变更」diff 只有一行 SHA | subtree pull,产生内容 diff |
手动 git pull |
— |
| 适用场景 | 要记录关联、又不想撑大主仓库——本 mission 的默认答案 | 要内容随仓库走、clone 即用、使用者无感 | 纯个人本地参考,无需他人复现 | 外部仓库本身很大,只想省磁盘/带宽地「用」它 |
常用命令
# submodule:添加 / 初始化 / 更新指针 / 移除
git submodule add https://example.com/ext-repo.git vendor/ext
git submodule update --init --recursive
# (子目录里 checkout 新提交后)
git add vendor/ext && git commit -m "chore: bump ext-repo"
git submodule deinit -f vendor/ext && git rm -f vendor/ext
# 主仓库体积实测(前后对比)
git count-objects -vH
# partial clone + sparse-checkout:按需拉外部大仓库
git clone --filter=blob:none --no-checkout https://example.com/big-repo.git
cd big-repo
git sparse-checkout init --cone
git sparse-checkout set src/some-dir
git checkout
依据:gitsubmodules(7) · Pro Git: Submodules · git-subtree.adoc · GitHub Blog: partial clone