Sub topic 3
Adding a submodule
A submodule lets one Git repository (the superproject) hold a pinned reference to a specific commit of another repository. This chapter covers git submodule add: what it does, what it writes to disk, which options matter, and which errors you will meet.
This chapter assumes you are comfortable with commits, branches, remotes, and the idea that a commit hash identifies one exact snapshot. The previous chapter covered the gitlink and .gitmodules model. Here you will see both created.
The basic command
The syntax is:
git submodule add [options] <repository-url> [<path>]If you leave out <path>, Git uses the last part of the URL without .git. For https://github.com/example/libfoo.git that is libfoo, placed at the top of your repository. Most projects pass an explicit path such as vendor/libfoo to keep third-party code in one place.
git submodule add https://github.com/example/libfoo.git vendor/libfoo
git status
git commit -m "Add libfoo as a submodule"The command changes your working tree and your index, but it does not commit. You finish the job with git commit, like any other staged change.
What Git does during the add
git submodule add performs several steps in a fixed order.
- It clones the external repository into the target path.
- It checks out the remote's default branch, or the branch you named with
-b. - It writes the submodule's Git directory to
.git/modules/<name>inside the superproject. The submodule directory itself holds only a small.gitfile that points there. - It creates or updates
.gitmodulesand stages it. - It registers the submodule in
.git/config(the same step asgit submodule init). - It stages a gitlink at the path, which records the commit the clone is currently on.
The result is two staged changes that belong together: .gitmodules says where the repository comes from, and the gitlink says which commit to use. Commit both in the same commit.
Try it locally
You can run the whole sequence without a network. This script builds a small library repository, then an application repository that includes it. It assumes user.name and user.email are already configured.
mkdir demo && cd demo
base="$PWD"
git init -b main libfoo
cd libfoo
echo "int parse(const char *s);" > parser.h
git add parser.h
git commit -m "Add parser header"
cd "$base"
git init -b main app
cd app
git -c protocol.file.allow=always submodule add "$base/libfoo" vendor/libfoo
git statusThe -c protocol.file.allow=always part is needed because of a security change in Git 2.38.1. Cloning a submodule over the file transport is blocked by default, since a malicious repository could use it to read local files. For real remote URLs over HTTPS or SSH you do not need this setting. Set it only for the single command, not globally.
The git status output looks like this:
On branch main
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitmodules
new file: vendor/libfooGit lists vendor/libfoo as one new file. It does not list the files inside the submodule, because the superproject tracks only the pointer.
Inspecting what was staged
Three commands show the pointer from different angles.
git ls-files --stage vendor/libfoo
git diff --cached --submodule
git commit -m "Add libfoo as a submodule"
git cat-file -p HEAD^{tree}The first command prints an entry with mode 160000, followed by a commit hash:
160000 3f2a9c1d0e5b7a6c8d4e2f1a0b9c8d7e6f5a4b3c 0 vendor/libfooMode 160000 is the gitlink. Regular files use 100644 or 100755, and directories use 040000. The hash is a commit in the library repository, and it does not exist as an object in the superproject's own object database.
git diff --cached --submodule shows a readable summary:
Submodule vendor/libfoo 0000000...3f2a9c1 (new submodule)After the commit, git cat-file -p HEAD^{tree} prints the top-level tree. If vendor has other contents, git cat-file -p HEAD:vendor lists the entry with the type commit instead of blob or tree.
The .gitmodules file
The staged .gitmodules file looks like this:
[submodule "vendor/libfoo"]
path = vendor/libfoo
url = https://github.com/example/libfoo.gitThe quoted name after submodule is the logical name. By default it equals the path. The name matters because it keys the entries in .git/config and the directory .git/modules/vendor/libfoo. Moving a submodule to a new path later does not rename it, so the name stays as it was.
.gitmodules is an ordinary tracked file. Everyone who clones the project receives it, and it is reviewed in pull requests. Treat changes to its url lines with care, because a changed URL decides where other developers' machines fetch code from.
Options that change the result
| Option | Effect |
|---|---|
| `-b <branch>` | Checks out that branch and records `branch = <branch>` in `.gitmodules`. Later `git submodule update --remote` follows it. |
| `--name <name>` | Uses a logical name different from the path. |
| `--depth <n>` | Makes a shallow clone with only the last `n` commits. |
| `-f`, `--force` | Adds the submodule even if the path is ignored by `.gitignore`. |
For example, to track a release branch and use a name that survives moving the directory:
git submodule add -b stable --name libfoo https://github.com/example/libfoo.git vendor/libfooThe -b option does not pin anything by itself. The gitlink still records one exact commit. The recorded branch is only a hint for the later --remote update, which a following chapter covers.
Pinning to a specific version
git submodule add records whatever commit the default branch has at that moment. If you want a tagged release instead, move the submodule's checkout and re-stage the pointer before committing:
git submodule add https://github.com/example/libfoo.git vendor/libfoo
cd vendor/libfoo
git checkout v1.4.0
cd ../..
git add vendor/libfoo
git commit -m "Add libfoo pinned to v1.4.0"Inside the submodule, git checkout v1.4.0 leaves it in detached HEAD state. That is normal for a pinned version. The superproject stores the commit hash that the tag points to, not the tag name.
Relative URLs
A submodule URL can start with ./ or ../. Git resolves it against the superproject's default remote URL.
git submodule add ../libfoo.git vendor/libfooIf the superproject's origin is https://github.com/example/app.git, this resolves to https://github.com/example/libfoo.git. If the project is cloned over SSH, the submodule is cloned over SSH too. This is useful when you host both repositories on one server and mirror them. It fails when the library lives on a different host, so use an absolute URL in that case. The .gitmodules file keeps the relative form, and Git resolves it on each machine.
Adding a repository you already cloned
If the target path already contains a Git repository whose remote matches the URL, Git does not clone again. It prints a message like Adding existing repo at 'vendor/libfoo' to the index and stages the gitlink and .gitmodules. This is useful when you have already been working in the library. One difference remains: the Git directory stays inside the submodule as a real .git directory instead of under .git/modules. Git can move it there later with git submodule absorbgitdirs.
Common errors
| Message | Cause | Fix |
|---|---|---|
| `'vendor/libfoo' already exists in the index` | The path is already tracked as regular files. | Remove them with `git rm -r --cached vendor/libfoo`, then add the submodule. |
| `The following paths are ignored by one of your .gitignore files` | An ignore rule matches the path. | Fix the rule, or pass `--force`. |
| `'vendor/libfoo' already exists and is not a valid git repo` | The directory exists, is non-empty, and is not a repository. | Move or delete the directory first. |
| `transport 'file' not allowed` | Git 2.38.1 or later blocks the `file` transport for submodules. | Use a remote URL, or pass `-c protocol.file.allow=always` for that one command in a trusted test. |
| `fatal: repository ... does not exist` | The URL is wrong, or you lack access. | Test it with `git ls-remote <url>`. |
Checking your work before you push
Before pushing the commit that adds a submodule, confirm three things.
git show --stat HEADlists exactly two changes:.gitmodulesand the submodule path.- The commit the gitlink points to has been pushed to the library's remote. This is true by default when you clone from a remote, since the commit came from there. It is not true if you added a local library that nobody else can reach.
- A fresh clone works. Run
git clone --recurse-submodules <your-app-url> /tmp/checkand confirm thatvendor/libfoois populated.
The third check catches wrong URLs and unpushed commits before a teammate does.
Exercise
You run git submodule add -b stable https://github.com/example/libfoo.git vendor/libfoo and commit. A teammate says the project always uses the newest commit of stable. Is that right? What does the commit actually store, and what does the -b option add?
Show answer
No. The commit stores a gitlink (mode 160000) with one exact commit hash, which is the tip of stable at the moment you ran the command. The -b option only checks out that branch at add time and writes branch = stable to .gitmodules. The recorded branch is used later by git submodule update --remote to fetch newer commits. Until someone updates the submodule and commits the new gitlink, every clone gets the same commit.
Exercise
After git submodule add, git ls-files --stage vendor/libfoo shows a line starting with 160000. Name two other places where the add left a record of the submodule, and say what each one stores.
Show answer
First, .gitmodules in the working tree (staged for commit) stores the submodule's path and URL, plus a branch if you used -b. Second, .git/config stores the registered URL under a submodule section, which marks the submodule as initialized in this clone. The submodule's own Git directory is also kept at .git/modules/<name>, and it holds the cloned history.