-
Notifications
You must be signed in to change notification settings - Fork 1
/
path.go
83 lines (75 loc) · 1.79 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
package godiff
import (
"fmt"
"strconv"
"strings"
)
const (
//PathKindRoot defines root path kind
PathKindRoot = PathKind(iota)
//PathKinField defines field path kind
PathKinField
//PathKindKey defines key path kind
PathKindKey
//PathKindIndex defines index path kind
PathKindIndex
)
type (
//PathKind defines patch kind
PathKind int
//Path represents an arbitrary data structure path
Path struct {
Kind PathKind `json:",omitempty"`
Path *Path `json:",omitempty"`
Name string `json:",omitempty"`
Index int `json:",omitempty"`
Key interface{} `json:",omitempty"`
}
)
//Field add fields node
func (p *Path) Field(name string) *Path {
return &Path{Name: name, Kind: PathKinField, Path: p}
}
//Entry adds map entry node
func (p *Path) Entry(name string) *Path {
return &Path{Key: name, Kind: PathKindKey, Path: p}
}
//Element adds slice element node
func (p *Path) Element(index int) *Path {
return &Path{Index: index, Kind: PathKindIndex, Path: p}
}
//String stringifies a path
func (p *Path) String() string {
builder := new(strings.Builder)
p.stringify(builder)
return builder.String()
}
func (p *Path) stringify(builder *strings.Builder) {
if p.Path != nil {
p.Path.stringify(builder)
}
switch p.Kind {
case PathKindKey:
builder.WriteByte('[')
switch actual := p.Key.(type) {
case string:
builder.WriteString(actual)
case int:
builder.WriteString(strconv.Itoa(actual))
case int64:
builder.WriteString(strconv.Itoa(int(actual)))
default:
builder.WriteString(fmt.Sprintf("%v", actual))
}
builder.WriteByte(']')
case PathKinField:
if builder.Len() > 0 {
builder.WriteByte('.')
}
builder.WriteString(p.Name)
case PathKindIndex:
builder.WriteByte('[')
builder.WriteString(strconv.Itoa(p.Index))
builder.WriteByte(']')
}
}