November 8, 2009

Avoiding disaster when using svn switch

So I was going to be my usual negative self again this month, but I created something, so I'll share that instead. Your regularly scheduled cynicism will return next month.

The problem

So you're working away on a branch of your project in SVN, and you need to switch to a different branch. svn switch does exactly that, but there's a catch. Say your repository has a top level with a README and CLI scripts and whatnot. But you've been hacking away in the src/ folder because that's where all the real code is. And you carelessly type svn switch svn://myrepo/branches/other_branch while your working directory is src/. What you should have typed was svn switch svn://myrepo/branches/other_branch/src - notice the subtle but important difference there.

As soon as you hit Enter, you've screwed the pooch. Remember, SVN doesn't know about branches - it just thinks they're all folders. So what you've done is tell it to switch the working directory, src/, to the top level directory of some other branch. It's going to delete everything in your folder and start checking out the whole root directory into your working directory. It's going to make a mess, then yell at you about conflicts and slotting and mismatches and you're probably going to end up getting frustrated and running rm -r on the whole folder. If there's a graceful way to recover from this mistake, I have yet to find it. I've done this enough times that I usually realize my mistake as soon as the first message pops up, and I often mash Ctrl-C in hopes of preventing further damage, but honestly I think that makes it worse.

After making this mistake for about the fiftieth time yesterday, I finally decided it would be in my best interest to protect me from myself, and so I wrote a bash script. It checks the directory (relative to the root of the branch) that you're asking to switch to against your current directory and won't let you continue if it thinks you're about to screw something up.

This script assumes that your repository follows the standard SVN repo format - your code should be in trunk or branches/branchname. And it assumes you're going to run svn switch on your current working directory - I didn't write any support for more than one argument.


Because of the nature of SVN commands, we have to wrap svn and just pass arguments for the other commands through untouched. Shawn Parker gets credit for the original inspiration. You'll need to put the below code in a file and make it executable. Then edit your .bashrc to add the following line:
alias svn='/path/to/'

No comments: