3ea0997c93
License: MIT Signed-off-by: Jakub Sztandera <kubuxu@protocol.ai>
50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/BurntSushi/toml"
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// FromFile loads config from a specified file overriding defaults specified in
|
|
// the def parameter. If file does not exist or is empty defaults are asummed.
|
|
func FromFile(path string, def interface{}) (interface{}, error) {
|
|
file, err := os.Open(path)
|
|
switch {
|
|
case os.IsNotExist(err):
|
|
return def, nil
|
|
case err != nil:
|
|
return nil, err
|
|
}
|
|
|
|
defer file.Close() //nolint:errcheck // The file is RO
|
|
return FromReader(file, def)
|
|
}
|
|
|
|
// FromReader loads config from a reader instance.
|
|
func FromReader(reader io.Reader, def interface{}) (interface{}, error) {
|
|
cfg := def
|
|
_, err := toml.DecodeReader(reader, cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
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
|
|
|
|
}
|