justusbot/internal/settings/settings.go

102 lines
2 KiB
Go

package settings
import (
"bytes"
"fmt"
"io/fs"
"net"
"os"
"github.com/pelletier/go-toml"
"git.destrealm.net/go/cwrap"
)
type Settings struct {
API *API `toml:"api"`
DailyScripture *DailyScripture `toml:"daily_scripture"`
Translations *Translations `toml:"translations"`
System *System `toml:"system"`
Service *Service `toml:"service"`
Chat *Chat `toml:"chat"`
}
type API struct {
BaseURL string `toml:"base_url"`
}
type Chat struct {
Channels []int64 `toml:"channels"`
}
type DailyScripture struct {
UserSubmitted bool `toml:"user_submitted"`
Schedule string `toml:"schedule"`
}
type System struct {
TimeZone string `toml:"timezone"`
}
type Service struct {
Method string `toml:"method"`
Webhook *Webhook `toml:"webhook"`
}
type Webhook struct {
URI string `toml:"uri"`
Port int `toml:"port"`
Host string `toml:"host"`
}
func (w *Webhook) ListenAddr() string {
return net.JoinHostPort(w.Host, fmt.Sprintf("%d", w.Port))
}
type Translations struct {
BaseDir string `toml:"basedir"`
Current string `toml:"current"`
Active []string `toml:"active"`
}
func (c *Settings) Marshal() ([]byte, error) {
buf := &bytes.Buffer{}
enc := toml.NewEncoder(cwrap.New(buf))
enc.ArraysWithOneElementPerLine(true)
enc.Indentation(" ")
enc.Order(toml.OrderPreserve)
enc.PromoteAnonymous(false)
if err := enc.Encode(c); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func LoadSettings(name string) (*Settings, error) {
conf := &Settings{}
buf, err := os.ReadFile(name)
if err != nil {
if _, ok := err.(*fs.PathError); ok {
return nil, ErrSettingsNotFound.Do(err)
}
return nil, ErrReadingSettings.Do(err)
}
err = toml.Unmarshal(buf, conf)
if err != nil {
return nil, ErrReadingSettings.Do(err)
}
return conf, nil
}
func SaveSettings(name string, settings *Settings) error {
buf, err := settings.Marshal()
if err != nil {
return err
}
return os.WriteFile(name, buf, 0o644)
}