configure command execution shells to sh/bash/zsh

This commit is contained in:
Dominik Richter 2016-04-18 00:48:18 -04:00
parent a40c6735ec
commit 0631779412
2 changed files with 63 additions and 2 deletions

View file

@ -4,6 +4,8 @@
# author: Christoph Hartmann
# license: All rights reserved
require 'shellwords'
module Inspec::Resources
class Cmd < Inspec.resource(1)
name 'command'
@ -17,14 +19,25 @@ module Inspec::Resources
end
"
SHELLS = {
'sh' => ->(x, path = 'sh') { path + ' -c ' + Shellwords.escape(x) },
'bash' => ->(x, path = 'bash') { path + ' -c ' + Shellwords.escape(x) },
'zsh' => ->(x, path = 'zsh') { path + ' -c ' + Shellwords.escape(x) },
}.freeze
attr_reader :command
def initialize(cmd)
def initialize(cmd, opts = {})
@command = cmd
unless opts.is_a?(Hash)
skip_resource "Called #{self} with invalid command options. See the resource help for valid examples."
opts = {}
end
@opts = opts
end
def result
@result ||= inspec.backend.run_command(@command)
@result ||= inspec.backend.run_command(wrap_cmd)
end
def stdout
@ -59,5 +72,18 @@ module Inspec::Resources
def to_s
"Command #{@command}"
end
private
def wrap_cmd
shell = @opts[:shell]
return @command if shell.nil?
wrapper = SHELLS[shell]
# TODO: fail with an error if the command isn't found
return @command if wrapper.nil?
wrapper.call(@command)
end
end
end

View file

@ -0,0 +1,35 @@
# encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
require 'helper'
require 'inspec/resource'
describe Inspec::Resources::Cmd do
it 'runs regular commands' do
x = rand.to_s
load_resource('command', x).method(:wrap_cmd).call
.must_equal x
end
it 'runs sh commands' do
x = rand.to_s
load_resource('command', '$("'+x+'")', {shell: 'sh'})
.method(:wrap_cmd).call
.must_equal "sh -c \\$\\(\\\"#{x}\\\"\\)"
end
it 'runs bash commands' do
x = rand.to_s
load_resource('command', '$("'+x+'")', {shell: 'bash'})
.method(:wrap_cmd).call
.must_equal "bash -c \\$\\(\\\"#{x}\\\"\\)"
end
it 'runs zsh commands' do
x = rand.to_s
load_resource('command', '$("'+x+'")', {shell: 'zsh'})
.method(:wrap_cmd).call
.must_equal "zsh -c \\$\\(\\\"#{x}\\\"\\)"
end
end