-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore_load.go
50 lines (38 loc) · 1.34 KB
/
store_load.go
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
package main
import (
"fmt"
"os"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
)
func loadStorage(path string) (store *Store, err error) {
var stat os.FileInfo
if stat, err = os.Stat(path); err != nil {
if os.IsNotExist(err) {
var f *os.File
if f, err = os.Create(path); err != nil {
return nil, fmt.Errorf("error validating storage: the path '%s' has an issue: had an error creating the file: %w", path, err)
}
if err = f.Close(); err != nil {
return nil, fmt.Errorf("error validating storage: the path '%s' has an issue: had an error closing the file after creating it: %w", path, err)
}
} else {
return nil, fmt.Errorf("error validating storage: the path '%s' has an issue: had an error reading the file: %w", path, err)
}
} else if stat.IsDir() {
return nil, fmt.Errorf("error validating storage: the path '%s' has an issue: it's a directory instead of a file", path)
}
ko := koanf.New(".")
kpath := file.Provider(path)
if err = ko.Load(kpath, yaml.Parser()); err != nil {
return nil, fmt.Errorf("error occurred loading file storage: %w", err)
}
store = &Store{
Tokens: map[string]TokenStore{},
}
if err = koUnmarshal(ko, store); err != nil {
return nil, fmt.Errorf("error occurred unmarshalling storage: %w", err)
}
return store, nil
}