zrokdir/config (#136)

This commit is contained in:
Michael Quigley 2023-01-09 11:28:26 -05:00
parent 21dd52507b
commit 0d8a3def4d
No known key found for this signature in database
GPG Key ID: 9B60314A9DD20A62
2 changed files with 69 additions and 0 deletions

61
zrokdir/config.go Normal file
View File

@ -0,0 +1,61 @@
package zrokdir
import (
"encoding/json"
"github.com/pkg/errors"
"os"
"path/filepath"
)
type Config struct {
ApiEndpoint string `json:"api_endpoint"`
}
func HasConfig() (bool, error) {
cf, err := configFile()
if err != nil {
return false, errors.Wrap(err, "error getting config file path")
}
_, err = os.Stat(cf)
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, errors.Wrapf(err, "error stat-ing config file '%v'", cf)
}
return true, nil
}
func LoadConfig() (*Config, error) {
cf, err := configFile()
if err != nil {
return nil, errors.Wrap(err, "error getting config file path")
}
data, err := os.ReadFile(cf)
if err != nil {
return nil, errors.Wrapf(err, "error reading config file '%v'", cf)
}
cfg := &Config{}
if err := json.Unmarshal(data, cfg); err != nil {
return nil, errors.Wrapf(err, "error unmarshaling config file '%v'", cf)
}
return cfg, nil
}
func SaveConfig(cfg *Config) error {
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return errors.Wrap(err, "error marshaling config")
}
cf, err := configFile()
if err != nil {
return errors.Wrap(err, "error getting config file path")
}
if err := os.MkdirAll(filepath.Dir(cf), os.FileMode(0700)); err != nil {
return errors.Wrapf(err, "error creating zrokdir path '%v'", filepath.Dir(cf))
}
if err := os.WriteFile(cf, data, os.FileMode(0600)); err != nil {
return errors.Wrap(err, "error saving config file")
}
return nil
}

View File

@ -5,6 +5,14 @@ import (
"path/filepath"
)
func configFile() (string, error) {
zrd, err := zrokDir()
if err != nil {
return "", err
}
return filepath.Join(zrd, "config.json"), nil
}
func environmentFile() (string, error) {
zrd, err := zrokDir()
if err != nil {