Module: Doing::Prompt

Extended by:
Color
Defined in:
lib/doing/prompt.rb

Overview

Terminal Prompt methods

Constant Summary

Constants included from Color

Color::ATTRIBUTES, Color::ATTRIBUTE_NAMES, Color::COLORED_REGEXP

Class Attribute Summary collapse

Class Method Summary collapse

Methods included from Color

attributes, coloring?, support?, uncolor

Class Attribute Details

.default_answerObject



23
24
25
# File 'lib/doing/prompt.rb', line 23

def default_answer
  @default_answer ||= false
end

.force_answerObject



19
20
21
# File 'lib/doing/prompt.rb', line 19

def force_answer
  @force_answer ||= nil
end

Class Method Details

.choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) ⇒ String

Generate a menu of options and allow user selection

Returns:

  • The selected option



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/doing/prompt.rb', line 230

def choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: [])
  return nil unless $stdout.isatty

  # fzf_args << '-1' # User is expecting a menu, and even if only one it seves as confirmation
  default_args = []
  default_args << %(--prompt="#{prompt}")
  default_args << "--height=#{options.count + 2}"
  default_args << '--info=inline'
  default_args << '--multi' if multiple
  header = "esc: cancel,#{multiple ? ' tab: multi-select, ctrl-a: select all,' : ''} return: confirm"
  default_args << %(--header="#{header}")
  default_args.concat(fzf_args)
  options.sort! if sorted

  res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{default_args.join(' ')}`
  return false if res.strip.size.zero?

  res
end

.choose_from_items(items, **opt) ⇒ Object

Create an interactive menu to select from a set of Items

Parameters:

  • list of items

  • Additional options

Options Hash (**opt):

  • :include_section (Boolean)

    Include section name for each item in menu

  • :header (String)

    A custom header string

  • :prompt (String)

    A custom prompt string

  • :query (String)

    Initial query

  • :show_if_single (Boolean)

    Show menu even if there's only one option

  • :menu (Boolean)

    Show menu

  • :sort (Boolean)

    Sort options

  • :multiple (Boolean)

    Allow multiple selections

  • :case (Symbol) — default: :sensitive, :ignore, :smart


266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/doing/prompt.rb', line 266

def choose_from_items(items, **opt)
  return items unless $stdout.isatty

  return nil unless items.count.positive?

  case_sensitive = opt.fetch(:case, :smart).normalize_case
  header = opt.fetch(:header, 'Arrows: navigate, tab: mark for selection, ctrl-a: select all, enter: commit')
  prompt = opt.fetch(:prompt, 'Select entries to act on > ')
  query = opt.fetch(:query) { opt.fetch(:search, '') }
  include_section = opt.fetch(:include_section, false)

  pad = items.length.to_s.length
  options = items.map.with_index do |item, i|
    out = [
      format("%#{pad}d", i),
      ') ',
      format('%16s', item.date.strftime('%Y-%m-%d %H:%M')),
      ' | ',
      item.title
    ]
    if include_section
      out.concat([
        ' (',
        item.section,
        ') '
      ])
    end
    out.join('')
  end

  fzf_args = [
    %(--header="#{header}"),
    %(--prompt="#{prompt.sub(/ *$/, ' ')}"),
    opt.fetch(:multiple) ? '--multi' : '--no-multi',
    '-0',
    '--bind ctrl-a:select-all',
    %(-q "#{query}"),
    '--info=inline'
  ]
  fzf_args.push('-1') unless opt.fetch(:show_if_single, false)
  fzf_args << case case_sensitive
              when :sensitive
                '+i'
              when :ignore
                '-i'
              end
  fzf_args << '-e' if opt.fetch(:exact, false)


  unless opt.fetch(:menu)
    raise InvalidArgument, "Can't skip menu when no query is provided" unless query && !query.empty?

    fzf_args.concat([%(--filter="#{query}"), opt.fetch(:sort) ? '' : '--no-sort'])
  end

  res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{fzf_args.join(' ')}`
  selected = []
  res.split(/\n/).each do |item|
    idx = item.match(/^ *(\d+)\)/)[1].to_i
    selected.push(items[idx])
  end

  opt.fetch(:multiple) ? selected : selected[0]
