June 02, 2009

Importing git history into a new svn repository

So the management has finally approved your project, and has asked you to start working on it. Heh ... little do they know that you'd already been working on it, and have a nice prototype working, and it's all saved on your local git repository. But your company is not as cool as you are - it has it's own svn repository, and now you have to import your code into it, history and all.

Here is the git tree, as you have developed it:

Original repostiory structure

.. and your svn repository looks similar to this -
$ svn co <svn repo url>
Checked out revision 0.

$ cd <svnrepo>

$ mkdir tags trunk branches

$ svn add *
A branches
A tags
A trunk

$ svn commit -m "initial directory structure"
Adding branches
Adding tags
Adding trunk

Committed revision 1.

Now you could copy all the files from the git repository into trunk, and commit it. But that is really not the way it should be. For one - no one will know the reason for *anything* in this repository before the big bang. Also, there might have been legitimate reasons for people to branch out from some earlier state of the code, but now no one will even know.

Fortunately, a mail on the kerneltrap archives tells us how we can export a git repository, along with all it's history, into an svn repository.
(from http://kerneltrap.org/mailarchive/git/2008/10/26/3815034)

From: Björn <B.Steinbrink@...>

...
...

This should do and uses a graft to simplify the process a bit:

Initialize git-svn:
git svn init -s --prefix=svn/ https://svn/svn/SANDBOX/warren/test2

The --prefix gives you remote tracking branches like "svn/trunk" which
is nice because you don't get ambiguous names if you call your local
branch just "trunk" then. And -s is a shortcut for the standard
trunk/tags/branches layout.

Fetch the initial stuff from svn:
git svn fetch

Now look up the hash of your root commit (should show a single commit):
git rev-list --parents master | grep '^.\{40\}$'

Then get the hash of the empty trunk commit:
git rev-parse svn/trunk

Create the graft:
echo <root-commit-hash> <svn-trunk-commit-hash>  >> .git/info/grafts

Now, "gitk" should show svn/trunk as the first commit on which your
master branch is based.

Make the graft permanent:
git filter-branch -- ^svn/trunk --all

Drop the graft:
rm .git/info/grafts

gitk should still show svn/trunk in the ancestry of master

Linearize your history on top of trunk:
git svn rebase

And now git svn dcommit -n should tell you that it is going to commit
to trunk.

If you check your svn repository log, it will look like this.
SVN log

All the history, nice and linearised for svn.

Keep in mind though, that this method is lossy. All the branches have been linearised, and you can no longer "check them out" in the original git repository. Apart from that, things work just fine, and you can continue to commit in your local git repository, and push to svn as and when needed.