643 字
3 分钟

子git的操作经验

Git 主仓库 + Submodule 子仓库工作流总结#

适用场景:前后端分离项目(如 rentsys + ruoyi-ui),主仓库管理整体工程,UI 作为 Git Submodule 独立维护。


一、核心概念#

  • Submodule 不是代码副本,而是一个 commit 指针(gitlink)
  • 主仓库只记录:
    ruoyi-ui -> 某一个 commit SHA
  • 两个仓库 完全独立:commit / push / tag 都互不影响

二、如何判断是否存在子仓库#

Terminal window
ls .gitmodules
git submodule status
git ls-tree HEAD

出现 160000 commit xxxx ruoyi-ui 即表示 submodule。


三、Clone 正确方式#

推荐(一步到位)#

Terminal window
git clone --recurse-submodules [email protected]:xxx/rentsys.git

普通 clone(必须补)#

Terminal window
git clone [email protected]:xxx/rentsys.git
cd rentsys
git submodule update --init --recursive

checkout tag / commit 后(必须)#

Terminal window
git checkout v0.0.3
git submodule update --init --recursive

四、日常开发 & 提交流程(最重要)#

同时修改 UI + 后端#

1️⃣ 提交子仓库(ruoyi-ui)#

Terminal window
cd ruoyi-ui
git checkout main
git pull
git add .
git commit -m "feat: ui change"
git push

2️⃣ 提交主仓库(记录指针 + 后端)#

Terminal window
cd ..
git add -A
git commit -m "feat: backend update + bump ruoyi-ui"
git push

⚠️ 必须先 push 子仓库,再 push 主仓库


五、为什么总是看到 ruoyi-ui (new commits)#

含义:子仓库前进了,但主仓库还没记录新指针。

解决:

Terminal window
git add ruoyi-ui
git commit -m "chore: bump ruoyi-ui"
git push

六、git add —all / git push 会发生什么?#

  • ❌ 不会提交子仓库代码
  • ✅ 只记录子仓库 commit 指针
  • ❌ 不会自动 push 子仓库

⚠️ 子仓库未 push 就提交主仓库会导致灾难性不同步。


七、Tag 与 Submodule 的关系#

在主仓库打 tag:#

Terminal window
git tag -a v0.0.3 -m "release"
git push origin v0.0.3

效果:

  • 主仓库有 tag
  • 子仓库 不会自动有 tag
  • 但 tag 锁定了当时的子仓库 commit

推荐发布规范(强烈建议)#

Terminal window
# 子仓库
cd ruoyi-ui
git tag -a v0.0.3 -m "ui release"
git push origin v0.0.3
# 主仓库
cd ..
git tag -a v0.0.3 -m "full release"
git push origin v0.0.3

八、Pull 如何处理子仓库#

推荐#

Terminal window
git pull
git submodule update --init --recursive

跟随子仓库远端最新(谨慎)#

Terminal window
git pull
git submodule update --remote --merge
git add ruoyi-ui
git commit -m "chore: bump ruoyi-ui"
git push

九、Detached HEAD 处理#

发生场景:checkout tag / submodule 默认状态。

正确做法:

Terminal window
git checkout main
git cherry-pick <commit>
git push

十、工程级心法总结#

1️⃣ 子仓库代码只在子仓库提交
2️⃣ 主仓库只记录子仓库指针
3️⃣ 子仓库先 push,主仓库再 push
4️⃣ tag 不跨仓库,必须分别打
5️⃣ 切 tag / commit 后必须 update submodule


十一、推荐脚本(可扩展)#

  • push_all.sh:一键 push UI + 主仓库
  • pull_all.sh:pull + submodule update
  • release.sh:双仓库打 tag + 校验

📌 本文档适用于长期维护的工程级 Git Submodule 项目。

赞助支持

如果这篇文章对你有帮助,欢迎赞助支持!

赞助
子git的操作经验
https://jkwei.com/posts/knowledge/子git的操作经验/
作者
Jacky
发布于
2025-12-29
许可协议
CC BY-NC-SA 4.0
最后更新于 2025-12-29,距今已过 17 天

部分内容可能已过时

目录