Merging Separate Git Repositories

On occasion I need to merge two git repositories together. Fortunately git has a solution which I usually have to google every time I do it.

Firstly you really need an empty commit on the root otherwise you get a strange commit in the repository where files are still in their original location. That can cause you some problems later since this commit will conflict with basically everything.

git checkout --orphan newroot
git rm -rf .

git commit --allow-empty -m "Root commit"
git rebase --onto newroot --root master
git branch -d newroot


Moving the files themselves is also easy by using a tree-filter.

git filter-branch --prune-empty \
  --tree-filter 'mkdir -p new-subdir; \
  git ls-tree --name-only $GIT_COMMIT | \
  xargs -I FILES mv FILES new-subdir'

Note that this is a tree-filter which involves checking out each revision in order to work on it and is therefore quite slow for some repositories. You can probably optimise this into an index-filter which would not do that.

Since the repositories won’t conflict now (I assume that new-subdir does not exist in the repository you’re merging into) then a simple git pull will merge the filtered repository into the other repository.

The commit history will look a bit weird because the dates will be out of order but you will still have the full history.

Merging Separate Git Repositories

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s