about summary refs log tree commit diff stats
path: root/internal/config/config.go
blob: 3947d18a1e5edd1f4fe428662f038aae6eb52275 (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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package config

import (
	"html/template"
	"log/slog"
	"maps"
	"net/url"
	"os"
	"time"

	"github.com/pelletier/go-toml/v2"
	"github.com/pkg/errors"
)

var (
	CommitSHA string
	ShortSHA  string
)

type URL struct {
	*url.URL
}

func (u *URL) MarshalText() ([]byte, error) {
	return []byte(u.URL.String()), nil
}

func (u *URL) UnmarshalText(text []byte) (err error) {
	u.URL, err = url.Parse(string(text))

	if err != nil {
		return errors.WithMessagef(err, "could not parse URL %s", string(text))
	}

	return nil
}

type Duration struct {
	time.Duration
}

func (d *Duration) MarshalText() ([]byte, error) {
	return []byte(d.Duration.String()), nil
}

func (d *Duration) UnmarshalText(text []byte) (err error) {
	d.Duration, err = time.ParseDuration(string(text))
	if err != nil {
		return errors.WithMessagef(err, "could not parse duration %s", string(text))
	}

	return nil
}

func mustURL(in string) (u URL) {
	var err error
	u.URL, err = url.Parse(in)
	if err != nil {
		panic(errors.Errorf("URL cannot be parsed: %s", in))
	}

	return u
}

func mustLocalTime(in string) (time toml.LocalTime) {
	err := time.UnmarshalText([]byte(in))
	if err != nil {
		panic(errors.Errorf("Could not parse time: %s", in))
	}

	return
}

type Web struct {
	ContentSecurityPolicy CSP
	ListenAddress         string
	Port                  int
	BaseURL               URL
	SentryDSN             string
	Environment           string
	ExtraHeadHTML         template.HTML
	Headers               map[string]string
}

type Importer struct {
	Sources  map[string]*Source
	Timeout  Duration
	UpdateAt toml.LocalTime
}

type Config struct {
	DataPath string
	LogLevel slog.Level
	Web      *Web
	Importer *Importer
}

var nixpkgs = Repository{
	Type:  "github",
	Owner: "NixOS",
	Repo:  "nixpkgs",
}

var defaultConfig = Config{
	DataPath: "./data",
	Web: &Web{
		ListenAddress: "localhost",
		Port:          3000,
		BaseURL:       mustURL("http://localhost:3000"),
		Environment:   "development",
		ContentSecurityPolicy: CSP{
			DefaultSrc: []string{"'self'"},
		},
		Headers: map[string]string{
			"x-content-type-options": "nosniff",
		},
	},
	Importer: &Importer{
		Timeout:  Duration{30 * time.Minute},
		UpdateAt: mustLocalTime("04:00:00"),
		Sources: map[string]*Source{
			"nixos": {
				Name:          "NixOS",
				Key:           "nixos",
				Enable:        true,
				Importer:      Options,
				Fetcher:       Channel,
				Channel:       "nixpkgs",
				URL:           "https://channels.nixos.org/nixos-unstable/nixexprs.tar.xz",
				ImportPath:    "nixos/release.nix",
				Attribute:     "options",
				OutputPath:    "share/doc/nixos",
				FetchTimeout:  Duration{5 * time.Minute},
				ImportTimeout: Duration{15 * time.Minute},
				Repo:          nixpkgs,
			},
			"darwin": {
				Name:          "Darwin",
				Key:           "darwin",
				Enable:        false,
				Importer:      Options,
				Fetcher:       Channel,
				Channel:       "darwin",
				URL:           "https://github.com/LnL7/nix-darwin/archive/master.tar.gz",
				ImportPath:    "release.nix",
				Attribute:     "options",
				OutputPath:    "share/doc/darwin",
				FetchTimeout:  Duration{5 * time.Minute},
				ImportTimeout: Duration{15 * time.Minute},
				Repo: Repository{
					Type:  "github",
					Owner: "LnL7",
					Repo:  "nix-darwin",
				},
			},
			"home-manager": {
				Name:          "Home Manager",
				Key:           "home-manager",
				Enable:        false,
				Importer:      Options,
				Channel:       "home-manager",
				URL:           "https://github.com/nix-community/home-manager/archive/master.tar.gz",
				Fetcher:       Channel,
				ImportPath:    "default.nix",
				Attribute:     "docs.json",
				OutputPath:    "share/doc/home-manager",
				FetchTimeout:  Duration{5 * time.Minute},
				ImportTimeout: Duration{15 * time.Minute},
				Repo: Repository{
					Type:  "github",
					Owner: "nix-community",
					Repo:  "home-manager",
				},
			},
			"nixpkgs": {
				Name:          "Nix Packages",
				Key:           "nixpkgs",
				Enable:        true,
				Importer:      Packages,
				Fetcher:       ChannelNixpkgs,
				Channel:       "nixos-unstable",
				OutputPath:    "packages.json.br",
				FetchTimeout:  Duration{5 * time.Minute},
				ImportTimeout: Duration{15 * time.Minute},
				Repo:          nixpkgs,
			},
		},
	},
}

func GetDefaultConfig() string {
	out, err := toml.Marshal(&defaultConfig)
	if err != nil {
		panic("could not read default configuration")
	}

	return string(out)
}

func GetConfig(filename string) (*Config, error) {
	config := defaultConfig
	if filename != "" {
		slog.Debug("reading config", "filename", filename)
		f, err := os.Open(filename)
		if err != nil {
			return nil, errors.Wrap(err, "reading config failed")
		}
		defer f.Close()

		dec := toml.NewDecoder(f)
		dec.DisallowUnknownFields()
		err = dec.Decode(&config)
		if err != nil {
			var tomlError *toml.DecodeError
			if errors.As(err, &tomlError) {
				return nil, errors.WithMessage(err, tomlError.Error())
			}
			var missingConfigError *toml.StrictMissingError
			if errors.As(err, &missingConfigError) {
				return nil, errors.Errorf("unexpected config: %s", missingConfigError.String())
			}

			return nil, errors.Wrap(err, "config error")
		}
	}

	maps.DeleteFunc(config.Importer.Sources, func(_ string, v *Source) bool {
		return !v.Enable
	})

	return &config, nil
}