Sub topic 2
Cloning a Project That Has Submodules
Assume you know everyday Git commands, remotes, branches, and commit hashes. A submodule is a separate Git repository checked out inside the main project. The main repository records the exact submodule commit it expects.
Clone and initialize submodules
Use --recurse-submodules when cloning:
git clone --recurse-submodules https://github.com/example/app.gitIf you already cloned without the option, initialize and check out the recorded commits:
git submodule update --init --recursiveThe --recursive option also handles submodules nested inside other submodules.
Update a submodule to a newer commit
Normal submodule updates restore the commit recorded by the parent. To follow a configured upstream branch, run:
git submodule update --remote vendor/libfoo
git add vendor/libfoo
git commit -m "Update libfoo"
git pushThe parent repository now points to the new submodule commit. The submodule commit must already be available on its remote before others can fetch it.
Make and publish submodule changes
A submodule often has a detached HEAD, meaning it is not on a local branch. Create a branch before editing:
cd vendor/libfoo
git switch -c fix-parser
# edit files
git commit -am "Fix parser edge case"
git push -u origin fix-parser
cd ../..
git add vendor/libfoo
git commit -m "Point libfoo at parser fix"
git pushPush the submodule first. Then commit the new pointer in the parent repository.
Configuration and pitfalls
Useful settings reduce missed steps:
git config --global submodule.recurse true
git config --global fetch.recurseSubmodules on-demand
git config --global push.recurseSubmodules checkpush.recurseSubmodules=check prevents a parent push when its referenced submodule commit is not available on a remote. Do not edit a detached submodule without creating a branch, and do not assume git pull automatically selects the newest upstream submodule commit.
Remove a submodule cleanly
git submodule deinit -f vendor/libfoo
git rm -f vendor/libfoo
rm -rf .git/modules/vendor/libfoo
git commit -m "Remove libfoo submodule"git rm removes the working-tree directory, gitlink, and .gitmodules entry. The final command removes leftover local metadata.
Exercise
After creating a commit inside a submodule, what must you do before pushing the parent repository?
Show answer
Push the submodule commit first, then commit and push the parent repository's updated gitlink.