end

.clear_screen(msg = nil) ⇒ Object

Clear the terminal screen



14
15
16
17
# File 'lib/doing/prompt.rb', line 14

def clear_screen(msg = nil)
  puts "\e[H\e[2J" if STDOUT.tty?
  puts msg if msg.good?
end

.enter_text(prompt, default_response: '') ⇒ Object



27
28
29
30
31
32
33
# File 'lib/doing/prompt.rb', line 27

def enter_text(prompt, default_response: '')
  $stdin.reopen('/dev/tty')
  return default_response if @default_answer

  print "#{yellow(prompt).sub(/:?$/, ':')} #{reset}"
  $stdin.gets.strip
end

.fzfObject



159
160
161
# File 'lib/doing/prompt.rb', line 159

def fzf
  @fzf ||= install_fzf
end

.install_fzf(force: false) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/doing/prompt.rb', line 188

def install_fzf(force: false)
  if force
    uninstall_fzf
  elsif which_fzf
    return which_fzf
  end

  fzf_dir = File.join(File.dirname(__FILE__), '../helpers/fzf')
  FileUtils.mkdir_p(fzf_dir) unless File.directory?(fzf_dir)
  fzf_bin = File.join(fzf_dir, 'bin/fzf')
  return fzf_bin if File.exist?(fzf_bin)

  prev_level = Doing.logger.level
  Doing.logger.adjust_verbosity({ log_level: :info })
  Doing.logger.log_now(:warn, 'fzf:', 'Compiling and installing fzf -- this will only happen once')
  Doing.logger.log_now(:warn, 'fzf:', 'fzf is copyright Junegunn Choi, MIT License <https://github.com/junegunn/fzf/blob/master/LICENSE>')

  silence_std
  `'#{fzf_dir}/install' --bin --no-key-bindings --no-completion --no-update-rc --no-bash --no-zsh --no-fish &> /dev/null`
  unless File.exist?(fzf_bin)
    restore_std
    Doing.logger.log_now(:warn, 'Error installing, trying again as root')
    silence_std
    `sudo '#{fzf_dir}/install' --bin --no-key-bindings --no-completion --no-update-rc --no-bash --no-zsh --no-fish &> /dev/null`
  end
  restore_std
  unless File.exist?(fzf_bin)
    Doing.logger.error('fzf:', 'unable to install fzf. You can install manually and Doing will use the system version.')
    Doing.logger.error('fzf:', 'see https://github.com/junegunn/fzf#installation')
    raise RuntimeError.new('Error installing fzf, please report at https://github.com/ttscoff/doing/issues')
  end

  Doing.logger.info('fzf:', "installed to #{fzf}")
  Doing.logger.adjust_verbosity({ log_level: prev_level })
  fzf_bin
end

.read_line(prompt: 'Enter text', completions: [], default_response: '') ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/doing/prompt.rb', line 35

