Ruby Subversion Bindings

Subversion has bindings for a variety of languages: Java, Perl, Python and Ruby. Of these I am most interested in the Ruby bindings as I'm building a Rails application. Unfortunately the documentation is completely lacking and bits of it are scattered throughout the web. This is an attempt to provide the code and how-to for the most common tasks.

Before we get to the code, validate you have the Ruby Subversion bindings installed correctly by running irb from a terminal:

irb(main):001:0> require 'svn/client'
=> true

Onto the source code. Start it off by including the required svn modules:

RUBY:
  1. require "svn/core"
  2. require "svn/client"
  3. require "svn/wc"
  4. require "svn/repos"

Then setup the context with your subversion credentials:

RUBY:
  1. ctx = Svn::Client::Context.new()
  2. ctx.add_simple_provider
  3. ctx.auth_baton[Svn::Core::AUTH_PARAM_DEFAULT_USERNAME] = 'username'
  4. ctx.auth_baton[Svn::Core::AUTH_PARAM_DEFAULT_PASSWORD] = 'password'

Now you can run any of the following commands on a remote subversion repository.

SVN Info

RUBY:
  1. repos_uri = 'http://svn.website.com/project/trunk'
  2. revision = 50
  3. begin
  4.   ctx.info(repos_uri, revision) do |path, info|
  5.     puts("Url: #{info.url}")
  6.     puts("Last changed rev: #{info.last_changed_rev}")
  7.     puts("Last changed author: #{info.last_changed_author}")
  8.     puts("Last changed date: #{info.last_changed_date}")
  9.     puts("Kind: #{info.kind}")
  10.   end
  11. rescue Svn::Error => e
  12.   # catch a generic svn error
  13.   raise "Failed to retrieve SVN info at revision " + revision.to_s
  14. end

SVN Checkout

RUBY:
  1. repos_uri = 'http://svn.website.com/project/trunk'
  2. output_dir '/home/billy/project_name'
  3. revision = 50
  4. begin
  5.   ctx.checkout(repos_uri, output_dir, revision.to_i, nil)
  6. rescue Svn::Error::CLIENT_UNRELATED_RESOURCES => e # revision doesn't exist
  7.   raise "No such revision " + revision.to_s + " at " + repos_uri
  8. end

SVN Log

RUBY:
  1. repos_uri = 'http://svn.website.com/project/trunk'
  2. ctx.log(repos_uri, 0, 'HEAD', 0, true, nil) do |changed_paths, rev, author, date, message|
  3.   puts("Revision: #{rev}")
  4.   puts("Author: #{author}")
  5.   puts("Date: #{date}")
  6.   puts("Message: #{message}")
  7.   puts("---------------------------")
  8. end

SVN List

RUBY:
  1. repos_uri = 'http://svn.website.com/project/trunk'
  2. ctx.list(repos_uri, "HEAD") do |path, dirent, lock, abs_path|
  3.   if !path.blank?
  4.     puts("Path: #{path}")
  5.   end
  6. end

That should get you started with the ruby bindings. If you want to know how to do anything else let me know in the comments.


One Response to “Ruby Subversion Bindings”

Leave a Reply