Class: ShellAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/shell_adapter.rb

Class Method Summary collapse

Class Method Details

.add_pipe(cmd:, to:, operator: '|') ⇒ Object



43
44
45
# File 'lib/shell_adapter.rb', line 43

def self.add_pipe(cmd:, to:, operator: '|')
  [cmd, operator, to].join(' ')
end

.add_redirect(cmd:, to:, operator: '>>') ⇒ Object



39
40
41
# File 'lib/shell_adapter.rb', line 39

def self.add_redirect(cmd:, to:, operator: '>>')
  [cmd, operator, to].join(' ')
end

.build_cmd(executable:, args: [], redirect_to: nil, pipe_to: nil) ⇒ Object



32
33
34
35
36
37
# File 'lib/shell_adapter.rb', line 32

def self.build_cmd(executable:, args: [], redirect_to: nil, pipe_to: nil)
  line = [executable, args].flatten.compact.join(' ')
  line = add_pipe(cmd: line, to: pipe_to) if pipe_to
  line = add_redirect(cmd: line, to: redirect_to) if redirect_to
  line
end

.capture_with_stdin(cmd: [], stdin: nil) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/shell_adapter.rb', line 22

def self.capture_with_stdin(cmd: [], stdin: nil)
  cmd_line = build_cmd( executable: cmd[0], args: cmd[1..-1] )

  stdout_str, status = Open3.capture2(cmd_line, stdin_data: stdin)
  unless status.success?
    raise CmdFailedError.new(cause: "#{$?}", message: "failing cmd: #{cmd_line}")
  end
  stdout_str
end

.exec(binary, *args) ⇒ Object

run the given binary with the given arguments, discarding the output

Raises:



9
10
11
12
13
14
15
16
# File 'lib/shell_adapter.rb', line 9

def self.exec(binary, *args)
  cmd_line = build_cmd( executable: binary, args: args )
  log "executing cmd #{cmd_line}"
  # TODO: maybe use Open3.popen2e instead, so that we
  # can get streaming output as well as exit code?
  result = Kernel.system(cmd_line)
  raise CmdFailedError.new(cause: "#{$?}", message: "failing cmd: #{cmd_line}") unless result
end

.output_of(*args) ⇒ Object



18
19
20
# File 'lib/shell_adapter.rb', line 18

def self.output_of(*args)
  capture_with_stdin(cmd: args).strip
end