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

module LicenseFinder
  class NPM
    def possible_package_paths
      [project_path.join('package.json')]
    end

    def prepare
      within_project_path do
        tool_box.install(tool: :nodejs, env: default_env)

        if lockfile?
          shell.execute([:npm, :ci, "--production"], env: default_env)
        else
          shell.execute([:npm, :install, '--no-save', "--production"], env: default_env)
        end
      end
    end

    def current_packages
      NpmPackage.packages_from_json(npm_json, detected_package_path).map do |item|
        Dependency.from(item, detected_package_path)
      end
    end

    private

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

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

    def default_env
      {
        'NPM_CONFIG_CAFILE' => ENV.fetch('NPM_CONFIG_CAFILE', shell.default_certificate_path).to_s
      }
    end
  end
end