-
Notifications
You must be signed in to change notification settings - Fork 16
/
parser.go
471 lines (396 loc) · 9.97 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
Package parser is a Parser for parse INI format content to golang data
There are example data:
# comments
name = inhere
age = 28
debug = true
hasQuota1 = 'this is val'
hasQuota2 = "this is val1"
shell = ${SHELL}
noEnv = ${NotExist|defValue}
; array in def section
tags[] = a
tags[] = b
tags[] = c
; comments
[sec1]
key = val0
some = value
stuff = things
; array in section
types[] = x
types[] = y
how to use, please see examples:
*/
package parser
import (
"bufio"
"bytes"
"fmt"
"io"
"reflect"
"regexp"
"strings"
"github.com/gookit/goutil/strutil/textscan"
"github.com/mitchellh/mapstructure"
)
// match: [section]
var sectionRegex = regexp.MustCompile(`^\[(.*)]$`)
// TokSection for mark a section
const TokSection = textscan.TokComments + 1 + iota
// SectionMatcher match section line: [section]
type SectionMatcher struct{}
// Match section line: [section]
func (m *SectionMatcher) Match(text string, _ textscan.Token) (textscan.Token, error) {
line := strings.TrimSpace(text)
if matched := sectionRegex.FindStringSubmatch(line); matched != nil {
section := strings.TrimSpace(matched[1])
tok := textscan.NewStringToken(TokSection, section)
return tok, nil
}
return nil, nil
}
// Parser definition
type Parser struct {
*Options
// parsed bool
// comments map, key is name
comments map[string]string
// for full parse(allow array, map section)
fullData map[string]any
// for simple parse(section only allow map[string]string)
liteData map[string]map[string]string
}
// New a lite mode Parser with some options
func New(fns ...OptFunc) *Parser {
return &Parser{Options: NewOptions(fns...)}
}
// NewLite create a lite mode Parser. alias of New()
func NewLite(fns ...OptFunc) *Parser { return New(fns...) }
// NewSimpled create a lite mode Parser
func NewSimpled(fns ...func(*Parser)) *Parser {
return New().WithOptions(fns...)
}
// NewFulled create a full mode Parser with some options
func NewFulled(fns ...func(*Parser)) *Parser {
return New(WithParseMode(ModeFull)).WithOptions(fns...)
}
// Parse a INI data string to golang
func Parse(data string, mode parseMode, opts ...func(*Parser)) (p *Parser, err error) {
p = New(WithParseMode(mode)).WithOptions(opts...)
err = p.ParseString(data)
return
}
// Decode INI content to golang data
func Decode(blob []byte, ptr any) error {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("ini: Decode of non-pointer %s", reflect.TypeOf(ptr))
}
p, err := Parse(string(blob), ModeFull, NoDefSection)
if err != nil {
return err
}
return p.MapStruct(ptr)
}
// NoDefSection set don't return DefSection title
//
// Usage:
//
// Parser.NoDefSection()
func NoDefSection(p *Parser) { p.NoDefSection = true }
// IgnoreCase set ignore-case
func IgnoreCase(p *Parser) { p.IgnoreCase = true }
// WithOptions apply some options
func (p *Parser) WithOptions(opts ...func(p *Parser)) *Parser {
for _, opt := range opts {
opt(p)
}
return p
}
// Unmarshal parse ini 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)
}
/*************************************************************
* do parsing
*************************************************************/
// ParseString parse from string data
func (p *Parser) ParseString(str string) error {
if str = strings.TrimSpace(str); str == "" {
return nil
}
return p.ParseReader(strings.NewReader(str))
}
// ParseBytes parse from bytes data
func (p *Parser) ParseBytes(bts []byte) (err error) {
if len(bts) == 0 {
return nil
}
return p.ParseReader(bytes.NewBuffer(bts))
}
// ParseReader parse from io reader
func (p *Parser) ParseReader(r io.Reader) (err error) {
_, err = p.ParseFrom(bufio.NewScanner(r))
return
}
// init parser
func (p *Parser) init() {
// if p.IgnoreCase {
// p.DefSection = strings.ToLower(p.DefSection)
// }
p.comments = make(map[string]string)
if p.ParseMode == ModeFull {
p.fullData = make(map[string]any)
if p.Collector == nil {
p.Collector = p.collectFullValue
}
} else {
p.liteData = make(map[string]map[string]string)
if p.Collector == nil {
p.Collector = p.collectLiteValue
}
}
}
// ParseFrom a data scanner
func (p *Parser) ParseFrom(in *bufio.Scanner) (count int64, err error) {
p.init()
count = -1
// create scanner
ts := textscan.NewScanner(in)
ts.AddKind(TokSection, "Section")
ts.AddMatchers(
&textscan.CommentsMatcher{
InlineChars: []byte{'#', ';'},
},
&SectionMatcher{},
&textscan.KeyValueMatcher{
MergeComments: true,
InlineComment: p.InlineComment,
},
)
section := p.DefSection
// scan and parsing
for ts.Scan() {
tok := ts.Token()
// comments has been merged to value token
if !tok.IsValid() || tok.Kind() == textscan.TokComments {
continue
}
if tok.Kind() == TokSection {
section = tok.Value()
// collect comments
if textscan.IsKindToken(textscan.TokComments, ts.PrevToken()) {
p.comments["_sec_"+section] = ts.PrevToken().Value()
}
continue
}
// collect value
if tok.Kind() == textscan.TokValue {
vt := tok.(*textscan.ValueToken)
var isSli bool
key := vt.Key()
// is array index
if strings.HasSuffix(key, "[]") {
// skip parse array on lite mode
if p.ParseMode == ModeLite {
continue
}
key = key[:len(key)-2]
isSli = true
}
p.collectValue(section, key, vt.Value(), isSli)
if vt.HasComment() {
p.comments[section+"_"+key] = vt.Comment()
}
}
}
count = 0
err = ts.Err()
return
}
func (p *Parser) collectValue(section, key, val string, isSlice bool) {
if p.IgnoreCase {
key = strings.ToLower(key)
section = strings.ToLower(section)
}
if p.ReplaceNl {
val = strings.ReplaceAll(val, `\n`, "\n")
}
p.Collector(section, key, val, isSlice)
}
func (p *Parser) collectFullValue(section, key, val string, isSlice bool) {
defSec := p.DefSection
// p.NoDefSection and current section is default section
if p.NoDefSection && section == defSec {
if isSlice {
curVal, ok := p.fullData[key]
if ok {
switch cd := curVal.(type) {
case []string:
p.fullData[key] = append(cd, val)
}
} else {
p.fullData[key] = []string{val}
}
} else {
p.fullData[key] = val
}
return
}
secData, exists := p.fullData[section]
// first create
if !exists {
if isSlice {
p.fullData[section] = map[string]any{key: []string{val}}
} else {
p.fullData[section] = map[string]any{key: val}
}
return
}
switch sd := secData.(type) {
case map[string]any: // existed section
if curVal, ok := sd[key]; ok {
switch cv := curVal.(type) {
case string:
if isSlice {
sd[key] = []string{cv, val}
} else {
sd[key] = val
}
case []string:
sd[key] = append(cv, val)
default:
return
}
} else {
if isSlice {
sd[key] = []string{val}
} else {
sd[key] = val
}
}
p.fullData[section] = sd
case string: // found default section value
if isSlice {
p.fullData[section] = map[string]any{key: []string{val}}
} else {
p.fullData[section] = map[string]any{key: val}
}
}
}
func (p *Parser) collectLiteValue(sec, key, val string, _ bool) {
if p.IgnoreCase {
key = strings.ToLower(key)
sec = strings.ToLower(sec)
}
if strMap, ok := p.liteData[sec]; ok {
strMap[key] = val
p.liteData[sec] = strMap
} else {
// create the section if it does not exist
p.liteData[sec] = map[string]string{key: val}
}
}
/*************************************************************
* export data
*************************************************************/
// Decode the parsed data to struct ptr
func (p *Parser) Decode(ptr any) error {
return p.MapStruct(ptr)
}
// MapStruct mapping the parsed data to struct ptr
func (p *Parser) MapStruct(ptr any) (err error) {
if p.ParseMode == ModeFull {
if p.NoDefSection {
return mapStruct(p.TagName, p.fullData, ptr)
}
// collect all default section data to top
anyMap := make(map[string]any, len(p.fullData)+4)
if defData, ok := p.fullData[p.DefSection]; ok {
for key, val := range defData.(map[string]any) {
anyMap[key] = val
}
}
for group, mp := range p.fullData {
if group == p.DefSection {
continue
}
anyMap[group] = mp
}
return mapStruct(p.TagName, anyMap, ptr)
}
defData := p.liteData[p.DefSection]
defLen := len(defData)
anyMap := make(map[string]any, len(p.liteData)+defLen)
// collect all default section data to top
if defLen > 0 {
for key, val := range defData {
anyMap[key] = val
}
}
for group, smp := range p.liteData {
if group == p.DefSection {
continue
}
anyMap[group] = smp
}
return mapStruct(p.TagName, anyMap, ptr)
}
func mapStruct(tagName string, data any, ptr any) error {
mapConf := &mapstructure.DecoderConfig{
Metadata: nil,
Result: ptr,
TagName: tagName,
// will auto convert string to int/uint
WeaklyTypedInput: true,
}
decoder, err := mapstructure.NewDecoder(mapConf)
if err != nil {
return err
}
return decoder.Decode(data)
}
/*************************************************************
* helper methods
*************************************************************/
// Comments get
func (p *Parser) Comments() map[string]string {
return p.comments
}
// ParsedData get parsed data
func (p *Parser) ParsedData() any {
if p.ParseMode == ModeFull {
return p.fullData
}
return p.liteData
}
// FullData get parsed data by full parse
func (p *Parser) FullData() map[string]any {
return p.fullData
}
// LiteData get parsed data by simple parse
func (p *Parser) LiteData() map[string]map[string]string {
return p.liteData
}
// SimpleData get parsed data by simple parse
func (p *Parser) SimpleData() map[string]map[string]string {
return p.liteData
}
// LiteSection get parsed data by simple parse
func (p *Parser) LiteSection(name string) map[string]string {
return p.liteData[name]
}
// Reset parser, clear parsed data
func (p *Parser) Reset() {
// p.parsed = false
if p.ParseMode == ModeFull {
p.fullData = make(map[string]any)
} else {
p.liteData = make(map[string]map[string]string)
}
}