Module: EasyShell

Defined in:
lib/easy_shell.rb,
lib/easy_shell/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.confirm(msg) ⇒ Object



39
40
41
42
43
# File 'lib/easy_shell.rb', line 39

def self.confirm(msg)
  STDOUT << "#{msg} [Yn] "
  response = STDIN.gets.chomp
  response.empty? || !!response.match(/^(y|yes)$/i)
end

.run(cmd, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/easy_shell.rb', line 5

def self.run(cmd, options = {})
  defaults = {
    :quiet => false,
    :confirm_first => false,
    :continue_on_failure => false,
  }
  unknown_options = options.keys - defaults.keys
  raise "Unknown options #{unknown_options.inspect}" unless unknown_options.empty?
  options = defaults.merge(options)
  cmd.gsub!(/\s+/, ' ')
  cmd.strip!
  cmd_sanitized = cmd.gsub(%r{(https://[-\w]+:)[-\w]+@}, '\1[password sanitized]@')
  puts "=> Running #{cmd_sanitized.inspect}\n" unless options[:quiet]

  return unless confirm("Execute [Yn]? ") if options[:confirm_first]

  output = `#{cmd} 2>&1`
  success = $?.success?
  puts output if success && !options[:quiet]

  unless success
    if options[:continue_on_failure]
      msg = "Continuing, ignoring error while running #{cmd_sanitized.inspect}"
      msg += "\nOutput:\n#{output}" if output
      puts msg
    else
      msg = "ERROR running #{cmd_sanitized.inspect}"
      msg += "\nOutput:\n#{output}" if output
      raise msg
    end
  end
  output
end