summaryrefslogtreecommitdiff
path: root/lib/license/finder/ext/dependency.rb
blob: 6e4aff64b94ddfdbb4cf17fceb538fce7ec42669 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

module LicenseFinder
  class Dependency < Package
    attr_accessor :detection_path, :package_manager

    def initialize(package_manager, name, version, options = {})
      @package_manager = package_manager
      @detection_path = options[:detection_path] || Pathname.pwd
      options[:spec_licenses] = split_licenses_from(options[:spec_licenses]) if options[:spec_licenses]
      super(name, version, options)
    end

    def self.from(other, detection_path)
      new(
        other.package_manager,
        other.name,
        other.version,
        description: other.description,
        detection_path: detection_path,
        homepage: other.homepage,
        install_path: other.install_path,
        spec_licenses: other.license_names_from_spec,
        summary: other.summary
      )
    end

    private

    def split_licenses_from(declared_licenses)
      declared_licenses.map do |declared|
        license_for(::Spandx::Spdx::Expression.new.parse(declared)[0])
      rescue StandardError
        declared
      end.flatten.compact
    end

    def license_for(node)
      return [node&.to_s] unless node.is_a?(Hash)

      [license_for(node[:left]), license_for(node[:right])]
    end
  end
end