def read_line(prompt: 'Enter text', completions: [], default_response: '')
  $stdin.reopen('/dev/tty')
  return default_response if @default_answer

  unless completions.empty?
    completions.sort!
    comp = proc { |s| completions.grep(/^#{Regexp.escape(s)}/) }
    Readline.completion_append_character = ' '
    Readline.completion_proc = comp
  end

  begin
    Readline.readline("#{yellow(prompt).sub(/:?$/, ':')} #{reset}", true).strip
  rescue Interrupt
    raise UserCancelled
  end
end

.read_lines(prompt: 'Enter text', completions: [], default_response: '') ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/doing/prompt.rb', line 53

def read_lines(prompt: 'Enter text', completions: [], default_response: '')
  $stdin.reopen('/dev/tty')
  return default_response if @default_answer

  completions.sort!
  comp = proc { |s| completions.grep(/^#{Regexp.escape(s)}/) }
  Readline.completion_append_character = ' '
  Readline.completion_proc = comp
  prompt_text = []
  prompt_text << boldgreen(prompt.sub(/:?$/, ':'))
  prompt_text << yellow(' Enter a blank line (')
  prompt_text << boldwhite('return twice')
  prompt_text << yellow(') to end editing and save, ')
  prompt_text << boldwhite('CTRL-C')
  prompt_text << yellow(' to cancel')
  puts prompt_text.join('')

  res = []

  begin
    while (line = Readline.readline('> ', true))
      break if line.strip.empty?

      res << line.chomp
    end
  rescue Interrupt
    raise UserCancelled
  end

  res.join("\n").strip
end

.request_lines(prompt: 'Enter text', default_response: '') ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/doing/prompt.rb', line 85

def request_lines(prompt: 'Enter text', default_response: '')
  $stdin.reopen('/dev/tty')
  return default_response if @default_answer

  ask_note = []
  reader = TTY::Reader.new(interrupt: -> { raise Errors::UserCancelled }, track_history: false)
  puts "#{boldgreen(prompt.sub(/:?$/, ':'))} #{yellow('Hit return for a new line, ')}#{boldwhite('enter a blank line (')}#{boldyellow('return twice')}#{boldwhite(') to end editing')}"
  loop do
    res = reader.read_line(green('> '))
    break if res.strip.empty?

    ask_note.push(res)
  end
  ask_note.join("\n").strip
end

.restore_stdObject



183
184
185
186
# File 'lib/doing/prompt.rb', line 183

def restore_std
  $stdout = STDOUT
  $stderr = STDERR
end

.silence_std(file = '/dev/null') ⇒ Object



178
179
180
181
# File 'lib/doing/prompt.rb', line 178

def silence_std(file = '/dev/null')
  $stdout = File.new(file, 'w')
  $stderr = File.new(file, 'w')
end

.uninstall_fzfObject



163
164
165
166
167
# File 'lib/doing/prompt.rb', line 163

def uninstall_fzf
  fzf_bin = File.join(File.dirname(__FILE__), '../helpers/fzf/bin/fzf')
  FileUtils.rm_f(fzf_bin) if File.exist?(fzf_bin)
  Doing.logger.warn('fzf:', "removed #{fzf_bin}")
end

.which_fzfObject



169
170
171
172
173
174
175
176
# File 'lib/doing/prompt.rb', line 169

def which_fzf
  fzf_dir = File.join(File.dirname(__FILE__), '../helpers/fzf')
  fzf_bin = File.join(fzf_dir, 'bin/fzf')
  return fzf_bin if File.exist?(fzf_bin)

  Doing.logger.debug('fzf:', 'Using user-installed fzf')
  TTY::Which.which('fzf')
end

.yn(question, default_response: false) ⇒ Bool

Ask a yes or no question in the terminal

Parameters:

  • The question to ask

  • (defaults to: false)

    default response if no input

Returns:

  • yes or no



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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/doing/prompt.rb', line 111

def yn(question, default_response: false)
  return @force_answer == :yes ? true : false unless @force_answer.nil?

  $stdin.reopen('/dev/tty')

  default = if default_response.is_a?(String)
              default_response =~ /y/i ? true : false
            else
              default_response
            end

  # if global --default is set, answer default
  return default if @default_answer

  # if this isn't an interactive shell, answer default
  return default unless $stdout.isatty

  # clear the buffer
  if ARGV&.length
    ARGV.length.times do
      ARGV.shift
    end
  end
  system 'stty cbreak'

  cw = white
  cbw = boldwhite
  cbg = boldgreen
  cd = Color.default

  options = unless default.nil?
              "#{cw}[#{default ? "#{cbg}Y#{cw}/#{cbw}n" : "#{cbw}y#{cw}/#{cbg}N"}#{cw}]#{cd}"
            else
              "#{cw}[#{cbw}y#{cw}/#{cbw}n#{cw}]#{cd}"
            end
  $stdout.syswrite "#{cbw}#{question.sub(/\?$/, '')} #{options}#{cbw}?#{cd} "
  res = $stdin.sysread 1
  puts
  system 'stty cooked'

  res.chomp!
  res.downcase!

  return default if res.empty?

  res =~ /y/i ? true : false
end