Sub topic 1
Git Submodules and Subtrees: Managing Code from Other Repositories
Prerequisites
You should know everyday Git commands such as commit, branch, merge, pull, and push. You should also understand that a commit hash identifies one exact version of a repository.
Why embed another repository, and the options available
A project may depend on code that has its own Git repository. Embedding that repository keeps the dependency near the application while preserving a connection to its upstream project.
Common options include:
- A package manager, which downloads a published version during a build.
- A submodule, which records an exact commit from another repository.
- A subtree, which copies the other repository's files and history into the current repository.
- A plain copy, which is simple but loses the automatic connection to upstream changes.
Submodules keep repositories separate. Subtrees make the embedded code look like ordinary files in the parent repository.
How submodules work: gitlinks and .gitmodules
A submodule is a separate repository checked out inside a directory of the parent repository. The parent does not store the submodule's files in its own tree. Instead, it stores a gitlink, a special tree entry containing the submodule's exact commit ID.
The parent also commonly tracks .gitmodules. This text file maps the local path to the repository URL:
[submodule "vendor/libfoo"]
path = vendor/libfoo
url = https://github.com/example/libfoo.gitThe gitlink selects the version. .gitmodules tells Git where to obtain it. These records are independent, so changing the URL does not change the selected commit.
Adding a submodule
Run git submodule add from the parent repository. Git clones the other repository, creates .gitmodules, and stages the gitlink and configuration:
git submodule add https://github.com/example/libfoo.git vendor/libfoo
git status
git commit -m "Add libfoo as a submodule"The commit records the relationship in the parent. The submodule's own commits remain in its separate repository.
Exercise
What does the parent repository record when you add a submodule?
Show answer
It records a gitlink for an exact submodule commit and usually records the path and URL in .gitmodules.