Module: ShellTools
- Extended by:
- ShellTools
- Included in:
- ShellTools
- Defined in:
- lib/shell_tools.rb,
lib/shell_tools/version.rb
Constant Summary collapse
- VERSION =
"0.1.2"
Instance Method Summary collapse
- #capture ⇒ Object
- #capture_all ⇒ Object
- #capture_stdout ⇒ Object
- #escape(*command) ⇒ Object
- #escape_word(str) ⇒ Object
- #sh(cmd, base = nil) ⇒ Object
-
#sh_with_code(cmd, base = nil) ⇒ Object
Run in shell, return both status and output.
Instance Method Details
#capture ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/shell_tools.rb', line 41 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 |
#capture_all ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/shell_tools.rb', line 63 def capture_all old_out, old_err = STDOUT.dup, STDERR.dup stdall_read, stdall_write = IO.pipe $stdout.reopen(stdall_write) $stderr.reopen(stdall_write) yield stdall_write.close stdall_write.rewind && stdall_write.read rescue "" ensure $stdout.reopen(old_out) $stderr.reopen(old_err) end |
#capture_stdout ⇒ Object
58 59 60 61 |
# File 'lib/shell_tools.rb', line 58 def capture_stdout out, _ = capture { yield } out end |
#escape(*command) ⇒ Object
20 21 22 |
# File 'lib/shell_tools.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 |
# File 'lib/shell_tools.rb', line 24 def escape_word(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end |
#sh(cmd, base = nil) ⇒ Object
6 7 8 9 |
# File 'lib/shell_tools.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
13 14 15 16 17 18 |
# File 'lib/shell_tools.rb', line 13 def sh_with_code(cmd, base = nil) cmd << " 2>&1" outbuf = '' outbuf = `#{base && "cd '#{base}' && "}#{cmd}` [outbuf, $?] end |