Class: Brut::CLI::Executor

Inherits:
Object
  • Object
show all
Defined in:
lib/brut/cli/executor.rb

Overview

  • Assumes spawned commands should succeed, raising an error if they do not.

Instance Method Summary collapse

Constructor Details

#initialize(out:, err:) ⇒ Executor

Create the executor

Parameters:



14
15
16
17
# File 'lib/brut/cli/executor.rb', line 14

def initialize(out:,err:)
  @out = out
  @err = err
end

Instance Method Details

#system(*args) ⇒ int

Execute a command, logging it to the standard output and outputing the commands output and error to the standard output and error, respectively. If the command exits nonzero, the exit status is returned.

Generally, you want to use #system! for commands that must succeed for the caller to continue. Only use this method if you need to do special error-handling when the underlying command fails.

Parameters:

  • args (String|Array)

    Whatever you would give to Kernel#system or Open3.popen3.

Returns:

  • (int)

    0 if the command completed normally, otherwise the nonzero exit status. DO NOT TREAT THIS AS A BOOLEAN VALUE

See Also:



32
33
34
35
36
37
# File 'lib/brut/cli/executor.rb', line 32

def system(*args)
  self.system!(*args)
  0
rescue Brut::CLI::SystemExecError => e
  e.exit_status
end

#system!(*args) ⇒ int

Execute a command, logging it to the standard output and outputing the commands output and error to the standard output and error, respectively. If the command exits nonzero, an exception is raised and your CLI app will also exit nonzero.

If you need to handle the command exiting nonzero, use #system instead, as it will not raise an exception.

Parameters:

  • args (String|Array)

    Whatever you would give to Kernel#system or Open3.popen3.

Returns:

  • (int)

    Always returns 0

Raises:

  • Brut::CLI::Error::SystemExecError if the spawed command exits nonzero

See Also:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/brut/cli/executor.rb', line 53

def system!(*args)
  @out.puts "Executing #{args}"
  wait_thread = Open3.popen3(*args) do |_stdin,stdout,stderr,wait_thread|
    o = stdout.read_nonblock(10, exception: false)
    e = stderr.read_nonblock(10, exception: false)
    while o || e
      if o
        if o != :wait_readable
          @out.print o
          @out.flush
        end
        o = stdout.read_nonblock(10, exception: false)
      end
      if e
        if e != :wait_readable
          @err.print e
          @err.flush
        end
        e = stderr.read_nonblock(10, exception: false)
      end
    end
    wait_thread
  end
  if wait_thread.value.success?
    @out.puts "#{args} succeeded"
  else
    raise Brut::CLI::SystemExecError.new(args,wait_thread.value.exitstatus)
  end
  0
end