-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_resolvers.go
72 lines (57 loc) · 1.31 KB
/
file_resolvers.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
package king
import (
"io"
"io/ioutil"
"github.com/BurntSushi/toml"
"github.com/alecthomas/kong"
"gopkg.in/yaml.v3"
)
// FileResolver represents a kong fileresolver.
type FileResolver string
// All supported file resolvers.
const (
YAML FileResolver = "yaml"
TOML FileResolver = "toml"
)
// NewFileResolver creates a new fileresolver.
func NewFileResolver(f FileResolver) kong.ConfigurationLoader {
switch f {
case TOML:
return tomlResolver
default:
return yamlResolver
}
}
func yamlResolver(r io.Reader) (kong.Resolver, error) {
values := map[string]interface{}{}
err := yaml.NewDecoder(r).Decode(&values)
if err != nil {
return nil, err
}
var f kong.ResolverFunc = func(ctx *kong.Context, parent *kong.Path, flag *kong.Flag) (interface{}, error) {
raw, ok := values[flag.Name]
if !ok {
return nil, nil
}
return raw, nil
}
return f, nil
}
func tomlResolver(r io.Reader) (kong.Resolver, error) {
values := map[string]interface{}{}
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
if err := toml.Unmarshal(data, &values); err != nil {
return nil, err
}
var f kong.ResolverFunc = func(ctx *kong.Context, parent *kong.Path, flag *kong.Flag) (interface{}, error) {
raw, ok := values[flag.Name]
if !ok {
return nil, nil
}
return raw, nil
}
return f, nil
}