Module: BBLib::Console

Defined in:
lib/bblib/cli/util.rb,
lib/bblib/cli/color.rb

Constant Summary collapse

DEFAULT_FILE_EDITORS =
%w{vim vi notepad++ notepad}.freeze
COLOR_CODES =
{
  black:   30,
  red:     31,
  green:   32,
  orange:  33,
  yellow:  33,
  blue:    34,
  purple:  35,
  cyan:    36,
  gray:    37,
  grey:    37,
  white:   37,
  none:    0,
  default: 39
}.freeze
SEVERITY_COLORS =
{
  debug:   :light_purple,
  info:    :light_blue,
  warn:    :yellow,
  error:   :light_red,
  fatal:   :red,
  success: :green,
  ok:      :green,
  fail:    :red
}

Class Method Summary collapse

Class Method Details

.colorize(text, color = :none, background: false, light: false) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/bblib/cli/color.rb', line 31

def self.colorize(text, color = :none, background: false, light: false)
  color = SEVERITY_COLORS[color.to_s.downcase.to_sym] if SEVERITY_COLORS.include?(color.to_s.downcase.to_sym)
  if color.to_s.start_with?('light_')
    color = color.to_s.split('_', 2).last.to_sym
    light = true
  end
  light = true if color == :grey || color == :gray
  color = COLOR_CODES[color] if COLOR_CODES.include?(color)
  color = COLOR_CODES[:default] unless color.is_a?(Integer)
  color += 10 if background
  "\e[#{light ? 1 : 0};#{color}m#{text}\e[0m"
end

.confirm?(message = 'Confirm?', yes: 'y', no: 'n', default: true, enter_is_default: true) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/bblib/cli/util.rb', line 21

def self.confirm?(message = 'Confirm?', yes: 'y', no: 'n', default: true, enter_is_default: true)
  response = nil
  until response == yes || response == no
    # TODO Support carriage return to overwrite line
    # print "\b" if response
    print "#{message} [#{default ? 'Y/n' : 'y/N'}]: "
    response = STDIN.gets.chomp.downcase
    response = default ? yes : no if enter_is_default && response.empty?
  end
  response == yes
end

.default_editorObject



17
18
19
# File 'lib/bblib/cli/util.rb', line 17

def self.default_editor
  DEFAULT_FILE_EDITORS.find { |editor| OS.which(editor) }
end

.edit_file(file, editor = default_editor) ⇒ Object

Simple method to open a file in a system text editor. The text editor can be specified otherwise the first default editor that can be found in the path will be used



12
13
14
15
# File 'lib/bblib/cli/util.rb', line 12

def self.edit_file(file, editor = default_editor)
  pid = spawn("#{editor} \"#{file}\"")
  Process.wait(pid)
end

.get(limit: nil) ⇒ Object

TODO Fix this function. Currently requires two hits of enter to move on.



34
35
36
37
38
39
40
41
42
43
# File 'lib/bblib/cli/util.rb', line 34

def self.get(limit: nil)
  str = ''
  loop do
    char = STDIN.raw(&:getc)
    STDOUT.print char
    break if ["\r", "\n", "\r\n"].include?(char)
    str += char
  end
  str.chomp
end