my-log/config/load.go
2024-02-10 11:06:00 -06:00

72 lines
1.4 KiB
Go

package config
import (
"encoding/json"
"fmt"
"os"
fp "path/filepath"
"time"
"codeberg.org/danjones000/my-log/tools"
"github.com/BurntSushi/toml"
"github.com/caarlos0/env/v10"
mapst "github.com/mitchellh/mapstructure"
)
var ConfigPath string
var Overrides map[string]string
func init() {
conf, _ := os.UserConfigDir()
ConfigPath = fp.Join(conf, "my-log", "config.toml")
}
func Load() (Config, error) {
c, _ := DefaultConfig()
_, err := os.Stat(ConfigPath)
if !os.IsNotExist(err) {
_, err = toml.DecodeFile(ConfigPath, &c)
if err != nil {
return c, err
}
}
env.Parse(&c)
// @todo how to handle env on options so cli args aren't overwrittem?
l := ""
for k, v := range Overrides {
val := tools.ParseString(v)
if val == nil {
continue
}
if _, isJson := val.(json.RawMessage); isJson {
continue
}
valout := fmt.Sprintf("%v", val)
if vals, isString := val.(string); isString {
valout = fmt.Sprintf(`"%s"`, vals)
}
if valt, isTime := val.(time.Time); isTime {
valout = valt.Format(time.RFC3339)
}
l = l + "\n" + fmt.Sprintf("%s = %s", k, valout)
}
_, err = toml.Decode(l, &c)
return c, err
}
func (oo Outputs) Stdout() (s Stdout, enabled bool) {
o, ok := oo["stdout"]
if !ok {
return s, false
}
st := struct {
Enabled bool `env:"LOG_STDOUT_ENABLED"`
}{o.Enabled}
env.Parse(&st)
enabled = st.Enabled
mapst.Decode(o.Config, &s)
env.Parse(&s)
return
}