aboutsummaryrefslogtreecommitdiffsponsor
path: root/internal/service/config.go
blob: 0f349970bb99ad294bedc0da268ea4f6a4de4f15 (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
115
116
117
package service

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"git.server.ky/slackcoder/mirror/internal"
	"github.com/BurntSushi/toml"
)

// 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 readConfigFile(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

	confDDir, err := os.ReadDir(fp)
	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 := readConfigFile(filepath.Join(fp, entry.Name()))
		if err != nil {
			return nil, err
		}

		cfg.Append(entryCfg)
	}

	return &cfg, nil
}

// Read all configuration in the given directory.
func ReadConfig(fps ...string) (*Config, error) {
	var cfg Config

	for _, fp := range fps {
		stat, err := os.Stat(fp)
		if err != nil {
			return nil, err
		}

		var c *Config

		if stat.IsDir() {
			c, err = readConfigDir(fp)
			if err != nil {
				return nil, err
			}
		} else {
			c, err = readConfigFile(fp)
		}

		cfg.Append(c)
	}

	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...)
}