scotty/internal/cli/prompt.go
2024-01-13 14:11:58 +01:00

108 lines
2.4 KiB
Go

/*
Copyright © 2023 Philipp Wolfer <phw@uploadedlobster.com>
Scotty is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
Scotty is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Scotty. If not, see <https://www.gnu.org/licenses/>.
*/
package cli
import (
"fmt"
"strconv"
"github.com/manifoldco/promptui"
"go.uploadedlobster.com/scotty/internal/i18n"
"go.uploadedlobster.com/scotty/internal/models"
)
func Prompt(opt models.BackendOption) (any, error) {
switch opt.Type {
case models.Bool:
return PromptBool(opt)
case models.Secret:
return PromptSecret(opt)
case models.String:
return PromptString(opt)
case models.Int:
return PromptInt(opt)
default:
return nil, fmt.Errorf("unknown prompt type %v", opt.Type)
}
}
func PromptString(opt models.BackendOption) (string, error) {
prompt := promptui.Prompt{
Label: opt.Label,
Validate: opt.Validate,
Default: opt.Default,
}
val, err := prompt.Run()
return val, err
}
func PromptSecret(opt models.BackendOption) (string, error) {
prompt := promptui.Prompt{
Label: opt.Label,
Validate: opt.Validate,
Default: opt.Default,
Mask: '*',
}
val, err := prompt.Run()
return val, err
}
func PromptBool(opt models.BackendOption) (bool, error) {
return PromptYesNo(opt.Label, opt.Default == "true")
}
func PromptYesNo(label string, defaultValue bool) (bool, error) {
yes := i18n.Tr("Yes")
no := i18n.Tr("No")
selected := 1
if defaultValue {
selected = 0
}
sel := promptui.Select{
Label: label,
Items: []string{yes, no},
CursorPos: selected,
}
_, val, err := sel.Run()
return val == yes, err
}
func PromptInt(opt models.BackendOption) (int, error) {
validate := func(s string) error {
if opt.Validate != nil {
if err := opt.Validate(s); err != nil {
return err
}
}
if _, err := strconv.Atoi(s); err != nil {
return err
}
return nil
}
prompt := promptui.Prompt{
Label: opt.Label,
Validate: validate,
Default: opt.Default,
}
val, err := prompt.Run()
if err != nil {
return 0, err
}
return strconv.Atoi(val)
}