Last active
January 12, 2021 19:49
-
-
Save brand-it/e64ddff96760a76eb529d7be945f9c2e to your computer and use it in GitHub Desktop.
Lazy code to move gems from one gem inabox to another. requires the gem inabox to be installed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'net/http' | |
require 'open-uri' | |
require 'tempfile' | |
require File.expand_path('ruby_bash', __dir__).to_s | |
options = {} | |
parser = OptionParser.new do |opts| | |
opts.banner = 'Usage: replicate gem inabox' | |
opts.on('-f', '--from [HOST]', String) do |host| | |
options[:from_host] = host | |
end | |
opts.on('-t', '--to [HOST]', String) do |host| | |
options[:to_host] = host | |
end | |
opts.on_tail('-h', '--help', 'Prints this help') do | |
puts opts | |
exit | |
end | |
options | |
end | |
parser.parse! | |
class DownloadGemInabox | |
attr_reader :to, :from | |
def initialize(to, from) | |
@to = URI(to) | |
@from = URI(from) | |
end | |
def call | |
to_paths = to_gems_urls.map(&:path) | |
from_gem_urls.each_with_index do |url, index| | |
next puts "Already Exists #{url.path} #{from_gem_urls.size - index}" if to_paths.include?(url.path) | |
print "Downloading #{url.path} #{from_gem_urls.size - index} \r" | |
gemname = url.path.gsub('/gems/', '').gsub('.gem', '') | |
file = download(gemname, url) | |
print "Uploading #{url.path} #{from_gem_urls.size - index} \r" | |
system!("gem inabox #{file.path} -g #{to}") | |
file.unlink | |
puts "Uploaded #{url.path} #{from_gem_urls.size - index} " | |
end | |
end | |
private | |
def download(gemname, uri) | |
Tempfile.new(gemname).tap do |file| | |
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.is_a?(URI::HTTPS)) do |http| | |
request = Net::HTTP::Get.new uri | |
file.write(http.request(request).body) | |
end | |
file.close | |
end | |
end | |
def to_gems_urls | |
@to_gems_urls ||= gem_urls(to) | |
end | |
def from_gem_urls | |
@from_gem_urls ||= gem_urls(from) | |
end | |
def gem_urls(uri) | |
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.is_a?(URI::HTTPS)) do |http| | |
request = Net::HTTP::Get.new uri | |
http.request(request).body | |
end.scan(%r{/gems/.*.gem}).uniq.map { |x| URI.join(uri, x) } | |
end | |
end | |
Errors.add('From host is missing --from') if options[:from_host].to_s == '' | |
Errors.add('To host is missing --to') if options[:to_host].to_s == '' | |
abort_and_display_errors | |
DownloadGemInabox.new(options[:to_host], options[:from_host]).call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment