Sub topic 3
How Git Subtrees Work
Assume you know Git commits, branches, remotes, and basic command-line use.
The Subtree Model
A subtree copies another repository into a directory inside your repository. The copied project becomes ordinary files in your working tree. Git can also retain the copied project's history.
This differs from a submodule. A submodule records a pointer to a commit in another repository. A subtree records the files and history in the parent repository itself.
With --squash, Git combines the upstream history into one commit. This keeps the parent project's history smaller, but it removes the individual upstream commits from that history.
Adding and Pulling a Subtree
Add a subtree by naming its destination directory, remote URL, and branch:
git subtree add --prefix=vendor/libfoo https://github.com/example/libfoo.git main --squashGit creates vendor/libfoo, merges the upstream content, and commits the result. Later, pull upstream changes into the same directory:
git subtree pull --prefix=vendor/libfoo https://github.com/example/libfoo.git main --squashResolve merge conflicts as usual, then commit the result if Git does not create the commit automatically.
Sending Changes Upstream
You can edit files under the subtree directory as part of normal parent-repository work. To send those changes to an upstream branch, run:
git subtree push --prefix=vendor/libfoo https://github.com/example/libfoo.git my-fixTo create a branch containing only the subtree's history, use:
git subtree split --prefix=vendor/libfoo -b libfoo-onlyThe new branch is useful when another repository needs to receive the subtree's changes independently.
Choosing Between Subtrees and Submodules
| Need | Better choice |
|---|---|
| Simple clone and ordinary files | Subtree |
| A separate repository with an exact pinned commit | Submodule |
| Frequent upstream collaboration | Either, depending on team workflow |
| Keeping the parent history small | Subtree with `--squash` |
Choose a subtree when contributors should work with one repository and no setup step. Choose a submodule when the embedded project must remain clearly independent and each parent commit should pin an exact external commit.
Exercise
What does --squash change when adding or pulling a subtree?
Show answer
It combines the upstream changes into one commit instead of importing each upstream commit into the parent repository's history.