Module: Philiprehberger::TaskRunner

Defined in:
lib/philiprehberger/task_runner.rb,
lib/philiprehberger/task_runner/result.rb,
lib/philiprehberger/task_runner/version.rb

Defined Under Namespace

Classes: CommandError, Error, Result, TimeoutError

Constant Summary collapse

VERSION =
'0.4.0'

Class Method Summary collapse

Class Method Details

.run(cmd, *args, timeout: nil, env: nil, chdir: nil, signal: :TERM, kill_after: 5, stdin: nil) {|line, stream| ... } ⇒ Result

Run a shell command with output capture, optional timeout, streaming, signal handling, and stdin piping.

When a block is given, each line of stdout/stderr is yielded as it arrives. If the block accepts two arguments, it receives (line, stream) where stream is :stdout or :stderr. If the block accepts one argument, it receives only the line (stdout lines only, for backward compatibility).

Parameters:

  • cmd (String)

    the command to execute

  • args (Array<String>)

    additional command arguments

  • timeout (Numeric, nil) (defaults to: nil)

    maximum seconds to wait (nil for no timeout)

  • env (Hash, nil) (defaults to: nil)

    environment variables to set

  • chdir (String, nil) (defaults to: nil)

    working directory for the command

  • signal (Symbol) (defaults to: :TERM)

    signal to send on timeout (default :TERM)

  • kill_after (Numeric) (defaults to: 5)

    seconds to wait before sending SIGKILL after initial signal (default 5)

  • stdin (String, IO, nil) (defaults to: nil)

    data to pipe to the process’s stdin

Yields:

  • (line, stream)

    each line as it arrives (streaming mode)

Yield Parameters:

  • line (String)

    a line of output

  • stream (Symbol)

    :stdout or :stderr (only if block accepts 2 params)

Returns:

  • (Result)

    the command result

Raises:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/philiprehberger/task_runner.rb', line 44

def self.run(cmd, *args, timeout: nil, env: nil, chdir: nil, signal: :TERM, kill_after: 5, stdin: nil, &block)
  full_cmd = args.empty? ? cmd : [cmd, *args]
  spawn_opts = {}
  spawn_opts[:chdir] = chdir if chdir

  env_hash = env || {}
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  if block
    run_streaming(env_hash, full_cmd, spawn_opts, timeout, start_time, signal, kill_after, stdin, &block)
  else
    run_capture(env_hash, full_cmd, spawn_opts, timeout, start_time, signal, kill_after, stdin)
  end
end

.run!(cmd) ⇒ Result

Run a shell command, raising CommandError on non-zero exit.

Accepts the same arguments as run.

Returns:

  • (Result)

    the command result

Raises:



66
67
68
69
70
71
# File 'lib/philiprehberger/task_runner.rb', line 66

def self.run!(cmd, ...)
  result = run(cmd, ...)
  raise CommandError, result unless result.success?

  result
end