/
ffyaml.go
90 lines (81 loc) · 1.93 KB
/
ffyaml.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
// Package ffyaml provides a YAML config file paser.
package ffyaml
import (
"fmt"
"io"
"strconv"
"github.com/peterbourgon/ff"
"gopkg.in/yaml.v2"
)
// Parser is a parser for YAML file format. Flags and their values are read
// from the key/value pairs defined in the config file.
func Parser(r io.Reader, set func(name, value string) error) error {
var m map[string]interface{}
d := yaml.NewDecoder(r)
if err := d.Decode(&m); err != nil && err != io.EOF {
return ParseError{err}
}
for key, val := range m {
values, err := valsToStrs(val)
if err != nil {
return ParseError{err}
}
for _, value := range values {
if err := set(key, value); err != nil {
return err
}
}
}
return nil
}
func valsToStrs(val interface{}) ([]string, error) {
if vals, ok := val.([]interface{}); ok {
ss := make([]string, len(vals))
for i := range vals {
s, err := valToStr(vals[i])
if err != nil {
return nil, err
}
ss[i] = s
}
return ss, nil
}
s, err := valToStr(val)
if err != nil {
return nil, err
}
return []string{s}, nil
}
func valToStr(val interface{}) (string, error) {
switch v := val.(type) {
case byte:
return string([]byte{v}), nil
case string:
return v, nil
case bool:
return strconv.FormatBool(v), nil
case uint64:
return strconv.FormatUint(v, 10), nil
case int:
return strconv.Itoa(v), nil
case int64:
return strconv.FormatInt(v, 10), nil
case float64:
return strconv.FormatFloat(v, 'g', -1, 64), nil
default:
return "", ff.StringConversionError{Value: val}
}
}
// ParseError wraps all errors originating from the YAML parser.
type ParseError struct {
Inner error
}
// Error implenents the error interface.
func (e ParseError) Error() string {
return fmt.Sprintf("error parsing YAML config: %v", e.Inner)
}
// Unwrap implements the xerrors.Wrapper interface, allowing
// xerrors.Is and xerrors.As to work with ParseErrors.
func (e ParseError) Unwrap() error {
return e.Inner
}