aboutsummaryrefslogtreecommitdiffsponsor
path: root/internal/service/config.go
blob: bfe271e19dbbbdda548cd2b6d996ad4b241095e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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...)
}