package service import ( "fmt" "os" "path" "path/filepath" "time" "git.server.ky/slackcoder/mirror/internal" "github.com/BurntSushi/toml" ) type Duration struct { time.Duration } func DurationRef(v time.Duration) *Duration { return &Duration{v} } func (s Duration) MarshalText() ([]byte, error) { return []byte(s.Duration.String()), nil } func (s *Duration) UnmarshalText(text []byte) error { v, err := time.ParseDuration(string(text)) if err != nil { return err } *s = Duration{v} return nil } // Global parameters type GlobalConfig struct { MaxInterval *Duration `toml:"max-interval"` MinInterval *Duration `toml:"min-interval"` } type Config struct { GlobalConfig `toml:"global"` Mirrors []*Mirror `toml:"mirrors,omitempty"` } func (c *Config) String() string { return internal.MustTOML(c) } var DefaultConfig = Config{ GlobalConfig: GlobalConfig{ MaxInterval: DurationRef(24 * time.Hour), MinInterval: DurationRef(time.Hour), }, } // Read the given configuration file. func ReadConfig(fp string) (*Config, error) { var config Config f, err := os.Open(fp) if err != nil { return nil, err } defer f.Close() _, err = toml.NewDecoder(f).Decode(&config) if err != nil { return nil, fmt.Errorf("loading configuration file: %w", err) } return &config, nil } // Read all configuration in the given directory. func ReadConfigDir(fp string) (*Config, error) { var cfg Config confDPath := path.Join(path.Join(fp, "conf.d")) confDDir, err := os.ReadDir(confDPath) if os.IsNotExist(err) { // No directory is an empty one. return &Config{}, nil } else if err != nil { return nil, err } for _, entry := range confDDir { if filepath.Ext(entry.Name()) != ".toml" { continue } entryCfg, err := ReadConfig(filepath.Join(confDPath, entry.Name())) if err != nil { return nil, err } cfg.Append(entryCfg) } return &cfg, nil } // Apply the given configuration parameters. func (c *Config) Append(src *Config) { if src.MaxInterval != nil { c.MaxInterval = src.MaxInterval } if src.MinInterval != nil { c.MinInterval = src.MinInterval } c.Mirrors = append(c.Mirrors, src.Mirrors...) }