Debian Codegraph @

pkg/util/generator/generator_common.go

raw
1 // Package generator provides common utilities for interactive CLI generators.
2 //
3 // The generator package facilitates question/answer-based user interaction through
4 // the UserDialog type. It supports capturing various input types including strings,
5 // integers, booleans, and regex patterns with built-in validation. The package is
6 // designed to support service configuration generation in CLI applications.
7 //
8 // Key features:
9 // - Interactive prompts with validation
10 // - Support for multiple input types (string, int, bool)
11 // - Regex pattern matching for input validation
12 // - Property-based input for non-interactive usage
13 // - Colored output for better user experience
14 package generator
15
16 import (
17 "bufio"
18 "errors"
19 "fmt"
20 "io"
21 "regexp"
22 "strconv"
23
24 "github.com/nicholas-fedor/shoutrrr/pkg/color"
25 "github.com/nicholas-fedor/shoutrrr/pkg/format"
26 )
27
28 // UserDialog facilitates question/answer-based user interaction for CLI generators.
29 // It provides methods to prompt users for various input types with validation,
30 // supporting both interactive and property-based (non-interactive) modes.
31 //
32 // The UserDialog uses a bufio.Scanner for reading input from the provided reader,
33 // and writes output to the provided writer. It maintains a map of pre-defined
34 // properties that can be used instead of prompting the user interactively.
35 type UserDialog struct {
36 reader io.Reader // source for reading user input
37 writer io.Writer // destination for writing prompts and messages
38 scanner *bufio.Scanner // buffered scanner for reading lines of input
39 props map[string]string // pre-defined properties for non-interactive mode
40 }
41
42 // errInvalidFormat indicates that the user input does not match the expected format.
43 // This error is returned when input fails to match a regex pattern or validation rule.
44 var errInvalidFormat = errors.New("invalid format")
45
46 // errRequired indicates that a required field was left empty.
47 // This error is returned when validation requires at least one character of input.
48 var errRequired = errors.New("field is required")
49
50 // errNotANumber indicates that the input could not be parsed as a number.
51 // This error is returned when parsing integer input fails.
52 var errNotANumber = errors.New("not a number")
53
54 // errInvalidBoolFormat indicates that a boolean answer was not "yes" or "no".
55 // This error is returned when boolean parsing fails to recognize the input.
56 var errInvalidBoolFormat = errors.New("answer must be yes or no")
57
58 // NewUserDialog initializes a new UserDialog instance with safe defaults.
59 //
60 // If the provided props map is nil, an empty map is created to prevent nil
61 // pointer dereferences during property lookups.
62 //
63 // Parameters:
64 // - reader: the source for reading user input (typically os.Stdin)
65 // - writer: the destination for writing prompts and output (typically os.Stdout)
66 // - props: a map of pre-defined property values keyed by field name; may be nil
67 //
68 // Returns:
69 // - *UserDialog: a configured UserDialog instance ready for user interaction
70 func NewUserDialog(reader io.Reader, writer io.Writer, props map[string]string) *UserDialog {
71 if props == nil {
72 props = map[string]string{}
73 }
74
75 return &UserDialog{
76 reader: reader,
77 writer: writer,
78 scanner: bufio.NewScanner(reader),
79 props: props,
80 }
81 }
82
83 // Query prompts the user with the given prompt and returns regex capture groups
84 // if the input matches the validator pattern.
85 //
86 // If a property with the given key exists in the UserDialog's props map,
87 // the property value is validated and used instead of prompting interactively.
88 //
89 // Parameters:
90 // - prompt: the message displayed to the user
91 // - validator: a compiled regular expression for validating and capturing input
92 // - key: the property key for looking up pre-defined values
93 //
94 // Returns:
95 // - []string: the regex capture groups from the matched input; nil if no match
96 func (ud *UserDialog) Query(prompt string, validator *regexp.Regexp, key string) []string {
97 var groups []string
98
99 ud.QueryString(prompt, ValidateFormat(func(answer string) bool {
100 groups = validator.FindStringSubmatch(answer)
101
102 return groups != nil
103 }), key)
104
105 return groups
106 }
107
108 // QueryAll prompts the user with the given prompt and returns multiple regex matches
109 // up to the specified maximum number of matches.
110 //
111 // If a property with the given key exists in the UserDialog's props map,
112 // the property value is validated and used instead of prompting interactively.
113 //
114 // Parameters:
115 // - prompt: the message displayed to the user
116 // - validator: a compiled regular expression for validating and capturing input
117 // - key: the property key for looking up pre-defined values
118 // - maxMatches: the maximum number of matches to return; negative for all matches
119 //
120 // Returns:
121 // - [][]string: a slice of regex capture groups for each match; nil if no matches
122 func (ud *UserDialog) QueryAll(
123 prompt string,
124 validator *regexp.Regexp,
125 key string,
126 maxMatches int,
127 ) [][]string {
128 var matches [][]string
129
130 ud.QueryString(prompt, ValidateFormat(func(answer string) bool {
131 matches = validator.FindAllStringSubmatch(answer, maxMatches)
132
133 return matches != nil
134 }), key)
135
136 return matches
137 }
138
139 // QueryBool prompts the user with the given prompt and returns the answer as a boolean.
140 //
141 // The method accepts various boolean representations through format.ParseBool,
142 // including "yes"/"no", "true"/"false", "y"/"n", "1"/"0", etc.
143 //
144 // If a property with the given key exists in the UserDialog's props map,
145 // the property value is validated and used instead of prompting interactively.
146 //
147 // Parameters:
148 // - prompt: the message displayed to the user
149 // - key: the property key for looking up pre-defined values
150 //
151 // Returns:
152 // - bool: the parsed boolean value; defaults to false if input cannot be parsed
153 func (ud *UserDialog) QueryBool(prompt, key string) bool {
154 var value bool
155
156 ud.QueryString(prompt, func(answer string) error {
157 parsed, ok := format.ParseBool(answer, false)
158 if ok {
159 value = parsed
160
161 return nil
162 }
163
164 return fmt.Errorf(
165 "%w: use %v or %v",
166 errInvalidBoolFormat,
167 format.ColorizeTrue("yes"),
168 format.ColorizeFalse("no"),
169 )
170 }, key)
171
172 return value
173 }
174
175 // QueryInt prompts the user with the given prompt and returns the answer as an integer.
176 //
177 // The method supports decimal, hexadecimal (with 0x or # prefix), and negative numbers.
178 // Hexadecimal input with # prefix (e.g., #ffa080) is explicitly treated as base 16.
179 //
180 // If a property with the given key exists in the UserDialog's props map,
181 // the property value is validated and used instead of prompting interactively.
182 //
183 // Parameters:
184 // - prompt: the message displayed to the user
185 // - key: the property key for looking up pre-defined values
186 // - bitSize: the integer type bit size (0 for int, 8 for int8, 16 for int16, etc.)
187 //
188 // Returns:
189 // - int64: the parsed integer value; 0 if parsing fails
190 func (ud *UserDialog) QueryInt(prompt, key string, bitSize int) int64 {
191 validator := regexp.MustCompile(`^((0x|#)([0-9a-fA-F]+))|(-?\d+)$`)
192
193 var value int64
194
195 ud.QueryString(prompt, func(answer string) error {
196 groups := validator.FindStringSubmatch(answer)
197 if len(groups) < 1 {
198 return errNotANumber
199 }
200
201 number := groups[0]
202
203 base := 0
204 if groups[2] == "#" {
205 // Explicitly treat #ffa080 as hexadecimal
206 base = 16
207 number = groups[3]
208 }
209
210 var err error
211
212 value, err = strconv.ParseInt(number, base, bitSize)
213 if err != nil {
214 return fmt.Errorf("parsing integer from %q: %w", answer, err)
215 }
216
217 return nil
218 }, key)
219
220 return value
221 }
222
223 // QueryString prompts the user with the given prompt and returns the answer
224 // if it passes the provided validator function.
225 //
226 // If a property with the given key exists in the UserDialog's props map and
227 // passes validation, that value is returned without prompting interactively.
228 // If the property value fails validation, an error message is displayed and
229 // interactive prompting begins.
230 //
231 // If the validator parameter is nil, a no-op validator is used that accepts
232 // any input.
233 //
234 // The method loops until valid input is received or the input source is closed.
235 // When input is closed (EOF), an empty string is returned.
236 //
237 // Parameters:
238 // - prompt: the message displayed to the user
239 // - validator: a function that validates the input and returns an error if invalid; may be nil
240 // - key: the property key for looking up pre-defined values
241 //
242 // Returns:
243 // - string: the validated user input; empty string if input source is closed
244 func (ud *UserDialog) QueryString(prompt string, validator func(string) error, key string) string {
245 if validator == nil {
246 validator = func(string) error { return nil }
247 }
248
249 answer, foundProp := ud.props[key]
250 if foundProp {
251 err := validator(answer)
252 colAnswer := format.ColorizeValue(answer, false)
253 colKey := format.ColorizeProp(key)
254
255 if err == nil {
256 ud.Writelnf("Using prop value %v for %v", colAnswer, colKey)
257
258 return answer
259 }
260
261 ud.Writelnf("Supplied prop value %v is not valid for %v: %v", colAnswer, colKey, err)
262 }
263
264 for {
265 ud.Write("%v ", prompt)
266
267 cfg := color.DefaultConfig()
268 c := color.NewWithConfig(cfg, color.FgHiWhite)
269 c.Set()
270
271 if !ud.scanner.Scan() {
272 if err := ud.scanner.Err(); err != nil {
273 ud.Writelnf(err.Error())
274 c.Unset()
275
276 continue
277 }
278 // Input closed, return an empty string
279 c.Unset()
280
281 return ""
282 }
283
284 answer = ud.scanner.Text()
285
286 c.Unset()
287
288 if err := validator(answer); err != nil {
289 ud.Writelnf("%v", err)
290 ud.Writelnf("")
291
292 continue
293 }
294
295 return answer
296 }
297 }
298
299 // QueryStringPattern prompts the user with the given prompt and returns the answer
300 // if it matches the provided regex pattern.
301 //
302 // This is a convenience method that wraps QueryString with regex pattern validation.
303 // Unlike Query, this method does not return capture groups, only the matched string.
304 //
305 // If a property with the given key exists in the UserDialog's props map,
306 // the property value is validated and used instead of prompting interactively.
307 //
308 // Parameters:
309 // - prompt: the message displayed to the user
310 // - validator: a compiled regular expression that the input must match; must not be nil
311 // - key: the property key for looking up pre-defined values
312 //
313 // Returns:
314 // - string: the validated user input that matches the pattern
315 //
316 // Panics:
317 // - If validator is nil, the method panics with an appropriate error message
318 func (ud *UserDialog) QueryStringPattern(
319 prompt string,
320 validator *regexp.Regexp,
321 key string,
322 ) string {
323 if validator == nil {
324 panic("validator cannot be nil")
325 }
326
327 return ud.QueryString(prompt, func(s string) error {
328 if validator.MatchString(s) {
329 return nil
330 }
331
332 return errInvalidFormat
333 }, key)
334 }
335
336 // Write sends a formatted message to the user through the configured writer.
337 //
338 // The message is formatted using fmt.Fprintf with the provided variadic arguments.
339 // If writing fails, an error message is written to the same writer.
340 //
341 // Parameters:
342 // - message: the format string for the message
343 // - v: variadic arguments for formatting the message
344 func (ud *UserDialog) Write(message string, v ...any) {
345 if _, err := fmt.Fprintf(ud.writer, message, v...); err != nil {
346 _, _ = fmt.Fprint(ud.writer, "failed to write to output: ", err, "\n")
347 }
348 }
349
350 // Writelnf writes a formatted message to the user, appending a newline character.
351 //
352 // This is a convenience method that calls Write with the format string and
353 // appends "\n" to complete the line.
354 //
355 // Parameters:
356 // - fmtStr: the format string for the message
357 // - v: variadic arguments for formatting the message
358 func (ud *UserDialog) Writelnf(fmtStr string, v ...any) {
359 ud.Write(fmtStr+"\n", v...)
360 }
361
362 // ValidateFormat wraps a boolean validator function to return an error on false results.
363 //
364 // This utility function adapts simple boolean validators to the error-returning
365 // validator signature used by QueryString. When the wrapped validator returns false,
366 // errInvalidFormat is returned.
367 //
368 // Parameters:
369 // - validator: a function that takes a string and returns true if valid, false otherwise
370 //
371 // Returns:
372 // - func(string) error: a validator function that returns nil on success or errInvalidFormat on failure
373 func ValidateFormat(validator func(string) bool) func(string) error {
374 return func(answer string) error {
375 if validator(answer) {
376 return nil
377 }
378
379 return errInvalidFormat
380 }
381 }
382
383 // Required validates that the input string contains at least one character.
384 //
385 // This is a common validator function that ensures non-empty input from the user.
386 // It is typically used with QueryString to make fields mandatory.
387 //
388 // Parameters:
389 // - answer: the input string to validate
390 //
391 // Returns:
392 // - error: nil if the answer is non-empty, errRequired if the answer is empty
393 func Required(answer string) error {
394 if answer == "" {
395 return errRequired
396 }
397
398 return nil
399 }