forked from PlakarKorp/plakar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
345 lines (304 loc) · 7.67 KB
/
config.go
File metadata and controls
345 lines (304 loc) · 7.67 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package utils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"gopkg.in/ini.v1"
"github.com/PlakarKorp/kloset/config"
"go.yaml.in/yaml/v3"
)
type configHandler struct {
Path string
}
const CONFIG_VERSION = "v1.0.0"
type storesConfig struct {
Version string `yaml:"version"`
Default string `yaml:"default,omitempty"`
Stores map[string]map[string]string `yaml:"stores"`
}
type sourcesConfig struct {
Version string `yaml:"version"`
Sources map[string]map[string]string `yaml:"sources"`
}
type destinationsConfig struct {
Version string `yaml:"version"`
Destinations map[string]map[string]string `yaml:"destinations"`
}
func newConfigHandler(path string) *configHandler {
return &configHandler{
Path: path,
}
}
func (cl *configHandler) Load() (*config.Config, error) {
sources := sourcesConfig{}
destinations := destinationsConfig{}
stores := storesConfig{}
err := cl.load("sources.yml", &sources)
if err != nil {
if os.IsNotExist(err) {
return cl.LoadFallback()
}
return nil, err
}
err = cl.load("destinations.yml", &destinations)
if err != nil {
if os.IsNotExist(err) {
return cl.LoadFallback()
}
return nil, err
}
err = cl.load("stores.yml", &stores)
if err != nil && os.IsNotExist(err) {
// try to load former file
err = cl.load("klosets.yml", &stores)
}
if err != nil {
if os.IsNotExist(err) {
return cl.LoadFallback()
}
return nil, err
}
cfg := config.NewConfig()
cfg.Sources = sources.Sources
cfg.Destinations = destinations.Destinations
cfg.Repositories = stores.Stores
cfg.DefaultRepository = stores.Default
return cfg, nil
}
func (cl *configHandler) LoadFallback() (*config.Config, error) {
// Load old config if found
oldpath := filepath.Join(cl.Path, "plakar.yml")
cfg, err := LoadOldConfigIfExists(oldpath)
if err != nil {
return nil, fmt.Errorf("error reading file %s: %w", oldpath, err)
}
// Save the config in the new format right now
err = SaveConfig(cl.Path, cfg)
if err != nil {
return nil, fmt.Errorf("failed to update config file: %w", err)
}
// Do we want to remove the old file?
return cfg, nil
}
func (cl *configHandler) Save(cfg *config.Config) error {
err := cl.save("sources.yml", sourcesConfig{
Version: CONFIG_VERSION,
Sources: cfg.Sources,
})
if err != nil {
return err
}
err = cl.save("destinations.yml", destinationsConfig{
Version: CONFIG_VERSION,
Destinations: cfg.Destinations,
})
if err != nil {
return err
}
err = cl.save("stores.yml", storesConfig{
Version: CONFIG_VERSION,
Default: cfg.DefaultRepository,
Stores: cfg.Repositories,
})
if err != nil {
return err
}
return nil
}
func (cl *configHandler) load(filename string, dst any) error {
path := filepath.Join(cl.Path, filename)
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return err
}
return fmt.Errorf("failed to open file %s: %w", path, err)
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return fmt.Errorf("failed to stat file %s: %w", path, err)
}
if info.Size() == 0 {
return nil
}
// try to load the new format
err = yaml.NewDecoder(f).Decode(dst)
var version string
switch t := dst.(type) {
case *storesConfig:
version = t.Version
case *destinationsConfig:
version = t.Version
case *sourcesConfig:
version = t.Version
default:
return fmt.Errorf("invalid configuration type %v", t)
}
if err == nil && version == CONFIG_VERSION {
return nil
}
// fallback to the previous format
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return fmt.Errorf("failed to rewind config file: %w", err)
}
switch t := dst.(type) {
case *storesConfig:
err = yaml.NewDecoder(f).Decode(&t.Stores)
if err == nil {
for k, v := range t.Stores {
if _, ok := v[".isDefault"]; ok {
if t.Default != "" {
return fmt.Errorf("multiple default store")
}
t.Default = k
delete(v, ".isDefault")
}
}
}
case *destinationsConfig:
err = yaml.NewDecoder(f).Decode(&t.Destinations)
case *sourcesConfig:
err = yaml.NewDecoder(f).Decode(&t.Sources)
}
if err != nil {
return fmt.Errorf("failed to parse config file: %w", err)
}
return nil
}
func (cl *configHandler) save(filename string, src any) error {
path := filepath.Join(cl.Path, filename)
tmpFile, err := os.CreateTemp(cl.Path, "config.*.yml")
if err != nil {
return err
}
err = yaml.NewEncoder(tmpFile).Encode(src)
tmpFile.Close()
if err == nil {
err = os.Rename(tmpFile.Name(), path)
}
if err != nil {
os.Remove(tmpFile.Name())
return err
}
return nil
}
func LoadConfig(configDir string) (*config.Config, error) {
cl := newConfigHandler(configDir)
cfg, err := cl.Load()
if err != nil {
return nil, err
}
return cfg, nil
}
func SaveConfig(configDir string, cfg *config.Config) error {
return newConfigHandler(configDir).Save(cfg)
}
// toString converts various primitive types to string.
func toString(v interface{}) string {
switch t := v.(type) {
case string:
return t
case int, int64, float64, bool:
return fmt.Sprintf("%v", t)
default:
return ""
}
}
func LoadINI(rd io.Reader) (map[string]map[string]string, error) {
cfg, err := ini.Load(rd)
if err != nil {
return nil, err
}
keysMap := make(map[string]struct{})
result := make(map[string]map[string]string)
for _, section := range cfg.Sections() {
name := section.Name()
if name == ini.DefaultSection {
continue
}
keysMap[name] = struct{}{}
result[name] = make(map[string]string)
for _, key := range section.Keys() {
result[name][key.Name()] = key.Value()
}
}
return result, nil
}
func LoadYAML(rd io.Reader) (map[string]map[string]string, error) {
var raw map[string]interface{}
decoder := yaml.NewDecoder(rd)
if err := decoder.Decode(&raw); err != nil {
return nil, err
}
result := make(map[string]map[string]string)
for section, value := range raw {
sectionMap, ok := value.(map[string]interface{})
if !ok {
continue // skip non-object top-level keys
}
result[section] = make(map[string]string)
for k, v := range sectionMap {
result[section][k] = toString(v)
}
}
return result, nil
}
// LoadJSON loads a JSON object and returns a nested map[string]map[string]string.
func LoadJSON(rd io.Reader) (map[string]map[string]string, error) {
var raw map[string]map[string]string
decoder := json.NewDecoder(rd)
if err := decoder.Decode(&raw); err != nil {
return nil, err
}
return raw, nil
}
func GetConf(rd io.Reader, thirdParty string) (map[string]map[string]string, error) {
data, err := io.ReadAll(rd)
if err != nil {
return nil, fmt.Errorf("failed to read config data: %w", err)
}
var configMap map[string]map[string]string
if configMap, err = LoadYAML(bytes.NewReader(data)); err == nil {
} else if configMap, err = LoadJSON(bytes.NewReader(data)); err == nil {
} else if configMap, err = LoadINI(bytes.NewReader(data)); err != nil {
return nil, fmt.Errorf("failed to parse config data: %w", err)
}
if thirdParty != "" {
for _, section := range configMap {
var ignore []string
for key, value := range section {
if slices.Contains(ignore, key) {
continue
}
if value != "" {
newKey := thirdParty + "_" + key
section[newKey] = value
ignore = append(ignore, newKey)
}
delete(section, key)
}
section["location"] = thirdParty + "://"
}
}
seenLocation := false
for _, section := range configMap {
for key, value := range section {
if key == "location" {
seenLocation = true
}
if value == "" {
delete(section, key)
}
}
}
if !seenLocation {
return nil, fmt.Errorf("missing 'location' key in config data, `-rclone` import option missing ?")
}
return configMap, nil
}