dsw88
dsw88

Reputation: 4592

Remove all installed Gems except for specific versions

I'm tasked with writing an automated cleanup script that removes unused versions of RubyGems on our Build system. The system doesn't use Bundler, so what we've done is manually keep track of which parts of our Build system use which versions of certain gems. Different parts of the system can use different versions of the same gem.

This leaves us in a pickle as to automated cleanup. We have a list of versions that we need to keep, but we'd like to get rid of every other unused version of that Gem. I've looked at the RubyForge docs, and it doesn't look like there's an easy way to accomplish that.

Is there a reasonable way to remove all versions of a gem except certain specified versions?

Upvotes: 1

Views: 513

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

It's actually 8 effective lines of code :) (not including gathering inputs)

# output of `gem list` command
all_gems = <<-GEMS
rvm-capistrano (1.2.7, 1.2.6)
sinatra (1.4.2, 1.3.5, 1.3.3)
tilt (1.4.1, 1.3.7, 1.3.6, 1.3.5, 1.3.3)
GEMS

we_need_these = {
  'sinatra' => '1.4.2',
  'tilt' => '1.4.1'
}

all_gems.split("\n").each do |line|
  versions = line.gsub(/[\(\),]/, '').split(' ')
  gem_name = versions.shift

  versions.each do |v|
    unless we_need_these[gem_name] == v
      # `puts` is used for demonstration purposes. 
      # you'll want to use backticks or `system` method or similar
      puts "gem uninstall #{gem_name} -v #{v}"
    end
  end
end
# >> gem uninstall rvm-capistrano -v 1.2.7
# >> gem uninstall rvm-capistrano -v 1.2.6
# >> gem uninstall sinatra -v 1.3.5
# >> gem uninstall sinatra -v 1.3.3
# >> gem uninstall tilt -v 1.3.7
# >> gem uninstall tilt -v 1.3.6
# >> gem uninstall tilt -v 1.3.5
# >> gem uninstall tilt -v 1.3.3

Upvotes: 4

Related Questions