Prevent adding duplicate services

This commit is contained in:
Philipp Wolfer 2023-12-07 23:09:16 +01:00
parent 8743a9d81c
commit 091b3c2f49
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
2 changed files with 57 additions and 5 deletions

View file

@ -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,

View file

@ -15,7 +15,11 @@ Scotty. If not, see <https://www.gnu.org/licenses/>.
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)
}