Skip to content

Commit

Permalink
Support passing array commands to format_command
Browse files Browse the repository at this point in the history
The use of an array with Open3 spawns a process directly without a shell
which removes the need to escape values for a shell.
  • Loading branch information
ekohl committed Oct 18, 2024
1 parent 59513de commit ddecdbe
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/kafo/puppet_command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,21 @@ def self.aio_puppet?
false
end

# Format a command for use in Open3 that properly filters the environment
# for use with Puppet
#
# @param command [String, Array]
# The command to execute. A string implies it'll run with a shell while
# an array runs without. That removes the need to escape input and is
# recommended.
# @return [Array]
# A command for use in Open3
def self.format_command(command)
cmd = command.is_a?(Array) ? command : [command]
if aio_puppet?
[clean_env_vars, command, :unsetenv_others => true]
[clean_env_vars] + cmd + [:unsetenv_others => true]
else
[::ENV, command, :unsetenv_others => false]
[::ENV] + cmd + [:unsetenv_others => false]
end
end

Expand Down
38 changes: 38 additions & 0 deletions test/kafo/puppet_command_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,5 +118,43 @@ module Kafo
end
end
end

describe '.format_command' do
describe 'with Puppet AIO' do
specify 'with a string' do
PuppetCommand.stub(:aio_puppet?, true) do
PuppetCommand.stub(:clean_env_vars, {'FOO' => 'bar'}) do
expected = [{'FOO' => 'bar'}, 'echo hello world', { :unsetenv_others => true }]
assert_equal(expected, PuppetCommand.format_command('echo hello world'))
end
end
end

specify 'with an array' do
PuppetCommand.stub(:aio_puppet?, true) do
PuppetCommand.stub(:clean_env_vars, {'FOO' => 'bar'}) do
expected = [{'FOO' => 'bar'}, 'echo', 'hello', 'world', { :unsetenv_others => true }]
assert_equal(expected, PuppetCommand.format_command(['echo', 'hello', 'world']))
end
end
end
end

describe 'with regular Puppet' do
specify 'with a string' do
PuppetCommand.stub(:aio_puppet?, false) do
expected = [::ENV, 'echo hello world', { :unsetenv_others => false }]
assert_equal(expected, PuppetCommand.format_command('echo hello world'))
end
end

specify 'with an array' do
PuppetCommand.stub(:aio_puppet?, false) do
expected = [::ENV, 'echo', 'hello', 'world', { :unsetenv_others => false }]
assert_equal(expected, PuppetCommand.format_command(['echo', 'hello', 'world']))
end
end
end
end
end
end

0 comments on commit ddecdbe

Please sign in to comment.