Module: Kernel

Defined in:
lib/run-command.rb

Defined Under Namespace

Classes: RunCommandFailed

Instance Method Summary collapse

Instance Method Details

#run_command(*args, **options) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/run-command.rb', line 7

def run_command(*args, **options)
  args = args.flatten.compact.map(&:to_s)
  command = args.shift
  env = options.delete(:env) || {}
  verbose = options.delete(:verbose) || false
  pretend = options.delete(:pretend) || false
  argv0 = options.delete(:argv0)
  input = options.delete(:input)
  interactive = options.delete(:interactive)
  if verbose
    warn "$ %s%s" % [
      env.empty? ? nil : env.map { |kv| kv.join('=') }.join(' ') + ' ',
      [command, *args].shelljoin,
    ]
  end
  unless pretend
    if interactive
      system(env, *command)
      output = nil
    else
      output = IO.popen(env, [argv0 ? [command, argv0] : command, *args], 'r+', options) do |io|
        io.write(input.to_s) if input
        io.close_write
        io.read
      end
    end
    raise RunCommandFailed, "Command #{command.to_s.inspect} failed: #{$?}" if $? != 0
    output
  end
end