diff --git a/lib/rake/file_utils.rb b/lib/rake/file_utils.rb index c52091715..5ec141edf 100644 --- a/lib/rake/file_utils.rb +++ b/lib/rake/file_utils.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "rbconfig" require "fileutils" +require "shellwords" #-- # This a FileUtils extension that defines several additional commands to be @@ -70,18 +71,24 @@ def create_shell_runner(cmd) # :nodoc: def sh_show_command(cmd, options = nil) # :nodoc: cmd = cmd.dup + env = nil if Hash === cmd.first - env = cmd.first - env = env.map { |name, value| "#{name}=#{value}" }.join " " - cmd[0] = env + env = cmd.shift.map { |name, value| + "#{name}=#{Shellwords.shellescape(value.to_s)}" + }.join(" ") end - cmd = cmd.join " " + # One string is a shell command line. Several arguments are passed + # through to exec, so quote each one. Otherwise an argument that + # contains a space is printed as two words (rake#501). + shown = cmd.length > 1 ? cmd.map { |arg| Shellwords.shellescape(arg.to_s) } : cmd + shown = [env, *shown].compact.join(" ") + if options and chdir = options[:chdir] - "(cd #{chdir} && #{cmd})" + "(cd #{Shellwords.shellescape(chdir.to_s)} && #{shown})" else - cmd + shown end end private :sh_show_command diff --git a/test/test_rake_file_utils.rb b/test/test_rake_file_utils.rb index 88e06f714..210c894ea 100644 --- a/test/test_rake_file_utils.rb +++ b/test/test_rake_file_utils.rb @@ -324,9 +324,23 @@ def test_sh_show_command show_cmd = send :sh_show_command, cmd - expected_cmd = "RAKE_TEST_SH=someval #{RUBY} some_file.rb some argument" + assert_equal [RUBY, "some_file.rb", "some argument"], + Shellwords.split(show_cmd.sub(/\ARAKE_TEST_SH=someval /, "")) + end + + def test_sh_show_command_quotes_arguments_with_spaces + cmd = ["ruby", "extconf.rb", "--", "--with-cflags=-Wundef -Werror"] + + show_cmd = send :sh_show_command, cmd + + assert_equal cmd, Shellwords.split(show_cmd) + + env = { "CFLAGS" => "-Wundef -Werror" } + show_cmd = send :sh_show_command, [env, "gcc", "file name.c"] + assert_equal ["CFLAGS=-Wundef -Werror", "gcc", "file name.c"], + Shellwords.split(show_cmd) - assert_equal expected_cmd, show_cmd + assert_equal "echo hello | wc", send(:sh_show_command, ["echo hello | wc"]) end def test_sh_if_a_command_exits_with_error_status_its_full_output_is_printed