package settings import ( "bytes" "fmt" "io" "net" "os" "github.com/pelletier/go-toml" "go.destrealm.net/cwrap" "go.destrealm.net/vfs" ) type Settings struct { file string `toml:"-"` fs vfs.VFS `toml:"-"` 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"` } // Reload previously loaded configuration. func (s *Settings) Reload() error { st, err := LoadSettings(s.file, s.fs) if err != nil { return err } s.API = st.API s.DailyScripture = st.DailyScripture s.Translations = st.Translations s.System = st.System s.Service = st.Service s.Chat = st.Chat return nil } func (s *Settings) Save() error { buf, err := s.Marshal() if err != nil { return err } fp, err := s.fs.Mutable().OpenFile(s.file, os.O_TRUNC|os.O_CREATE, 0644) if err != nil { return err } defer fp.Close() _, err = fp.Write(buf) return err } 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, fs vfs.VFS) (*Settings, error) { conf := &Settings{} file, err := fs.Open(name) if err != nil { return nil, err } defer file.Close() buf, err := io.ReadAll(file) if err != nil { return nil, ErrReadingSettings.Do(err) } err = toml.Unmarshal(buf, conf) if err != nil { return nil, ErrReadingSettings.Do(err) } conf.file = name return conf, nil } func SaveSettings(name string, settings *Settings) error { return settings.Save() }