Sha256: 1b47f7a27404d0a941ad3857f4ef64dc4ba807bc7e7ff5ec9c6f059cb7325dba

Contents?: true

Size: 1.7 KB

Versions: 5

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

require 'awesome_print'
require 'open3'

module Uffizzi
  module UI
    class Shell
      class ExitError < Thor::Error; end
      attr_accessor :output_format

      PRETTY_JSON = 'pretty-json'
      REGULAR_JSON = 'json'

      def initialize
        @shell = Thor::Shell::Basic.new
      end

      def say(message)
        @shell.say(format_message(message))
      end

      def say_error_and_exit(message)
        raise ExitError.new(format_message(message))
      end

      def print_in_columns(messages)
        @shell.print_in_columns(messages)
      end

      def print_table(table_data)
        @shell.print_table(table_data)
      end

      def ask(message, *args)
        answer = @shell.ask(message, *args)
        options = args.last.is_a?(Hash) ? args.pop : {}
        say("\n") unless options.fetch(:echo, true)
        answer
      end

      def last_message
        @shell.send(:stdout).string.strip
      end

      def disable_stdout
        $stdout = StringIO.new
      end

      def enable_stdout
        $stdout = IO.new(1, 'w')
      end

      def stdout_pipe?
        $stdout.stat.pipe?
      end

      def popen2e(command, &block)
        Open3.popen2e(command, &block)
      end

      def capture3(command)
        Open3.capture3(command)
      end

      private

      def format_to_json(data)
        data.to_json
      end

      def format_to_pretty_json(data)
        JSON.pretty_generate(data)
      end

      def format_message(message)
        case output_format
        when PRETTY_JSON
          format_to_pretty_json(message)
        when REGULAR_JSON
          format_to_json(message)
        else
          message
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
uffizzi-cli-2.2.0 lib/uffizzi/shell.rb
uffizzi-cli-2.1.4 lib/uffizzi/shell.rb
uffizzi-cli-2.1.3 lib/uffizzi/shell.rb
uffizzi-cli-2.1.2 lib/uffizzi/shell.rb
uffizzi-cli-2.1.0 lib/uffizzi/shell.rb