Git Submodules¶
Git submodules are a way to nest repositories within other repositories.
Adding a Submodule¶
Use the git submodule add command to add a submodule to an existing repo.
[URL] is the location of the repository to be added as a submodule.
For example, adding a submodule via SSH destination:
This does a couple of things:-
Adds a directory for the submodule.
-
The submodule is named after the repo name, and by default is put in a self-named directory where you ran the command.
-
If you ran the
git submodule addcommand in the root directory of yourmy-reporepository, the submodule will be inmy-repo/repo-name.
-
-
Adds a
.gitmodulesfile to the root of the repository.- This is an INI-style file:
The submodule will store a commit hash. This is the commit at which the submodule's files will be in sync with.
Cloning a Project with Submodules¶
When you clone a project that contains submodules, it will not populate those
submodule directories by default.
repo-name submodule that we added earlier,
we can see if we have the files:
Empty!
However, you can use the --recurse-submodules option when cloning to populate the
submodule.
If you've already cloned the repository but you forgot to use --recurse-submodules,
you can use git submodule update with --init and --recursive to populate the
submodules:
This is identical to running:
git submodule init: Initialize your local configuration file.git submodule update: Fetch all the data from that project and check out the appropriate commit listed in the parent project.
Turning a Directory into a Submodule¶
If there is a subdirectory in a git repo that needs to be turned into a
submodule (e.g., it needs to be its own repository and maintain its git
history), it can be converted with git subtree split.
It is good practice to make a backup branch before performing this operation.
Then, extract the directory's git history.
git subtree split: Creates a new history containing only a single directory.--prefix=my-repo/subdir: Specifies the directory being extracted.--branch=new-repo-history: Creates a local branch containing the rewritten git history.
This will make it so my-repo/subdir/src/main.py becomes src/main.py