Sha256: 0d8039c6abf96d3012883b20441a883869e0e12b6e016831aa09b77aadf5086e

Contents?: true

Size: 1.43 KB

Versions: 3

Compression:

Stored size: 1.43 KB

Contents

require 'open3'
require 'straight_line/common/shell_error'
# Basic class for wrapping shell execution
class Command
  attr_accessor :working_dir
  def initialize(command, args = [])
    @command = command
    @args = args || []
    @working_dir = Dir.pwd
    @sub_commands = []
  end

  def arg(argument, *args)
    @args << argument
    @args += args if args
    self
  end

  def self.from_file(_file_name); end

  def run(return_stderr = false)
    Dir.chdir working_dir do
      command_with_params = "#{@command} #{@args.join ' '}"

      if return_stderr
        res, status = Open3.capture2e command_with_params
      else
        res, stderr, status = Open3.capture3(command_with_params)
      end
      unless status.exitstatus.zero?
        output = return_stderr ? res : "#{res}\n#{stderr}"
        raise ShellError, %(Command `#{command_with_params}` exited with
          status code: #{status.exitstatus}. Command outputted:\n #{output})
      end

      sub_res = run_sub_commands return_stderr

      res + "\n" + sub_res
    end
  end

  def run_sub_commands(return_stderr)
    sub_res = ''
    unless @sub_commands.empty?
      sub_res = @sub_commands.map do |sub_command|
        sub_command.run return_stderr
      end.join("\n")
    end
    sub_res
  end

  def sub_command(command)
    unless command.is_a? Command
      raise ArgumentError, 'command must be of type straight_line/common/command'
    end
    @sub_commands << command
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
straight_line-0.1.4.0 lib/straight_line/common/command.rb
straight_line-0.1.3.0 lib/straight_line/common/command.rb
straight_line-0.1.2.0 lib/straight_line/common/command.rb