Sha256: 7e03ce340cf75fbc38234d25cc7aae3f6d0ea55e00f044a2abc362673224c102

Contents?: true

Size: 1.7 KB

Versions: 37

Compression:

Stored size: 1.7 KB

Contents

require "inspec/resources/command"
require "shellwords" unless defined?(Shellwords)

module Inspec::Resources
  class NpmPackage < Inspec.resource(1)
    name "npm"
    supports platform: "unix"
    supports platform: "windows"
    desc "Use the npm InSpec audit resource to test if a global npm package is installed. npm is the the package manager for Nodejs packages, such as bower and StatsD."
    example <<~EXAMPLE
      describe npm('bower') do
        it { should be_installed }
      end

      describe npm('tar', path: '/path/to/project') do
        it { should be_installed }
      end
    EXAMPLE

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

    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

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

    def version
      info[:version]
    end

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

Version data entries

37 entries across 37 versions & 1 rubygems

Version Path
inspec-core-4.56.58 lib/inspec/resources/npm.rb
inspec-core-5.17.4 lib/inspec/resources/npm.rb
inspec-core-5.14.0 lib/inspec/resources/npm.rb
inspec-core-4.56.20 lib/inspec/resources/npm.rb
inspec-core-5.12.2 lib/inspec/resources/npm.rb
inspec-core-5.10.5 lib/inspec/resources/npm.rb
inspec-core-4.56.19 lib/inspec/resources/npm.rb
inspec-core-5.7.9 lib/inspec/resources/npm.rb
inspec-core-4.56.17 lib/inspec/resources/npm.rb
inspec-core-4.52.9 lib/inspec/resources/npm.rb
inspec-core-4.50.3 lib/inspec/resources/npm.rb
inspec-core-4.49.0 lib/inspec/resources/npm.rb
inspec-core-4.46.13 lib/inspec/resources/npm.rb
inspec-core-4.41.20 lib/inspec/resources/npm.rb
inspec-core-4.41.2 lib/inspec/resources/npm.rb
inspec-core-4.38.9 lib/inspec/resources/npm.rb
inspec-core-4.38.3 lib/inspec/resources/npm.rb
inspec-core-4.37.30 lib/inspec/resources/npm.rb
inspec-core-4.37.25 lib/inspec/resources/npm.rb
inspec-core-4.37.23 lib/inspec/resources/npm.rb