Using Git Subtrees

With Git Subtrees it is possible to attach a remote git repository as a single commit to the repository.

  • A simple git clone will not download all the git submodules
  • Modifying code in a git submodule folder can be a nightmare, especially when the code should be comitted back to the origin

With Git Subtrees it is possible to attach a remote git repository as a single commit to the repository. To add a subproject as a git subtree, one would execute something like

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

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 here: https://developer.atlassian.com/blog/2015/05/the-power-of-git-subtree/