Skip to content

Instantly share code, notes, and snippets.

@Dagnan
Created October 9, 2012 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dagnan/3857662 to your computer and use it in GitHub Desktop.
Save Dagnan/3857662 to your computer and use it in GitHub Desktop.
Gemfile parser: outputs the same Gemfile with the version of each gem used in the current project. Does not handle version of gems from a git repo.
require 'active_support/core_ext/object/try.rb'
trap("INT") { puts "Exiting..."; exit }
FILENAME = ARGV[0]
if FILENAME.nil? || FILENAME.empty?
puts 'Usage:'
puts 'ruby parse_gemfile.rb path-to-your-Gemfile'
exit
end
file =
begin
File.open(FILENAME)
rescue Errno::ENOENT => e
puts "Could not open file #{FILENAME}" ; exit
end
file.each_line do |l|
gem = l.match(/^(\s*)gem\s?['"]([\-a-zA-z]+)['"](,\s*['"](.*[-\.0-9a-zA-Z]+)['"])?(.*)/)
# Puts the line if it does not declare a gem
(puts l ; next) unless gem
# Skips gems with already a version specified
actual_version = gem[4]
(puts l ; next) if actual_version
spaces, gem_name, end_of_line = gem[1], gem[2], gem[5]
output = `bundle show #{gem_name}`
version = output.match(/.*-([0-9\.]+)/).try(:[], 1) or nil
if version
puts %|#{spaces}gem '#{gem_name}', '~> #{version}'#{end_of_line}|
else
puts l
end
end
@Dagnan
Copy link
Author

Dagnan commented Oct 9, 2012

Could be enhanced parsing gem version from the Gemfile.lock instead of calling bundle show.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment