-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
89 lines (74 loc) · 1.78 KB
/
util.go
File metadata and controls
89 lines (74 loc) · 1.78 KB
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
package jpatch
import (
"strconv"
"strings"
)
func ValidArrayIndex(in interface{}) bool {
_, ok := in.(int)
if ok {
return true
}
st, ok := in.(string)
if ok {
if st == "-" {
return true
}
if _, err := strconv.Atoi(st); err == nil {
return true
}
}
return false
}
// Shift adjusts the path segement. Useful for handing the patch off to a child object for processing
func (p Patch) Shift() Patch {
nPatch := Patch{Op: p.Op, Value: p.Value}
split := strings.Split(p.Path, "/")[1:]
nPatch.Path = "/" + strings.Join(split[1:], "/")
if p.From != "" {
split = strings.Split(p.From, "/")[1:]
nPatch.From = "/" + strings.Join(split[1:], "/")
}
return nPatch
}
// Segments returns a slice of the path segments
func (p Patch) Segments() []string {
return strings.Split(p.Path, "/")[1:]
}
// ArrayIndex returns the index int if the final segement of a path is an index
func (p Patch) ArrayIndex(which string) (int, bool) {
var split []string
switch which {
case "path":
split = strings.Split(p.Path, "/")[1:]
case "from":
split = strings.Split(p.From, "/")[1:]
default:
return -1, false
}
if i, err := strconv.Atoi(split[len(split)-1]); err == nil {
if i < 0 {
return -1, false
}
return i, true
}
return -1, false
}
func (p *PathSegment) AddValue(pathName, actualName string, supportedOps ...string) {
if p.Values == nil {
p.Values = make(map[string]*PathValue)
}
p.Values[pathName] = &PathValue{actualName, supportedOps}
}
func (p *PathSegment) AddChild(pathName string, child *PathSegment) {
if p.Children == nil {
p.Children = make(map[string]*PathSegment)
}
p.Children[pathName] = child
}
func (p Patch) PathIndexIn(which string, length int) bool {
l, ok := p.ArrayIndex(which)
if !ok || l > length {
return false
}
return ok && l < length
}