Friday, August 17, 2007

Automating SVN stuff with Ruby

Ahoy hoy.

The other day at work I was looking at upgrading an SVN installation at an off-site and came across a good 70 odd repositories dumped to backup. Rather than take the typical windows muppet route and unzip each one, create an svn directory and import them manually, I scripted the whole thing.

Ruby lends itself to this sort of work. I've used it in the past to automate daily and weekly backups of another repository so I knew it would be pretty easy to sort this out. The best part is it didn't take more than 15 minutes from go to whoah. Here it is in it's entirety, it's not a shining example of best practice, nor does it profess to be, but it does what it's supposed to do.



 1 ################################################################################
 2 #
 3 # SVN importer
 4 #
 5 # rubyzip must be installed: gem install rubyzip
 6 #
 7 ################################################################################
 8
 9 require 'zip/zipfilesystem'
10
11 SVN_REPOS_URL = "http://paleale:8090/svn-repos/"
12 SVN_REPOS_PATH = "C:/svn-repos"
13 BACKUP_DIR = "//sparkling/SVNbackups/"
14 UNZIP_DIR = "C:/Documents and Settings/dan/My Documents/"
15
16 # unzip all the dump files into the UNZIP_DIR
17 # we make the assumption that the dump file inside the zip shares the same name
18 # i.e. web_indicator.dump.zip has web.indicator.dump inside it
19 Dir["#{BACKUP_DIR}*/*.zip"].each do |zipFile|
20   dumpFile = zipFile.gsub(/^.*\//,'').gsub(/\.zip/,'')
21   Zip::ZipFile.open(zipFile) do |unZip|  
22     unZip.extract(dumpFile, UNZIP_DIR + dumpFile)
23   end 
24 end  
25
26 # create svn directories for each dumpFile, load into SVN then delete the file
27 Dir.glob("#{UNZIP_DIR}*.dump").each do |dumpFile|
28   projName = dumpFile.gsub(/^.*\//,'').gsub(/\.dump/,'')
29   cmd = %{svn mkdir -m "automated: creating project structure from import" } 
30   cmd << SVN_REPOS_URL << projName
31   %x"#{cmd}"
32   cmd = "svnadmin load --parent-dir #{projName} #{SVN_REPOS_PATH}"
33   cmd << %{ < "#{dumpFile}"}
34   %x"#{cmd}"  
35   File.delete(dumpFile)
36 end

4 comments:

Jeremy Weiskotten said...

This is cool. I suggest you post this on snippets.dzone.com.

I like the title of your blog too.

dan said...

Cheers Jeremy, I'm glad you found it useful. I'll look into getting it over to snippets, sure got a lot of snippets :)

Anonymous said...

This is cool but I'm amazed at how similar Ruby is to Perl. Oh man, you even have regular-expressions in there! :P

dan said...

Ta rudolf, maybe i just write Ruby with a Perl bent...I really gotta work on it :) I figure for small scripts like this it doesn't really warrant much of an OO abstraction.