Class: Command

Inherits:
Object
  • Object
show all
Defined in:
lib/straight_line/common/command.rb

Overview

Basic class for wrapping shell execution

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, args = []) ⇒ Command

Returns a new instance of Command.



6
7
8
9
10
11
# File 'lib/straight_line/common/command.rb', line 6

def initialize(command, args = [])
  @command = command
  @args = args || []
  @working_dir = Dir.pwd
  @sub_commands = []
end

Instance Attribute Details

#working_dirObject

Returns the value of attribute working_dir.



5
6
7
# File 'lib/straight_line/common/command.rb', line 5

def working_dir
  @working_dir
end

Class Method Details

.from_file(_file_name) ⇒ Object



19
# File 'lib/straight_line/common/command.rb', line 19

def self.from_file(_file_name); end

Instance Method Details

#arg(argument, *args) ⇒ Object



13
14
15
16
17
# File 'lib/straight_line/common/command.rb', line 13

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

#run(return_stderr = false) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/straight_line/common/command.rb', line 21

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

#run_sub_commands(return_stderr) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/straight_line/common/command.rb', line 42

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

#sub_command(command) ⇒ Object



52
53
54
55
56
57
# File 'lib/straight_line/common/command.rb', line 52

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