Git
subtree vs submodule
Learn the difference between subtree and submodule.
What is a subtree?
Git subtree allows you to include the contents of another repository in a specific subdirectory of the current repository. The added project's files appear like normal files in the main repository and are managed in its history.
git subtree add --prefix=libs/tool \
https://example.com/tool.git main
With the subtree approach, the dependent project's contents become part of the main repository.
Comparing subtree and submodule
A submodule connects another repository inside the main repository as a separate Git repository and records a specific commit reference. A subtree adds the other repository's files to a subdirectory of the main repository.
# Submodule
git submodule add https://example.com/lib.git libs/lib
# Subtree
git subtree add --prefix=libs/tool \
https://example.com/tool.git main
A submodule preserves the independent repository structure. A subtree makes it easier to manage the contents directly inside the main repository.
Exercise Write a subtree add command
Add the main branch of the repository at https://example.com/shared.git to the vendor/shared directory in the main repository. Use the git subtree add command and the --prefix parameter.
Show example solution
git subtree add --prefix=vendor/shared https://example.com/shared.git main
echo 'Subtree eklendi: vendor/shared'
Test yourself
-
You want to manage a library's files like normal files in the main repository. Which approach is suitable?
- Sparse-checkout
- Git worktree
- Git submodule
- Git subtree
Show answer
Git subtree — Subtree includes another repository's contents in a subdirectory of the main repository and manages the files in its history.
-
Specify the subtree directory
git subtree add --prefix=____ https://example.com/tool.git main
Show answer
git subtree add --prefix=libs/tool https://example.com/tool.git main
-
Subtree and submodule features
- Subtree
- Includes files in the main repository
- Submodule
- Keeps a separate repository reference
- --prefix
- Specifies the target directory
- Commit referansı
- Identifies the submodule revision
Next lesson: Summary - Monorepo