Last active
March 14, 2017 04:12
-
-
Save jrochkind/247e128d216cecf39e0758f303c4a4a4 to your computer and use it in GitHub Desktop.
gem_visit command line utility
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 | |
# Call the file just `gem-visit`, not `gem-visit.rb`, and put it in your path | |
# (maybe you want ~/bin in your $PATH), to be able to do: | |
# | |
# . gem-visit name_of_gem | |
# | |
# And have a browser window opened pointing to the (preferable, if it can) github | |
# homepage of the gem, or other gem project page (last resort). | |
require 'net/http' | |
require 'json' | |
API_HOST = "rubygems.org" | |
PREFERRED_URI_RE = %r{\Ahttps?\://github.com} | |
OPEN_CMD = 'open %s' | |
def usage(err_msg = nil) | |
usage = "USAGE: gem_visit gem_name" | |
if err_msg | |
usage = "Error: #{err_msg}\n#{usage}" | |
end | |
usage | |
end | |
def present?(str) | |
str && ! str.empty? | |
end | |
gem_name = ARGV[0] | |
unless gem_name | |
$stderr.puts usage("Need a gem name") | |
exit 1 | |
end | |
http = Net::HTTP.new(API_HOST, 443).tap { |h| h.use_ssl = true } | |
response = http.get("/api/v1/gems/#{gem_name}.json") | |
if response.code == "404" | |
$stderr.puts "rubygems can't find gem named `#{gem_name}`" | |
exit 1 | |
end | |
unless response.code == "200" | |
$stderr.puts "Error from rubygems: #{response}" | |
exit 1 | |
end | |
data = JSON.parse(response.body) | |
go_to_url = if present?(data["homepage_uri"]) && data["homepage_uri"] =~ PREFERRED_URI_RE | |
data["homepage_uri"] | |
elsif present?(data["source_code_uri"]) && data["source_code_uri"] =~ PREFERRED_URI_RE | |
data["source_code_uri"] | |
elsif present?(data["homepage_uri"]) | |
data["homepage_uri"] | |
elsif present?(data["source_code_uri"]) | |
data["source_code_uri"] | |
else | |
data["project_uri"] | |
end | |
`#{OPEN_CMD % go_to_url}` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment