Method: Cmds#capture

Defined in:
lib/cmds/capture.rb

#capture(*args, **kwds, &input_block) ⇒ Cmds::Result Also known as: call

executes the command and returns a Result with the captured outputs.

Parameters:

  • *args (Array<Object>)

    positional parameters to append to those in @args for rendering into the command string.

  • **kwds (Hash{Symbol => Object})

    keyword parameters that override those in @kwds for rendering into the command string.

  • &input_block (#call)

    optional block that returns a string or readable object to override @input.

Returns:

  • (Cmds::Result)

    result of execution with command string, status, stdout and stderr.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cmds/capture.rb', line 21

def capture *args, **kwds, &input_block
  logger.trace "entering Cmds#capture",
    args: args,
    kwds: kwds,
    input: input
  
  # extract input from block via `call` if one is provided,
  # otherwise default to instance variable (which may be `nil`)
  input = input_block.nil? ? input : input_block.call
  
  logger.trace "configured input",
    input: input
  
  # strings output will be concatenated onto
  out = ''
  err = ''

  logger.trace "calling Cmds.spawn..."
  
  status = spawn(*args, **kwds) do |io|
    # send the input to stream, which sends it to spawn
    io.in = input

    # and concat the output lines as they come in
    io.on_out do |line|
      out += line
    end

    io.on_err do |line|
      err += line
    end
  end
  
  logger.trace "Cmds.spawn completed",
    status: status

  # build a Result
  # result = Cmds::Result.new cmd, status, out_reader.value, err_reader.value
  result = Cmds::Result.new last_prepared_cmd, status, out, err

  # tell the Result to assert if the Cmds has been told to, which will
  # raise a SystemCallError with the exit status if it was non-zero
  result.assert if assert

  return result
end