-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotpath.go
93 lines (80 loc) · 1.74 KB
/
dotpath.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
package gofigure
import (
"fmt"
"strconv"
)
type DotPath struct {
Key string
Index int
}
//nolint:gocyclo
func ParseDotPath(path string) ([]*DotPath, error) {
if path == "" {
return nil, nil
}
var paths []*DotPath
curr := ""
isInBracket := false
if path[0] == '.' || path[len(path)-1] == '.' { // cannot start with dot
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
for i := 0; i < len(path); i++ {
if path[i] == '.' {
if isInBracket { // unterminated bracket
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
if curr == "" { // no key specified
if len(paths) > 0 && paths[len(paths)-1].Key == "" {
continue
}
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
paths = append(paths, &DotPath{
Key: curr,
})
curr = ""
continue
}
if path[i] == '[' {
if isInBracket { // unterminated bracket
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
if curr != "" {
paths = append(paths, &DotPath{
Key: curr,
})
curr = ""
}
isInBracket = true
continue
}
if path[i] == ']' {
if !isInBracket { // not in bracket
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
if curr == "" { // no index specified
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
index, err := strconv.Atoi(curr)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
isInBracket = false
paths = append(paths, &DotPath{
Index: index,
})
curr = ""
continue
}
curr += string(path[i])
}
if isInBracket { // unterminated bracket
return nil, fmt.Errorf("%s: %w", path, ErrInvalidPath)
}
if curr != "" {
paths = append(paths, &DotPath{
Key: curr,
})
}
return paths, nil
}