Class: Inspec::Resources::NpmPackage

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/resources/npm.rb

Instance Method Summary collapse

Constructor Details

#initialize(package_name, opts = {}) ⇒ NpmPackage

Returns a new instance of NpmPackage.



20
21
22
23
24
# File 'lib/inspec/resources/npm.rb', line 20

def initialize(package_name, opts = {})
  @package_name = package_name
  @location = opts[:path]
  @cache = nil
end

Instance Method Details

#infoObject



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
# File 'lib/inspec/resources/npm.rb', line 26

def info
  return @info if defined?(@info)

  if @location
    command_separator = inspec.os.platform?("windows") ? ";" : "&&"
    invocation = "cd #{Shellwords.escape @location} #{command_separator} npm"
  else
    invocation = "npm -g"
  end

  invocation = "#{invocation} ls --json #{@package_name}"

  # If on unix, wrap in sh -c to protect against sudo
  unless inspec.os.platform?("windows")
    invocation = "sh -c '#{invocation}'"
  end

  cmd = inspec.command(invocation)
  @info = {
    name: @package_name,
    type: "npm",
    installed: cmd.exit_status == 0,
  }
  return @info unless @info[:installed]

  pkgs = JSON.parse(cmd.stdout)
  @info[:version] = pkgs["dependencies"][@package_name]["version"]
  @info
end

#installed?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/inspec/resources/npm.rb', line 56

def installed?
  info[:installed] == true
end

#resource_idObject



64
65
66
# File 'lib/inspec/resources/npm.rb', line 64

def resource_id
  @package_name || "npm"
end

#to_sObject



68
69
70
# File 'lib/inspec/resources/npm.rb', line 68

def to_s
  "Npm Package #{@package_name}"
end

#versionObject



60
61
62
# File 'lib/inspec/resources/npm.rb', line 60

def version
  info[:version]
end