Skip to content

Instantly share code, notes, and snippets.

@seasonedgeek
Created February 28, 2020 18:28
Show Gist options
  • Save seasonedgeek/e5a4cfdf08db5fc1fcf0643feb751c64 to your computer and use it in GitHub Desktop.
Save seasonedgeek/e5a4cfdf08db5fc1fcf0643feb751c64 to your computer and use it in GitHub Desktop.
Programmatically uninstall one or more target gems including ALL of their dependencies.
#!/usr/bin/env ruby
# -- coding: utf-8 --
# frozen_string_literal: true
require 'json'
require 'ostruct'
require 'logger'
# This module attempts to trash (uninstall) one or more target gems,
# including ALL of their dependent gems.
module TrashTargetGems
def init_logger
@logger ||= Logger.new(STDOUT)
@logger.level = Logger::INFO
end
# Returns true if successful.
#
# Process a list of gems to be uninstalled.
def cleanup_gem_mess
json_string = '[
{ "name": "http-cookie", "version": "1.0.3" },
{ "name": "netrc", "version": "0.11.0" },
{ "name": "rest-client", "version": "1.8.0" },
{ "name": "domain_name", "version": "0.5.20190701" },
{ "name": "mime-types", "version": "2.99.3" },
{ "name": "unf", "version": "0.1.4" },
{ "name": "unf_ext", "version": "0.0.7.6" },
{ "name": "zip-zip", "version": "0.3" },
{ "name": "behave", "version": "0.4.0" }]'
deps = JSON.parse(json_string, object_class: OpenStruct)
cleansed = Array.new(deps.count) { |i| 0 }
index = 0
deps.each do |gem_obj|
@logger.info("Trash this gem? #{gem_obj.name}, #{gem_obj.version}")
# store 1=true; 0=false based on action
cleansed[index] = cleanup_this_gem(gem_obj.name, gem_obj.version)
index += 1
end
result = (cleansed.inject(0) { |sum, x| sum + x } > 0)
end
# Given this gem's attributes, execute shell commands
# to uninstall unattended. ignore dependencies.
def cleanup_this_gem(gem_name, gem_version)
puts `gem list -i #{gem_name} -v #{gem_version}`
if $?.success?
puts `yes|gem uninstall #{gem_name} -v #{gem_version} -x -I`
cleaned = $?.success? ? 1 : 0
else
cleaned = 0
end
end
end
# This class is an interface.
class UnwantedGems
include TrashTargetGems
end
# execute the cleanup process
janitor = UnwantedGems.new
janitor.init_logger
if janitor.cleanup_gem_mess
puts 'Gem(s) Uninstalled. Cleanup complete.'
else
puts 'Gem(s) Not Found: maybe an issue.'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment