57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/urfave/cli/v2"
|
|
"gopkg.in/yaml.v2"
|
|
"os"
|
|
)
|
|
|
|
type Config struct {
|
|
InstanceUrl string `yaml:"instance_url"`
|
|
}
|
|
|
|
func LoadConfig(configLocation string) (Config, error) {
|
|
c := Config{}
|
|
dat, err := os.ReadFile(configLocation)
|
|
if err != nil {
|
|
return c, errors.New(fmt.Sprintf("could not read config file %s", configLocation))
|
|
}
|
|
|
|
err = yaml.Unmarshal(dat, &c)
|
|
if err != nil {
|
|
return c, errors.New("could not parse yaml")
|
|
}
|
|
|
|
validate := validator.New()
|
|
err = validate.Struct(c)
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
|
|
return c, nil
|
|
}
|
|
|
|
func LoadConfigFromContext(cCtx *cli.Context) (Config, error) {
|
|
return LoadConfig(cCtx.String("config"))
|
|
}
|
|
|
|
func SaveConfig(configLocation string, config Config) error {
|
|
dat, err := yaml.Marshal(config)
|
|
if err != nil {
|
|
return errors.New("could not cast config to yaml")
|
|
}
|
|
|
|
err = os.WriteFile(configLocation, dat, 0644)
|
|
if err != nil {
|
|
return errors.New(fmt.Sprintf("could not write config file %s", configLocation))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func SaveConfigFromContext(cCtx *cli.Context, config Config) error {
|
|
return SaveConfig(cCtx.String("config"), config)
|
|
}
|