80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"slices"
|
|
"time"
|
|
|
|
"code.humancabbage.net/sam/moonmath/coindesk"
|
|
"code.humancabbage.net/sam/moonmath/moon"
|
|
"github.com/knadh/koanf/parsers/toml"
|
|
"github.com/knadh/koanf/providers/file"
|
|
"github.com/knadh/koanf/providers/structs"
|
|
"github.com/knadh/koanf/v2"
|
|
)
|
|
|
|
var k = koanf.New(".")
|
|
|
|
func Load(path string) (data Data, err error) {
|
|
err = k.Load(structs.Provider(Default, "koanf"), nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if path != "" {
|
|
err = k.Load(file.Provider(path), toml.Parser())
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
err = k.Unmarshal("", &data)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
var Default = Data{
|
|
Asset: coindesk.BTC,
|
|
Goals: moon.DefaultGoals,
|
|
ConstantBases: moon.DefaultConstantBases,
|
|
RelativeBases: moon.DefaultRelativeBases,
|
|
}
|
|
|
|
type Data struct {
|
|
Asset coindesk.Asset `koanf:"asset"`
|
|
Goals []moon.Goal `koanf:"goals"`
|
|
ConstantBases []moon.ConstantBase `koanf:"constantBases"`
|
|
RelativeBases []moon.RelativeBase `koanf:"relativeBases"`
|
|
}
|
|
|
|
type Goal struct {
|
|
Name string `koanf:"name"`
|
|
Value float64 `koanf:"value"`
|
|
}
|
|
|
|
// GetBases returns the concatenation of the constant and relative bases, sorted
|
|
// from most recent to least recent in time.
|
|
func GetBases(d *Data) (bases []moon.Base) {
|
|
for _, b := range d.ConstantBases {
|
|
bases = append(bases, b)
|
|
}
|
|
for _, b := range d.RelativeBases {
|
|
bases = append(bases, b)
|
|
}
|
|
now := time.Now()
|
|
slices.SortFunc(bases, func(a, b moon.Base) int {
|
|
aTime := a.From(now)
|
|
bTime := b.From(now)
|
|
aFirst := aTime.Before(bTime)
|
|
bFirst := bTime.Before(aTime)
|
|
switch {
|
|
case aFirst:
|
|
return 1
|
|
case bFirst:
|
|
return -1
|
|
}
|
|
return 0
|
|
})
|
|
return
|
|
}
|