Using Git Submodules


In setting up the stad.us blog and website, I had the opportunity to start using the git submodule command for the first time to work with submodules. I don’t pretend that there are other ways to use submodules, but these are the commands I use the most.

Add

Anything can be added as a submodule to an existing git project as long as the submodule is itself a git project. In my case, I forked the Beautiful Hugo theme for this Hugo based website. It needs to be linked from the themes directory in my site repository.

To add the theme to my website repository, I use the git submodule command (here I use the actual Beautiful Hugo repository instead of my custom theme):

mkdir themes
cd themes
git submodule add https://github.com/halogenica/beautifulhugo.git beautifulhugo

Note that you will have a new .gitmodules file that you will want to add to your parent repository.

Using the submodule command in the above example will automatically clone the repository and pull content so you are ready to go after this command. If you clone your parent repository, you will need to execute these commands to fetch your submodules:

git submodule init
git submodule update

You can also use the --recurse-submodules argument in your original clone:

git clone --recurse-submodules <url>

Changes

If you make changes to the code within the submodule, you can commit those changes just like any other change. They are tracked within the submodule and not within the parent module. Also see the git submodule update command to pull changes that others have made to the submodule and have committed to the repository.

Remove

To remove a submodule, use the git rm command:

git rm (submodule)

This will change the .gitmodules file so you will need to commit that change.

More Information

Look at the submodule command.

git  example