summaryrefslogtreecommitdiff
path: root/lib/license/finder/ext/pip.rb
blob: b32968181119b0aebf43c1c30e8b95cc740d580e (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
# frozen_string_literal: true

module LicenseFinder
  class Pip
    def current_packages
      return legacy_results unless virtual_env?

      dependencies = python.pip_licenses(detection_path: detected_package_path)
      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_path do
        shell.execute(['virtualenv -p', python_executable, '--activators=bash --seeder=app-data .venv'])
        shell.sh([". .venv/bin/activate", "&&", pip_install_command], env: python.default_env)
      end
    end

    def pip_install_command
      [:pip, :install, '-v', '-i', python.pip_index_url, '-r', @requirements_path]
    end

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

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

    def legacy_results
      pip_output.map do |name, version, _children, _location|
        spec = PyPI.definition(name, version)
        Dependency.new(
          'Pip',
          name,
          version,
          description: spec['description'],
          detection_path: detected_package_path,
          homepage: spec['home_page'],
          spec_licenses: PipPackage.license_names_from_spec(spec)
        )
      end
    end
  end
end