Class: IO

Inherits:
Object
  • Object
show all
Defined in:
lib/branch_io_cli/core_ext/io.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.command_from_args(*args) ⇒ Object

Raises:

  • (ArgumentError)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/branch_io_cli/core_ext/io.rb', line 61

def IO.command_from_args(*args)
  raise ArgumentError, "sh requires at least one argument" unless args.count > 0

  # Ignore any trailing options in the output
  if args.last.kind_of?(Hash)
    options = args.pop
    obfuscate = options[:obfuscate]
  end

  command = ""

  # Optional initial environment Hash
  if args.first.kind_of?(Hash)
    command = args.shift.map { |k, v| "#{k}=#{v.shellescape}" }.join(" ") + " "
  end

  # Support [ "/usr/local/bin/foo", "foo" ], "-x", ...
  if args.first.kind_of?(Array)
    command += args.shift.first.shellescape + " " + args.shelljoin
    command.chomp! " "
  elsif args.count == 1 && args.first.kind_of?(String)
    command += args.first
  else
    command += args.shelljoin
  end

  if obfuscate
    BranchIOCLI::Configuration::Environment.obfuscate_user(command)
  else
    command
  end
end

Instance Method Details

#sh(*args) ⇒ Object

Report the command. Execute the command, capture stdout and stderr and report line by line. Report the exit status at the end in case of error. Returns a Process::Status object.

Parameters:

  • command

    a shell command to execute and report



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/branch_io_cli/core_ext/io.rb', line 12

def sh(*args)
  write "$ #{IO.command_from_args(*args)}\n\n"

  obfuscate = args.last.delete(:obfuscate) if args.last.kind_of?(Hash)

  Open3.popen2e(*args) do |stdin, output, thread|
    # output is stdout and stderr merged
    output.each do |line|
      if obfuscate
        puts BranchIOCLI::Configuration::Environment.obfuscate_user(line)
      else
        puts line
      end
    end

    status = thread.value
    if status == 0
      write "Success.\n\n"
    else
      write "#{status}\n\n"
    end
    return status
  end
end