lurk/config/config.go

95 lines
2.2 KiB
Go
Raw Normal View History

package config
import (
_ "embed"
"fmt"
"os"
"regexp"
"strings"
"time"
"github.com/pelletier/go-toml"
"github.com/rs/zerolog/log"
)
//go:embed lurk.toml
var defaultConfig []byte
func Init(configPath string) error {
if _, err := os.Lstat(configPath); err == nil {
return fmt.Errorf("config exists at %q", configPath)
}
fi, err := os.Create(configPath)
if err != nil {
return err
}
defer fi.Close()
_, err = fi.Write(defaultConfig)
return err
}
type Config struct {
Backoff time.Duration `toml:"backoff"`
Reddit RedditConfig `toml:"reddit"`
Twitter TwitterConfig `toml:"twitter"`
}
func (c *Config) loadReddit() {
for _, sub := range c.Reddit.SubReddits {
c.Reddit.Map[strings.ToLower(sub.Name)] = sub
if sub.TitleLimit == 0 || sub.TitleLimit > 253 {
sub.TitleLimit = 253
}
if sub.BodyLimit == 0 || sub.BodyLimit > 2045 {
sub.BodyLimit = 2045
}
sub.FlairAllowlistRe = make([]*regexp.Regexp, len(sub.FlairAllowlist))
for idx, f := range sub.FlairAllowlist {
sub.FlairAllowlistRe[idx] = regexp.MustCompile(f)
}
sub.FlairBlocklistRe = make([]*regexp.Regexp, len(sub.FlairBlocklist))
for idx, f := range sub.FlairBlocklist {
sub.FlairBlocklistRe[idx] = regexp.MustCompile(f)
}
sub.TitleAllowlistRe = make([]*regexp.Regexp, len(sub.TitleAllowlist))
for idx, t := range sub.TitleAllowlist {
sub.TitleAllowlistRe[idx] = regexp.MustCompile(t)
}
sub.TitleBlocklistRe = make([]*regexp.Regexp, len(sub.TitleBlocklist))
for idx, t := range sub.TitleBlocklist {
sub.TitleBlocklistRe[idx] = regexp.MustCompile(t)
}
sub.BodyAllowlistRe = make([]*regexp.Regexp, len(sub.BodyAllowlist))
for idx, b := range sub.BodyAllowlist {
sub.BodyAllowlistRe[idx] = regexp.MustCompile(b)
}
sub.BodyBlocklistRe = make([]*regexp.Regexp, len(sub.BodyBlocklist))
for idx, b := range sub.BodyBlocklist {
sub.BodyBlocklistRe[idx] = regexp.MustCompile(b)
}
}
}
func Load(configPath string) (*Config, error) {
cfg := Config{
Reddit: RedditConfig{
Map: make(map[string]*SubReddit),
},
}
tree, err := toml.LoadFile(configPath)
if err != nil {
return nil, err
}
if err := tree.Unmarshal(&cfg); err != nil {
return nil, err
}
cfg.loadReddit()
log.Debug().Msgf("%#v", cfg)
return &cfg, nil
}