2019-07-03 16:59:49 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2019-10-30 16:38:39 +00:00
|
|
|
"bytes"
|
2019-07-03 16:59:49 +00:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/BurntSushi/toml"
|
2019-10-30 16:38:39 +00:00
|
|
|
"golang.org/x/xerrors"
|
2019-07-03 16:59:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// FromFile loads config from a specified file overriding defaults specified in
|
2019-10-30 16:38:39 +00:00
|
|
|
// the def parameter. If file does not exist or is empty defaults are asummed.
|
|
|
|
func FromFile(path string, def interface{}) (interface{}, error) {
|
2019-07-03 16:59:49 +00:00
|
|
|
file, err := os.Open(path)
|
|
|
|
switch {
|
|
|
|
case os.IsNotExist(err):
|
2019-10-30 16:38:39 +00:00
|
|
|
return def, nil
|
2019-07-03 16:59:49 +00:00
|
|
|
case err != nil:
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer file.Close() //nolint:errcheck // The file is RO
|
2019-10-30 16:38:39 +00:00
|
|
|
return FromReader(file, def)
|
2019-07-03 16:59:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// FromReader loads config from a reader instance.
|
2019-10-30 16:38:39 +00:00
|
|
|
func FromReader(reader io.Reader, def interface{}) (interface{}, error) {
|
|
|
|
cfg := def
|
2019-07-03 16:59:49 +00:00
|
|
|
_, err := toml.DecodeReader(reader, cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cfg, nil
|
|
|
|
}
|
2019-10-30 16:38:39 +00:00
|
|
|
|
|
|
|
func ConfigComment(t interface{}) ([]byte, error) {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
_, _ = buf.WriteString("# Default config:\n")
|
|
|
|
e := toml.NewEncoder(buf)
|
|
|
|
if err := e.Encode(t); err != nil {
|
|
|
|
return nil, xerrors.Errorf("encoding config: %w", err)
|
|
|
|
}
|
|
|
|
b := buf.Bytes()
|
|
|
|
b = bytes.ReplaceAll(b, []byte("\n"), []byte("\n#"))
|
|
|
|
return b, nil
|
|
|
|
|
|
|
|
}
|