Skip to content

Instantly share code, notes, and snippets.

@Narnach
Created January 29, 2009 15:20
Show Gist options
  • Select an option

  • Save Narnach/54574 to your computer and use it in GitHub Desktop.

Select an option

Save Narnach/54574 to your computer and use it in GitHub Desktop.
Bump a gem's version, tag it and commit it to git
#!/usr/bin/env ruby
# bump.rb - Perform a project version bump
# * If a .gemspec file is present, use it to determine the current project version
# * Scans for the first line that contains .version and a 1.2.3-ish part
# * If no gemspec is present, use the highest tagged version
# * The expected tag format is '1.2.3'
# * Depending on the command line options 'major', 'minor', 'build' it will
# bump the 1st, 2nd, 4th digit of the version. No option implies a 'release',
# which bumps the 3rd digit. Example: 1.2.3 -> 1.2.4 is a release.
# * Overwrites the current gemspec with the new one if a gemspec was found
# * Bumps the gemspec date to today's date
require 'date'
def stop(msg,code=1)
puts msg
exit code
end
class Array
def map_with_index(&block)
ary=[]
each_with_index do |item, index|
ary << block.call(item, index)
end
ary
end
end
bump = [nil, nil, nil, nil]
case ARGV.first
when 'major'
bump = [1,0,0,0]
when 'minor'
bump = [nil,1,0,0]
when 'build'
bump = [nil, nil, nil, 1]
else # when 'release'
bump = [nil, nil, 1, 0]
end
gemspec_file = Dir.glob('*.gemspec').first
if gemspec_file
gemspec = File.read(gemspec_file)
version_line = gemspec.grep(/\.version.*\d+(\.\d)+/).first
version_ary = version_line.scan(/\d+/).map{|digit_str| digit_str.to_i}
old_version_str = version_ary.join(".")
else # Only commit + bump tag
tags = `git tag -l`.split("\n").map{|line| line.strip}
version_tags = tags.select {|tag| tag.match /\A\d(\.\d)+\Z/}
old_version_str = version_tags.max
version_ary = old_version_str.split(".").map{|digit_str| digit_str.to_i}
end
new_version = version_ary.map_with_index do |digit, index|
case bump[index]
when 0
0
when nil
digit
else
digit + bump[index]
end
end
new_version_str = new_version.join(".")
puts "Bump from %s to %s" % [old_version_str, new_version_str]
if gemspec_file
# Bump version
new_version_line = version_line.gsub(old_version_str, new_version_str)
new_gemspec = gemspec.gsub(version_line, new_version_line)
# Bump date
old_date_line = gemspec.grep(/date.*?["'][0-9\-]+["']/).first
old_date = old_date_line.match(/["']([0-9\-]+)["']/)[1]
date = Date.today
new_date = "%04i-%02i-%02i" % [date.year, date.month, date.day]
new_date_line = old_date_line.gsub(old_date,new_date)
new_gemspec = new_gemspec.gsub!(old_date_line,new_date_line)
# Write gemspec
File.open(gemspec_file,'w') {|f| f.puts(new_gemspec)}
end
system("git commit -va -m \"Version #{new_version_str}\" && git tag -fa #{new_version_str} -m \"Version #{new_version_str}\"")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment