EdgexAgent/SubmoudleUage.md

3.9 KiB
Raw Permalink Blame History


🧩 Git Submodule 使用说明(父子仓库)


一、什么是子模块Submodule

子模块允许你在一个 Git 仓库中嵌套另一个 Git 仓库作为子目录。适用于代码复用、模块化开发。

典型例子:

  • 主仓库:EdgeXAgent
  • 子仓库:device-ble-go(作为模块引入)

二、添加子模块

git submodule add <子仓库地址> <目标路径>

示例:

git submodule add git@github.com:yourname/device-ble-go.git res/device-ble-go

这会做两件事:

  1. 在项目目录中添加子仓库代码到 res/device-ble-go
  2. 创建 .gitmodules 文件,记录子模块信息

提交:

git add .gitmodules res/device-ble-go
git commit -m "Add device-ble-go as submodule"
git push

三、克隆带子模块的父仓库

方法一(推荐):

git clone --recurse-submodules <父仓库地址>

方法二(先 clone再初始化

git clone <父仓库地址>
cd 项目目录
git submodule update --init --recursive

四、更新子模块代码(获取最新提交)

进入子模块目录:

cd res/device-ble-go
git pull origin main  # 拉取最新代码

回到主项目目录,更新引用:

cd ../..
git add res/device-ble-go
git commit -m "Update submodule device-ble-go to latest"
git push

五、一键更新所有子模块

git submodule update --remote --merge

或:

git submodule foreach git pull origin main

六、查看子模块状态

git submodule status

七、删除子模块

⚠️ 删除子模块不止 rm,需要多个步骤:

# 1. 删除子模块的 tracked 信息
git rm --cached res/device-ble-go

# 2. 删除子模块目录
rm -rf res/device-ble-go

# 3. 编辑 .gitmodules 文件,手动删掉对应的条目

# 4. 如果有 .git/config 里也记录了子模块,清除:
git config -f .git/config --remove-section submodule.res/device-ble-go

# 5. 提交更改
git commit -m "Remove submodule device-ble-go"
git push

八、配置 .gitmodules自动跟踪分支

默认子模块是绑定某个 commit可以改成绑定分支

编辑 .gitmodules 文件:

[submodule "res/device-ble-go"]
    path = res/device-ble-go
    url = git@github.com:yourname/device-ble-go.git
    branch = main

之后用这个命令自动拉子模块的指定分支:

git submodule update --remote --merge

九、常见问题与解答

问题 解决方法
子模块目录是空的 没有初始化:git submodule update --init --recursive
修改了子模块内容但父仓库没变 需要在父仓库中 git add <子模块> 并提交更新引用
克隆下来没有子模块内容 --recurse-submodules 或手动 submodule update
子模块 push 后,别人 pull 没有更新 子模块更新后,要在父仓库提交“引用变化”

十、推荐项目结构

EdgeXAgent/
├── .gitmodules
├── main.go
└── res/
    └── device-ble-go/   <-- 子模块(独立 Git 仓库)

总结常用命令表

操作 命令
添加子模块 git submodule add URL path
初始化子模块 git submodule update --init --recursive
克隆并带子模块 git clone --recurse-submodules
更新所有子模块 git submodule update --remote --merge
删除子模块 多步骤,见上
查看状态 git submodule status