Module: ShellUtils

Extended by:
ShellUtils
Included in:
ShellUtils
Defined in:
lib/shell_utils.rb,
lib/shell_utils/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#captureObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/shell_utils.rb', line 42

def capture
  old_out, old_err = STDOUT.dup, STDERR.dup
  stdout_read, stdout_write = IO.pipe
  stderr_read, stderr_write = IO.pipe
  $stdout.reopen(stdout_write)
  $stderr.reopen(stderr_write)
  yield
  stdout_write.close
  stderr_write.close
  out = stdout_read.rewind && stdout_read.read rescue nil
  err = stderr_read.rewind && stderr_read.read rescue nil
  [out, err]
ensure
  $stdout.reopen(old_out)
  $stderr.reopen(old_err)
end

#escape(*command) ⇒ Object



20
21
22
# File 'lib/shell_utils.rb', line 20

def escape(*command)
  command.flatten.map {|word| escape_word(word) }.join(' ')
end

#escape_word(str) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/shell_utils.rb', line 24

def escape_word(str)
  if str.empty?
    "''"
  elsif %r{\A[0-9A-Za-z+,./:=@_-]+\z} =~ str
    str
  else
    result = ''
    str.scan(/('+)|[^']+/) {
      if $1
        result << %q{\'} * $1.length
      else
        result << "'#{$&}'"
      end
    }
    result
  end
end

#sh(cmd, base = nil) ⇒ Object



6
7
8
9
# File 'lib/shell_utils.rb', line 6

def sh(cmd, base = nil)
  out, code = sh_with_code(cmd)
  code == 0 ? out : raise(out.empty? ? "Running `#{cmd}' failed. Run this command directly for more detailed output." : out)
end

#sh_with_code(cmd, base = nil) ⇒ Object

Run in shell, return both status and output

See Also:



13
14
15
16
17
18
# File 'lib/shell_utils.rb', line 13

def sh_with_code(cmd, base = nil)
  cmd << " 2>&1"
  outbuf = ''
  outbuf = `#{base && "cd '#{base}' && "}#{cmd}`
  [outbuf, $?]
end