Module: Rbop::Shell

Defined in:
lib/rbop/shell.rb

Overview

Shell runner for executing system commands

Defined Under Namespace

Classes: CommandFailed

Class Method Summary collapse

Class Method Details

.run(cmd, env = {}) ⇒ Array<String, Integer>

Run a command and return stdout and exit status

Parameters:

  • cmd (String, Array)

    Command to execute

  • env (Hash) (defaults to: {})

    Environment variables to prepend

Returns:

  • (Array<String, Integer>)

    stdout and exit status



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
# File 'lib/rbop/shell.rb', line 26

def run(cmd, env = {})
  cmd_string = cmd.is_a?(Array) ? shell_escape_array(cmd) : cmd

  # Log command execution if debug mode is enabled
  if Rbop.debug
    $stderr.puts "[RBOP DEBUG] Executing: #{cmd_string}"
    $stderr.puts "[RBOP DEBUG] Environment: #{env.inspect}" unless env.empty?
  end

  # Merge env into current ENV for the command
  if env.empty?
    stdout = `#{cmd_string}`
  else
    # Use bash -c to ensure variable expansion works properly
    env_string = env.map { |k, v| "#{k}='#{v}'" }.join(" ")
    full_cmd = "#{env_string} bash -c '#{cmd_string}'"
    $stderr.puts "[RBOP DEBUG] Full command: #{full_cmd}" if Rbop.debug
    stdout = `#{full_cmd}`
  end

  status = $?.exitstatus

  # Log results if debug mode is enabled
  if Rbop.debug
    $stderr.puts "[RBOP DEBUG] Exit status: #{status}"
    if stdout.length > 200
      $stderr.puts "[RBOP DEBUG] Output (truncated): #{stdout[0..200]}..."
    else
      $stderr.puts "[RBOP DEBUG] Output: #{stdout}"
    end
  end

  if status != 0
    # For authentication errors, include stderr/stdout in the exception
    error_output = stdout.empty? ? "" : ": #{stdout}"
    raise CommandFailed.new("#{cmd_string}#{error_output}", status)
  end

  [ stdout, status ]
end

.shell_escape_array(cmd_array) ⇒ Object



67
68
69
# File 'lib/rbop/shell.rb', line 67

def shell_escape_array(cmd_array)
  Shellwords.join(cmd_array)
end