98 lines
		
	
	
	
		
			1.8 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			98 lines
		
	
	
	
		
			1.8 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)
 | |
| 	c.Outputs["stdout"] = loadStdout(c.Outputs["stdout"])
 | |
| 	c.Formatters["json"] = loadJsonFormat(c.Formatters["json"])
 | |
| 
 | |
| 	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 loadStdout(stdout Output) Output {
 | |
| 	st := stdoutEnabled{stdout.Enabled}
 | |
| 	env.Parse(&st)
 | |
| 	stdout.Enabled = st.Enabled
 | |
| 	var std Stdout
 | |
| 	mapst.Decode(stdout.Config, &std)
 | |
| 	env.Parse(&std)
 | |
| 	mapst.Decode(std, &stdout.Config)
 | |
| 	return stdout
 | |
| }
 | |
| 
 | |
| func (oo Outputs) Stdout() (s Stdout, enabled bool) {
 | |
| 	o, ok := oo["stdout"]
 | |
| 	if !ok {
 | |
| 		return s, false
 | |
| 	}
 | |
| 
 | |
| 	enabled = o.Enabled
 | |
| 	mapst.Decode(o.Config, &s)
 | |
| 
 | |
| 	return
 | |
| }
 | |
| 
 | |
| func loadJsonFormat(c map[string]any) map[string]any {
 | |
| 	jf := JsonFormat{}
 | |
| 	mapst.Decode(c, &jf)
 | |
| 	env.Parse(&jf)
 | |
| 	mapst.Decode(jf, &c)
 | |
| 	return c
 | |
| }
 | |
| 
 | |
| func (ff Formatters) Json() (jf JsonFormat) {
 | |
| 	o, ok := ff["json"]
 | |
| 	if !ok {
 | |
| 		return
 | |
| 	}
 | |
| 
 | |
| 	mapst.Decode(o, &jf)
 | |
| 	return
 | |
| }
 |