Git Submodule Guide

#code#git#tips#shortcuts#maintainability

Sometimes you may have to keep third party libraries included in you project up to date in an easy way. Submodules in Git makes this as simple as a pimple.

Adding a Submodule to a Git Repository

First, lets add the third party repository as a submodule to a sub folder in our own repository:

~/code > git submodule add git@mygithost:project.git lib/folder
Cloning into lib/folder...
remote: Counting objects: 448, done.
remote: Compressing objects: 100% (444/444), done.
remote: Total 448 (delta 290), reused 0 (delta 0)
Receiving objects: 100% (448/448), 493.84 KiB | 322 KiB/s, done.
Resolving deltas: 100% (290/290), done.

Now, lets see what this did to our repository:

~/code > git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#new file:   .gitmodules
#new file:   lib/folder

The .gitmodules file basically tells Git to keep track of lib/folder as a git submodule. Add those files and get on with it:

git add . && git commit -m "Submodule added"

Using and Updating a Git Submodule

When cloning a repository with submodules in it for the first time, the folders where the submodules live are empty. In order to get the latest source you can initialize the submodule:

git submodule init

And then update it:

git submodule update

Voila!

You can look at submodules as its own repositories inside yours. And as submodules updated this way are headless, we can make sure to pull from a specific branch in our submodule (in this case, master):

cd lib/folder
git checkout master
git pull

Commit those changes and we're done!