-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwizard.go
More file actions
183 lines (155 loc) · 4.16 KB
/
wizard.go
File metadata and controls
183 lines (155 loc) · 4.16 KB
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
package wizard
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/charmbracelet/huh"
"github.com/ktr0731/go-fuzzyfinder"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Execute wraps a standard Cobra root command with an interactive fuzzy-finder fallback.
// If the user runs the CLI without a subcommand, it launches the interactive UI.
func Execute(root *cobra.Command) error {
targetCmd, _, err := root.Find(os.Args[1:])
if err == nil && targetCmd == root {
selectedArgs, selectedCmd, fuzzyErr := triggerFuzzyMenu(root)
if fuzzyErr != nil {
if fuzzyErr == fuzzyfinder.ErrAbort {
fmt.Println("Canceled.")
return nil
}
return fuzzyErr
}
flagArgs, flagErr := promptForFlags(selectedCmd)
if flagErr != nil {
return fmt.Errorf("prompt canceled")
}
finalArgs := append(selectedArgs, flagArgs...)
root.SetArgs(finalArgs)
}
return root.Execute()
}
// triggerFuzzyMenu handles the fzf UI (Internal)
func triggerFuzzyMenu(root *cobra.Command) ([]string, *cobra.Command, error) {
availableCmds := getRunnableCommands(root)
if len(availableCmds) == 0 {
return nil, nil, fmt.Errorf("no subcommands available")
}
idx, err := fuzzyfinder.Find(
availableCmds,
func(i int) string { return availableCmds[i].CommandPath() },
fuzzyfinder.WithPreviewWindow(func(i, w, h int) string {
if i == -1 {
return ""
}
return fmt.Sprintf("Command: %s\n\n%s", availableCmds[i].CommandPath(), availableCmds[i].Short)
}),
)
if err != nil {
return nil, nil, err
}
selectedCmd := availableCmds[idx]
args := []string{}
current := selectedCmd
for current != root && current != nil {
args = append([]string{current.Name()}, args...)
current = current.Parent()
}
return args, selectedCmd, nil
}
// promptForFlags dynamically generates interactive prompts based on pflag types (Internal)
func promptForFlags(cmd *cobra.Command) ([]string, error) {
var flagArgs []string
if !cmd.HasLocalFlags() {
return flagArgs, nil
}
fmt.Printf("⚙️ Configure options for '%s':\n", cmd.Name())
var promptErr error
cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
if promptErr != nil {
return
}
flagType := f.Value.Type()
if flagType == "bool" {
var val bool
promptErr = huh.NewConfirm().
Title(fmt.Sprintf("Enable --%s?", f.Name)).
Description(f.Usage).
Value(&val).
Run()
if promptErr == nil && val {
flagArgs = append(flagArgs, fmt.Sprintf("--%s=true", f.Name))
}
return
}
var validator func(string) error
if strings.Contains(flagType, "int") {
validator = func(v string) error {
if v == "" {
return nil
}
_, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return fmt.Errorf("must be a valid integer")
}
return nil
}
} else if strings.Contains(flagType, "float") {
validator = func(v string) error {
if v == "" {
return nil
}
_, err := strconv.ParseFloat(v, 64)
if err != nil {
return fmt.Errorf("must be a valid number")
}
return nil
}
}
val := f.DefValue
desc := fmt.Sprintf("%s\n[Type: %s]", f.Usage, flagType)
isMultiline := false
if ann, ok := f.Annotations["editor"]; ok && len(ann) > 0 && ann[0] == "multiline" {
isMultiline = true
}
if isMultiline {
promptErr = huh.NewText().
Title(fmt.Sprintf("Set --%s", f.Name)).
Description(desc + " (Press Esc then Enter to submit)").
Lines(8).
Value(&val).
Run()
} else {
inputPrompt := huh.NewInput().
Title(fmt.Sprintf("Set --%s", f.Name)).
Description(desc).
Value(&val)
if validator != nil {
inputPrompt.Validate(validator)
}
promptErr = inputPrompt.Run()
}
if promptErr == nil && val != "" {
flagArgs = append(flagArgs, fmt.Sprintf("--%s=%s", f.Name, val))
}
})
return flagArgs, promptErr
}
// getRunnableCommands recursively walks the Cobra tree (Internal)
func getRunnableCommands(cmd *cobra.Command) []*cobra.Command {
var cmds []*cobra.Command
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.Name() == "help" {
continue
}
if c.Runnable() {
cmds = append(cmds, c)
}
if c.HasSubCommands() {
cmds = append(cmds, getRunnableCommands(c)...)
}
}
return cmds
}