Dynamic per-backend configuration options

This commit is contained in:
Philipp Wolfer 2023-12-05 23:25:15 +01:00
parent ae5f1c5f26
commit c9fa21be73
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
14 changed files with 262 additions and 17 deletions

View file

@ -28,6 +28,7 @@ import (
"github.com/spf13/cobra"
"go.uploadedlobster.com/scotty/internal/backends"
"go.uploadedlobster.com/scotty/internal/config"
"go.uploadedlobster.com/scotty/internal/models"
)
// addCmd represents the add command
@ -43,10 +44,7 @@ var addCmd = &cobra.Command{
Size: 10,
}
_, backend, err := sel.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
cobra.CheckErr(err)
// Set service name
prompt := promptui.Prompt{
@ -54,21 +52,22 @@ var addCmd = &cobra.Command{
Validate: config.ValidateKey,
Default: backend,
}
name, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
cobra.CheckErr(err)
// Save the service config
// Prepate service config
service := config.ServiceConfig{
Name: name,
Backend: backend,
}
err = service.Save()
// Additional options
err = extraOptions(&service)
cobra.CheckErr(err)
// Save the service config
err = service.Save()
cobra.CheckErr(err)
fmt.Printf("Saved service %v using backend %v\n", service.Name, service.Backend)
},
}
@ -86,3 +85,68 @@ func init() {
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func extraOptions(config *config.ServiceConfig) error {
backend, err := backends.BackendByName(config.Backend)
if err != nil {
return err
}
opts := backend.Options()
if opts == nil {
return nil
}
values := make(map[string]any, len(*opts))
for _, opt := range *opts {
var val any
var err error
switch opt.Type {
case models.Bool:
val, err = promptBool(opt)
case models.Secret:
val, err = promptSecret(opt)
case models.String:
val, err = promptString(opt)
}
if err != nil {
return err
}
values[opt.Name] = val
}
config.ConfigValues = values
return nil
}
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) {
sel := promptui.Select{
Label: opt.Label,
Items: []string{"Yes", "No"},
}
_, val, err := sel.Run()
return val == "Yes", err
}