CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

terminal
# Subtree deposunu hedef dizine ekle

Sample solution

terminal
git subtree add --prefix=vendor/shared https://example.com/shared.git main
echo 'Subtree eklendi: vendor/shared'

Expected output

Subtree eklendi: vendor/shared

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer

Explanation: Subtree includes another repository's contents in a subdirectory of the main repository and manages the files in its history.

2 Specify the subtree directory

Question
git subtree add --prefix=____ https://example.com/tool.git main
Answer
git subtree add --prefix=libs/tool https://example.com/tool.git main

Explanation: The <code>--prefix</code> parameter specifies the directory in the main repository where the other repository's contents will be added.

3 Subtree and submodule features

Term Meaning
Subtree Includes files in the main repository
Submodule Keeps a separate repository reference
--prefix Specifies the target directory
Commit referansı Identifies the submodule revision

All lessons in Expert