Posted on

Table of Contents

Preface

My first contact with the submodule was a happy accident when looking at how to create my blog. Reading the Zola's documentation. It was recommended to use when adding a new theme to the project.

With the flow to update, fix, and improve my blog, I had some issues understanding how the submodule works. So, I've decided to create this article with some information. Enjoy.

What is a submodule?

The submodule allows you to add another git project inside your project. But why? Have you ever tried to get some project to your project? Probably the approach will be: download the repository (zip file) and unzip your project. If you need to update, you'll do it everything again. Seems like a lot of work, and the submodule will remove for you.

This submodule will not be pushed with your commits. And when downloading the project will also download the submodule. The update will be one git command.

But it's not just that. You will be able to keep your custom codes in the library, making it easy to merge when a new version comes out.

Adding a Submodule

The command to add a submodule is a simple line:

git submodule <url> <name>

Ok, you need more information before continuing. The URL is a git endpoint to download the project. And the name is how you want to have this submodule called on your project.

Example:

git submodule https://github.com/gscavalcante/apollo.git themes/apollo

This execution will create a folder themes/apollo with the content of this repository in the last commit at the root of your project. Since my example have a name separated by a slash (/), it will create a folder with the submodule inside.

.
├── README.md
├── content
   └── about.md
├── sass
├── static
├── templates
└── themes
    └── apollo

6 directories, 2 files

Now you can use everything from this project on your own.

Adding From a Branch

Another way to add the submodule is with a branch, so it'll not stay at a specific SHA1 when updating. To accomplish this

git submodule -b <branch> <url> <name>

But if you already have the submodule added, you can change the .gitmodules file, for example:

[submodule "<name>"]
    path = <path>
    url = <url>
    branch = <branch>

Add the option branch with the one you want to get this submodule.

Update a Submodule

Update from a remote repository is easy when you track with a branch. For this, run the command below:

git submodule update --remote

If your submodule is not following from a branch, then go back and read Adding From a Branch.

How to Delete a Submodule

git rm <submodule-name>

But the old directory will stay at .git/modules/<path-to_submodule>. Delete this folder, and you can download another submodule with the same name without a problem.

rm -rf .git/modules/<path-to_submodule>