package hmsecrets import ( "errors" "fmt" "os" "path" "runtime" "gopkg.in/yaml.v3" ) type config struct { APIBase string `yaml:"api-base"` CA string `yaml:"ca"` ClientCert string `yaml:"client-cert"` ClientKey string `yaml:"client-key"` } func mustLoadConfig() config { var baseConfigDir string var err error switch runtime.GOOS { case "windows": fallthrough case "linux": baseConfigDir, err = os.UserConfigDir() if err != nil { panic(fmt.Errorf("determining user config dir: %w", err)) } case "darwin": // We want $HOME/.config in macOS. homeDir, err := os.UserHomeDir() if err != nil { panic(fmt.Errorf("determining user home dir: %w", err)) } baseConfigDir = path.Join(homeDir, ".config") } configDir := path.Join(baseConfigDir, "hmsecrets") configBytes, err := os.ReadFile(path.Join(configDir, "config.yaml")) if err != nil { panic(fmt.Errorf("reading config file: %w", err)) } var conf config err = yaml.Unmarshal(configBytes, &conf) if err != nil { panic(fmt.Errorf("parsing config file: %w", err)) } if conf.APIBase == "" { panic(errors.New("api base must be present in config")) } if conf.CA == "" { conf.CA = path.Join(configDir, "ca.crt") } if !fileAccesible(conf.CA) { panic(fmt.Errorf("ca file '%s' does not exist or is inaccesible", conf.CA)) } if conf.ClientCert == "" { conf.ClientCert = path.Join(configDir, "client.crt") } if !fileAccesible(conf.ClientCert) { panic(fmt.Errorf("client cert file '%s' does not exist or is inaccesible", conf.ClientCert)) } if conf.ClientKey == "" { conf.ClientKey = path.Join(configDir, "client.key") } if !fileAccesible(conf.ClientKey) { panic(fmt.Errorf("client key file '%s' does not exist or is inaccesible", conf.ClientKey)) } return conf } func fileAccesible(f string) bool { _, err := os.Stat(f) return err == nil }