Module: Rap::Utils

Defined in:
lib/rap/utils.rb

Overview

Provides several shell utility methods for calling programs.

Windows

MSDOS has command line length limits specific to the version of Windows being run (from www.ss64.com/nt/cmd.html):

Windows NT

256 characters

Windows 2000

2046 characters

Windows XP

8190 characters

Commands longer than these limits fail, usually with something like: ‘the input line is too long’

Instance Method Summary collapse

Instance Method Details

#capture_sh(cmd, quiet = false, &block) ⇒ Object

Runs the system command cmd and returns the output as a string.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rap/utils.rb', line 49

def capture_sh(cmd, quiet=false, &block) # :yields: ok, status, tempfile_path
  tempfile = Tempfile.new('shell_utils')
  tempfile.close
  redirect_sh(cmd, tempfile.path) do |ok, status|
    if block_given?
      yield(ok, $?, tempfile.path)
    else
      ok or raise %Q{Command failed with status (#{$?.exitstatus}): [#{cmd}]
-------------- command output -------------------
#{File.read(tempfile.path)}
-------------------------------------------------
}
    end
  end

  quiet == true ? "" : File.read(tempfile.path)
end

#redirect_sh(cmd, path, &block) ⇒ Object

Runs the system command cmd using sh, redirecting the output to the specified file path. Uses the redirection command:

"> \"#{path}\" 2>&1 #{cmd}"

This redirection has been tested on Windows, OS X, and Fedora. See en.wikipedia.org/wiki/Redirection_(Unix) for pointers on redirection. This style of redirection SHOULD NOT be used with commands that contain other redirections.



44
45
46
# File 'lib/rap/utils.rb', line 44

def redirect_sh(cmd, path, &block) # :yields: ok, status
  sh( "> \"#{path}\" 2>&1 #{cmd}", &block)
end

#sh(*cmd) ⇒ Object

:startdoc:::- Run the system command cmd, passing the result to the block, if given. Raises an error if the command fails. Uses the same semantics as Kernel::exec and Kernel::system.

Based on FileUtils#sh from Rake. :startdoc:::+



25
26
27
28
29
30
31
32
33
# File 'lib/rap/utils.rb', line 25

def sh(*cmd) # :yields: ok, status
  ok = system(*cmd)

  if block_given?
    yield(ok, $?)
  else
    ok or raise "Command failed with status (#{$?.exitstatus}): [#{ cmd.join(' ')}]"
  end
end