Skip to main content

Using Git Subtrees

Git subtrees attach a remote git repository as a single commit. This feature stands in contrast to submodules which simply attaches a Git reference and a path to a git repository.

If a git subtree is updated then the updated diff is added to the git repository.

Commands #

Adding a git repository as a subtree #

git subtree add --prefix target_dir git_remote.git branch --squash

This will create a checkout of git_remote on branch in the target_dir. And adds it to your current repository as a single commit (--squash) together with a merge commit:

commit f5ddddda7d42d06cd7883f7c495124f7dd4f503f
Merge: ed74e04 688ea1d
Author: Pascal <pascal@localhost>
Date:   Fri Sep 16 12:02:58 2016 +0200

Merge commit '688ea1de2af40776bfda21e59a14f97e6204e294' as 'foo'

commit 688ea1de2af40776bfda21e59a14f97e6204e294
Author: Pascal <pascal@localhost>
Date:   Fri Sep 16 12:02:58 2016 +0200

    Squashed 'target_directory/' content from commit 62372d7

    git-subtree-dir: target_directory
    git-subtree-split: 62372d78da03021a81c12972e483d3d074469be7

Updating a git subtree #

In order to update this subtree one can generally do

git subtree pull --prefix target_directory git_remote.git branch --squash

which will add the updated code and will add it as a merge commit.

A possible use-case would be the management of static dependencies that are stored in a separate git repository. More information on git subtree can be found in this write up on atlassian.com.