Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 20 total  RSS 

SVN Diff While Ignoring Whitespace

A command line alias for doing an svn diff while ignoring whitespace differences. Placed in ~/.bashrc or your profile.

Can be used in a directory:
$ dw

Or on a single file:
$ dw functions.php

alias dw="svn diff --diff-cmd diff -x -uw"

Ruby script for performing checkout in Subversion

This Ruby script checkouts Subversion repositories. If during checkout it encounters two or more externals that point to the same directory, that directory is only downloaded once and symbolic links are created where appropriate, avoiding duplication. It requires the Ruby Subversion bindings.

This is my first Ruby program.

#!/usr/bin/env ruby

require 'optparse'
require 'ostruct'
require 'uri'
require 'pathname'
require 'fileutils'
require 'svn/repos'

class Checkout  
	attr_accessor :url, :pathname, :revision

	def initialize(url,pathname, revision=nil)
		@url = url
		@pathname = pathname  
		@revision = revision
	end

	def perform(ctx)
		ctx.checkout @url, @pathname.to_s, @revision, nil, true, true
		proppy = (ctx.propget "svn:externals", @url)[@url]

		if proppy==nil
			proppy=[]
		else
			lines = proppy.split "\n"

			lines.map { |line|
				splitted = line.split " "
				sub_path= Pathname.new(splitted.shift)
				sub_url= splitted.pop
				sub_revision= nil

				if !splitted.empty?
					revnumber_string = splitted.shift.scan(/[0-9]+/).shift
					sub_revision = revnumber_string.to_i
				end

				Checkout.new(sub_url,@pathname.join(sub_path),sub_revision)		
			}
		end
	end
end  

def parse_args(args)
	options = OpenStruct.new

	options.revision = nil;

 	opts = OptionParser.new do |opts|
        	opts.banner = "Usage: example.rb URL [PATH]"

        	opts.separator ""
        	opts.separator "Valid options:"

        	# Mandatory argument.
        	opts.on("-r", "--revision arg","Revision number") do |rev|
          		options.revision = rev.to_i
		end

		opts.on_tail("-h", "--help", "Show this message") do
			puts opts
			exit
        	end
	end

	opts.parse!(args)

	if args.empty?
		print "Repository URL needed", "\n"
		exit
	end

	options.url = args.shift

	if !args.empty?
		options.pathname = Pathname.new(args.shift)
	else
		uri = URI.parse(options.url)
		options.pathname = Pathname.new(uri.path).basename
	end
	
	if !args.empty?
		print "Too many arguments", "\n"
		exit
	end

	Checkout.new(options.url,options.pathname,options.revision)
end


# we parse the args
initial_checkout = parse_args(ARGV)

# we create a client context
ctx = Svn::Client::Context.new
ctx.add_simple_provider
homedir=ENV['HOME']
ctx.auth_baton[Svn::Core::AUTH_PARAM_CONFIG_DIR] = "#{homedir}/.subversion"
# ctx.auth_baton[Svn::Core::AUTH_PARAM_DEFAULT_USERNAME] = "foouser"
# ctx.auth_baton[Svn::Core::AUTH_PARAM_DEFAULT_PASSWORD] = "foopasswd"

# we initialize the data structures
checkout_queue = [initial_checkout]
pathname_cache = {}

# we traverse the tree
while !checkout_queue.empty?
	checkout = checkout_queue.shift

	cached_path = pathname_cache[checkout.url]

	if cached_path==nil
		colist = checkout.perform ctx
		colist.each { |co| checkout_queue.push co }
		pathname_cache[checkout.url] = checkout.pathname

		puts "check out #{checkout.url} -> #{checkout.pathname}"
	else
		relative_path=cached_path.relative_path_from(checkout.pathname.dirname)
		FileUtils.ln_sf(relative_path, checkout.pathname)

		puts "link #{cached_path} -> #{checkout.pathname}"
	end
end

Checkout a Git clone of an SVN repository in parent folder

Here is a quick executable cmd that you run inside a folder checked out with Subversion. It will clone the repository using Git into the parent folder as <projname>.git

Stick this code into ~/bin/gitify and add ~/bin to your path:

#!/usr/bin/env ruby -wKU

# get svn info location
svnurl = `svn info | grep "^URL:"`.gsub('URL: ','').chomp

# project = basename
project = File.basename(Dir.pwd)

puts cmd = "git-svn clone #{svnurl} ../#{project}.git"

`#{cmd}`

Subversion basic commands Part II

This code shows how to checkout, commit, and verify the changes to a project file in subversion. See also Subversion basic commands part 1 http://urltea.com/1urp . The Subversion Online book can be read here http://svnbook.red-bean.com/

