UX Design and Development course

Quick and easy git-submodules

A submodule in a git repository is like a sub-directory which is really a separate git repository in its own right. This is a useful feature when you have a project in git which depends on a particular versions of other projects.


WAT?! Why?

Submodules are a really great way to include another Github project into your new project. Why would you want to do this? The best example I can give is, when building a wrapper around another project.

Take for example this Gitbook. There are sections of this book that are actually independent projects themselves. When you want to include something that exists individually into your project and it is not in a packaged state, you have two choices; one: you can clone the project and simply add it to your own or, two: you can add it as a submodule.

The real benefit of adding it as a submodule is that as the other project gets updated, there is a simple command you can use to pull from that submodules master. That way, the two projects can grow independently, but always have a way to stay in sync.

How to create a git-submodule

The steps are pretty simple:

$ midir [your-new-project]

$ cd [your-new-project]

$ git init

$ git submodule add https://github.com/[submodule-project]


Project state with submodule

In your project you wil see a new directory for the submodule. The entire project has been cloned into your local repo for the sake of development and it has it's whole git history with it.

When you push this project to Github, what you will see is that the reference library is NOT in your repo. There is simply a reference, like an alias, to that repo.

Tracking submodules

Looking at the commit history, you will see a new dot file called .gitmodules added. This is the submodule configuration to the included library.

Maintaining your project

Maintaining a project is pretty simple, but there are some issues that you need to be aware of. Even though in your local project is included in your project, it's in a detached head state and it is easy to really screw things up. I really suggest that if there are changes to be done in the submodule, you do this in the original repo, NOT in the repo that contains the submodule.

Updating the submodule

Let's assume that the submodule's host project has been updated. To get updated, simply run:

$ git submodule -q foreach git pull -q origin master

You can remove the -q flag to follow the whole process.