build source

This commit is contained in:
build 2026-04-16 04:16:36 +00:00
commit ee1fec43ed
4171 changed files with 1351288 additions and 0 deletions

View file

@ -0,0 +1,321 @@
/*
Copyright 2025 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package field
import (
"fmt"
"reflect"
"regexp"
"strings"
)
// NormalizationRule holds a pre-compiled regular expression and its replacement string
// for normalizing field paths.
type NormalizationRule struct {
Regexp *regexp.Regexp
Replacement string
}
// ErrorMatcher is a helper for comparing Error objects.
type ErrorMatcher struct {
// TODO(thockin): consider whether type is ever NOT required, maybe just
// assume it.
matchType bool
// TODO(thockin): consider whether field could be assumed - if the
// "want" error has a nil field, don't match on field.
matchField bool
// TODO(thockin): consider whether value could be assumed - if the
// "want" error has a nil value, don't match on value.
matchValue bool
matchOrigin bool
matchDetail func(want, got string) bool
requireOriginWhenInvalid bool
// normalizationRules holds the pre-compiled regex patterns for path normalization.
normalizationRules []NormalizationRule
}
// Matches returns true if the two Error objects match according to the
// configured criteria. When field normalization is configured, only the
// "got" error's field path is normalized (to bring older API versions up
// to the internal/latest format), while "want" is assumed to already be
// in the canonical internal API format.
func (m ErrorMatcher) Matches(want, got *Error) bool {
if m.matchType && want.Type != got.Type {
return false
}
if m.matchField {
// Try direct match first (common case)
if want.Field != got.Field {
// Fields don't match, try normalization if rules are configured.
// Only normalize "got" - it may be from an older API version that
// needs to be brought up to the internal/latest format that "want"
// is already in.
if want.Field != m.normalizePath(got.Field) {
return false
}
}
}
if m.matchValue && !reflect.DeepEqual(want.BadValue, got.BadValue) {
return false
}
if m.matchOrigin {
if want.Origin != got.Origin {
return false
}
if m.requireOriginWhenInvalid && want.Type == ErrorTypeInvalid {
if want.Origin == "" || got.Origin == "" {
return false
}
}
}
if m.matchDetail != nil && !m.matchDetail(want.Detail, got.Detail) {
return false
}
return true
}
// normalizePath applies configured path normalization rules.
func (m ErrorMatcher) normalizePath(path string) string {
for _, rule := range m.normalizationRules {
normalized := rule.Regexp.ReplaceAllString(path, rule.Replacement)
if normalized != path {
// Only apply the first matching rule.
return normalized
}
}
return path
}
// Render returns a string representation of the specified Error object,
// according to the criteria configured in the ErrorMatcher.
func (m ErrorMatcher) Render(e *Error) string {
buf := strings.Builder{}
comma := func() {
if buf.Len() > 0 {
buf.WriteString(", ")
}
}
if m.matchType {
comma()
buf.WriteString(fmt.Sprintf("Type=%q", e.Type))
}
if m.matchField {
comma()
if normalized := m.normalizePath(e.Field); normalized != e.Field {
buf.WriteString(fmt.Sprintf("Field=%q (aka %q)", normalized, e.Field))
} else {
buf.WriteString(fmt.Sprintf("Field=%q", e.Field))
}
}
if m.matchValue {
comma()
if s, ok := e.BadValue.(string); ok {
buf.WriteString(fmt.Sprintf("Value=%q", s))
} else {
rv := reflect.ValueOf(e.BadValue)
if rv.Kind() == reflect.Pointer && !rv.IsNil() {
rv = rv.Elem()
}
if rv.IsValid() && rv.CanInterface() {
buf.WriteString(fmt.Sprintf("Value=%v", rv.Interface()))
} else {
buf.WriteString(fmt.Sprintf("Value=%v", e.BadValue))
}
}
}
if m.matchOrigin || m.requireOriginWhenInvalid && e.Type == ErrorTypeInvalid {
comma()
buf.WriteString(fmt.Sprintf("Origin=%q", e.Origin))
}
if m.matchDetail != nil {
comma()
buf.WriteString(fmt.Sprintf("Detail=%q", e.Detail))
}
return "{" + buf.String() + "}"
}
// Exactly returns a derived ErrorMatcher which matches all fields exactly.
func (m ErrorMatcher) Exactly() ErrorMatcher {
return m.ByType().ByField().ByValue().ByOrigin().ByDetailExact()
}
// ByType returns a derived ErrorMatcher which also matches by type.
func (m ErrorMatcher) ByType() ErrorMatcher {
m.matchType = true
return m
}
// ByField returns a derived ErrorMatcher which also matches by field path.
// If you need to mutate the field path (e.g. to normalize across versions),
// see ByFieldNormalized.
func (m ErrorMatcher) ByField() ErrorMatcher {
m.matchField = true
return m
}
// ByFieldNormalized returns a derived ErrorMatcher which also matches by field path
// after applying normalization rules to the actual (got) error's field path.
// This allows matching field paths from older API versions against the canonical
// internal API format.
//
// The normalization rules are applied ONLY to the "got" error's field path, bringing
// older API version field paths up to the latest/internal format. The "want" error
// is assumed to always be in the internal API format (latest).
//
// The rules slice holds pre-compiled regular expressions and their replacement strings.
//
// Example:
//
// rules := []NormalizationRule{
// {
// Regexp: regexp.MustCompile(`spec\.devices\.requests\[(\d+)\]\.allocationMode`),
// Replacement: "spec.devices.requests[$1].exactly.allocationMode",
// },
// }
// matcher := ErrorMatcher{}.ByFieldNormalized(rules)
func (m ErrorMatcher) ByFieldNormalized(rules []NormalizationRule) ErrorMatcher {
m.matchField = true
m.normalizationRules = rules
return m
}
// ByValue returns a derived ErrorMatcher which also matches by the errant
// value.
func (m ErrorMatcher) ByValue() ErrorMatcher {
m.matchValue = true
return m
}
// ByOrigin returns a derived ErrorMatcher which also matches by the origin.
// When this is used and an origin is set in the error, the matcher will
// consider all expected errors with the same origin to be a match. The only
// expception to this is when it finds two errors which are exactly identical,
// which is too suspicious to ignore. This multi-matching allows tests to
// express a single expectation ("I set the X field to an invalid value, and I
// expect an error from origin Y") without having to know exactly how many
// errors might be returned, or in what order, or with what wording.
func (m ErrorMatcher) ByOrigin() ErrorMatcher {
m.matchOrigin = true
return m
}
// RequireOriginWhenInvalid returns a derived ErrorMatcher which also requires
// the Origin field to be set when the Type is Invalid and the matcher is
// matching by Origin.
func (m ErrorMatcher) RequireOriginWhenInvalid() ErrorMatcher {
m.requireOriginWhenInvalid = true
return m
}
// ByDetailExact returns a derived ErrorMatcher which also matches errors by
// the exact detail string.
func (m ErrorMatcher) ByDetailExact() ErrorMatcher {
m.matchDetail = func(want, got string) bool {
return got == want
}
return m
}
// ByDetailSubstring returns a derived ErrorMatcher which also matches errors
// by a substring of the detail string.
func (m ErrorMatcher) ByDetailSubstring() ErrorMatcher {
m.matchDetail = func(want, got string) bool {
return strings.Contains(got, want)
}
return m
}
// ByDetailRegexp returns a derived ErrorMatcher which also matches errors by a
// regular expression of the detail string, where the "want" string is assumed
// to be a valid regular expression.
func (m ErrorMatcher) ByDetailRegexp() ErrorMatcher {
m.matchDetail = func(want, got string) bool {
return regexp.MustCompile(want).MatchString(got)
}
return m
}
// TestIntf lets users pass a testing.T while not coupling this package to Go's
// testing package.
type TestIntf interface {
Helper()
Errorf(format string, args ...any)
}
// Test compares two ErrorLists by the criteria configured in this matcher, and
// fails the test if they don't match. The "want" errors are expected to be in
// the internal API format (latest), while "got" errors may be from any API version
// and will be normalized if field normalization rules are configured.
//
// If matching by origin is enabled and the error has a non-empty origin, a given
// "want" error can match multiple "got" errors, and they will all be consumed.
// The only exception to this is if the matcher got multiple identical (in every way,
// even those not being matched on) errors, which is likely to indicate a bug.
func (m ErrorMatcher) Test(tb TestIntf, want, got ErrorList) {
tb.Helper()
exactly := m.Exactly() // makes a copy
// If we ever find an EXACT duplicate error, it's almost certainly a bug
// worth reporting. If we ever find a use-case where this is not a bug, we
// can revisit this assumption.
seen := map[string]bool{}
for _, g := range got {
key := exactly.Render(g)
if seen[key] {
tb.Errorf("exact duplicate error:\n%s", key)
}
seen[key] = true
}
remaining := got
for _, w := range want {
tmp := make(ErrorList, 0, len(remaining))
matched := false
for i, g := range remaining {
if m.Matches(w, g) {
matched = true
if m.matchOrigin && w.Origin != "" {
// When origin is included in the match, we allow multiple
// matches against the same wanted error, so that tests
// can be insulated from the exact number, order, and
// wording of cases that might return more than one error.
continue
} else {
// Single-match, save the rest of the "got" errors and move
// on to the next "want" error.
tmp = append(tmp, remaining[i+1:]...)
break
}
} else {
tmp = append(tmp, g)
}
}
if !matched {
tb.Errorf("expected an error matching:\n%s", m.Render(w))
}
remaining = tmp
}
if len(remaining) > 0 {
for _, e := range remaining {
tb.Errorf("unmatched error:\n%s", exactly.Render(e))
}
}
}

View file

@ -0,0 +1,409 @@
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package field
import (
"encoding/json"
"fmt"
"strconv"
"strings"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
)
// Error is an implementation of the 'error' interface, which represents a
// field-level validation error.
type Error struct {
Type ErrorType
Field string
BadValue interface{}
Detail string
// Origin uniquely identifies where this error was generated from. It is used in testing to
// compare expected errors against actual errors without relying on exact detail string matching.
// This allows tests to verify the correct validation logic triggered the error
// regardless of how the error message might be formatted or localized.
//
// The value should be either:
// - A simple camelCase identifier (e.g., "maximum", "maxItems")
// - A structured format using "format=<dash-style-identifier>" for validation errors related to specific formats
// (e.g., "format=dns-label", "format=qualified-name")
//
// If the Origin corresponds to an existing declarative validation tag or JSON Schema keyword,
// use that same name for consistency.
//
// Origin should be set in the most deeply nested validation function that
// can still identify the unique source of the error.
Origin string
// CoveredByDeclarative is true when this error is covered by declarative
// validation. This field is to identify errors from imperative validation
// that should also be caught by declarative validation.
CoveredByDeclarative bool
}
var _ error = &Error{}
// Error implements the error interface.
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.ErrorBody())
}
type OmitValueType struct{}
var omitValue = OmitValueType{}
// ErrorBody returns the error message without the field name. This is useful
// for building nice-looking higher-level error reporting.
func (e *Error) ErrorBody() string {
var s string
switch e.Type {
case ErrorTypeRequired, ErrorTypeForbidden, ErrorTypeTooLong, ErrorTypeInternal:
s = e.Type.String()
case ErrorTypeInvalid, ErrorTypeTypeInvalid, ErrorTypeNotSupported,
ErrorTypeNotFound, ErrorTypeDuplicate, ErrorTypeTooMany:
if e.BadValue == omitValue {
s = e.Type.String()
break
}
switch t := e.BadValue.(type) {
case int64, int32, float64, float32, bool:
// use simple printer for simple types
s = fmt.Sprintf("%s: %v", e.Type, t)
case string:
s = fmt.Sprintf("%s: %q", e.Type, t)
default:
// use more complex techniques to render more complex types
valstr := ""
jb, err := json.Marshal(e.BadValue)
if err == nil {
// best case
valstr = string(jb)
} else if stringer, ok := e.BadValue.(fmt.Stringer); ok {
// anything that defines String() is better than raw struct
valstr = stringer.String()
} else {
// worst case - fallback to raw struct
// TODO: internal types have panic guards against json.Marshalling to prevent
// accidental use of internal types in external serialized form. For now, use
// %#v, although it would be better to show a more expressive output in the future
valstr = fmt.Sprintf("%#v", e.BadValue)
}
s = fmt.Sprintf("%s: %s", e.Type, valstr)
}
default:
internal := InternalError(nil, fmt.Errorf("unhandled error code: %s: please report this", e.Type))
s = internal.ErrorBody()
}
if len(e.Detail) != 0 {
s += fmt.Sprintf(": %s", e.Detail)
}
return s
}
// WithOrigin adds origin information to the FieldError
func (e *Error) WithOrigin(o string) *Error {
e.Origin = o
return e
}
// MarkCoveredByDeclarative marks the error as covered by declarative validation.
func (e *Error) MarkCoveredByDeclarative() *Error {
e.CoveredByDeclarative = true
return e
}
// ErrorType is a machine readable value providing more detail about why
// a field is invalid. These values are expected to match 1-1 with
// CauseType in api/types.go.
type ErrorType string
// TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it.
const (
// ErrorTypeNotFound is used to report failure to find a requested value
// (e.g. looking up an ID). See NotFound().
ErrorTypeNotFound ErrorType = "FieldValueNotFound"
// ErrorTypeRequired is used to report required values that are not
// provided (e.g. empty strings, null values, or empty arrays). See
// Required().
ErrorTypeRequired ErrorType = "FieldValueRequired"
// ErrorTypeDuplicate is used to report collisions of values that must be
// unique (e.g. unique IDs). See Duplicate().
ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
// ErrorTypeInvalid is used to report malformed values (e.g. failed regex
// match, too long, out of bounds). See Invalid().
ErrorTypeInvalid ErrorType = "FieldValueInvalid"
// ErrorTypeNotSupported is used to report unknown values for enumerated
// fields (e.g. a list of valid values). See NotSupported().
ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
// ErrorTypeForbidden is used to report valid (as per formatting rules)
// values which would be accepted under some conditions, but which are not
// permitted by the current conditions (such as security policy). See
// Forbidden().
ErrorTypeForbidden ErrorType = "FieldValueForbidden"
// ErrorTypeTooLong is used to report that the given value is too long.
// This is similar to ErrorTypeInvalid, but the error will not include the
// too-long value. See TooLong().
ErrorTypeTooLong ErrorType = "FieldValueTooLong"
// ErrorTypeTooMany is used to report "too many". This is used to
// report that a given list has too many items. This is similar to FieldValueTooLong,
// but the error indicates quantity instead of length.
ErrorTypeTooMany ErrorType = "FieldValueTooMany"
// ErrorTypeInternal is used to report other errors that are not related
// to user input. See InternalError().
ErrorTypeInternal ErrorType = "InternalError"
// ErrorTypeTypeInvalid is for the value did not match the schema type for that field
ErrorTypeTypeInvalid ErrorType = "FieldValueTypeInvalid"
)
// String converts a ErrorType into its corresponding canonical error message.
func (t ErrorType) String() string {
switch t {
case ErrorTypeNotFound:
return "Not found"
case ErrorTypeRequired:
return "Required value"
case ErrorTypeDuplicate:
return "Duplicate value"
case ErrorTypeInvalid:
return "Invalid value"
case ErrorTypeNotSupported:
return "Unsupported value"
case ErrorTypeForbidden:
return "Forbidden"
case ErrorTypeTooLong:
return "Too long"
case ErrorTypeTooMany:
return "Too many"
case ErrorTypeInternal:
return "Internal error"
case ErrorTypeTypeInvalid:
return "Invalid value"
default:
return fmt.Sprintf("<unknown error %q>", string(t))
}
}
// TypeInvalid returns a *Error indicating "type is invalid"
func TypeInvalid(field *Path, value interface{}, detail string) *Error {
return &Error{ErrorTypeTypeInvalid, field.String(), value, detail, "", false}
}
// NotFound returns a *Error indicating "value not found". This is
// used to report failure to find a requested value (e.g. looking up an ID).
func NotFound(field *Path, value interface{}) *Error {
return &Error{ErrorTypeNotFound, field.String(), value, "", "", false}
}
// Required returns a *Error indicating "value required". This is used
// to report required values that are not provided (e.g. empty strings, null
// values, or empty arrays).
func Required(field *Path, detail string) *Error {
return &Error{ErrorTypeRequired, field.String(), "", detail, "", false}
}
// Duplicate returns a *Error indicating "duplicate value". This is
// used to report collisions of values that must be unique (e.g. names or IDs).
func Duplicate(field *Path, value interface{}) *Error {
return &Error{ErrorTypeDuplicate, field.String(), value, "", "", false}
}
// Invalid returns a *Error indicating "invalid value". This is used
// to report malformed values (e.g. failed regex match, too long, out of bounds).
func Invalid(field *Path, value interface{}, detail string) *Error {
return &Error{ErrorTypeInvalid, field.String(), value, detail, "", false}
}
// NotSupported returns a *Error indicating "unsupported value".
// This is used to report unknown values for enumerated fields (e.g. a list of
// valid values).
func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *Error {
detail := ""
if len(validValues) > 0 {
quotedValues := make([]string, len(validValues))
for i, v := range validValues {
quotedValues[i] = strconv.Quote(fmt.Sprint(v))
}
detail = "supported values: " + strings.Join(quotedValues, ", ")
}
return &Error{ErrorTypeNotSupported, field.String(), value, detail, "", false}
}
// Forbidden returns a *Error indicating "forbidden". This is used to
// report valid (as per formatting rules) values which would be accepted under
// some conditions, but which are not permitted by current conditions (e.g.
// security policy).
func Forbidden(field *Path, detail string) *Error {
return &Error{ErrorTypeForbidden, field.String(), "", detail, "", false}
}
// TooLong returns a *Error indicating "too long". This is used to report that
// the given value is too long. This is similar to Invalid, but the returned
// error will not include the too-long value. If maxLength is negative, it will
// be included in the message. The value argument is not used.
func TooLong(field *Path, _ interface{}, maxLength int) *Error {
var msg string
if maxLength >= 0 {
bs := "bytes"
if maxLength == 1 {
bs = "byte"
}
msg = fmt.Sprintf("may not be more than %d %s", maxLength, bs)
} else {
msg = "value is too long"
}
return &Error{ErrorTypeTooLong, field.String(), "<value omitted>", msg, "", false}
}
// TooLongMaxLength returns a *Error indicating "too long".
// Deprecated: Use TooLong instead.
func TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error {
return TooLong(field, "", maxLength)
}
// TooMany returns a *Error indicating "too many". This is used to
// report that a given list has too many items. This is similar to TooLong,
// but the returned error indicates quantity instead of length.
func TooMany(field *Path, actualQuantity, maxQuantity int) *Error {
var msg string
if maxQuantity >= 0 {
is := "items"
if maxQuantity == 1 {
is = "item"
}
msg = fmt.Sprintf("must have at most %d %s", maxQuantity, is)
} else {
msg = "has too many items"
}
var actual interface{}
if actualQuantity >= 0 {
actual = actualQuantity
} else {
actual = omitValue
}
return &Error{ErrorTypeTooMany, field.String(), actual, msg, "", false}
}
// InternalError returns a *Error indicating "internal error". This is used
// to signal that an error was found that was not directly related to user
// input. The err argument must be non-nil.
func InternalError(field *Path, err error) *Error {
return &Error{ErrorTypeInternal, field.String(), nil, err.Error(), "", false}
}
// ErrorList holds a set of Errors. It is plausible that we might one day have
// non-field errors in this same umbrella package, but for now we don't, so
// we can keep it simple and leave ErrorList here.
type ErrorList []*Error
// NewErrorTypeMatcher returns an errors.Matcher that returns true
// if the provided error is a Error and has the provided ErrorType.
func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher {
return func(err error) bool {
if e, ok := err.(*Error); ok {
return e.Type == t
}
return false
}
}
// WithOrigin sets the origin for all errors in the list and returns the updated list.
func (list ErrorList) WithOrigin(origin string) ErrorList {
for _, err := range list {
err.Origin = origin
}
return list
}
// MarkCoveredByDeclarative marks all errors in the list as covered by declarative validation.
func (list ErrorList) MarkCoveredByDeclarative() ErrorList {
for _, err := range list {
err.CoveredByDeclarative = true
}
return list
}
// PrefixDetail adds a prefix to the Detail for all errors in the list and returns the updated list.
func (list ErrorList) PrefixDetail(prefix string) ErrorList {
for _, err := range list {
err.Detail = prefix + err.Detail
}
return list
}
// ToAggregate converts the ErrorList into an errors.Aggregate.
func (list ErrorList) ToAggregate() utilerrors.Aggregate {
if len(list) == 0 {
return nil
}
errs := make([]error, 0, len(list))
errorMsgs := sets.NewString()
for _, err := range list {
msg := fmt.Sprintf("%v", err)
if errorMsgs.Has(msg) {
continue
}
errorMsgs.Insert(msg)
errs = append(errs, err)
}
return utilerrors.NewAggregate(errs)
}
func fromAggregate(agg utilerrors.Aggregate) ErrorList {
errs := agg.Errors()
list := make(ErrorList, len(errs))
for i := range errs {
list[i] = errs[i].(*Error)
}
return list
}
// Filter removes items from the ErrorList that match the provided fns.
func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList {
err := utilerrors.FilterOut(list.ToAggregate(), fns...)
if err == nil {
return nil
}
// FilterOut takes an Aggregate and returns an Aggregate
return fromAggregate(err.(utilerrors.Aggregate))
}
// ExtractCoveredByDeclarative returns a new ErrorList containing only the errors that should be covered by declarative validation.
func (list ErrorList) ExtractCoveredByDeclarative() ErrorList {
newList := ErrorList{}
for _, err := range list {
if err.CoveredByDeclarative {
newList = append(newList, err)
}
}
return newList
}
// RemoveCoveredByDeclarative returns a new ErrorList containing only the errors that should not be covered by declarative validation.
func (list ErrorList) RemoveCoveredByDeclarative() ErrorList {
newList := ErrorList{}
for _, err := range list {
if !err.CoveredByDeclarative {
newList = append(newList, err)
}
}
return newList
}

View file

@ -0,0 +1,117 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package field
import (
"bytes"
"fmt"
"strconv"
)
type pathOptions struct {
path *Path
}
// PathOption modifies a pathOptions
type PathOption func(o *pathOptions)
// WithPath generates a PathOption
func WithPath(p *Path) PathOption {
return func(o *pathOptions) {
o.path = p
}
}
// ToPath produces *Path from a set of PathOption
func ToPath(opts ...PathOption) *Path {
c := &pathOptions{}
for _, opt := range opts {
opt(c)
}
return c.path
}
// Path represents the path from some root to a particular field.
type Path struct {
name string // the name of this field or "" if this is an index
index string // if name == "", this is a subscript (index or map key) of the previous element
parent *Path // nil if this is the root element
}
// NewPath creates a root Path object.
func NewPath(name string, moreNames ...string) *Path {
r := &Path{name: name, parent: nil}
for _, anotherName := range moreNames {
r = &Path{name: anotherName, parent: r}
}
return r
}
// Root returns the root element of this Path.
func (p *Path) Root() *Path {
for ; p.parent != nil; p = p.parent {
// Do nothing.
}
return p
}
// Child creates a new Path that is a child of the method receiver.
func (p *Path) Child(name string, moreNames ...string) *Path {
r := NewPath(name, moreNames...)
r.Root().parent = p
return r
}
// Index indicates that the previous Path is to be subscripted by an int.
// This sets the same underlying value as Key.
func (p *Path) Index(index int) *Path {
return &Path{index: strconv.Itoa(index), parent: p}
}
// Key indicates that the previous Path is to be subscripted by a string.
// This sets the same underlying value as Index.
func (p *Path) Key(key string) *Path {
return &Path{index: key, parent: p}
}
// String produces a string representation of the Path.
func (p *Path) String() string {
if p == nil {
return "<nil>"
}
// make a slice to iterate
elems := []*Path{}
for ; p != nil; p = p.parent {
elems = append(elems, p)
}
// iterate, but it has to be backwards
buf := bytes.NewBuffer(nil)
for i := range elems {
p := elems[len(elems)-1-i]
if p.parent != nil && len(p.name) > 0 {
// This is either the root or it is a subscript.
buf.WriteString(".")
}
if len(p.name) > 0 {
buf.WriteString(p.name)
} else {
fmt.Fprintf(buf, "[%s]", p.index)
}
}
return buf.String()
}