package config import ( _ "embed" "fmt" "os" "regexp" "strings" "time" "github.com/rs/zerolog/log" "gopkg.in/yaml.v3" ) //go:embed config.yaml 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 `yaml:"backoff"` Reddit RedditConfig `yaml:"reddit"` Twitter TwitterConfig `yaml:"twitter"` } func (c *Config) initReddit() { 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), }, } fi, err := os.Open(configPath) if err != nil { return nil, fmt.Errorf("could not open config: %v", err) } if err := yaml.NewDecoder(fi).Decode(&cfg); err != nil { return nil, fmt.Errorf("could not decode config: %v", err) } cfg.initReddit() log.Debug().Msgf("%#v", cfg) return &cfg, nil }