Module: Gem::License

Defined in:
lib/gem_license.rb

Overview

Container for license fetching utilities

Class Method Summary collapse

Class Method Details

.download(shortname, opt) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/gem_license.rb', line 46

def download(shortname, opt)
  license_list = fetch_license_list
  id_list = license_list.collect { |l_obj| l_obj['licenseId'] }

  id = match_license_id(shortname, id_list)
  license_obj = license_list.find { |l_obj| l_obj['licenseId'] == id }

  path = opt[:output_path]
  path = 'LICENSE' + (opt[:markdown] ? '.md' : '') if path.nil? && !opt[:stdout]

  write_license license_obj, path
end

.fetch_license_listObject



9
10
11
12
13
14
# File 'lib/gem_license.rb', line 9

def fetch_license_list
  list_uri = URI('https://spdx.org/licenses/licenses.json')
  JSON.parse(list_uri.read)['licenses']
rescue OpenURI::HTTPError => e
  raise Gem::CommandLineError, "Unable to get license list. [#{e.message}]"
end

.fetch_license_text(url) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/gem_license.rb', line 16

def fetch_license_text(url)
  license_uri = URI(url)
  license_obj = JSON.parse(license_uri.read)
  license_obj['licenseText']
rescue OpenURI::HTTPError => e
  raise Gem::CommandLineError, "Unable to get license text. [#{e.message}]"
end

.match_license_id(license_id, id_list) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/gem_license.rb', line 24

def match_license_id(license_id, id_list)
  perfect_match = id_list.find { |id| id.downcase == license_id.downcase }
  return perfect_match if perfect_match

  spell_checker = DidYouMean::SpellChecker.new(dictionary: id_list)
  id = spell_checker.correct(license_id).first
  abort 'Unable to find a matching SPDX identifier.' + (id ? " Did you mean `#{id}'?" : '')
end

.write_license(license_obj, path = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gem_license.rb', line 33

def write_license(license_obj, path = nil)
  text = fetch_license_text(license_obj['detailsUrl'])
  text = format_license(text) if format

  if path
    File.open(path, 'w+') do |f|
      f.write text
    end
  else
    $DEFAULT_OUTPUT.puts text
  end
end