-
Notifications
You must be signed in to change notification settings - Fork 0
/
koanf_file.go
93 lines (76 loc) · 2.09 KB
/
koanf_file.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
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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package configx
import (
"context"
"os"
"path/filepath"
"strings"
"github.com/clinia/x/stringslice"
"github.com/clinia/x/watcherx"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/json"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/parsers/yaml"
"github.com/pkg/errors"
)
// KoanfFile implements a KoanfFile provider.
type KoanfFile struct {
subKey string
path string
ctx context.Context
parser koanf.Parser
}
// Provider returns a file provider.
func NewKoanfFile(ctx context.Context, path string) (*KoanfFile, error) {
return NewKoanfFileSubKey(ctx, path, "")
}
func NewKoanfFileSubKey(ctx context.Context, path, subKey string) (*KoanfFile, error) {
kf := &KoanfFile{
path: filepath.Clean(path),
ctx: ctx,
subKey: subKey,
}
switch e := filepath.Ext(path); e {
case ".toml":
kf.parser = toml.Parser()
case ".json":
kf.parser = json.Parser()
case ".yaml", ".yml":
kf.parser = yaml.Parser()
default:
return nil, errors.Errorf("unknown config file extension: %s", e)
}
return kf, nil
}
// ReadBytes reads the contents of a file on disk and returns the bytes.
func (f *KoanfFile) ReadBytes() ([]byte, error) {
return nil, errors.New("file provider does not support this method")
}
// Read is not supported by the file provider.
func (f *KoanfFile) Read() (map[string]interface{}, error) {
//#nosec G304 -- false positive
fc, err := os.ReadFile(f.path)
if err != nil {
return nil, errors.WithStack(err)
}
v, err := f.parser.Unmarshal(fc)
if err != nil {
return nil, errors.WithStack(err)
}
if f.subKey == "" {
return v, nil
}
path := strings.Split(f.subKey, Delimiter)
for _, k := range stringslice.Reverse(path) {
v = map[string]interface{}{
k: v,
}
}
return v, nil
}
// WatchChannel watches the file and triggers a callback when it changes. It is a
// blocking function that internally spawns a goroutine to watch for changes.
func (f *KoanfFile) WatchChannel(c watcherx.EventChannel) (watcherx.Watcher, error) {
return watcherx.WatchFile(f.ctx, f.path, c)
}