File: question.rb

package info (click to toggle)
ruby-tty-prompt 0.23.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,452 kB
  • sloc: ruby: 8,847; makefile: 4
file content (391 lines) | stat: -rw-r--r-- 9,721 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
84
85
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# frozen_string_literal: true

require_relative "converters"
require_relative "evaluator"
require_relative "question/modifier"
require_relative "question/validation"
require_relative "question/checks"
require_relative "utils"

module TTY
  # A class responsible for shell prompt interactions.
  class Prompt
    # A class responsible for gathering user input
    #
    # @api public
    class Question
      include Checks

      UndefinedSetting = Class.new do
        def to_s
          "undefined"
        end
        alias_method :inspect, :to_s
      end

      # Store question message
      # @api public
      attr_reader :message

      attr_reader :modifier

      attr_reader :validation

      # Initialize a Question
      #
      # @api public
      def initialize(prompt, **options)
        # Option deprecation
        if options[:validation]
          warn "[DEPRECATION] The `:validation` option is deprecated. Use `:validate` instead."
          options[:validate] = options[:validation]
        end

        @prompt       = prompt
        @prefix       = options.fetch(:prefix) { @prompt.prefix }
        @default      = options.fetch(:default) { UndefinedSetting }
        @required     = options.fetch(:required) { false }
        @echo         = options.fetch(:echo) { true }
        @in           = options.fetch(:in) { UndefinedSetting }
        @modifier     = options.fetch(:modifier) { [] }
        @validation   = options.fetch(:validate) { UndefinedSetting }
        @convert      = options.fetch(:convert) { UndefinedSetting }
        @active_color = options.fetch(:active_color) { @prompt.active_color }
        @help_color   = options.fetch(:help_color) { @prompt.help_color }
        @error_color  = options.fetch(:error_color) { :red }
        @value        = options.fetch(:value) { UndefinedSetting }
        @quiet        = options.fetch(:quiet) { @prompt.quiet }
        @messages     = Utils.deep_copy(options.fetch(:messages) { {} })
        @done         = false
        @first_render = true
        @input        = nil

        @evaluator = Evaluator.new(self)

        @evaluator << CheckRequired
        @evaluator << CheckDefault
        @evaluator << CheckRange
        @evaluator << CheckValidation
        @evaluator << CheckModifier
        @evaluator << CheckConversion
      end

      # Stores all the error messages displayed to user
      # The currently supported messages are:
      #  * :range?
      #  * :required?
      #  * :valid?
      attr_reader :messages

      # Retrieve message based on the key
      #
      # @param [Symbol] name
      #   the name of message key
      #
      # @param [Hash] tokens
      #   the tokens to evaluate
      #
      # @return [Array[String]]
      #
      # @api private
      def message_for(name, tokens = nil)
        template = @messages[name]
        if template && !template.match(/\%\{/).nil?
          [template % tokens]
        else
          [template || ""]
        end
      end

      # Call the question
      #
      # @param [String] message
      #
      # @return [self]
      #
      # @api public
      def call(message = "", &block)
        @message = message
        block.call(self) if block
        @prompt.subscribe(self) do
          render
        end
      end

      # Read answer and convert to type
      #
      # @api private
      def render
        @errors = []
        until @done
          result = process_input(render_question)
          if result.failure?
            @errors = result.errors
            @prompt.print(render_error(result.errors))
          else
            @done = true
          end
          question    = render_question
          input_line  = question + result.value.to_s
          total_lines = @prompt.count_screen_lines(input_line)
          @prompt.print(refresh(question.lines.count, total_lines))
        end
        @prompt.print(render_question) unless @quiet
        result.value
      end

      # Render question
      #
      # @return [String]
      #
      # @api private
      def render_question
        header = []
        if !Utils.blank?(@prefix) || !Utils.blank?(message)
          header << "#{@prefix}#{message} "
        end
        if !echo?
          header
        elsif @done
          header << @prompt.decorate(@input.to_s, @active_color)
        elsif default? && !Utils.blank?(@default)
          header << @prompt.decorate("(#{default})", @help_color) + " "
        end
        header << "\n" if @done
        header.join
      end

      # Decide how to handle input from user
      #
      # @api private
      def process_input(question)
        @input = read_input(question)
        if Utils.blank?(@input)
          @input = default? ? default : nil
        end
        @evaluator.(@input)
      end

      # Process input
      #
      # @api private
      def read_input(question)
        options = { echo: echo }
        if value? && @first_render
          options[:value] = @value
          @first_render = false
        end
        @prompt.read_line(question, **options).chomp
      end

      # Handle error condition
      #
      # @return [String]
      #
      # @api private
      def render_error(errors)
        errors.reduce([]) do |acc, err|
          acc << @prompt.decorate(">>", :red) + " " + err
          acc
        end.join("\n")
      end

      # Determine area of the screen to clear
      #
      # @param [Integer] lines
      #   number of lines to clear
      #
      # @return [String]
      #
      # @api private
      def refresh(lines, lines_to_clear)
        output = []
        if @done
          if @errors.count.zero?
            output << @prompt.cursor.up(lines)
          else
            lines += @errors.count
            lines_to_clear += @errors.count
          end
        else
          output << @prompt.cursor.up(lines)
        end
        output.join + @prompt.clear_lines(lines_to_clear)
      end

      # Convert value to expected type
      #
      # @param [Object] value
      #
      # @api private
      def convert_result(value)
        if convert? && !Utils.blank?(value)
          case @convert
          when Proc
            @convert.call(value)
          else
            Converters.convert(@convert, value)
          end
        else
          value
        end
      end

      # Specify answer conversion
      #
      # @api public
      def convert(value = (not_set = true), message = nil)
        messages[:convert?] = message if message
        if not_set
          @convert
        else
          @convert = value
        end
      end

      # Check if conversion is set
      #
      # @return [Boolean]
      #
      # @api public
      def convert?
        @convert != UndefinedSetting
      end

      # Set default value.
      #
      # @api public
      def default(value = (not_set = true))
        return @default if not_set

        @default = value
      end

      # Check if default value is set
      #
      # @return [Boolean]
      #
      # @api public
      def default?
        @default != UndefinedSetting
      end

      # Ensure that passed argument is present or not
      #
      # @return [Boolean]
      #
      # @api public
      def required(value = (not_set = true), message = nil)
        messages[:required?] = message if message
        return @required if not_set

        @required = value
      end
      alias required? required

      # Set validation rule for an argument
      #
      # @param [Object] value
      #
      # @return [Question]
      #
      # @api public
      def validate(value = nil, message = nil, &block)
        messages[:valid?] = message if message
        @validation = (value || block)
      end

      # Prepopulate input with custom content
      #
      # @api public
      def value(val)
        return @value if val.nil?

        @value = val
      end

      # Check if custom value is present
      #
      # @api private
      def value?
        @value != UndefinedSetting
      end

      def validation?
        @validation != UndefinedSetting
      end

      # Modify string according to the rule given.
      #
      # @param [Symbol] rule
      #
      # @api public
      def modify(*rules)
        @modifier = rules
      end

      # Turn terminal echo on or off. This is used to secure the display so
      # that the entered characters are not echoed back to the screen.
      #
      # @api public
      def echo(value = nil)
        return @echo if value.nil?

        @echo = value
      end
      alias echo? echo

      # Turn raw mode on or off. This enables character-based input.
      #
      # @api public
      def raw(value = nil)
        return @raw if value.nil?

        @raw = value
      end
      alias raw? raw

      # Set expected range of values
      #
      # @param [String] value
      #
      # @api public
      def in(value = (not_set = true), message = nil)
        messages[:range?] = message if message
        if in? && !@in.is_a?(Range)
          @in = Converters.convert(:range, @in)
        end
        return @in if not_set

        @in = Converters.convert(:range, value)
      end

      # Check if range is set
      #
      # @return [Boolean]
      #
      # @api public
      def in?
        @in != UndefinedSetting
      end

      # Set quiet mode.
      #
      # @api public
      def quiet(value)
        @quiet = value
      end

      # @api public
      def to_s
        message.to_s
      end

      # String representation of this question
      # @api public
      def inspect
        "#<#{self.class.name} @message=#{message}, @input=#{@input}>"
      end
    end # Question
  end # Prompt
end # TTY