Mar 02

Using Git Submodules

If you want to reference code from external repositories within your own repository in GIT – you’ll have to use GIT submodules.

Let’s say that we have a repo called sandbox, and inside sandbox, we have a lib sub directory that refers to multiple libraries from other repos, looking like the following

/sandbox # your repo
 +-> /lib
      +-> /subA # submodule A
      +-> /subB # submodule B

To add the submodules, you need to use the git submodule add command at the root of your repo as follows

$ cd ~/sandbox
$ git submodule add <git_repo_path_of_submodule_A> lib/subA
$ git submodule add <git_repo_path_of_submodule_B> lib/subB
$ ...

Each git submodule add will create a clone of the external git repo into your existing repo and manage them as a submodule.

Because each submodule is also a git repo clone, you can modify/change source code inside submodule and then push it back to the origin.

$ cd ~/sandbox/lib/subA
<make changes and edits>
$ git commit -a -m "reason of change..."
$ git push
$ cd ~/sandbox
$ git add lib/subA
$ git commit -m "updated submodule"

Submodule changes has to be pushed back out to the origin before the rest of the code, otherwise it will break the dependency.

Also submodules are “fixed” to a particular version of the original repo – so if you want to keep up the latest version, remember to issue the following

# at the root of the repo
$ git submodule update

You can put the above into a cronjob to refresh it automatically, or use git config alias as described in this link.

That’s it – enjoy git submodules.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create