forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner_test.go
84 lines (70 loc) · 1.41 KB
/
scanner_test.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
package textscan_test
import (
"fmt"
"testing"
"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/strutil/textscan"
"github.com/gookit/goutil/testutil/assert"
)
func ExampleNewScanner() {
ts := textscan.NewScanner(`source code`)
// add token matcher, can add your custom matcher
ts.AddMatchers(
&textscan.CommentsMatcher{
InlineChars: []byte{'#'},
},
&textscan.KeyValueMatcher{
MergeComments: true,
},
)
// scan and parsing
for ts.Scan() {
tok := ts.Token()
if !tok.IsValid() {
continue
}
// Custom handle the parsed token
if tok.Kind() == textscan.TokValue {
vt := tok.(*textscan.ValueToken)
fmt.Println(vt)
}
}
if ts.Err() != nil {
fmt.Println("ERROR:", ts.Err())
}
}
func TestTextScanner_kvLine(t *testing.T) {
ts := textscan.TextScanner{}
ts.AddMatchers(
&textscan.CommentsMatcher{},
&textscan.KeyValueMatcher{},
)
ts.SetInput(`
# comments 1
name = inhere
// comments 2
age = 28
/*
multi line
comments 3
*/
desc = '''
a multi
line string
'''
`)
data := make(map[string]string)
err := ts.Each(func(t textscan.Token) {
fmt.Println("====> Token kind:", t.Kind())
fmt.Println(t.String())
if t.Kind() == textscan.TokValue {
v := t.(*textscan.ValueToken)
data[v.Key()] = v.Value()
}
})
fmt.Println("\n==== Collected data:")
dump.P(data)
assert.NoErr(t, err)
assert.NotEmpty(t, data)
assert.ContainsKeys(t, data, []string{"age", "name", "desc"})
}