85 lines
1.6 KiB
Go
85 lines
1.6 KiB
Go
|
package ui
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"strconv"
|
||
|
|
||
|
"github.com/charmbracelet/huh"
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
proceedTemplate = "%s (y/n): "
|
||
|
defaultTemplate = "%s: "
|
||
|
chooseTemplate = "%d : %s\n"
|
||
|
)
|
||
|
|
||
|
func AskToConfirm(question, affirmative, negative string) bool {
|
||
|
confirm := Confirm(question, "res")
|
||
|
confirm.Affirmative(affirmative)
|
||
|
confirm.Negative(negative)
|
||
|
form := huh.NewForm(huh.NewGroup(confirm))
|
||
|
form.Run()
|
||
|
|
||
|
if form.State != huh.StateCompleted {
|
||
|
log.Fatal("canceled")
|
||
|
}
|
||
|
|
||
|
return form.GetBool("res")
|
||
|
}
|
||
|
|
||
|
func AskToValue(question string) (string, error) {
|
||
|
input := Input(question, "res")
|
||
|
form := huh.NewForm(huh.NewGroup(input))
|
||
|
form.Run()
|
||
|
|
||
|
if form.State != huh.StateCompleted {
|
||
|
log.Fatal("canceled")
|
||
|
}
|
||
|
|
||
|
return form.GetString("res"), nil
|
||
|
}
|
||
|
|
||
|
func AskToInt(question string) (int, error) {
|
||
|
v, err := AskToValue(question)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
value, err := strconv.Atoi(v)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
return value, nil
|
||
|
}
|
||
|
|
||
|
func AskToChoose(question string, list map[int]string) string {
|
||
|
for i, item := range list {
|
||
|
fmt.Printf(chooseTemplate, i, item)
|
||
|
}
|
||
|
|
||
|
answer, err := AskToInt(question)
|
||
|
if err != nil {
|
||
|
log.WithError(err).Error("failed to read the answer")
|
||
|
}
|
||
|
|
||
|
return list[answer]
|
||
|
}
|
||
|
|
||
|
func AskToChooseInteractive(question string, list []string) string {
|
||
|
values := make(map[string]string)
|
||
|
if len(list) == 0 {
|
||
|
log.Fatal("no items found")
|
||
|
}
|
||
|
for _, item := range list {
|
||
|
values[item] = item
|
||
|
}
|
||
|
widget := InteractiveList(question, "res", values)
|
||
|
form := huh.NewForm(huh.NewGroup(widget)).WithShowHelp(false)
|
||
|
form.Run()
|
||
|
|
||
|
if form.State != huh.StateCompleted {
|
||
|
log.Fatal("canceled")
|
||
|
}
|
||
|
return form.GetString("res")
|
||
|
}
|