Git Submodule Usage Guide
·
2 min read
Git Submodule allows you to use a Git repository as a subdirectory of another Git repository. It lets you clone another repository into your project while keeping commits separate.
Recently, I’ve been using this in actual project development and encountered some detailed issues. So I’ve summarized common Git submodule operations below for future reference.
Adding Submodules
# Add submodule
git submodule add https://github.com/alanhe421/Angular-group.git
# Set mapping path alias lib
git submodule add https://github.com/alanhe421/Angular-group.git lib
For specific usage settings, execute the help command
git submodule --help
Cloning Projects with Submodules
Getting Project Code
- Method 1
- Clone the project, submodule directories are cloned by default but are empty
git clone https://github.com/chaconinc/MainProject
- Initialize submodules: initialize local configuration file
git submodule init
- Fetch all data from that project and check out the appropriate commit listed in the superproject
git submodule update
One command:git pull --recurse-submodules && git submodule update --init --recursive
- Clone the project, submodule directories are cloned by default but are empty
- Method 2
git clone --recursive https://github.com/chaconinc/MainProject
Updating Submodule Code
Method 1
cd DbConnector git fetch git merge origin/master
Method 2
git submodule update --remote DbConnector # This updates master branch by default, for other branches git config -f .gitmodules submodule.DbConnector.branch stable git submodule update --remote git merge origin/master
Committing Submodule Updates
cd DbConnector
git checkout stable
git submodule update --remote --merge
git push
Removing Submodules
Simply deleting the .gitmodules
file won’t work, because .git still contains related mapping records. So you need to execute the following commands for safe removal.
rm -rf .git/modules
# Remove module info recorded in .gitmodules (--cached option clears cache in .git/modules)
git rm --cached {MOD_NAME}
Pulling Updated Submodule Code
git submodule update --remote --merge