2019-07-03 16:59:49 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2019-10-30 16:38:39 +00:00
|
|
|
"bytes"
|
2020-05-22 14:51:18 +00:00
|
|
|
"fmt"
|
2019-07-03 16:59:49 +00:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/BurntSushi/toml"
|
2020-05-22 14:51:18 +00:00
|
|
|
"github.com/kelseyhightower/envconfig"
|
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
|
2020-06-09 23:30:30 +00:00
|
|
|
// the def parameter. If file does not exist or is empty defaults are assumed.
|
2019-10-30 16:38:39 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-05-22 14:51:18 +00:00
|
|
|
err = envconfig.Process("LOTUS", cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("processing env vars overrides: %s", err)
|
|
|
|
}
|
|
|
|
|
2019-07-03 16:59:49 +00:00
|
|
|
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#"))
|
2019-12-16 11:46:52 +00:00
|
|
|
b = bytes.ReplaceAll(b, []byte("#["), []byte("["))
|
2019-10-30 16:38:39 +00:00
|
|
|
return b, nil
|
|
|
|
}
|