-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
94 lines (69 loc) · 1.56 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
package yamlink
import (
"gopkg.in/yaml.v3"
"io"
"os"
"strconv"
"strings"
)
func ParseYaml(reader io.Reader) (interface{}, error) {
var m map[string]interface{}
decoder := yaml.NewDecoder(reader)
err := decoder.Decode(&m)
if err != nil {
return nil, err
}
return m, nil
}
func ReadFile(path string) (interface{}, error) {
if _, err := os.Stat(path); err != nil {
return nil, os.ErrNotExist
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return ParseYaml(file)
}
func PathLookup(path string, m interface{}) (string, error) {
keys := strings.Split(path, "/")
if keys[len(keys)-1] == "" {
keys = keys[:len(keys)-1]
}
return lookup(keys[1:], m)
}
func lookup(key []string, lookupTree interface{}) (string, error) {
if _, err := strconv.Atoi(key[0]); err == nil {
return indexLookup(key, lookupTree.([]interface{}))
} else {
return namedLookup(key, lookupTree.(map[string]interface{}))
}
}
func namedLookup(keys []string, lookupTree map[string]interface{}) (string, error) {
key := keys[0]
subMap, ok := lookupTree[key]
if !ok {
return "", os.ErrNotExist
}
if len(keys) == 1 {
return subMap.(string), nil
} else {
return lookup(keys[1:], subMap)
}
}
func indexLookup(keys []string, lookupTree []interface{}) (string, error) {
index, err := strconv.Atoi(keys[0])
if err != nil {
return "", err
}
if index >= len(lookupTree) {
return "", os.ErrNotExist
}
subMap := lookupTree[index]
if len(keys) == 1 {
return subMap.(string), nil
} else {
return lookup(keys[1:], subMap)
}
}