summaryrefslogtreecommitdiff
path: root/lib/license/finder/ext/pip.rb
blob: b57d7c8ef61cc96ed3d80c4db1e867c55f1a9353 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true

module LicenseFinder
  class Pip
    def current_packages
      return legacy_results unless virtual_env?

      dependencies = python.pip_licenses
      dependencies.any? ? dependencies : legacy_results
    end

    def possible_package_paths
      path = project_path || Pathname.pwd

      [
        path.join(@requirements_path),
        path.join('setup.py')
      ]
    end

    def prepare
      return install_packages if detected_package_path == @requirements_path

      requirements_path = detected_package_path.dirname.join('requirements.txt')
      requirements_path.write('.') unless requirements_path.exist?
      install_packages
    end

    private

    def python
      @python ||= ::License::Management::Python.new
    end

    def install_packages
      within_project_dir do
        shell.execute(['virtualenv -p', python_executable, '--activators=bash --seeder=app-data .venv'])
        shell.sh([". .venv/bin/activate", "&&", :pip, :install, '-i', python.pip_index_url, '-r', @requirements_path])
      end
    end

    def python_executable
      '"$(asdf where python)/bin/python"'
    end

    def virtual_env?
      within_project_dir { File.exist?('.venv/bin/activate') }
    end

    def within_project_dir
      Dir.chdir(project_path) { yield }
    end

    def shell
      @shell ||= ::License::Management::Shell.new
    end

    def pypi
      @pypi ||= Spandx::Python::PyPI.new(sources: [
        Spandx::Python::Source.new({
          'name' => 'pypi',
          'url' => python.pip_index_url,
          'verify_ssl' => true
        })
      ])
    end

    def legacy_results
      pip_output.map do |name, version, children, location|
        spec = pypi.definition_for(name, version)
        Package.new(
          name,
          version,
          description: spec['description'],
          homepage: spec['home_page'],
          spec_licenses: PipPackage.license_names_from_spec(spec)
        )
      end
    end
  end
end