Skip to content

Instantly share code, notes, and snippets.

@vindia
Created June 25, 2021 19:36
Show Gist options
  • Save vindia/a446632ad098ff13d409ab0a45c73bdc to your computer and use it in GitHub Desktop.
Save vindia/a446632ad098ff13d409ab0a45c73bdc to your computer and use it in GitHub Desktop.
List licences for a given Ruby project based on the Gemfile
require "bundler"
require "net/http"
require "json"
output = []
debug_mode = ARGV[0] == "--debug"
gems = Bundler::LockfileParser.new(Bundler.read_file(Bundler.default_lockfile))
dependencies =
Bundler::Definition.build('Gemfile', 'Gemfile.lock', nil)
.dependencies
.each_with_object(Hash.new { |h,k| h[k] = [] }) do |dep, obj|
dep.groups.each do |group|
obj[group] << dep.name
end
end
gems.specs.each do |spec|
# We only want gems that are used in production, which means the :default group
next unless dependencies[:default].include? spec.name
puts "Fetching license info for #{spec.name}" if debug_mode
uri = URI("https://rubygems.org/api/v1/gems/#{spec.name}.json")
response = Net::HTTP.get_response(uri)
if response.code != "200"
# We use a few internal gems that are not published on RubyGems
# and do not need to be included here either
# If you see another gem being skipped, please check what's going on
puts "Skipping #{spec.name}" if debug_mode
next
end
parsed_body = JSON.parse(response.body)
spec_info = [
spec.name,
spec.version,
parsed_body["licenses"].to_a.join(" + "),
parsed_body["metadata"]["source_code_uri"]
]
output << spec_info.join(";")
end
puts output.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment