Friday, August 30, 2013

Always use git-svn with --prefix

TLDR: I've recently been forced back into using git-svn, and while I was at it, I noticed that git-svn generally behaves a lot better when it is initialized using the --prefix option.

Frankly, I can't see any reason why you would ever want to use git-svn without --prefix. It even added some major simplifications to my old git-svn mirror setup.

Update: Some of the advantages of this solution will disappear in newer versions of Git.

For example, make a standard-layout svn clone:

$ git svn clone -s https://svn.company.com/repos/project-foo/

You'll get this .git/config:

[svn-remote "svn"]
        url = https://svn.company.com/repos/
        fetch = project-foo/trunk:refs/remotes/trunk
        branches = project-foo/branches/*:refs/remotes/*
        tags = project-foo/tags/*:refs/remotes/tags/*

And the remote branches looks like this (git branch -a):
    remotes/trunk
    remotes/feat-bar

(Compared to regular remote branches, they look very odd because there is no remote name in between there.)

Now, let's say you want to work on the feat-bar branch, so you attempt to create a tracking branch feat-bar that will track remotes/feat-bar:

$ git checkout feat-bar #short hand form, usually works.
> You are in 'detached HEAD' state. #no branch created

$ git checkout remotes/feat-bar #more explicit maybe? 
> You are in 'detached HEAD' state. #duh

$ git checkout -t remotes/feat-bar #even more?
> fatal: Missing branch name; try -b

$ git checkout -tb remotes/feat-bar 
> Branch remotes/feat-bar set up to track local branch master.

A local branch called remotes/feat-bar?? Well, that's not what I wanted.. So I end up doing it the good old-fashioned way:

$ git checkout -tb feat-bar remotes/feat-bar

That works, and I am up and rolling, but I now get this warning with every checkout or rebase:

     warning: refname 'feat-bar' is ambiguous.

This is because we have two separate branches, but Git somehow interprets them has having the same name:

    feat-bar
    remotes/feat-bar

Enter the --prefix

So, let's see what happens when I create the svn clone using a --prefix=mirror/ instead. Here's the config:

[svn-remote "svn"]
        url = https://svn.company.com/repos/
        fetch = project-foo/trunk:refs/remotes/mirror/trunk
        branches = project-foo/branches/*:refs/remotes/mirror/*
        tags = project-foo/tags/*:refs/remotes/mirror/tags/*

Here's what my remote branches look like now:
     remotes/mirror/trunk
     remotes/mirror/feat-bar

Let's create the tracking branch:

$ git checkout feat-bar  
> Branch feat-bar set up to track remote branch feat-bar from mirror.

Voila, worked on the first try. And no more warnings about ambiguous refnames!

I think this is so useful that I've asked the git-devs why they don't make this default behavior in git-svn, but haven't gotten any reactions so far.

Update: There is a reaction now.