class Geny::Actions::Shell

Utilities for executing shell commands

Public Class Methods

new(ui:) click to toggle source

Create a new shell @param ui [UI]

# File lib/geny/actions/shell.rb, line 10
def initialize(ui:)
  @ui = ui
end

Public Instance Methods

capture(*args, **opts) click to toggle source

Run a shell command and return it's output @raise [ExitError] when the command exits with a non-zero status @return [String]

@example

shell.capture("echo", "hello") #=> "hello"
# File lib/geny/actions/shell.rb, line 20
def capture(*args, **opts)
  cmd = build_command(*args, **opts)
  cmd_str = stringify_command(args)
  out, _err, status = Open3.capture3(*cmd)
  assert_success!(status, cmd_str)
  out.chomp
rescue Errno::ENOENT
  raise ExitError.new(command: cmd_str, code: 127)
end
run(*args, verbose: true, **opts) click to toggle source

Run a shell command @raise [ExitError] when the command exits with a non-zero status

@example

shell.capture("echo", "hello") # prints "hello"
# File lib/geny/actions/shell.rb, line 35
def run(*args, verbose: true, **opts)
  cmd = build_command(*args, **opts)
  cmd_str = stringify_command(args)

  @ui.status("run", cmd_str) if verbose

  Kernel.system(*cmd)
  assert_success!($?, cmd_str)
end

Private Instance Methods

assert_success!(status, cmd) click to toggle source
# File lib/geny/actions/shell.rb, line 55
def assert_success!(status, cmd)
  unless status.success?
    raise ExitError.new(command: cmd, code: status.exitstatus)
  end
end
build_command(*args, env: nil, **opts) click to toggle source
# File lib/geny/actions/shell.rb, line 47
def build_command(*args, env: nil, **opts)
  [*env, *args, **opts]
end
stringify_command(args) click to toggle source
# File lib/geny/actions/shell.rb, line 51
def stringify_command(args)
  args.map { |arg| arg.match?(/\s/) ? arg.inspect : arg }.join(" ")
end