2022-08-04 10:39:24 +00:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
2022-08-05 14:20:00 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/juju/errors"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
|
2022-08-04 10:39:24 +00:00
|
|
|
"git.home.m-and-m.ovh/mderasse/gouick/helpers/models"
|
2022-08-05 14:20:00 +00:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2022-08-04 10:39:24 +00:00
|
|
|
)
|
|
|
|
|
2022-08-05 14:20:00 +00:00
|
|
|
const configFile = ".gouick.yml"
|
2022-08-04 10:39:24 +00:00
|
|
|
|
2022-08-05 14:20:00 +00:00
|
|
|
// ReadConfig will search the config file in the given path, read it and return a Config object.
|
2022-08-04 10:39:24 +00:00
|
|
|
func ReadConfig(path string) (*models.Config, error) {
|
2022-08-05 14:20:00 +00:00
|
|
|
|
|
|
|
configFilePath := filepath.Join(path, configFile)
|
|
|
|
|
|
|
|
log.Debugf("Opening configuration file in %s", configFilePath)
|
|
|
|
|
|
|
|
//nolint:gosec // we did compute the file path
|
|
|
|
f, err := os.ReadFile(configFilePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Trace(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var config models.Config
|
|
|
|
|
|
|
|
log.Debug("Unmarshal config file")
|
|
|
|
if err := yaml.Unmarshal(f, &config); err != nil {
|
|
|
|
return nil, errors.Trace(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &config, nil
|
2022-08-04 10:39:24 +00:00
|
|
|
}
|
|
|
|
|
2022-08-05 14:20:00 +00:00
|
|
|
// WriteConfig will write the new or updated config.
|
2022-08-04 10:39:24 +00:00
|
|
|
func WriteConfig(path string, config *models.Config) error {
|
|
|
|
|
2022-08-05 14:20:00 +00:00
|
|
|
configFilePath := filepath.Join(path, configFile)
|
|
|
|
|
|
|
|
log.Debug("Marshal config into YAML Format")
|
|
|
|
|
|
|
|
data, err := yaml.Marshal(config)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Trace(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debugf("Writing config to %s", configFilePath)
|
|
|
|
|
2022-08-05 14:52:14 +00:00
|
|
|
err = os.WriteFile(configFilePath, data, 0600)
|
2022-08-05 14:20:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Trace(err)
|
|
|
|
}
|
|
|
|
|
2022-08-04 10:39:24 +00:00
|
|
|
return nil
|
|
|
|
}
|