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

module LicenseFinder
  class NPM
    def active?
      return if project_path.to_path.include?('/node_modules/')

      project_path.join('package.json').exist?
    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, capture: false)
        else
          shell.execute([:npm, :install, '--no-save', "--production"], env: default_env, capture: false)
        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