Git多仓库管理与并行开发

Git 多仓库管理与并行开发

微服务架构下,一个项目目录里有 N 个 git 仓库,怎么优雅管理?

一个功能没写完又要修 bug,怎么不切分支同时干两件事?

1. 多仓库管理:Git Submodule

痛点

微服务项目,每个服务独立仓库、独立部署:

project/
├── user-service/    (.git)  → github.com/org/user-service
├── order-service/   (.git)  → github.com/org/order-service
└── gateway/         (.git)  → github.com/org/gateway

问题来了:

  • 新人入职,怎么一次性拉下来整个项目?
  • 怎么记录"哪些服务的哪个版本组合在一起能跑"?

解法:Submodule

父仓库不存代码,只存指针(指向子仓库的某个 commit)

# 添加子仓库
git submodule add https://github.com/org/user-service.git exp1/user-service
git submodule add https://github.com/org/order-service.git exp1/order-service

# 提交父仓库
git add .
git commit -m "add submodules"

生成 .gitmodules 文件:

[submodule "exp1/user-service"]
    path = exp1/user-service
    url = https://github.com/org/user-service.git
[submodule "exp1/order-service"]
    path = exp1/order-service
    url = https://github.com/org/order-service.git

常用命令

场景 命令
一次性 clone 全部 git clone --recurse-submodules <url>
已 clone 补拉子仓库 git submodule update --init --recursive
更新某个子仓库 cd exp1/user-service && git pull
批量查看状态 git submodule foreach 'git status'
批量拉取 git submodule foreach 'git pull origin master'

注意事项

  • 子仓库更新后,父仓库要重新 commit(记录新的 commit hash)
  • git status 看到子仓库 dirty 不要慌,进去处理就行
  • 删除 submodule 比较麻烦,需要改 .gitmodules + .git/config + 删目录

适合:微服务、monorepo 里嵌第三方库、共享组件库


2. 并行开发:Git Worktree

痛点

你在 feature/add-auth 分支写到一半,突然:

  • 线上出 bug 要修 hotfix
  • 同事让你 review 他的分支

传统做法:stash → 切分支 → 修完 → 切回来 → stash pop

烦,容易丢东西,心智负担大

解法:Worktree

一个仓库,多个工作目录,每个目录对应不同分支,互不干扰

cd exp2/api-gateway  # 当前在 master 分支

# 创建 worktree
git worktree add ../gateway-middleware feature/add-middleware
git worktree add ../gateway-auth feature/add-auth

# 现在有三个目录可以同时工作:
# exp2/api-gateway/         → master
# exp2/gateway-middleware/  → feature/add-middleware
# exp2/gateway-auth/        → feature/add-auth

开两个终端,同时写两个功能,不用切分支。

常用命令

场景 命令
查看所有 worktree git worktree list
新建 worktree(已有分支) git worktree add <路径> <分支>
新建 worktree(新分支) git worktree add -b <新分支> <路径>
删除 worktree git worktree remove <路径>
清理无效引用 git worktree prune

注意事项

  • 一个分支只能被一个 worktree 检出(不能两个目录同时用同一分支)
  • worktree 共享同一个 .git(所有 commit、stash 是通的)
  • 开发完记得 worktree remove 清理,不然分支删不掉

适合:并行开发、紧急 hotfix、代码 review、对比测试


对比总结

Submodule Worktree
解决的问题 多仓库统一管理 单仓库并行开发
核心思想 父仓库记录子仓库指针 一个 .git 多个工作目录
典型场景 微服务、第三方库 修 bug 同时写 feature
一句话 管多个仓库 管多个分支

Submodule → 横向管多仓库 Worktree → 纵向管多分支

组合使用 = 微服务项目里每个服务都能并行开发,效率拉满

github