Skip to content

Git Submodules

Kirill Nedostoev edited this page Sep 29, 2017 · 10 revisions

Git Submodules

Eventually, any interesting software project will come to depend on another project, library, or framework. Git provides submodules to help with this. Submodules allow you to include or embed one or more repositories as a sub-folder inside another repository.

Adding a Submodule

To add a new submodule you use the git submodule add command with the URL of the project you would like to start tracking. For example, you would add traces as a submodule of mipt-mips. In the mipt-mips repository:

git submodule add https://github.com/<user>/traces 

By default, submodules will add the subproject into a directory named the same as the repository, in this case traces.

If everything looks good, you can commit this change and you'll have a traces folder in the mipt-mips repository with all the content from the traces repository.

On GitHub, the traces folder icon will have a little indicator showing that it is a submodule:

traces

Starting with Submodules

You're a new collaborator joining Project mipt-mips. You'd start by running git clone to download the contents of the mipt-mips repository. At this point, if you were to peek inside the traces folder, you'd see nothing. If you're cloning mipt-mips for the first time, you can use a modified clone command to ensure you download everything, including any submodules:

git clone --recursive <project url>

or use

git submodule init
git submodule update

Working on a Project with Submodules

If you want to check for new work in a submodule, you can go into the directory and run git fetch and git merge the upstream branch to update the local code. Now if you go back into the main project and run

git diff --submodule

you can see that the submodule was updated and get a list of commits that were added to it.

There is an easier way to do this as well, if you prefer to not manually fetch and merge in the subdirectory. If you run

git submodule update --remote

Git will go into your submodules and fetch and update for you.

Clone this wiki locally