# get the project to edit
svn checkout http://mysite.com/svn/my-repository/my-project

#add a new file to the project
svn add feed/changelog

# commit the changes to the repository
svn commit feed

# check to see that the actual changes have been committed.
svn cat 
http://mysite.com/svn/my-repository/my-project/trunk/gwd/feed/gwd.rb

#remove the local project files
rm my-project -Rf

#get the project files without version control
svn export http://mysite.com/my-repository/my-project/trunk/gwd

Subversion basic commands Part I

New users to SVN should be familiar with the following commands. Examples based on the code from Gentoo-wiki - HOWTO subversion SVN http://urltea.com/1urj .

#server side

# create the project directory structure outside of svn
mkdir -p ~/Documents/code/my-project/{trunk,tags,branches} 

# create the new repository
svnadmin create /var/svn/my-repository 

# add the new project
svn import my-project file:////var/svn/my-repository/my-project

# remove the project
rm -rf /var/svn/my-repository/my-project 


#client side

# list the contents of my-project
svn list --verbose http://my-site.com/svn/my-repository/my-project 


# *update 29-Oct-07*
# it's possible to import, or remove the project from the client-side

# add the new project
svn import my-project http://my-site.com/svn/my-repository/my-project 

# remove the project
svn delete http://my-site.com/svn/my-repository/my-project 



Note: To use http on the client side, it's necessary to have Apache configured using SVN and DAV. Refer to HOWTO Apache2 with subversion SVN and DAV. http://urltea.com/1uqg

Set common svn:externals easily

#!/usr/bin/env ruby
shared = 'shared' # Directorio protegido sobre el que jamás se ejecutara nada.
# Lista de directorios con elementos externos:
elementos_externos = { # 'directorio' => {'elemento_externo => 'URL del repositorio'}
  'public/images' => {'_app' => 'svn://server/rails_app/public/images/_gw'},
  'public/javascripts' => {'_app' => 'svn://server/paxx/public/gooworks/rails_app/public/javascripts/_gw'},
  'public/stylesheets' => {'_app' => 'svn://server/rails_app/public/stylesheets/_gw'},
  'vendor' => {'rails' => 'http://dev.rubyonrails.com/svn/rails/trunk'}
# 'dir' => ['ext' => 'url', 'ext2' => 'url'] <-- para varios externos en un mismo directorio
}

if ARGV[0].nil?
  puts "Especifica el directorio en el que quieres trabajar: #{$0} <directorio>"
  exit
end

max_dir_size = 0; max_ext_size = 0
elementos_externos.each do |dir, extlist|
  max_dir_size = dir.size if dir.size > max_dir_size
  extlist.each do |ext, url|
    max_ext_size = ext.size if ext.size > max_ext_size
  end
end

script_dir = Dir.pwd
tmp_file = "#{script_dir}/_svnext_temp_file"

