DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby Subversion Pre-commit Hook To Prevent Conflicting Rails Migrations

10.26.2006
| 12819 views |
  • submit to reddit
        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