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

Source: http://stackoverflow.com/questions/645450/insert-a-commit-before-the-root-commit-in-git

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.

Advertisements
Merging Separate Git Repositories

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s