generated from inherelab/go-pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
214 lines (183 loc) · 4.07 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package properties
import (
"bytes"
"errors"
"io"
"strings"
"github.com/gookit/goutil/envutil"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil/textscan"
"github.com/mitchellh/mapstructure"
)
// special chars consts
const (
MultiLineValMarkS = "'''"
MultiLineValMarkD = `"""`
MultiLineValMarkQ = "\\"
MultiLineCmtEnd = "*/"
VarRefStartChars = "${"
)
// Parser for parse properties contents
type Parser struct {
maputil.Data
// last parse error
err error
// lex *lexer
// text string
opts *Options
// key path map
smap maputil.SMap
// comments map
comments map[string]string
}
// NewParser instance
func NewParser(optFns ...OpFunc) *Parser {
p := &Parser{
opts: newDefaultOption(),
smap: make(maputil.SMap),
Data: make(maputil.Data),
// comments map
comments: make(map[string]string),
}
return p.WithOptions(optFns...)
}
// WithOptions for the parser
func (p *Parser) WithOptions(optFns ...OpFunc) *Parser {
for _, fn := range optFns {
fn(p.opts)
}
return p
}
// Unmarshal parse properties text and decode to struct
func (p *Parser) Unmarshal(v []byte, ptr any) error {
if err := p.ParseBytes(v); err != nil {
return err
}
return p.MapStruct("", ptr)
}
// Parse text contents
func (p *Parser) Parse(text string) error {
if text = strings.TrimSpace(text); text == "" {
return errors.New("cannot input empty contents to parse")
}
return p.ParseFrom(strings.NewReader(text))
}
// ParseBytes text contents
func (p *Parser) ParseBytes(bs []byte) error {
if len(bs) == 0 {
return errors.New("cannot input empty contents to parse")
}
return p.ParseFrom(bytes.NewReader(bs))
}
// ParseFrom contents
func (p *Parser) ParseFrom(r io.Reader) error {
ts := textscan.NewScanner(r)
ts.AddMatchers(
&textscan.CommentsMatcher{
InlineChars: []byte{'#', '!'},
},
&textscan.KeyValueMatcher{
InlineComment: p.opts.InlineComment,
MergeComments: true,
},
)
// scan and parsing
for ts.Scan() {
tok := ts.Token()
// collect value
if tok.Kind() == textscan.TokValue {
p.setValue(tok.(*textscan.ValueToken))
}
}
p.err = ts.Err()
return p.err
}
// collect set value
func (p *Parser) setValue(tok *textscan.ValueToken) {
var value string
if tok.Mark() == textscan.MultiLineValMarkQ {
value = strings.Join(tok.Values(), "")
} else {
value = tok.Value()
}
key := tok.Key()
if tok.HasComment() {
p.comments[key] = tok.Comment()
}
ln := len(value)
if p.opts.TrimValue && ln > 0 {
value = strings.TrimSpace(value)
}
if p.opts.ParseVar && ln > 3 {
refName, ok := parseVarRefName(value)
if ok {
value = p.smap.Default(refName, value)
}
}
var setVal any
setVal = value
p.smap[key] = value
if p.opts.ParseEnv && ln > 3 {
setVal = envutil.ParseEnvValue(value)
}
if p.opts.InlineSlice && ln > 2 {
ss, ok := parseInlineSlice(value, ln)
if ok {
setVal = ss
}
}
var keys []string
if strings.ContainsRune(key, '.') {
keys = strings.Split(key, ".")
} else {
keys = []string{key}
}
if p.opts.BeforeCollect != nil {
setVal = p.opts.BeforeCollect(key, setVal)
}
// set value by keys
if len(keys) == 1 {
p.Data[key] = setVal
} else if len(p.Data) == 0 {
p.Data = maputil.MakeByKeys(keys, setVal)
} else {
err := p.Data.SetByKeys(keys, setVal)
if err != nil {
p.err = err
}
}
}
// ErrNotFound error
var ErrNotFound = errors.New("this key does not exists")
// Decode the parsed data to struct ptr
func (p *Parser) Decode(ptr any) error {
return p.MapStruct("", ptr)
}
// MapStruct mapping data to a struct ptr
func (p *Parser) MapStruct(key string, ptr any) error {
var data any
if key == "" { // binding all data
data = p.Data
} else { // sub data of the p.Data
var ok bool
data, ok = p.Value(key)
if !ok {
return ErrNotFound
}
}
decConf := p.opts.makeDecoderConfig()
decConf.Result = ptr // set result ptr
decoder, err := mapstructure.NewDecoder(decConf)
if err == nil {
err = decoder.Decode(data)
}
return err
}
// SMap data
func (p *Parser) SMap() maputil.SMap {
return p.smap
}
// Comments data
func (p *Parser) Comments() map[string]string {
return p.comments
}