diff options
Diffstat (limited to 'internal/service/config.go')
-rw-r--r-- | internal/service/config.go | 59 |
1 files changed, 46 insertions, 13 deletions
diff --git a/internal/service/config.go b/internal/service/config.go index 27368b3..bfe271e 100644 --- a/internal/service/config.go +++ b/internal/service/config.go @@ -3,6 +3,8 @@ package service import ( "fmt" "os" + "path" + "path/filepath" "time" "git.server.ky/slackcoder/mirror/internal" @@ -13,6 +15,10 @@ 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 } @@ -29,8 +35,8 @@ func (s *Duration) UnmarshalText(text []byte) error { // Global parameters type GlobalConfig struct { - MaxInterval Duration `toml:"max-interval"` - MinInterval Duration `toml:"min-interval"` + MaxInterval *Duration `toml:"max-interval"` + MinInterval *Duration `toml:"min-interval"` } type Config struct { @@ -44,18 +50,17 @@ func (c *Config) String() string { var DefaultConfig = Config{ GlobalConfig: GlobalConfig{ - MaxInterval: Duration{24 * time.Hour}, - MinInterval: Duration{time.Hour}, + 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 os.IsNotExist(err) { - return nil, nil - } else if err != nil { + if err != nil { return nil, err } defer f.Close() @@ -68,14 +73,42 @@ func ReadConfig(fp string) (*Config, error) { return &config, nil } -func (c *Config) Merge(src *Config) { - if c.MaxInterval.Duration == 0 && src.MaxInterval.Duration != 0 { +// 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 c.MinInterval.Duration == 0 && src.MinInterval.Duration != 0 { + if src.MinInterval != nil { c.MinInterval = src.MinInterval } - if len(c.Mirrors) == 0 { - c.Mirrors = src.Mirrors - } + c.Mirrors = append(c.Mirrors, src.Mirrors...) } |