Git Submodules
What is a Submodule
A submodule is a separate Git repository connected inside your main repository (hereafter — superproject) as a dependency. The superproject stores a reference to a specific commit of the submodule (not its files). This approach ensures stability and predictability when working with project submodules.
Use cases:
- Shared libraries and templates reused across multiple projects;
- "Vendoring" external repositories without copying files.
Adding Submodules
# In the project root
git submodule add https://gitflic.ru/project/user/repo.git path/to/submodule
git add .gitmodules path/to/submodule
git commit -m "Added submodule <submodule>"
The repository will contain:
- .gitmodules file — stores path, URL, and branch.
- A gitlink reference to the submodule commit in the main repository.
Example .gitmodules
:
[submodule "submodule"]
path = path/to/submodule
url = https://gitflic.ru/project/user/repo.git
branch = master
Cloning Submodules
Cloning the Project Including Submodules
git clone --recurse-submodules https://gitflic.ru/project/user/repo.git
If the Project Was Previously Cloned Without Submodules
git submodule update --init --recursive
Cloning Submodules to Latest Changes from Branch
To initialize submodules to the latest commit of the branch specified in .gitmodules
, use:
git submodule update --init --recursive --remote
Updating Submodules
Automatically (to the Latest Commit of the Branch)
git submodule update --remote --recursive
git commit -am "Submodule updated"
Manually (to a Specific Commit or Tag)
cd path/to/submodule
git fetch
git checkout <commit-or-tag>
cd ../..
git add path/to/submodule
git commit -m "New submodule commit recorded"
Removing Submodules
git submodule deinit -f path/to/submodule
git rm -f path/to/submodule
rm -rf .git/modules/submodule
git commit -m "Submodule removed"
Additional Settings
Automatic Submodule Management in the Superproject
git config --global submodule.recurse true
Synchronizing a Changed URL
If you manually changed the URL in .gitmodules
, run:
git submodule sync --recursive
Shallow Update for Faster Performance
git submodule update --init --recursive --depth 1
The --depth 1
option clones submodules with only the latest commit, without the full history.
This saves space and time during cloning, especially in CI/CD.
Main Commands
Action | Command |
---|---|
Add submodule | git submodule add <url> <path> |
Clone with submodules | git clone --recurse-submodules <url> |
Initialize | git submodule update --init --recursive |
Update | git submodule update --remote --recursive |
Remove | git submodule deinit -f <path> && git rm -f <path> |
For working with submodules in GitFlic CI/CD, refer to this article
Automated translation!
This page was translated using automatic translation tools. The text may contain inaccuracies.