-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.go
108 lines (94 loc) · 2.57 KB
/
prompt.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
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
package main
import (
"fmt"
"strings"
"unicode/utf8"
"github.com/erikgeiser/promptkit/selection"
"github.com/erikgeiser/promptkit/textinput"
"github.com/muesli/termenv"
)
const (
maxPadSpacing = 5
minChoiceFiltering = 5
accentColor = termenv.ANSI256Color(32)
)
func selectCommand(command ConfigCommand) (ConfigCommand, error) {
commandsLength := len(command.Commands)
maxNameLength := maxStringLength(command.Commands, func(c ConfigCommand) string {
return c.Name
})
sp := selection.New("Choose command", command.Commands)
sp.SelectedChoiceStyle = func(c *selection.Choice[ConfigCommand]) string {
return renderChoiceStyle(c.Value.Name, c.Value.Description, maxNameLength, true)
}
sp.UnselectedChoiceStyle = func(c *selection.Choice[ConfigCommand]) string {
return renderChoiceStyle(c.Value.Name, c.Value.Description, maxNameLength, false)
}
if commandsLength <= minChoiceFiltering {
sp.Filter = nil
}
if choice, err := sp.RunPrompt(); err != nil {
return command, err
} else {
return choice, nil
}
}
func askInput(input ConfigInput) (string, error) {
if input.Selectable() {
return selectInput(input)
} else {
return getInput(input)
}
}
func selectInput(input ConfigInput) (string, error) {
prompt := input.Description
if prompt == "" {
prompt = fmt.Sprintf("Choose a %s", termenv.String(input.Name).Underline().String())
}
sp := selection.New(prompt, input.Options)
if len(input.Options) <= minChoiceFiltering {
sp.Filter = nil
}
if option, err := sp.RunPrompt(); err == nil {
return option.Value, err
} else {
return "", err
}
}
func getInput(input ConfigInput) (string, error) {
prompt := input.Description
if prompt == "" {
prompt = fmt.Sprintf("Please specify a %s", termenv.String(input.Name).Underline().String())
}
ti := textinput.New(prompt)
ti.InitialValue = input.DefaultValue
ti.Validate = func(value string) error {
if input.Valid(value) {
return nil
} else {
return fmt.Errorf("invalid value")
}
}
return ti.RunPrompt()
}
func renderChoiceStyle(name, desc string, maxNameLength int, selected bool) string {
padLen := maxNameLength - utf8.RuneCountInString(name)
if padLen < 0 {
padLen = 0
}
if selected {
name = termenv.String(name).Foreground(accentColor).Bold().String()
}
if desc != "" {
desc = strings.Repeat(" ", padLen+maxPadSpacing) + termenv.String(desc).Faint().String()
}
return name + desc
}
func maxStringLength[T any](items []T, fun func(T) string) int {
maxLen := 0
for _, item := range items {
s := fun(item)
maxLen = max(maxLen, utf8.RuneCountInString(s))
}
return maxLen
}