summaryrefslogtreecommitdiff
path: root/lib/license/finder/ext/npm.rb
blob: e0d4e415c38a96df996b5dee2c95881e316c76b5 (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 NPM
    def current_packages
      NpmPackage.packages_from_json(npm_json, detected_package_path).map do |item|
        Dependency.from(item, detected_package_path)
      end
    end

    def prepare_command
      lockfile? ? 'npm ci' : 'npm install --no-save'
    end

    def possible_package_paths
      [project_path.join('package.json')]
    end

    def prepare
      Dir.chdir(project_path) do
        shell.execute("#{prepare_command} --production", env: default_env)
      end
    end

    private

    def lockfile?
      File.exist?(project_path.join('package-lock.json'))
    end

    def npm_json
      stdout, _stderr, status = Dir.chdir(project_path) do
        shell.execute("npm list --json --long --production")
      end
      status.success? ? JSON.parse(stdout) : {}
    end

    def default_env
      return {} unless shell.custom_certificate_installed?

      { 'NPM_CONFIG_CAFILE' => ENV.fetch('NPM_CONFIG_CAFILE', shell.custom_certificate_path.to_s) }
    end
  end
end