We all find ourselves using separately maintained Git projects inside of our own personal projects. It’s a common situation and most projects I’ve worked on used Git Submodules for the task. However, if you’ve worked on enough projects that use submodules you know it’s terribly, well…terrible.

Instead of dealing with submodule headaches I find it’s much easier (and preferable) to use subtree merging. First off, we create/clone our main repository the normal way. From within the main repository we can merge the master or another branch of a separate repository into specified subdirectory of the main repository:

$ git remote add -f subtree-repo /path/to/subtree-repo
$ git merge -s ours --no-commit subtree-repo/master
$ git read-tree --prefix=subtree-repo/ -u subtree-repo/master
$ git commit -m "Merge subtree-repo as a subdirectory."

Now when the other repository changes we can pull those changes into your main repository by using a subtree merge strategy:

$ git pull -s subtree subtree-repo master

And here is a GitHub Gist for your reference and bookmarking pleasure:

There are some caveats to this approach, not least of which would be squashing subtree commit messages to prevent updating our own project’s HEAD reference. I would recommend that you to read up on Subtree Merging to become familiar with this approach and to help avoid any potential merge hiccups that may arise: http://git-scm.com/book/en/Git-Tools-Subtree-Merging.

This approach works for me as I’m typically just grabbing external code to include in my own projects. An example would be a client website repository that relies on an external library such as Responsive Nav. Using this approach has made me nearly forget why I ever used submodules.

I am certainly no Git master and I’m always open to better approaches to how I work. If you have any suggestions please leave me a comment on the GitHub Gist I have posted to accompany this article. Cheers!