Module: PiotrbCliUtils::ShellHelpers

Defined in:
lib/piotrb_cli_utils/shell_helpers.rb

Instance Method Summary collapse

Instance Method Details

#capture_shell(command, error: true, echo_command: true, indent: 0, raise_on_error: false, detailed_result: false) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/piotrb_cli_utils/shell_helpers.rb', line 36

def capture_shell(command, error: true, echo_command: true, indent: 0, raise_on_error: false, detailed_result: false)
  command = join_cmd(command)
  puts "#{' ' * indent}<< #{command}" if echo_command
  command += ' 2>/dev/null' unless error
  value = `#{command}`
  code = $CHILD_STATUS.exitstatus
  if raise_on_error && code > 0
    raise("capture_shell: #{command.inspect} failed with code: #{code}")
  end

  if detailed_result
    OpenStruct.new({
                     status: code,
                     output: value
                   })
  else
    value
  end
end

#join_cmd(args) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/piotrb_cli_utils/shell_helpers.rb', line 5

def join_cmd(args)
  if args.is_a? Array
    Shellwords.join(args)
  else
    args
  end
end

#run_shell(command, return_status: false, echo_command: true, quiet: false, indent: 0) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/piotrb_cli_utils/shell_helpers.rb', line 13

def run_shell(command, return_status: false, echo_command: true, quiet: false, indent: 0)
  command = join_cmd(command)
  puts "#{' ' * indent}$> #{command}" if echo_command
  command += ' 1>/dev/null 2>/dev/null' if quiet
  system command.to_s
  code = $CHILD_STATUS.exitstatus
  raise("failed with code: #{code}") if !return_status && code > 0

  code
end

#run_with_each_line(command) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/piotrb_cli_utils/shell_helpers.rb', line 24

def run_with_each_line(command)
  command = join_cmd(command)
  Open3.popen2e(command) do |_stdin, stdout_and_stderr, wait_thr|
    pid = wait_thr.pid # pid of the started process.
    until stdout_and_stderr.eof?
      raw_line = stdout_and_stderr.gets
      yield(raw_line)
    end
    wait_thr.value # Process::Status object returned.
  end
end