blob: 2efc8eec76d991311ba26f63094c8093ac8731a3 [file] [log] [blame]
Zack Williamse940c7a2019-08-21 14:25:39 -07001/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package field
18
19import (
20 "bytes"
21 "fmt"
22 "strconv"
23)
24
25// Path represents the path from some root to a particular field.
26type Path struct {
27 name string // the name of this field or "" if this is an index
28 index string // if name == "", this is a subscript (index or map key) of the previous element
29 parent *Path // nil if this is the root element
30}
31
32// NewPath creates a root Path object.
33func NewPath(name string, moreNames ...string) *Path {
34 r := &Path{name: name, parent: nil}
35 for _, anotherName := range moreNames {
36 r = &Path{name: anotherName, parent: r}
37 }
38 return r
39}
40
41// Root returns the root element of this Path.
42func (p *Path) Root() *Path {
43 for ; p.parent != nil; p = p.parent {
44 // Do nothing.
45 }
46 return p
47}
48
49// Child creates a new Path that is a child of the method receiver.
50func (p *Path) Child(name string, moreNames ...string) *Path {
51 r := NewPath(name, moreNames...)
52 r.Root().parent = p
53 return r
54}
55
56// Index indicates that the previous Path is to be subscripted by an int.
57// This sets the same underlying value as Key.
58func (p *Path) Index(index int) *Path {
59 return &Path{index: strconv.Itoa(index), parent: p}
60}
61
62// Key indicates that the previous Path is to be subscripted by a string.
63// This sets the same underlying value as Index.
64func (p *Path) Key(key string) *Path {
65 return &Path{index: key, parent: p}
66}
67
68// String produces a string representation of the Path.
69func (p *Path) String() string {
70 // make a slice to iterate
71 elems := []*Path{}
72 for ; p != nil; p = p.parent {
73 elems = append(elems, p)
74 }
75
76 // iterate, but it has to be backwards
77 buf := bytes.NewBuffer(nil)
78 for i := range elems {
79 p := elems[len(elems)-1-i]
80 if p.parent != nil && len(p.name) > 0 {
81 // This is either the root or it is a subscript.
82 buf.WriteString(".")
83 }
84 if len(p.name) > 0 {
85 buf.WriteString(p.name)
86 } else {
87 fmt.Fprintf(buf, "[%s]", p.index)
88 }
89 }
90 return buf.String()
91}