-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipt.go
62 lines (49 loc) · 1.36 KB
/
ipt.go
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
package ipt
import (
"errors"
"github.com/AlecAivazis/survey/v2"
)
// Option represents a label-value pair for the selection
type Option[T any] struct {
Label string
Value T
}
// Ipt prompts the user with a list of options and returns the value of the selected option.
func Ipt[T any](message string, options []Option[T]) (T, error) {
var zeroValue T // Default value of type T
if len(options) == 0 {
return zeroValue, errors.New("options cannot be empty")
}
// Extract labels for display
labels := make([]string, len(options))
for i, opt := range options {
labels[i] = opt.Label
}
// Store the selected label
var selectedLabel string
// Use survey to ask the question
err := survey.AskOne(&survey.Select{
Message: message,
Options: labels,
}, &selectedLabel)
if err != nil {
return zeroValue, err
}
// Find the corresponding value based on the selected label
for _, opt := range options {
if opt.Label == selectedLabel {
return opt.Value, nil
}
}
return zeroValue, errors.New("invalid selection")
}
func IptRaw(message string, options []string) (string, error) {
return Ipt[string](message, convertOptions[string](options))
}
func convertOptions[T any](options []string) []Option[string] {
var result []Option[string]
for _, opt := range options {
result = append(result, Option[string]{Label: opt, Value: opt})
}
return result
}