Module: Howzit::Prompt

Defined in:
lib/howzit/prompt.rb

Overview

Command line prompt utils

Class Method Summary collapse

Class Method Details

.choose(matches, height: :auto) ⇒ Array

Choose from a list of items. If fzf is available, uses that, otherwise generates its own list of options and accepts a numeric response

Parameters:

  • matches (Array)

    The options list

  • height (Symbol) (defaults to: :auto)

    height of fzf menu (:auto adjusts height to number of options, anything else gets max height for terminal)

Returns:

  • (Array)

    the selected results



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/howzit/prompt.rb', line 86

def choose(matches, height: :auto)
  return [] if !$stdout.isatty || matches.count.zero?

  if Util.command_exist?('fzf')
    height = if height == :auto
               matches.count + 3
             else
               TTY::Screen.rows
             end

    settings = [
      '-0',
      '-1',
      '-m',
      "--height=#{height}",
      '--header="Use tab to mark multiple selections, enter to display/run"',
      '--prompt="Select a section > "',
      '--preview="howzit {}"'
    ]
    res = `echo #{Shellwords.escape(matches.join("\n"))} | fzf #{settings.join(' ')}`.strip
    if res.nil? || res.empty?
      Howzit.console.info 'Cancelled'
      Process.exit 0
    end
    return res.split(/\n/)
  end

  return matches if matches.count == 1

  res = matches[0..9]
  stty_save = `stty -g`.chomp

  trap('INT') do
    system('stty', stty_save)
    exit
  end

  options_list(matches)

  begin
    printf("Type 'q' to cancel, enter for first item", res.length)
    while (line = Readline.readline(': ', true))
      if line =~ /^[a-z]/i
        system('stty', stty_save) # Restore
        exit
      end
      line = line == '' ? 1 : line.to_i

      return [matches[line - 1]] if line.positive? && line <= matches.length

      puts 'Out of range'
      options_list(matches)
    end
  ensure
    system('stty', stty_save)
    exit
  end
end

.color_single_options(choices = %w[y n])) ⇒ String

Helper function to colorize the Y/N prompt

Parameters:

  • choices (Array) (defaults to: %w[y n]))

    The choices with default capitalized

Returns:

  • (String)

    colorized string



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/howzit/prompt.rb', line 43

def color_single_options(choices = %w[y n])
  out = []
  choices.each do |choice|
    case choice
    when /[A-Z]/
      out.push(Color.template("{bw}#{choice}{x}"))
    else
      out.push(Color.template("{dw}#{choice}{xg}"))
    end
  end
  Color.template("{xg}[#{out.join('/')}{xg}]{x}")
end

.options_list(matches) ⇒ Object

Create a numbered list of options. Outputs directly to console, returns nothing

Parameters:

  • matches (Array)

    The list items



62
63
64
65
66
67
68
69
70
# File 'lib/howzit/prompt.rb', line 62

def options_list(matches)
  counter = 1
  puts
  matches.each do |match|
    printf("%<counter>2d ) %<option>s\n", counter: counter, option: match)
    counter += 1
  end
  puts
end

.yn(prompt, default: true) ⇒ Boolean

Display and read a Yes/No prompt

Parameters:

  • prompt (String)

    The prompt string

  • default (Boolean) (defaults to: true)

    default value if return is pressed or prompt is skipped

Returns:

  • (Boolean)

    result



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/howzit/prompt.rb', line 18

def yn(prompt, default: true)
  return default unless $stdout.isatty

  return default if Howzit.options[:default]

  tty_state = `stty -g`
  system 'stty raw -echo cbreak isig'
  yn = color_single_options(default ? %w[Y n] : %w[y N])
  $stdout.syswrite "\e[1;37m#{prompt} #{yn}\e[1;37m? \e[0m"
  res = $stdin.sysread 1
  res.chomp!
  puts
  system 'stty cooked'
  system "stty #{tty_state}"
  res.empty? ? default : res =~ /y/i
end