From 091b3c2f49bd91e149dc44d8b44582bd324f7086 Mon Sep 17 00:00:00 2001 From: Philipp Wolfer Date: Thu, 7 Dec 2023 23:09:16 +0100 Subject: [PATCH] Prevent adding duplicate services --- cmd/add.go | 15 ++++++++---- internal/config/services.go | 47 ++++++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/cmd/add.go b/cmd/add.go index 830ff12..0d0bc8c 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -22,6 +22,7 @@ THE SOFTWARE. package cmd import ( + "errors" "fmt" "github.com/manifoldco/promptui" @@ -48,14 +49,20 @@ var addCmd = &cobra.Command{ // Set service name prompt := promptui.Prompt{ - Label: "Service name", - Validate: config.ValidateKey, - Default: backend, + Label: "Service name", + Default: backend, + Validate: func(s string) error { + srv, _ := config.GetService(s) + if srv != nil { + return errors.New("a service with this name already exists") + } + return config.ValidateKey(s) + }, } name, err := prompt.Run() cobra.CheckErr(err) - // Prepate service config + // Prepare service config service := config.ServiceConfig{ Name: name, Backend: backend, diff --git a/internal/config/services.go b/internal/config/services.go index e3a15e8..cb64f7f 100644 --- a/internal/config/services.go +++ b/internal/config/services.go @@ -15,7 +15,11 @@ Scotty. If not, see . package config -import "github.com/spf13/viper" +import ( + "fmt" + + "github.com/spf13/viper" +) type ServiceConfig struct { Name string @@ -23,6 +27,22 @@ type ServiceConfig struct { ConfigValues map[string]any } +func NewServiceConfig(name string, config *viper.Viper) ServiceConfig { + service := ServiceConfig{ + Name: name, + Backend: viper.GetString("backend"), + ConfigValues: make(map[string]any), + } + + for key, val := range viper.AllSettings() { + if key != "backend" { + service.ConfigValues[key] = val + } + } + + return service +} + func (c *ServiceConfig) Save() error { key := "service." + c.Name viper.Set(key+".backend", c.Backend) @@ -31,3 +51,28 @@ func (c *ServiceConfig) Save() error { } return viper.WriteConfig() } + +func AllServices() map[string]ServiceConfig { + services := make(map[string]ServiceConfig) + config := viper.Sub("service") + if config != nil { + for k, v := range config.AllSettings() { + s, ok := v.(*viper.Viper) + if ok { + services[k] = NewServiceConfig(k, s) + } + } + } + return services +} + +func GetService(name string) (*ServiceConfig, error) { + key := "service." + name + config := viper.Sub(key) + if config != nil { + service := NewServiceConfig(name, config) + return &service, nil + } + + return nil, fmt.Errorf("no service configuration \"%v\"", name) +}