Sub topic 9
How subtrees work
This chapter explains what a subtree is inside your repository and what git subtree records. The commands for adding and pulling, and for pushing and splitting, get their own chapters. Here you build the mental model those commands rely on.
It assumes you are comfortable with commit, branch, merge, push and pull. It also assumes you know that a commit hash identifies a snapshot and its history, and that you can use a shell. Examples use Git 2.28 or newer, because they use git init -b.
The core idea: a subtree is just your files
A submodule stores a pointer to another repository. A subtree stores the other project's files directly in your repository. After you add a subtree, vendor/libfoo/ holds ordinary files, tracked like any other directory in your project.
- There is no
.gitmodulesfile. - There is no gitlink entry, and no nested
.gitdirectory or.git/modulesclone. - Nobody who clones your project needs a special flag or an extra command. A plain
git clonegives them everything. - Build tools, editors and code search see the files as part of your project, because they are.
You can see this in the tree object that Git stores. The mode column shows the difference.
git ls-tree HEAD vendor/For a subtree, the output looks like this:
040000 tree 9c1e5a0b7d3f2e4a6b8c0d1e2f3a4b5c6d7e8f90 vendor/libfooMode 040000 and type tree mean a normal directory. For a submodule the same command prints mode 160000 and type commit. That entry is the gitlink, which points at a commit in a different repository that your repository does not contain.
What `git subtree` is
git subtree is a command shipped with Git, in the contrib area of the source tree, and most distributions install it with Git. It is a shell script built on ordinary Git plumbing: fetch, read-tree, merge and commit-tree. The data it creates is normal commits and trees, so you could reproduce its results by hand. It does not add a new kind of object to the repository.
This has a practical consequence. Git does not remember that vendor/libfoo is special, and no configuration file lists your subtrees. Later commands such as git subtree pull work only because you pass --prefix and the upstream address again, and because the script can find markers in your history. The next section covers those markers.
Where the history goes
When you add a subtree, you choose how much upstream history to bring in.
- Without
--squash, every upstream commit becomes part of your repository's history. Your history then contains two roots: your own and libfoo's. Git joins them with a merge commit. Tools such asgit logandgit blameshow upstream authors and messages for files in the prefix. - With
--squash, Git collapses the upstream history into a single commit that holds the upstream tree at one point. Your repository gains one commit per import instead of hundreds, and you lose the detailed upstream log.
Most teams that vendor third-party code use --squash, because they want the code and a record of the version, not a copy of the whole history. Teams that fork a project and expect to keep working on it often prefer full history, because blame and bisect then work through the boundary.
How Git remembers the upstream commit
If a subtree is plain files, something has to record which upstream commit those files came from. Otherwise a later pull could not tell what is new. git subtree stores this in the commit messages it creates, as trailer lines at the end of the message.
| Trailer | Meaning |
|---|---|
| `git-subtree-dir` | The prefix directory the content lives in, for example `vendor/libfoo` |
| `git-subtree-split` | The upstream commit that the squashed content corresponds to |
| `git-subtree-mainline` | The commit in your own history that was the tip when the subtree commit was made |
The trailers appear on the commits that add, pull and split create. A squash commit made by add or pull carries git-subtree-dir and git-subtree-split.
You can read them yourself:
git log --grep='git-subtree-dir: vendor/libfoo' --format='%h %s%n%b'The git-subtree-split value tells you exactly which upstream commit you currently have. This is the closest equivalent to a submodule's recorded commit, with one difference. For a submodule, the commit is a first-class part of the tree. For a subtree, it is text in a commit message that only the git subtree command reads.
What `add` and `pull` do internally
You don't need to memorize the mechanics, but knowing them explains the behavior you'll see.
With --squash, git subtree add does roughly this:
- Fetches the upstream branch into your object database.
- Creates a commit whose tree is the upstream tree and whose message carries the
git-subtree-dirandgit-subtree-splittrailers. This is the squash commit. - Merges that commit into your branch, placing the upstream tree under the prefix. The result is a merge commit whose message looks like
Merge commit '…' as 'vendor/libfoo'.
git subtree pull repeats the process. It finds the previous git-subtree-split value in your history, fetches the new upstream tip, makes a new squash commit on top of the previous one, and merges it with the subtree merge strategy. That strategy matches the upstream tree against the directory you name, even though the paths differ: upstream has src/parser.c, and your repository has vendor/libfoo/src/parser.c. This is why a subtree pull can merge upstream edits into files you have also changed locally.
The following diagram shows the history after one add and one pull, both with --squash.
Reading the diagram: s1 and s2 hold upstream content. The merges m1 and m2 bring that content into the prefix of your branch. Your own commits (a1, a2) never need to know about upstream commits u1 to u3.
A runnable example
This script creates a local "upstream" repository and an app, then adds the upstream as a subtree. It uses local paths so you don't need a network. It assumes user.name and user.email are configured.
set -e
rm -rf subtree-demo && mkdir subtree-demo && cd subtree-demo
# Upstream project
git init -q -b main libfoo
cd libfoo
echo 'int parse(const char *s);' > parser.h
git add parser.h
git commit -q -m "Add parser header"
cd ..
# Application that wants to embed it
git init -q -b main app
cd app
echo '# app' > README.md
git add README.md
git commit -q -m "Initial commit"
git subtree add --prefix=vendor/libfoo ../libfoo main --squash
echo "--- files in the prefix"
ls vendor/libfoo
echo "--- tree entry"
git ls-tree HEAD vendor/
echo "--- no submodule files"
test ! -e .gitmodules && echo ".gitmodules does not exist"
echo "--- markers in history"
git log --format='%h %s' --grep='git-subtree-dir'After it runs, vendor/libfoo/parser.h exists as a normal tracked file, .gitmodules does not exist, and the log shows the squash commit that records where the content came from.
Consequences of storing history this way
The model has trade-offs.
- Simple for consumers. Anyone who clones the repository has a working tree immediately. CI needs no submodule step, and archives made with
git archiveinclude the vendored code. - Local edits are easy and also easy to lose track of. You can change a vendored file in an ordinary commit, with no nested repository to enter. But that edit then sits in the same history as your own work. Unless commits touching the prefix are kept separate and labeled, it is hard to see later which changes are yours and which came from upstream.
- Repository size grows. The vendored files are in your history for good. With
--squashthat is one copy per import. Without it you carry the full upstream history, forever. - The upstream address is not recorded. Nothing in the repository says where
vendor/libfoocame from, except what you write in documentation. Many teams put the URL and branch in a README or in a small script, so everyone passes the same arguments. - Consistency matters. Use
--squashfor every operation on a given prefix, or for none. Mixing the two produces confusing merges, because the commits thatpulllooks for in your history no longer match what it expects. - Large histories slow down
pushandsplit. Those commands walk your whole history to find commits that touched the prefix. Later chapters cover this.
Submodules and subtrees side by side
This table summarizes the differences in what is stored. Choosing between them is covered at the end of the tutorial.
| Aspect | Submodule | Subtree |
|---|---|---|
| What the parent stores | A gitlink (mode `160000`) pointing at one commit | The files themselves, as normal trees and blobs |
| Extra metadata files | `.gitmodules`, plus entries in `.git/config` | None |
| Where upstream's commit is recorded | In the parent's tree | In trailers of commit messages |
| Fresh `git clone` gets the code | No, unless you use `--recurse-submodules` or run `git submodule update --init` | Yes |
| Upstream history in your repository | Not stored in the parent | Optional, or collapsed with `--squash` |
| Editing the vendored code | Commit inside the submodule, then update the parent pointer | Ordinary commit in the parent |
Common errors
- "Prefix 'vendor/libfoo' already exists."
addrefuses to overwrite an existing path. Remove or move the directory first. - "Can't squash-merge: 'vendor/libfoo' was never added." You ran
pullwith--squashfor a prefix whose history lacks the trailers. Check that the prefix matches the original exactly, without a trailing slash difference, and that your clone has the full history. A shallow clone may lack the commits thatgit subtreesearches. - Merge conflicts after a pull. These are normal when you have changed vendored files. Resolve them as with any merge, then commit.
- Using the wrong branch or URL on
pull. Git does not check that the arguments match the original add. A different URL or branch merges unrelated content into the prefix, so keep the arguments in one shared place.
Exercise
You run git ls-tree HEAD vendor/ and see 160000 commit 4f2a… vendor/libfoo. Is vendor/libfoo a subtree? What would the line look like for a subtree?
Show answer
No. Mode 160000 with type commit is a gitlink, which means vendor/libfoo is a submodule. A subtree appears as an ordinary directory entry with mode 040000 and type tree, because its files are stored directly in your repository.
Exercise
A teammate clones your project with a plain git clone and asks how Git knows which upstream commit vendor/libfoo came from. Where is that information, and how can they read it?
Show answer
It is stored in commit messages, as trailers created by git subtree, mainly git-subtree-dir (the prefix) and git-subtree-split (the upstream commit). They can read it with git log --grep='git-subtree-dir: vendor/libfoo' --format='%h %s%n%b'. The trailers exist only for squashed imports and for commits made by git subtree, so a manual copy of files into the directory would leave no such record.
Exercise
Your team used git subtree add --squash for vendor/libfoo. A colleague later runs git subtree pull --prefix=vendor/libfoo <url> main without --squash. Why is this a problem?
Show answer
pull looks for the squash commits and trailers from earlier imports. Without --squash, it merges the full upstream history, which does not line up with the squashed history already in your repository. The result is a confusing merge, possibly with many conflicts and duplicate content. Use --squash consistently for a given prefix.