Git Submodule 允許您將一個(gè) Git 倉(cāng)庫(kù)作為另一個(gè) Git 倉(cāng)庫(kù)的子目錄。這對(duì)于確保外部依賴性能保持更新以及重用其他項(xiàng)目的代碼片段非常有用。
以下是如何在您的 Git 倉(cāng)庫(kù)中添加和更新子模塊的基本步驟:
1. 添加子模塊
要將另一個(gè) Git 倉(cāng)庫(kù)作為子模塊添加到項(xiàng)目中,請(qǐng)使用以下命令:
git submodule add <repository_url> <path_to_submodule>
例如,要將一個(gè)庫(kù)添加到名為external_lib 的子目錄中,請(qǐng)運(yùn)行:
git submodule add https://github.com/username/repository_name.git external_lib
這將克隆子模塊并將其添加到 .gitmodules 文件中。
2. 克隆包含子模塊的項(xiàng)目
要克隆一個(gè)包含子模塊的項(xiàng)目,請(qǐng)使用以下命令:
git clone --recurse-submodules <project_repository_url>
此命令將確保項(xiàng)目的子模塊也被克隆。
3. 更新子模塊
對(duì)于已克隆子模塊的項(xiàng)目,要更新子模塊的內(nèi)容,先轉(zhuǎn)到子模塊所在目錄,然后運(yùn)行以下命令:
# 切換到子模塊目錄
cd external_lib
# 獲取所有遠(yuǎn)程更新
git fetch
# 切換到最新分支
git checkout main
# 更新子模塊
git pull
或簡(jiǎn)化為一條命令:
git submodule update --remote --merge
這將更新子模塊內(nèi)容并將它們與主存儲(chǔ)庫(kù)保持同步。
4. 刪除子模塊
要?jiǎng)h除子模塊,需要手動(dòng)執(zhí)行一些步驟,先從配置文件和本地文件中移除它們,再刪除剩余緩存。
# 從 .gitmodules 文件中移除子模塊條目
git config -f .gitmodules --remove-section submodule.external_lib
# 從 .git/config 文件中移除子模塊
git config --remove-section submodule.external_lib
# 移除子模塊文件和 submodule 處于掛起的狀態(tài)
git rm --cached external_lib
# 刪除外部庫(kù)目錄
rm -rf external_lib
# 提交更改
git add .gitmodules
git commit -m "Removed submodule external_lib"
這將徹底刪除子模塊。