-
Notifications
You must be signed in to change notification settings - Fork 62
/
path.go
298 lines (269 loc) · 7.2 KB
/
path.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
// Copyright (c) 2017 Arista Networks, Inc.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
package gnmi
import (
"fmt"
"sort"
"strings"
pb "github.com/openconfig/gnmi/proto/gnmi"
)
// nextTokenIndex returns the end index of the first token.
func nextTokenIndex(path string) int {
var inBrackets bool
var escape bool
for i, c := range path {
switch c {
case '[':
inBrackets = true
escape = false
case ']':
if !escape {
inBrackets = false
}
escape = false
case '\\':
escape = !escape
case '/':
if !inBrackets && !escape {
return i
}
escape = false
default:
escape = false
}
}
return len(path)
}
// SplitPath splits a gnmi path according to the spec. See
// https://github.com/openconfig/reference/blob/master/rpc/gnmi/gnmi-path-conventions.md
// No validation is done. Behavior is undefined if path is an invalid
// gnmi path. TODO: Do validation?
func SplitPath(path string) []string {
var result []string
if len(path) > 0 && path[0] == '/' {
path = path[1:]
}
for len(path) > 0 {
i := nextTokenIndex(path)
result = append(result, path[:i])
path = path[i:]
if len(path) > 0 && path[0] == '/' {
path = path[1:]
}
}
return result
}
// SplitPaths splits multiple gnmi paths
func SplitPaths(paths []string) [][]string {
out := make([][]string, len(paths))
for i, path := range paths {
out[i] = SplitPath(path)
}
return out
}
// StrPath builds a human-readable form of a gnmi path.
// e.g. /a/b/c[e=f]
func StrPath(path *pb.Path) string {
if path == nil {
return "/"
} else if len(path.Elem) != 0 {
return strPathV04(path)
} else if len(path.Element) != 0 {
return strPathV03(path)
}
return "/"
}
// writeKey is used as a helper to contain the logic of writing keys as a string.
func writeKey(b *strings.Builder, key map[string]string) {
// Sort the keys so that they print in a consistent
// order. We don't have the YANG AST information, so the
// best we can do is sort them alphabetically.
size := 0
keys := make([]string, 0, len(key))
for k, v := range key {
keys = append(keys, k)
size += len(k) + len(v) + 3 // [, =, ]
}
sort.Strings(keys)
b.Grow(size)
for _, k := range keys {
b.WriteByte('[')
b.WriteString(escapeKey(k))
b.WriteByte('=')
b.WriteString(escapeValue(key[k]))
b.WriteByte(']')
}
}
// KeyToString is used to get the string representation of the keys.
func KeyToString(key map[string]string) string {
if len(key) == 1 {
for k, v := range key {
return "[" + escapeKey(k) + "=" + escapeValue(v) + "]"
}
}
var b strings.Builder
writeKey(&b, key)
return b.String()
}
func writeElem(b *strings.Builder, elm *pb.PathElem) {
b.WriteString(escapeName(elm.Name))
if len(elm.Key) > 0 {
writeKey(b, elm.Key)
}
}
func escapeKey(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `=`, `\=`)
return s
}
func escapeValue(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `]`, `\]`)
return s
}
func escapeName(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `/`, `\/`)
s = strings.ReplaceAll(s, `[`, `\[`)
return s
}
// ElemToString is used to get the string representation of the Element.
func ElemToString(elm *pb.PathElem) string {
b := &strings.Builder{}
writeElem(b, elm)
return b.String()
}
// strPathV04 handles the v0.4 gnmi and later path.Elem member.
func strPathV04(path *pb.Path) string {
b := &strings.Builder{}
for _, elm := range path.Elem {
b.WriteRune('/')
writeElem(b, elm)
}
return b.String()
}
// strPathV03 handles the v0.3 gnmi and earlier path.Element member.
func strPathV03(path *pb.Path) string {
return "/" + strings.Join(path.Element, "/")
}
// upgradePath modernizes a Path by translating the contents of the Element field to Elem
func upgradePath(path *pb.Path) *pb.Path {
if path != nil && len(path.Elem) == 0 {
var elems []*pb.PathElem
for _, element := range path.Element {
n, keys, _ := parseElement(element)
elems = append(elems, &pb.PathElem{Name: n, Key: keys})
}
path.Elem = elems
path.Element = nil
}
return path
}
// JoinPaths joins multiple gnmi paths into a single path
func JoinPaths(paths ...*pb.Path) *pb.Path {
var elems []*pb.PathElem
for _, path := range paths {
if path != nil {
path = upgradePath(path)
elems = append(elems, path.Elem...)
}
}
return &pb.Path{Elem: elems}
}
// ParseGNMIElements builds up a gnmi path, from user-supplied text
func ParseGNMIElements(elms []string) (*pb.Path, error) {
var parsed []*pb.PathElem
for _, e := range elms {
n, keys, err := parseElement(e)
if err != nil {
return nil, err
}
parsed = append(parsed, &pb.PathElem{Name: n, Key: keys})
}
return &pb.Path{
Element: elms, // Backwards compatibility with pre-v0.4 gnmi
Elem: parsed,
}, nil
}
// parseElement parses a path element, according to the gNMI specification. See
// https://github.com/openconfig/reference/blame/master/rpc/gnmi/gnmi-path-conventions.md
//
// It returns the first string (the current element name), and an optional map of key name
// value pairs.
func parseElement(pathElement string) (string, map[string]string, error) {
// First check if there are any keys, i.e. do we have at least one '[' in the element
name, keyStart := findUnescaped(pathElement, '[')
if keyStart < 0 {
return name, nil, nil
}
// Error if there is no element name or if the "[" is at the beginning of the path element
if len(name) == 0 {
return "", nil, fmt.Errorf("failed to find element name in %q", pathElement)
}
keys, err := ParseKeys(pathElement[keyStart:])
if err != nil {
return "", nil, err
}
return name, keys, nil
}
// ParseKeys parses just the keys portion of the stringified elem and returns the map of stringified
// keys.
func ParseKeys(keyPart string) (map[string]string, error) {
// Look at the keys now.
keys := make(map[string]string)
for keyPart != "" {
k, v, nextKey, err := parseKey(keyPart)
if err != nil {
return nil, err
}
keys[k] = v
keyPart = nextKey
}
return keys, nil
}
// parseKey returns the key name, key value and the remaining string to be parsed,
func parseKey(s string) (string, string, string, error) {
if s[0] != '[' {
return "", "", "", fmt.Errorf("failed to find opening '[' in %q", s)
}
k, iEq := findUnescaped(s[1:], '=')
if iEq < 0 {
return "", "", "", fmt.Errorf("failed to find '=' in %q", s)
}
rhs := s[1+iEq+1:]
v, iClosBr := findUnescaped(rhs, ']')
if iClosBr < 0 {
return "", "", "", fmt.Errorf("failed to find ']' in %q", s)
}
next := rhs[iClosBr+1:]
return k, v, next, nil
}
// findUnescaped will return the index of the first unescaped match of 'find', and the unescaped
// string leading up to it.
func findUnescaped(s string, find byte) (string, int) {
// Take a fast track if there are no escape sequences
if strings.IndexByte(s, '\\') == -1 {
i := strings.IndexByte(s, find)
if i < 0 {
return s, -1
}
return s[:i], i
}
// Find the first match, taking care of escaped chars.
var b strings.Builder
var i int
len := len(s)
for i = 0; i < len; {
ch := s[i]
if ch == find {
return b.String(), i
} else if ch == '\\' && i < len-1 {
i++
ch = s[i]
}
b.WriteByte(ch)
i++
}
return b.String(), -1
}