Git Academy

Advanced · 6 min read

Submodules without tears

Include another repository at a fixed version — and the commands everyone forgets.

What a submodule is

Your repository stores a pointer to a precise commit of another repository, plus its URL in .gitmodules. The files themselves live in the other repository.

Safe
$ git submodule add https://github.com/OWNER/lib.git vendor/lib
$ git commit -m "chore: add lib as submodule"

Clone a project that has some

Without these options the submodule folders are empty.

Safe
$ git clone --recurse-submodules git@github.com:OWNER/REPO.git
# already cloned:
$ git submodule update --init --recursive

Update a submodule

Move it to the latest commit of its branch, then commit the new pointer in your repository.

Safe
$ git submodule update --remote vendor/lib
$ git add vendor/lib
$ git commit -m "chore: update lib"

Alternatives

Often a package manager (npm, composer, pip) is simpler. Submodules shine for shared code you also develop.