# Esto permite usar comodines, como '*'
ARGV.each do |wd|
  if FileTest.directory?(wd) && wd.chomp('/') != 'gooworks'
    puts "".ljust(80, '=')
    puts "Trabajando en #{wd}:"
    Dir.chdir(wd)
    elementos_externos.sort.each do |dir, extlist|
      file = File.open(tmp_file, 'w') if extlist.size > 1
      extlist.sort.each do |ext, url|
        if file.nil?
          out = %x[svn ps svn:externals '#{ext} #{url}' #{dir}]
        else
          file.puts "#{ext} #{url}"
          out = 'Escribiendo archivo temporal...'
        end
        puts "Configurando #{ext.ljust(max_ext_size)}: #{out}"
      end

      unless file.nil?
        file.close
        # Ejecutamos Subversion para que lea los elementos del archivo que creamos:
        out = %x[svn ps svn:externals -F #{tmp_file} #{dir}]
        puts "Configurado (#{extlist.size} elementos): #{out}"
        File.delete(tmp_file)
      end
    end
    Dir.chdir(script_dir)
  end
end

Opera Syncing using Svn

This batch file allows to run opera after checking out your web-based opera profile. When you terminate your opera session, the batch will commit the changes you made to your profile during the opera session.

 REM OperaSync.bat
 @echo off
 
 set PRG=Opera
 set TARGET=%APPDATA%/%PRG%/%PRG%/profile
 set EXEC=%PROGS%/%PRG%/%PRG%.exe
 set REPO=https://********.googlecode.com/svn/trunk/%PROG%Sync
 set USER=*************
 
 echo Checking out from %REPO% ...
 svn checkout %REPO% "%TARGET%" --username %USER%
 echo %PROG% running ...
 %EXEC%
 echo Commiting to %REPO% ...
 svn commit -m --force-log "%TARGET%"
 echo Done.
 
 @echo on


Here's the list of files that I update from a svn repo for my Opera profile
contacts.adr
files.txt
jscripts/
jscripts/deliciousmp3.js
notes.adr
opcacrt6.dat
opcert6.dat
opera6.adr
search.ini
sessions/
sessions/autosave.win
sessions/autosave.win.bak
speeddial.ini

Trac Subversion Repository scraper

Ruby script to pull code from a Trac repo browser. Useful if you are behind a firewall/proxy and the server has no http access to the subversion repo. (I'm sure its not the prettiest/best/rubiest way to do it, but it worked for me)

#!/usr/bin/env ruby

require 'rubygems'
require 'hpricot'
require 'open-uri'


#a Trac repo scraper. pass the url to scrape (the root of a repo)
#  and optionally the local path to write to.  defaults to .

class TracRepoScraper

  def initialize(trac_url, local_path='.')
    @trac_url = trac_url

    trac_url =~ /(http:\/\/.*?)\//
    @trac_server = $1
    @local_path =  local_path
  end

  def getallfiles(url,cur_localpath)
    if cur_localpath != '.'
      Dir.mkdir(cur_localpath)
    end
    doc = Hpricot(open(url).read)
    doc.search("//tbody//tr//td//a[@class='file']").each do |file_anchor|
      #get the file as curpath+/file_name

      #following gives us absolute path (excluding domain)
      actual_file_url = @trac_server + file_anchor['href']+'?format=raw'
      #temp
      puts "Saving #{actual_file_url} to #{cur_localpath}/#{file_anchor.inner_html}"
      #read the file and write to a file in the correct directory
      File.open(cur_localpath+"/"+file_anchor.inner_html, 'w') do |f|
        remote_file = open(actual_file_url)
        remote_file.each { |line|
          f.puts(line)
        }
      end
    end

    doc.search("//tbody//tr//td//a[@class='dir']").each do |dir_anchor|
      #go into the directory
      dir_url = @trac_server + dir_anchor['href']
      puts "*** stepping into #{dir_url}"
      #dir_anchor.inner_html is the name of the subdirectory (relative)
      getallfiles(dir_url, cur_localpath+"/"+dir_anchor.inner_html)
    end
  end

  def start
    getallfiles(@trac_url, @local_path)
  end
end


#### main

trac_url = ARGV[0]
localpath = '.'
if ARGV[1]
  if !ARGV[1].strip.empty?
    localpath = ARGV[1].strip
  end
end

TracRepoScraper.new(trac_url, localpath).start

Ruby subversion pre-commit hook to prevent conflicting Rails migrations

This is a subversion pre-commit hook that prevents a Ruby on Rails migration being committed that has the same version as an existing migration. To install you place this in a file called pre-commit in the hooks directory of your subversion repository. You can read about hooks here: http://svnbook.red-bean.com/en/1.0/ch05s02.html

#!/usr/bin/env ruby

repo_path = ARGV[0]
transaction = ARGV[1]
svnlook = '/usr/bin/svnlook'

commit_dirs_changed = `#{svnlook} dirs-changed #{repo_path} -t #{transaction}`
commit_changed = `#{svnlook} changed #{repo_path} -t #{transaction}`
#commit_author = `#{svnlook} author #{repo_path} -t #{transaction}`.chop
commit_log = `#{svnlook} log #{repo_path} -t #{transaction}`
#commit_diff = `#{svnlook} diff #{repo_path} -t #{transaction}`
#commit_date = `#{svnlook} date #{repo_path} -t #{transaction}`

# ******* Migration check ********
# if this is a migration then check that there is not already a migration with the same version number in the repository
files = commit_changed.split(/\n/)
current_migrations = nil
for file in files
  if(file =~ /A\s*(.*?\/migrate\/)(\d+)(.*)/)
    migration_path = $1
    migration_version = $2
    
    if(current_migrations == nil)
      current_migrations = {}
      migration_files = `#{svnlook} tree #{repo_path} #{migration_path}`
      for migration in migration_files
        current_migrations[$1] = true if(migration =~ /\s*(\d+)_(.*)/)
      end
    end
    
    if(current_migrations[migration_version])
     STDERR.puts("The is a pre-existing migration with version #{migration_version} in #{migration_path}")
     exit(1)
    end
  end
end


SVN revision from shell

I use this to set the subject of an email that notifies my team of a Capistrano deploy. The part of interest is how it gets the subversion revision number with a few piped shell commands.

echo "Subject: [rake deploy] Deployed revision `cd /home/www/current ; svn info | grep Revision | sed "s/Revision: //"` on `hostname` at `date`" > ~/sendmail_tmp
« Newer Snippets
Older Snippets »
Showing 1-10 of 20 total  RSS