Debian Codegraph @

path/path.go

raw symbols SCIP
1 // Copyright 2019 Red Hat, Inc
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.)
14
15 package path
16
17 import (
18 "fmt"
19 "strings"
20 )
21
22 type ContextPath struct {
23 Path []interface{}
24 Tag string
25 }
26
27 // New returns a new ContextPath with the given tag and path. It's a helper since go's
28 // literal syntax is quite verbose, especially with []interface{}{...}.
29 func New(tag string, path ...interface{}) ContextPath {
30 return ContextPath{
31 Tag: tag,
32 Path: path,
33 }
34 }
35
36 func (c ContextPath) String() string {
37 strs := []string{"$"}
38 for _, e := range c.Path {
39 strs = append(strs, fmt.Sprintf("%v", e))
40 }
41 return strings.Join(strs, ".")
42 }
43
44 // Append returns a new ContextPath with the specified elements appended.
45 // The underlying array is sometimes reused, so if the original path might
46 // be used in future Append operations, the returned ContextPath should not
47 // be stored into a long-lived data structure. (Store a copy instead.)
48 func (c ContextPath) Append(e ...interface{}) ContextPath {
49 return ContextPath{
50 Path: append(c.Path, e...),
51 Tag: c.Tag,
52 }
53 }
54
55 // Copy returns an identical ContextPath that shares no state with the
56 // original. When storing a ContextPath into a data structure, usually a
57 // copy should be stored instead of the original (for example, Report does
58 // this), since Append sometimes modifies the path's underlying array in
59 // place.
60 func (c ContextPath) Copy() ContextPath {
61 // make sure to preserve reflect.DeepEqual() equality
62 var path []interface{}
63 if c.Path != nil {
64 path = append(path, c.Path...)
65 }
66 return ContextPath{
67 Path: path,
68 Tag: c.Tag,
69 }
70 }
71
72 // Head returns the first element in the path, panics if empty.
73 func (c ContextPath) Head() interface{} {
74 return c.Path[0]
75 }
76
77 func (c ContextPath) Tail() ContextPath {
78 if len(c.Path) == 0 {
79 return ContextPath{}
80 }
81 return ContextPath{
82 Path: c.Path[1:],
83 Tag: c.Tag,
84 }
85 }
86
87 func (c ContextPath) Pop() ContextPath {
88 if len(c.Path) == 0 {
89 return ContextPath{}
90 }
91 return ContextPath{
92 Path: c.Path[:c.Len()-1],
93 Tag: c.Tag,
94 }
95 }
96
97 func (c ContextPath) Len() int {
98 return len(c.Path)
99 }