What is the best way to write rakefile to run commands on Windows?

As an example, I want to run the following command under a rake.

robocopy C:\Media \\other\Media /mir

In rakefile I was able to get a job

def sh(str)
  str.tr!('|', '\\')
  IO.popen(str) do |pipe|
    pipe.each do |line|
      puts line
    end
  end
end

task :default do
  sh 'robocopy C:|Media ||other|Media /mir'
end

However, processing a string literal is inconvenient.

If I use heredoc to enter a string literal

<<HEREDOC
copy C:\Media \\other\Media /mir
HEREDOC

I get an error

rakefile.rb:15: Invalid escape character syntax
copy C:\Media \\other\Media /mir
          ^
rakefile.rb:15: Invalid escape character syntax
copy C:\Media \\other\Media /mir
                        ^

If I use single quotes, one of the backslashes disappears.

irb(main):001:0> 'copy C:\Media \\other\Media /mir'
=> "copy C:\\Media \\other\\Media /mir"
+3
source share
1 answer

The double backslash is interpreted as a fluent single backslash. You must avoid every backslash in a string.

irb(main):001:0> puts 'robocopy C:\\Media \\\\other\\Media /mir'
robocopy C:\Media \\other\Media /mir

, , .

irb(main):001:0> <<'HEREDOC'
irb(main):002:0' copy C:\Media \\other\Media /mir
irb(main):003:0' HEREDOC
=> "copy C:\\Media \\\\other\\Media /mir\n"
irb(main):004:0> puts _
copy C:\Media \\other\Media /mir
+3

Source: https://habr.com/ru/post/1702892/


All Articles