Working with GIT Submodules

GIT submodules is a feature for linking together multiple distinct repositories. It’s useful, for example, if you have one library that you use in multiple different projects.

The easy way

The easiest way to use GIT submodules, is to have your submodules track a branch.

To add a submodule tracking a branch, use the following commands (note the “-b” argument) (don’t forget to commit and push your changes afterwards)

git submodule add -b [branch_to_track] [git_repo_url] [relative_dir]
git submodule update --init --recursive --remote

The “update” command above can also be used to pull updates.

To remove a submodule, use the following commands (don’t forget to commit and push your changes afterwards):

git submodule deinit mysubmodule
git rm --cached mysubmodule

The other way

So I mentioned that tracking a branch was “the easy way” to use submodules. However, tracking a branch is a relatively new feature. The previous usage of submodules “pins” each submodule to a specific revision¬†rather than a branch. Advocates of this approach will point out that specifying a specific revision means that your code will never be broken unexpectedly by upstream changes. If you find yourself working with a project in which this is the case, you will from time to time want to update your submodule references to a newer revision. Here’s how you do that.

This command pulls changes in the main repo and in submodules, then updates each submodule individually to the latest revision on the master branch also recursing into submodules of submodules of submodules. Finally, we commit our changes.

git pull --recurse-submodules
git submodule update --init --recursive --remote
git submodule foreach git pull origin master
git commit -a -m "updating submodule references"

There you have it. Submodules. Enjoy.