Class: Simple::CLI::Helpers::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/simple/cli/helpers.rb

Instance Method Summary collapse

Constructor Details

#initialize(cmd, *args) ⇒ Command

Returns a new instance of Command.



73
74
75
76
# File 'lib/simple/cli/helpers.rb', line 73

def initialize(cmd, *args)
  @cmd = cmd
  @args = [cmd] + args
end

Instance Method Details

#check_success!Object



99
100
101
102
# File 'lib/simple/cli/helpers.rb', line 99

def check_success!
  return if @process_status.success?
  raise "#{@cmd} failed with #{@process_status.exitstatus}: #{self}"
end

#runObject



84
85
86
87
88
89
90
91
92
93
# File 'lib/simple/cli/helpers.rb', line 84

def run
  ::Simple::CLI.logger.info "> #{self}"
  if @args.length > 1
    system to_s
  else
    system @args.first
  end
ensure
  @process_status = $?
end

#shObject



78
79
80
81
82
# File 'lib/simple/cli/helpers.rb', line 78

def sh
  ::Simple::CLI.logger.info "> #{self}"
  stdout_str, @process_status = Open3.capture2(*@args, binmode: true)
  stdout_str
end

#success?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/simple/cli/helpers.rb', line 95

def success?
  @process_status.success?
end

#to_sObject

Returns the command as a single string, escaping things as necessary.



105
106
107
108
109
110
111
112
113
114
115
# File 'lib/simple/cli/helpers.rb', line 105

def to_s
  require "shellwords"

  escaped_args = @args.map do |arg|
    escaped = Shellwords.escape(arg)
    next escaped if escaped == arg
    next escaped if arg.include?("'")
    "'#{arg}'"
  end
  escaped_args.join(" ")
end