Class: AppleBot::Shell
- Inherits:
-
Object
- Object
- AppleBot::Shell
- Defined in:
- lib/applebot/shell.rb
Instance Method Summary collapse
- #command(sys_command, verbose, format) ⇒ Object
- #puts_format_line(line, format) ⇒ Object
- #result(output, format, print_result) ⇒ Object
- #table(data) ⇒ Object
Instance Method Details
#command(sys_command, verbose, format) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/applebot/shell.rb', line 3 def command(sys_command, verbose, format) output = [] Open3.popen3(sys_command) do |stdin, stdout, stderr, wait_thr| while line = (stdout.gets || stderr.gets) output << line if verbose === true puts_format_line(line, format) end end exit_status = wait_thr.value output << JSON.generate(process_status: exit_status.inspect, thread: wait_thr.inspect) if exit_status.termsig raise SignalTermination.new(exit_status) end unless exit_status.success? raise AppleBotError.for_output(output) end end output.select {|o| o.include?('"result":') }.last end |
#puts_format_line(line, format) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/applebot/shell.rb', line 27 def puts_format_line(line, format) json = JSON.parse(line) case format.to_s when 'json' puts JSON.generate(json.except('normal_output')) else normal_output = json['normal_output'] return if normal_output.blank? return if normal_output.include?("[phantom]") puts(normal_output) end end |
#result(output, format, print_result) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/applebot/shell.rb', line 41 def result(output, format, print_result) result = JSON.parse(output)['result'] case format.to_s when 'pretty' table(result).tap do |t| puts t if print_result end true else result.tap do |json| puts json if print_result end end end |
#table(data) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/applebot/shell.rb', line 57 def table(data) table = nil if data.first && data.first[-1].is_a?(Hash) headings = ['key'] + data.first[-1].keys rows = data.to_a.map { |key_and_value| row = [] headings.each do |heading| if heading == 'key' row << key_and_value[0] else row << key_and_value[1][heading] end end row } table = Terminal::Table.new headings: headings, rows: rows else table = Terminal::Table.new rows: data.to_a end table end |