-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
114 lines (97 loc) · 2.46 KB
/
parser.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package boot
import (
"bufio"
"fmt"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v3"
"io"
"strings"
)
// PlainParser is a parser for config files in an extremely simple format. Each
// line is tokenized as a single key/value pair. The first whitespace-delimited
// token in the line is interpreted as the flag name, and all remaining tokens
// are interpreted as the value. Any leading hyphens on the flag name are
// ignored.
func PlainParser(r io.Reader, set func(name, value string) error) error {
s := bufio.NewScanner(r)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" {
continue // skip empties
}
if line[0] == '#' {
continue // skip comments
}
var (
name string
value string
index = strings.IndexRune(line, ' ')
)
if index < 0 {
name, value = line, "true" // boolean option
} else {
name, value = line[:index], strings.TrimSpace(line[index:])
}
if i := strings.Index(value, " #"); i >= 0 {
value = strings.TrimSpace(value[:i])
}
if err := set(name, value); err != nil {
return err
}
}
return nil
}
func DotEnvParser(r io.Reader, set func(name, value string) error) error {
s := bufio.NewScanner(r)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" {
continue // skip empties
}
if line[0] == '#' {
continue // skip comments
}
var (
name string
value string
index = strings.IndexRune(line, '=')
)
if index < 0 {
name, value = line, "true" // boolean option
} else {
name, value = line[:index], strings.TrimSpace(line[index+1:])
}
if i := strings.Index(value, " #"); i >= 0 {
value = strings.TrimSpace(value[:i])
}
name = strings.ToLower(strings.ReplaceAll(name, "_", "-"))
if err := set(name, value); err != nil {
return err
}
}
return nil
}
func configParser(r io.Reader, set func(name, value string) error) (err error) {
var (
m = make(map[string]interface{})
d = yaml.NewDecoder(r)
)
if err = mapstructure.Decode(r, d); err != nil && err != io.EOF {
return ParseError{err}
}
fmt.Println(m)
return nil
}
// 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 errors.Wrapper interface, allowing errors.Is and
// errors.As to work with ParseErrors.
func (e ParseError) Unwrap() error {
return e.Inner
}