Last Updated: May 15, 2019
·
3.178K
· alyphen

Adding another project's entire history with git using subtree merge

Sometimes, it's useful to have an entire project's history in your project when using git - this also allows us to pull in branches of that project and update their versions easily and quickly. Here's how we go about it.

First, if you haven't done so already, create your repository:

mkdir myrepo
cd myrepo
git init
touch .gitignore
git add .gitignore
git commit -m 'Initial commit'

Next, we need to add the repository you want to subtree-merge in as a remote:

git remote add -f myotherrepo https://github.com/me/myotherrepo.git

Then merge the branch you want:

git merge -s ours --no-commit myotherrepo/master

And place it wherever you want in your repo:

git read-tree --prefix=useful-stuff/myotherrepo/ -u myotherrepo/master
git commit -m 'Subtree merged in myotherrepo'

There we go, we now have the other repo with it's entire history in your repo.

If we want to update the repo we just subtree merged in, all we have to do is:

git pull -s subtree myotherrepo master

and it will automatically grab the latest changes.

You should note that cloning does not also clone the remotes though, so they have to be re-added if you're working from a fresh clone, for example on a different machine.

Sources:

kernel.org

github.com