2015-09-08 22:12:25 +00:00
# encoding: utf-8
2018-06-01 08:52:46 +00:00
require 'shellwords'
2016-03-08 18:06:55 +00:00
module Inspec::Resources
class NpmPackage < Inspec . resource ( 1 )
name 'npm'
2018-02-19 14:26:49 +00:00
supports platform : 'unix'
supports platform : 'windows'
2016-03-08 18:06:55 +00:00
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 "
describe npm ( 'bower' ) do
it { should be_installed }
end
2018-06-01 08:52:46 +00:00
describe npm ( 'tar' , path : '/path/to/project' ) do
it { should be_installed }
end
2016-03-08 18:06:55 +00:00
"
2018-06-01 08:52:46 +00:00
def initialize ( package_name , opts = { } )
2016-03-08 18:06:55 +00:00
@package_name = package_name
2018-06-01 08:52:46 +00:00
@location = opts [ :path ]
2016-03-08 18:06:55 +00:00
@cache = nil
2015-11-27 13:02:38 +00:00
end
2015-09-08 22:12:25 +00:00
2016-03-08 18:06:55 +00:00
def info
return @info if defined? ( @info )
2015-09-17 14:43:10 +00:00
2018-06-01 08:52:46 +00:00
if @location
npm = " cd #{ Shellwords . escape @location } && npm "
else
npm = 'npm -g'
end
cmd = inspec . command ( " #{ npm } ls --json #{ @package_name } " )
2016-03-08 18:06:55 +00:00
@info = {
name : @package_name ,
type : 'npm' ,
installed : cmd . exit_status == 0 ,
}
return @info unless @info [ :installed ]
2015-09-17 14:43:10 +00:00
2016-03-08 18:06:55 +00:00
pkgs = JSON . parse ( cmd . stdout )
@info [ :version ] = pkgs [ 'dependencies' ] [ @package_name ] [ 'version' ]
@info
end
2015-09-08 22:12:25 +00:00
2016-03-08 18:06:55 +00:00
def installed?
info [ :installed ] == true
end
2015-09-08 22:12:25 +00:00
2016-03-08 18:06:55 +00:00
def version
info [ :version ]
end
2015-09-08 22:12:25 +00:00
2016-03-08 18:06:55 +00:00
def to_s
" Npm Package #{ @package_name } "
end
2015-09-08 22:12:25 +00:00
end
end