This is a simple and basic Git Submodules memo for myself.
Because I find that I forget it every time I need to use it, resulting in asking GPT over and over again...
Cloning a Repository with Git Submodules#
# Method 1, one step
git clone --recurse-submodules <main repository URL>
# Method 2, conventional way, more cumbersome
git clone <main repository URL> <main repository directory?>
cd <main repository directory>
git submodule update --init --recursive
Adding Submodules to the Current Repository#
git submodule add <submodule repository URL> [path]
Updating Existing Submodules#
Update submodules based on the recorded Commit ID of the submodule
- When the submodule repository has updates
- When the commit point of the submodule referenced by the main project changes
git submodule update --init --recursive
Updating Existing Submodules to the Latest Commit#
# Enter the Submodules and pull the latest changes
cd path/to/my-submodule
git pull
# At the root path of the main project, save the commit
git add path/to/my-submodule
git commit -m "chore: update submodule"
Updating the Repository Address of Existing Submodules#
# Edit the .gitmodules file, modify the url field
# Synchronize changes in .gitmodules to .git/config
git submodule sync
# Update Submodules
git submodule update --init --recursive
# Save and commit
git add .gitmodules
git commit -m "chore: update submodule url"
git push
Deleting an Existing Submodule#
# Remove the Submodule directory using git
git rm -f <submodule_path>
# Edit `.gitmodules` and `.git/config` files
# Find and delete the configuration section related to that Submodule, as follows
# [submodule "submodule_name"]
# path = submodule_path
# url = https://github.com/username/repo.git
# Remove the `.git` directory reference under the Submodule directory.
# If you used `git rm` earlier, this step should have been completed automatically.
# Commit the changes
git add .
git commit -m "chore: remove submodule"
# Delete Submodule related data in `.git/modules`
rm -rf .git/modules/<submodule_path>