Relative working copy switching with Subversion

by gldnspud on December 11, 2007

Do you find yourself keeping a Subversion tree for your project similar to this one?

System Message: WARNING/2 (<stdin>, line 7)

Literal block expected; none found.

http://myproject.com/svn/

branches/
featureful-23/ fancy-47/

System Message: WARNING/2 (<stdin>, line 12)

Definition list ends without a blank line; unexpected unindent.

tags/ trunk/

Do you find yourself checking out paths like this?

$ svn co http://myproject.com/svn/trunk/ MyProject

And then, do you find yourself switching to a branch in your MyProject directory, like so?

$ svn sw http://myproject.com/svn/branches/featureful-23

Do you ever find it tiring that you have to type that URL so much?

The Python script below might be useful for you then!

It's called relsw.py.

Use it to switch the current working directory to a new relative directory on the server:

$ relsw.py ../branches/featureful-23
URL: http://myproject.com/svn/trunk/
  ...
URL: http://myproject.com/svn/branches/featureful-23/

$ relsw.py ../../trunk
URL: http://myproject.com/svn/branches/featureful-23/
  ...
URL: http://myproject.com/svn/trunk/

Without further ado, here's the script:

#!/usr/bin/env python

from StringIO import StringIO
from subprocess import Popen, PIPE
from sys import argv, exit
from urllib import basejoin


def main(arg0, relative_url=None):
    url = current_url()
    print 'URL:', url
    if relative_url is None:
        return 1
    else:
        new_url = basejoin(url, relative_url)
        result = Popen(['svn', 'sw', new_url]).wait()
        if result == 0:
            print 'URL:', current_url()
        return result


def current_url():
    info = StringIO()
    svn = Popen(['svn', 'info'], stdout=PIPE)
    url_line = [L.strip() for L in svn.stdout.readlines() if L.startswith('URL')][0]
    # Add a trailing slash to prevent off-by-one relative paths.
    url = url_line.split(': ')[-1] + '/'
    return url


if __name__ == '__main__':
    exit(main(argv[0], *argv[1:]))

Leave a Comment

Previous post:

Next post: