Debian Codegraph @

core/custom.go

raw
1 package core
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "slices"
8 "strconv"
9 "strings"
10
11 "github.com/cqroot/prompt"
12 "github.com/cqroot/prompt/choose"
13 "github.com/cqroot/prompt/constants"
14 "github.com/cqroot/prompt/input"
15 "github.com/cqroot/prompt/multichoose"
16 "github.com/cqroot/prompt/write"
17
18 tea "github.com/charmbracelet/bubbletea"
19 )
20
21 // CustomType determines the possible custom choice types.
22 // Current values are: `string`, `block`, `int`, `enum` and `enums`.
23 type CustomType string
24
25 const (
26 CustomString CustomType = "string"
27 CustomBlock CustomType = "block"
28 CustomInt CustomType = "int"
29 CustomEnum CustomType = "enum"
30 CustomEnums CustomType = "enums"
31 )
32
33 // enumsSeparator joins and splits the selected values of an "enums" custom
34 // choice, as the selections are stored as a single string.
35 const enumsSeparator = ", "
36
37 var (
38 errInvalidPromptType = errors.New("invalid prompt type")
39 errInvalidIntInput = errors.New("invalid number")
40 errIntTooLow = errors.New("input below minimum")
41 errIntTooHigh = errors.New("input above maximum")
42 errInputTooLong = errors.New("input length too long")
43 errInputTooShort = errors.New("input length too short")
44 errInvalidEnum = errors.New("invalid enum")
45 errInvalidCustomFormat = errors.New("invalid custom format, must be \"Key=Value\"")
46 base10 = 10
47 bit64 = 64
48 )
49
50 // Custom defines a custom choice that is asked when using 'changie new'.
51 // The result is an additional custom value in the change file for including in the change line.
52 //
53 // A simple one could be the issue number or authors github name.
54 // example: yaml
55 // - key: Author
56 // label: GitHub Name
57 // type: string
58 // minLength: 3
59 type Custom struct {
60 // Value used as the key in the custom map for the change format.
61 // This should only contain alpha numeric characters, usually starting with a capital.
62 // example: yaml
63 // key: Issue
64 Key string `yaml:"key" required:"true"`
65
66 // Specifies the type of choice which changes the prompt.
67 //
68 // | value | description | options
69 // | -- | -- | -- |
70 // string | Freeform text | [minLength](#custom-minlength) and [maxLength](#custom-maxlength)
71 // block | Multiline text | [minLength](#custom-minlength) and [maxLength](#custom-maxlength)
72 // int | Whole numbers | [minInt](#custom-minint) and [maxInt](#custom-maxint)
73 // enum | Limited set of strings | [enumOptions](#custom-enumoptions) is used to specify values
74 // enums | Multiple values from a limited set of strings | [enumOptions](#custom-enumoptions) is used to specify values
75 Type CustomType `yaml:"type" required:"true"`
76
77 // If true, an empty value will not fail validation.
78 // The optional check is handled before min so you can specify that the value is optional but if it
79 // is used it must have a minimum length or value depending on type.
80 //
81 // When building templates that allow for optional values you can compare the custom choice to an
82 // empty string to check for a value or empty.
83 //
84 // example: yaml
85 // custom:
86 // - key: TicketNumber
87 // type: int
88 // optional: true
89 // changeFormat: >-
90 // {{- if not (eq .Custom.TicketNumber "")}}
91 // PROJ-{{.Custom.TicketNumber}}
92 // {{- end}}
93 // {{.Body}}
94 Optional bool `yaml:"optional,omitempty" default:"false"`
95 // Description used in the prompt when asking for the choice.
96 // If empty key is used instead.
97 // example: yaml
98 // label: GitHub Username
99 Label string `yaml:"label,omitempty" default:""`
100 // If specified the input value must be greater than or equal to minInt.
101 MinInt *int64 `yaml:"minInt,omitempty" default:"nil"`
102 // If specified the input value must be less than or equal to maxInt.
103 MaxInt *int64 `yaml:"maxInt,omitempty" default:"nil"`
104 // If specified the string input must be at least this long
105 MinLength *int64 `yaml:"minLength,omitempty" default:"nil"`
106 // If specified string input must be no more than this long
107 MaxLength *int64 `yaml:"maxLength,omitempty" default:"nil"`
108 // When using the enum or enums type, you must also specify what possible options to allow.
109 // Users will be given a selection list to select the value, or values, they want.
110 EnumOptions []string `yaml:"enumOptions,omitempty"`
111 }
112
113 func (c Custom) DisplayLabel() string {
114 if c.Label == "" {
115 return c.Key
116 }
117
118 return c.Label
119 }
120
121 func (c Custom) askString(stdinReader io.Reader) (string, error) {
122 return prompt.New().Ask(c.DisplayLabel()).
123 Input(
124 "",
125 input.WithHelp(true),
126 input.WithValidateFunc(c.validateString),
127 input.WithTeaProgramOpts(tea.WithInput(stdinReader)),
128 )
129 }
130
131 func (c Custom) askBlock(stdinReader io.Reader) (string, error) {
132 return prompt.New().Ask(c.DisplayLabel()).
133 Write(
134 "",
135 write.WithHelp(true),
136 write.WithValidateFunc(c.validateString),
137 write.WithTeaProgramOpts(tea.WithInput(stdinReader)),
138 )
139 }
140
141 func (c Custom) askInt(stdinReader io.Reader) (string, error) {
142 return prompt.New().Ask(c.DisplayLabel()).
143 Input(
144 "",
145 input.WithHelp(true),
146 input.WithInputMode(input.InputInteger),
147 input.WithValidateFunc(c.validateInt),
148 input.WithTeaProgramOpts(tea.WithInput(stdinReader)),
149 )
150 }
151
152 // Scrolling theme for cqroot/prompt. Allows items to be scrolled through
153 // using the arrow keys.
154 //
155 // choices is a list of enum options to display.
156 // cursor is the index of the currently selected item.
157 func ThemeScroll(choices []choose.Choice, cursor int) string {
158 s := strings.Builder{}
159 s.WriteString("\n")
160
161 numChoices := len(choices)
162 index := cursor
163 limit := min(10, numChoices)
164 start := 0
165 end := limit
166
167 // Create a slice of items to display
168 if numChoices > limit {
169 if index < limit/2 {
170 end = limit
171 } else if index >= limit/2 && index <= numChoices-limit/2 {
172 start = index - limit/2
173 end = index + limit/2
174 index = limit / 2
175 } else {
176 start = numChoices - limit
177 end = numChoices
178 index = limit - (numChoices - index)
179 }
180 }
181
182 // Loop through the slice and display each item.
183 // We will determine if the item is selected or not by calling isSelected
184 // with the index of the item, but since we're only displaying a slice of
185 // the items we need to offset the index.
186 for i, choice := range choices[start:end] {
187 // Check if the item is the one at the cursor's location
188 isCursor := index == i
189
190 if isCursor {
191 s.WriteString(constants.DefaultSelectedItemStyle.Render(fmt.Sprintf("• %s", choice.Text)))
192 } else {
193 s.WriteString(constants.DefaultItemStyle.Render(fmt.Sprintf(" %s", choice.Text)))
194 }
195
196 s.WriteString("\n")
197 }
198
199 return s.String()
200 }
201
202 func (c Custom) askEnum(stdinReader io.Reader) (string, error) {
203 return prompt.New().Ask(c.DisplayLabel()).
204 Choose(
205 c.EnumOptions,
206 choose.WithHelp(true),
207 choose.WithTeaProgramOpts(tea.WithInput(stdinReader)),
208 choose.WithTheme(ThemeScroll),
209 )
210 }
211
212 func (c Custom) askEnums(stdinReader io.Reader) (string, error) {
213 values, err := prompt.New().Ask(c.DisplayLabel()).
214 MultiChoose(
215 c.EnumOptions,
216 multichoose.WithHelp(true),
217 multichoose.WithTeaProgramOpts(tea.WithInput(stdinReader)),
218 )
219 if err != nil {
220 return "", err
221 }
222
223 return strings.Join(values, enumsSeparator), nil
224 }
225
226 // CreatePrompt will create a promptui select or prompt from a custom choice
227 func (c Custom) AskPrompt(stdinReader io.Reader) (string, error) {
228 switch c.Type {
229 case CustomString:
230 return c.askString(stdinReader)
231 case CustomBlock:
232 return c.askBlock(stdinReader)
233 case CustomInt:
234 return c.askInt(stdinReader)
235 case CustomEnum:
236 return c.askEnum(stdinReader)
237 case CustomEnums:
238 return c.askEnums(stdinReader)
239 }
240
241 return "", errInvalidPromptType
242 }
243
244 func (c Custom) Validate(input string) error {
245 switch c.Type {
246 case CustomString, CustomBlock:
247 return c.validateString(input)
248 case CustomInt:
249 return c.validateInt(input)
250 case CustomEnum:
251 return c.validateEnum(input)
252 case CustomEnums:
253 return c.validateEnums(input)
254 }
255
256 return errInvalidPromptType
257 }
258
259 func (c Custom) validateString(input string) error {
260 length := int64(len(input))
261
262 if c.Optional && length == 0 {
263 return nil
264 }
265
266 if c.MinLength != nil && length < *c.MinLength {
267 return fmt.Errorf("%w: length of %v < %v", errInputTooShort, length, *c.MinLength)
268 }
269
270 if c.MaxLength != nil && length > *c.MaxLength {
271 return fmt.Errorf("%w: length of %v > %v", errInputTooLong, length, *c.MaxLength)
272 }
273
274 return nil
275 }
276
277 func (c Custom) validateInt(input string) error {
278 if c.Optional && input == "" {
279 return nil
280 }
281
282 value, err := strconv.ParseInt(input, base10, bit64)
283 if err != nil {
284 return errInvalidIntInput
285 }
286
287 if c.MinInt != nil && value < *c.MinInt {
288 return fmt.Errorf("%w: %v < %v", errIntTooLow, value, *c.MinInt)
289 }
290
291 if c.MaxInt != nil && value > *c.MaxInt {
292 return fmt.Errorf("%w: %v > %v", errIntTooHigh, value, *c.MinInt)
293 }
294
295 return nil
296 }
297
298 func (c Custom) validateEnum(input string) error {
299 if slices.Contains(c.EnumOptions, input) {
300 return nil
301 }
302
303 return fmt.Errorf("%w: %s", errInvalidEnum, input)
304 }
305
306 func (c Custom) validateEnums(input string) error {
307 if c.Optional && input == "" {
308 return nil
309 }
310
311 for _, value := range strings.Split(input, enumsSeparator) {
312 if !slices.Contains(c.EnumOptions, value) {
313 return fmt.Errorf("%w: %s", errInvalidEnum, value)
314 }
315 }
316
317 return nil
318 }
319
320 // CustomMapFromStrings will parse a CLI argument of strings into a key value map
321 // where each string is a key value pair separated by an equal sign.
322 // Eg: Issue=15 turns into {"Issue": "15"}
323 func CustomMapFromStrings(input []string) (map[string]string, error) {
324 ret := make(map[string]string)
325
326 for _, s := range input {
327 key, value, found := strings.Cut(s, "=")
328 if !found {
329 // error
330 return ret, fmt.Errorf("%w: %s", errInvalidCustomFormat, s)
331 }
332
333 ret[key] = value
334 }
335
336 return ret, nil
337 }