You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git:如何在子模块目录下添加由主项目管理的独立子模块?

解决Git主项目直接管理子模块目录下嵌套子模块的问题

Great question! This is a common gotcha with Git submodules—by default, Git treats any directory marked as a submodule (like your SubModule1) as an isolated repository, so any new submodules added inside it get tied to the submodule's repo instead of your main Project. Plus, Git implicitly ignores untracked content in submodule directories, which adds to the confusion.

Here's exactly how to set up your desired structure, where Project directly manages SubModule2 (located under SubModule1) without linking it to SubModule1's repository:

Step 1: Add SubModule1 to your main Project (if you haven't already)

First, make sure SubModule1 is set up as a submodule in your Project root. Run this from your Project's base directory:

git submodule add <SubModule1-repo-URL> SubModule1

This will add SubModule1's config to your Project's .gitmodules file and mark the SubModule1 directory as a submodule.

Step 2: Add SubModule2 directly to Project, targeting the SubModule1 path

The key here is to run the submodule add command from your Project's root, not from inside the SubModule1 directory. This tells Git to tie SubModule2 to your main Project, not SubModule1. Execute:

git submodule add <SubModule2-repo-URL> SubModule1/SubModule2

Step 3: Verify the setup

  • Check your Project's .gitmodules file: You'll see two entries—one for SubModule1, and another for SubModule2 with path = SubModule1/SubModule2. This confirms SubModule2 is managed by your main Project.
  • Head into the SubModule1 directory and run git status: You'll notice SubModule2 shows up as an untracked file. That's perfect! It means SubModule1's own repository has no knowledge of SubModule2, which is exactly what you want.

Step 4: Commit the changes to your main Project

Back in your Project root, stage and commit the new submodule config and reference:

git add .gitmodules SubModule1/SubModule2
git commit -m "Add SubModule2 as a Project-managed submodule under SubModule1"

Important Notes

  • Double-check that SubModule1's repository does not have SubModule2 in its .gitignore. While Git will prioritize your main Project's submodule config, an ignore rule in SubModule1 could cause unexpected behavior when pulling updates to SubModule1.
  • When cloning your Project repo later, use the --recurse-submodules flag to pull all submodules at once:
git clone --recurse-submodules <Project-repo-URL>

If you've already cloned the repo without this flag, run:

git submodule update --init --recursive

This setup lets your main Project fully control the SubModule2 dependency, even though it lives inside the SubModule1 directory—no link to SubModule1's repository required.

内容的提问来源于stack exchange,提问作者toomanychushki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:50:41