Update Structured Merge Diff to V3

This commit is contained in:
jennybuckley
2020-01-21 15:03:56 -08:00
committed by Jennifer Buckley
parent c9b4cf3d25
commit b33fbc84d9
105 changed files with 2848 additions and 1849 deletions

View File

@@ -1,226 +0,0 @@
/*
Copyright 2018 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 typed
import (
"sync"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
)
var vPool = sync.Pool{
New: func() interface{} { return &validatingObjectWalker{} },
}
func (tv TypedValue) walker() *validatingObjectWalker {
v := vPool.Get().(*validatingObjectWalker)
v.value = tv.value
v.schema = tv.schema
v.typeRef = tv.typeRef
return v
}
func (v *validatingObjectWalker) finished() {
v.value = value.Value{}
v.schema = nil
v.typeRef = schema.TypeRef{}
v.leafFieldCallback = nil
v.nodeFieldCallback = nil
v.inLeaf = false
vPool.Put(v)
}
type validatingObjectWalker struct {
errorFormatter
value value.Value
schema *schema.Schema
typeRef schema.TypeRef
// If set, this is called on "leaf fields":
// * scalars: int/string/float/bool
// * atomic maps and lists
// * untyped fields
leafFieldCallback func(fieldpath.Path)
// If set, this is called on "node fields":
// * list items
// * map items
nodeFieldCallback func(fieldpath.Path)
// internal housekeeping--don't set when constructing.
inLeaf bool // Set to true if we're in a "big leaf"--atomic map/list
// Allocate only as many walkers as needed for the depth by storing them here.
spareWalkers *[]*validatingObjectWalker
}
func (v *validatingObjectWalker) prepareDescent(pe fieldpath.PathElement, tr schema.TypeRef) *validatingObjectWalker {
if v.spareWalkers == nil {
// first descent.
v.spareWalkers = &[]*validatingObjectWalker{}
}
var v2 *validatingObjectWalker
if n := len(*v.spareWalkers); n > 0 {
v2, *v.spareWalkers = (*v.spareWalkers)[n-1], (*v.spareWalkers)[:n-1]
} else {
v2 = &validatingObjectWalker{}
}
*v2 = *v
v2.typeRef = tr
v2.errorFormatter.descend(pe)
return v2
}
func (v *validatingObjectWalker) finishDescent(v2 *validatingObjectWalker) {
// if the descent caused a realloc, ensure that we reuse the buffer
// for the next sibling.
v.errorFormatter = v2.errorFormatter.parent()
*v.spareWalkers = append(*v.spareWalkers, v2)
}
func (v *validatingObjectWalker) validate() ValidationErrors {
return resolveSchema(v.schema, v.typeRef, &v.value, v)
}
// doLeaf should be called on leaves before descending into children, if there
// will be a descent. It modifies v.inLeaf.
func (v *validatingObjectWalker) doLeaf() {
if v.inLeaf {
// We're in a "big leaf", an atomic map or list. Ignore
// subsequent leaves.
return
}
v.inLeaf = true
if v.leafFieldCallback != nil {
// At the moment, this is only used to build fieldsets; we can
// add more than the path in here if needed.
v.leafFieldCallback(v.path)
}
}
// doNode should be called on nodes after descending into children
func (v *validatingObjectWalker) doNode() {
if v.inLeaf {
// We're in a "big leaf", an atomic map or list. Ignore
// subsequent leaves.
return
}
if v.nodeFieldCallback != nil {
// At the moment, this is only used to build fieldsets; we can
// add more than the path in here if needed.
v.nodeFieldCallback(v.path)
}
}
func (v *validatingObjectWalker) doScalar(t *schema.Scalar) ValidationErrors {
if errs := v.validateScalar(t, &v.value, ""); len(errs) > 0 {
return errs
}
// All scalars are leaf fields.
v.doLeaf()
return nil
}
func (v *validatingObjectWalker) visitListItems(t *schema.List, list *value.List) (errs ValidationErrors) {
observedKeys := fieldpath.MakePathElementSet(len(list.Items))
for i, child := range list.Items {
pe, err := listItemToPathElement(t, i, child)
if err != nil {
errs = append(errs, v.errorf("element %v: %v", i, err.Error())...)
// If we can't construct the path element, we can't
// even report errors deeper in the schema, so bail on
// this element.
continue
}
if observedKeys.Has(pe) {
errs = append(errs, v.errorf("duplicate entries for key %v", pe.String())...)
}
observedKeys.Insert(pe)
v2 := v.prepareDescent(pe, t.ElementType)
v2.value = child
errs = append(errs, v2.validate()...)
v2.doNode()
v.finishDescent(v2)
}
return errs
}
func (v *validatingObjectWalker) doList(t *schema.List) (errs ValidationErrors) {
list, err := listValue(v.value)
if err != nil {
return v.error(err)
}
if t.ElementRelationship == schema.Atomic {
v.doLeaf()
}
if list == nil {
return nil
}
errs = v.visitListItems(t, list)
return errs
}
func (v *validatingObjectWalker) visitMapItems(t *schema.Map, m *value.Map) (errs ValidationErrors) {
for i := range m.Items {
item := &m.Items[i]
pe := fieldpath.PathElement{FieldName: &item.Name}
if sf, ok := t.FindField(item.Name); ok {
v2 := v.prepareDescent(pe, sf.Type)
v2.value = item.Value
errs = append(errs, v2.validate()...)
v.finishDescent(v2)
} else {
v2 := v.prepareDescent(pe, t.ElementType)
v2.value = item.Value
errs = append(errs, v2.validate()...)
v2.doNode()
v.finishDescent(v2)
}
}
return errs
}
func (v *validatingObjectWalker) doMap(t *schema.Map) (errs ValidationErrors) {
m, err := mapValue(v.value)
if err != nil {
return v.error(err)
}
if t.ElementRelationship == schema.Atomic {
v.doLeaf()
}
if m == nil {
return nil
}
errs = v.visitMapItems(t, m)
return errs
}

View File

@@ -13,12 +13,12 @@ go_library(
"serialize-pe.go",
"set.go",
],
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/fieldpath",
importpath = "sigs.k8s.io/structured-merge-diff/fieldpath",
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/v3/fieldpath",
importpath = "sigs.k8s.io/structured-merge-diff/v3/fieldpath",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/json-iterator/go:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/value:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/value:go_default_library",
],
)

View File

@@ -21,7 +21,7 @@ import (
"sort"
"strings"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// PathElement describes how to select a child field given a containing object.
@@ -34,7 +34,7 @@ type PathElement struct {
// Key selects the list element which has fields matching those given.
// The containing object must be an associative list with map typed
// elements.
// elements. They are sorted alphabetically.
Key *value.FieldList
// Value selects the list element with the given value. The containing
@@ -49,50 +49,90 @@ type PathElement struct {
// Less provides an order for path elements.
func (e PathElement) Less(rhs PathElement) bool {
return e.Compare(rhs) < 0
}
// Compare provides an order for path elements.
func (e PathElement) Compare(rhs PathElement) int {
if e.FieldName != nil {
if rhs.FieldName == nil {
return true
return -1
}
return *e.FieldName < *rhs.FieldName
return strings.Compare(*e.FieldName, *rhs.FieldName)
} else if rhs.FieldName != nil {
return false
return 1
}
if e.Key != nil {
if rhs.Key == nil {
return true
return -1
}
return e.Key.Less(*rhs.Key)
return e.Key.Compare(*rhs.Key)
} else if rhs.Key != nil {
return false
return 1
}
if e.Value != nil {
if rhs.Value == nil {
return true
return -1
}
return e.Value.Less(*rhs.Value)
return value.Compare(*e.Value, *rhs.Value)
} else if rhs.Value != nil {
return false
return 1
}
if e.Index != nil {
if rhs.Index == nil {
return true
return -1
}
return *e.Index < *rhs.Index
if *e.Index < *rhs.Index {
return -1
} else if *e.Index == *rhs.Index {
return 0
}
return 1
} else if rhs.Index != nil {
// Yes, I know the next statement is the same. But this way
// the obvious way of extending the function wil be bug-free.
return false
return 1
}
return false
return 0
}
// Equals returns true if both path elements are equal.
func (e PathElement) Equals(rhs PathElement) bool {
return !e.Less(rhs) && !rhs.Less(e)
if e.FieldName != nil {
if rhs.FieldName == nil {
return false
}
return *e.FieldName == *rhs.FieldName
} else if rhs.FieldName != nil {
return false
}
if e.Key != nil {
if rhs.Key == nil {
return false
}
return e.Key.Equals(*rhs.Key)
} else if rhs.Key != nil {
return false
}
if e.Value != nil {
if rhs.Value == nil {
return false
}
return value.Equals(*e.Value, *rhs.Value)
} else if rhs.Value != nil {
return false
}
if e.Index != nil {
if rhs.Index == nil {
return false
}
return *e.Index == *rhs.Index
} else if rhs.Index != nil {
return false
}
return true
}
// String presents the path element as a human-readable string.
@@ -103,12 +143,12 @@ func (e PathElement) String() string {
case e.Key != nil:
strs := make([]string, len(*e.Key))
for i, k := range *e.Key {
strs[i] = fmt.Sprintf("%v=%v", k.Name, k.Value)
strs[i] = fmt.Sprintf("%v=%v", k.Name, value.ToString(k.Value))
}
// Keys are supposed to be sorted.
return "[" + strings.Join(strs, ",") + "]"
case e.Value != nil:
return fmt.Sprintf("[=%v]", e.Value)
return fmt.Sprintf("[=%v]", value.ToString(*e.Value))
case e.Index != nil:
return fmt.Sprintf("[%v]", *e.Index)
default:
@@ -127,10 +167,7 @@ func KeyByFields(nameValues ...interface{}) *value.FieldList {
}
out := value.FieldList{}
for i := 0; i < len(nameValues)-1; i += 2 {
out = append(out, value.Field{
Name: nameValues[i].(string),
Value: nameValues[i+1].(value.Value),
})
out = append(out, value.Field{Name: nameValues[i].(string), Value: value.NewValueInterface(nameValues[i+1])})
}
out.Sort()
return &out

View File

@@ -17,7 +17,7 @@ limitations under the License.
package fieldpath
import (
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// SetFromValue creates a set containing every leaf field mentioned in v.
@@ -43,37 +43,37 @@ type objectWalker struct {
func (w *objectWalker) walk() {
switch {
case w.value.Null:
case w.value.FloatValue != nil:
case w.value.IntValue != nil:
case w.value.StringValue != nil:
case w.value.BooleanValue != nil:
case w.value.IsNull():
case w.value.IsFloat():
case w.value.IsInt():
case w.value.IsString():
case w.value.IsBool():
// All leaf fields handled the same way (after the switch
// statement).
// Descend
case w.value.ListValue != nil:
case w.value.IsList():
// If the list were atomic, we'd break here, but we don't have
// a schema, so we can't tell.
for i, child := range w.value.ListValue.Items {
list := w.value.AsList()
for i := 0; i < list.Length(); i++ {
w2 := *w
w2.path = append(w.path, GuessBestListPathElement(i, child))
w2.value = child
w2.path = append(w.path, GuessBestListPathElement(i, list.At(i)))
w2.value = list.At(i)
w2.walk()
}
return
case w.value.MapValue != nil:
case w.value.IsMap():
// If the map/struct were atomic, we'd break here, but we don't
// have a schema, so we can't tell.
for i := range w.value.MapValue.Items {
child := w.value.MapValue.Items[i]
w.value.AsMap().Iterate(func(k string, val value.Value) bool {
w2 := *w
w2.path = append(w.path, PathElement{FieldName: &child.Name})
w2.value = child.Value
w2.path = append(w.path, PathElement{FieldName: &k})
w2.value = val
w2.walk()
}
return true
})
return
}
@@ -97,7 +97,7 @@ var AssociativeListCandidateFieldNames = []string{
// whether item has any of the fields listed in
// AssociativeListCandidateFieldNames which have scalar values.
func GuessBestListPathElement(index int, item value.Value) PathElement {
if item.MapValue == nil {
if !item.IsMap() {
// Non map items could be parts of sets or regular "atomic"
// lists. We won't try to guess whether something should be a
// set or not.
@@ -106,15 +106,15 @@ func GuessBestListPathElement(index int, item value.Value) PathElement {
var keys value.FieldList
for _, name := range AssociativeListCandidateFieldNames {
f, ok := item.MapValue.Get(name)
f, ok := item.AsMap().Get(name)
if !ok {
continue
}
// only accept primitive/scalar types as keys.
if f.Value.Null || f.Value.MapValue != nil || f.Value.ListValue != nil {
if f.IsNull() || f.IsMap() || f.IsList() {
continue
}
keys = append(keys, *f)
keys = append(keys, value.Field{Name: name, Value: f})
}
if len(keys) > 0 {
keys.Sort()

View File

@@ -13,6 +13,11 @@ limitations under the License.
package fieldpath
import (
"fmt"
"strings"
)
// APIVersion describes the version of an object or of a fieldset.
type APIVersion string
@@ -95,3 +100,14 @@ func (lhs ManagedFields) Difference(rhs ManagedFields) ManagedFields {
return diff
}
func (lhs ManagedFields) String() string {
s := strings.Builder{}
for k, v := range lhs {
fmt.Fprintf(&s, "%s:\n", k)
fmt.Fprintf(&s, "- Applied: %v\n", v.Applied())
fmt.Fprintf(&s, "- APIVersion: %v\n", v.APIVersion())
fmt.Fprintf(&s, "- Set: %v\n", v.Set())
}
return s.String()
}

View File

@@ -20,7 +20,7 @@ import (
"fmt"
"strings"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// Path describes how to select a potentially deeply-nested child field given a
@@ -37,32 +37,35 @@ func (fp Path) String() string {
// Equals returns true if the two paths are equivalent.
func (fp Path) Equals(fp2 Path) bool {
return !fp.Less(fp2) && !fp2.Less(fp)
if len(fp) != len(fp2) {
return false
}
for i := range fp {
if !fp[i].Equals(fp2[i]) {
return false
}
}
return true
}
// Less provides a lexical order for Paths.
func (fp Path) Less(rhs Path) bool {
func (fp Path) Compare(rhs Path) int {
i := 0
for {
if i >= len(fp) && i >= len(rhs) {
// Paths are the same length and all items are equal.
return false
return 0
}
if i >= len(fp) {
// LHS is shorter.
return true
return -1
}
if i >= len(rhs) {
// RHS is shorter.
return false
return 1
}
if fp[i].Less(rhs[i]) {
// LHS is less; return
return true
}
if rhs[i].Less(fp[i]) {
// RHS is less; return
return false
if c := fp[i].Compare(rhs[i]); c != 0 {
return c
}
// The items are equal; continue.
i++

View File

@@ -19,7 +19,7 @@ package fieldpath
import (
"sort"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// PathElementValueMap is a map from PathElement to value.Value.
@@ -76,10 +76,10 @@ func (s *PathElementValueMap) Get(pe PathElement) (value.Value, bool) {
return !s.members[i].PathElement.Less(pe)
})
if loc == len(s.members) {
return value.Value{}, false
return nil, false
}
if s.members[loc].PathElement.Equals(pe) {
return s.members[loc].Value, true
}
return value.Value{}, false
return nil, false
}

View File

@@ -24,7 +24,7 @@ import (
"strings"
jsoniter "github.com/json-iterator/go"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
var ErrUnknownPathElementType = errors.New("unknown path element type")
@@ -84,6 +84,7 @@ func DeserializePathElement(s string) (PathElement, error) {
iter := readPool.BorrowIterator(b)
defer readPool.ReturnIterator(iter)
fields := value.FieldList{}
iter.ReadObjectCB(func(iter *jsoniter.Iterator, key string) bool {
v, err := value.ReadJSONIter(iter)
if err != nil {
@@ -134,19 +135,20 @@ func serializePathElementToWriter(w io.Writer, pe PathElement) error {
return err
}
stream.WriteObjectStart()
for i, field := range *pe.Key {
if i > 0 {
stream.WriteMore()
}
stream.WriteObjectField(field.Name)
field.Value.WriteJSONStream(stream)
value.WriteJSONStream(field.Value, stream)
}
stream.WriteObjectEnd()
case pe.Value != nil:
if _, err := stream.Write(peValueSepBytes); err != nil {
return err
}
pe.Value.WriteJSONStream(stream)
value.WriteJSONStream(*pe.Value, stream)
case pe.Index != nil:
if _, err := stream.Write(peIndexSepBytes); err != nil {
return err

View File

@@ -87,6 +87,12 @@ func (s *Set) emitContents_v1(includeSelf bool, stream *jsoniter.Stream, r *reus
stream.WriteMore()
}
if includeSelf && !(len(s.Members.members) == 0 && len(s.Children.members) == 0) {
preWrite()
stream.WriteObjectField(".")
stream.WriteEmptyObject()
}
for mi < len(s.Members.members) && ci < len(s.Children.members) {
mpe := s.Members.members[mi]
cpe := s.Children.members[ci].pathElement
@@ -155,11 +161,6 @@ func (s *Set) emitContents_v1(includeSelf bool, stream *jsoniter.Stream, r *reus
ci++
}
if includeSelf && !first {
preWrite()
stream.WriteObjectField(".")
stream.WriteEmptyObject()
}
return manageMemory(stream)
}

View File

@@ -6,12 +6,12 @@ go_library(
"conflict.go",
"update.go",
],
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/merge",
importpath = "sigs.k8s.io/structured-merge-diff/merge",
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/v3/merge",
importpath = "sigs.k8s.io/structured-merge-diff/v3/merge",
visibility = ["//visibility:public"],
deps = [
"//vendor/sigs.k8s.io/structured-merge-diff/fieldpath:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/typed:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/fieldpath:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/typed:go_default_library",
],
)

View File

@@ -21,7 +21,7 @@ import (
"sort"
"strings"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
)
// Conflict is a conflict on a specific field with the current manager of

View File

@@ -16,8 +16,8 @@ package merge
import (
"fmt"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/typed"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/typed"
)
// Converter is an interface to the conversion logic. The converter
@@ -208,6 +208,7 @@ func (s *Updater) prune(merged *typed.TypedValue, managers fieldpath.ManagedFiel
}
return nil, fmt.Errorf("failed to convert merged object to last applied version: %v", err)
}
pruned := convertedMerged.RemoveItems(lastSet.Set())
pruned, err = s.addBackOwnedItems(convertedMerged, pruned, managers, applyingManager)
if err != nil {

View File

@@ -8,8 +8,8 @@ go_library(
"equals.go",
"schemaschema.go",
],
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/schema",
importpath = "sigs.k8s.io/structured-merge-diff/schema",
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/v3/schema",
importpath = "sigs.k8s.io/structured-merge-diff/v3/schema",
visibility = ["//visibility:public"],
)

View File

@@ -17,12 +17,16 @@ limitations under the License.
package schema
// Equals returns true iff the two Schemas are equal.
func (a Schema) Equals(b Schema) bool {
func (a *Schema) Equals(b *Schema) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if len(a.Types) != len(b.Types) {
return false
}
for i := range a.Types {
if !a.Types[i].Equals(b.Types[i]) {
if !a.Types[i].Equals(&b.Types[i]) {
return false
}
}
@@ -33,7 +37,10 @@ func (a Schema) Equals(b Schema) bool {
//
// Note that two typerefs that have an equivalent type but where one is
// inlined and the other is named, are not considered equal.
func (a TypeRef) Equals(b TypeRef) bool {
func (a *TypeRef) Equals(b *TypeRef) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if (a.NamedType == nil) != (b.NamedType == nil) {
return false
}
@@ -43,19 +50,25 @@ func (a TypeRef) Equals(b TypeRef) bool {
}
//return true
}
return a.Inlined.Equals(b.Inlined)
return a.Inlined.Equals(&b.Inlined)
}
// Equals returns true iff the two TypeDefs are equal.
func (a TypeDef) Equals(b TypeDef) bool {
func (a *TypeDef) Equals(b *TypeDef) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if a.Name != b.Name {
return false
}
return a.Atom.Equals(b.Atom)
return a.Atom.Equals(&b.Atom)
}
// Equals returns true iff the two Atoms are equal.
func (a Atom) Equals(b Atom) bool {
func (a *Atom) Equals(b *Atom) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if (a.Scalar == nil) != (b.Scalar == nil) {
return false
}
@@ -69,16 +82,19 @@ func (a Atom) Equals(b Atom) bool {
case a.Scalar != nil:
return *a.Scalar == *b.Scalar
case a.List != nil:
return a.List.Equals(*b.List)
return a.List.Equals(b.List)
case a.Map != nil:
return a.Map.Equals(*b.Map)
return a.Map.Equals(b.Map)
}
return true
}
// Equals returns true iff the two Maps are equal.
func (a Map) Equals(b Map) bool {
if !a.ElementType.Equals(b.ElementType) {
func (a *Map) Equals(b *Map) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if !a.ElementType.Equals(&b.ElementType) {
return false
}
if a.ElementRelationship != b.ElementRelationship {
@@ -88,7 +104,7 @@ func (a Map) Equals(b Map) bool {
return false
}
for i := range a.Fields {
if !a.Fields[i].Equals(b.Fields[i]) {
if !a.Fields[i].Equals(&b.Fields[i]) {
return false
}
}
@@ -96,7 +112,7 @@ func (a Map) Equals(b Map) bool {
return false
}
for i := range a.Unions {
if !a.Unions[i].Equals(b.Unions[i]) {
if !a.Unions[i].Equals(&b.Unions[i]) {
return false
}
}
@@ -104,7 +120,10 @@ func (a Map) Equals(b Map) bool {
}
// Equals returns true iff the two Unions are equal.
func (a Union) Equals(b Union) bool {
func (a *Union) Equals(b *Union) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if (a.Discriminator == nil) != (b.Discriminator == nil) {
return false
}
@@ -120,7 +139,7 @@ func (a Union) Equals(b Union) bool {
return false
}
for i := range a.Fields {
if !a.Fields[i].Equals(b.Fields[i]) {
if !a.Fields[i].Equals(&b.Fields[i]) {
return false
}
}
@@ -128,7 +147,10 @@ func (a Union) Equals(b Union) bool {
}
// Equals returns true iff the two UnionFields are equal.
func (a UnionField) Equals(b UnionField) bool {
func (a *UnionField) Equals(b *UnionField) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if a.FieldName != b.FieldName {
return false
}
@@ -139,16 +161,22 @@ func (a UnionField) Equals(b UnionField) bool {
}
// Equals returns true iff the two StructFields are equal.
func (a StructField) Equals(b StructField) bool {
func (a *StructField) Equals(b *StructField) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if a.Name != b.Name {
return false
}
return a.Type.Equals(b.Type)
return a.Type.Equals(&b.Type)
}
// Equals returns true iff the two Lists are equal.
func (a List) Equals(b List) bool {
if !a.ElementType.Equals(b.ElementType) {
func (a *List) Equals(b *List) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if !a.ElementType.Equals(&b.ElementType) {
return false
}
if a.ElementRelationship != b.ElementRelationship {

View File

@@ -8,18 +8,19 @@ go_library(
"merge.go",
"parser.go",
"remove.go",
"tofieldset.go",
"typed.go",
"union.go",
"validate.go",
],
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/typed",
importpath = "sigs.k8s.io/structured-merge-diff/typed",
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/v3/typed",
importpath = "sigs.k8s.io/structured-merge-diff/v3/typed",
visibility = ["//visibility:public"],
deps = [
"//vendor/gopkg.in/yaml.v2:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/fieldpath:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/schema:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/value:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/fieldpath:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/schema:go_default_library",
"//vendor/sigs.k8s.io/structured-merge-diff/v3/value:go_default_library",
],
)

View File

@@ -21,14 +21,14 @@ import (
"fmt"
"strings"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// ValidationError reports an error about a particular field
type ValidationError struct {
Path fieldpath.Path
Path string
ErrorMessage string
}
@@ -56,75 +56,83 @@ func (errs ValidationErrors) Error() string {
return strings.Join(messages, "\n")
}
// errorFormatter makes it easy to keep a list of validation errors. They
// should all be packed into a single error object before leaving the package
// boundary, since it's weird to have functions not return a plain error type.
type errorFormatter struct {
path fieldpath.Path
}
func (ef *errorFormatter) descend(pe fieldpath.PathElement) {
ef.path = append(ef.path, pe)
}
// parent returns the parent, for the purpose of buffer reuse. It's an error to
// call this if there is no parent.
func (ef *errorFormatter) parent() errorFormatter {
return errorFormatter{
path: ef.path[:len(ef.path)-1],
// Set the given path to all the validation errors.
func (errs ValidationErrors) WithPath(p string) ValidationErrors {
for i := range errs {
errs[i].Path = p
}
return errs
}
func (ef errorFormatter) errorf(format string, args ...interface{}) ValidationErrors {
// WithPrefix prefixes all errors path with the given pathelement. This
// is useful when unwinding the stack on errors.
func (errs ValidationErrors) WithPrefix(prefix string) ValidationErrors {
for i := range errs {
errs[i].Path = prefix + errs[i].Path
}
return errs
}
// WithLazyPrefix prefixes all errors path with the given pathelement.
// This is useful when unwinding the stack on errors. Prefix is
// computed lazily only if there is an error.
func (errs ValidationErrors) WithLazyPrefix(fn func() string) ValidationErrors {
if len(errs) == 0 {
return errs
}
prefix := ""
if fn != nil {
prefix = fn()
}
for i := range errs {
errs[i].Path = prefix + errs[i].Path
}
return errs
}
func errorf(format string, args ...interface{}) ValidationErrors {
return ValidationErrors{{
Path: append(fieldpath.Path{}, ef.path...),
ErrorMessage: fmt.Sprintf(format, args...),
}}
}
func (ef errorFormatter) error(err error) ValidationErrors {
return ValidationErrors{{
Path: append(fieldpath.Path{}, ef.path...),
ErrorMessage: err.Error(),
}}
}
func (ef errorFormatter) prefixError(prefix string, err error) ValidationErrors {
return ValidationErrors{{
Path: append(fieldpath.Path{}, ef.path...),
ErrorMessage: prefix + err.Error(),
}}
}
type atomHandler interface {
doScalar(*schema.Scalar) ValidationErrors
doList(*schema.List) ValidationErrors
doMap(*schema.Map) ValidationErrors
errorf(msg string, args ...interface{}) ValidationErrors
}
func resolveSchema(s *schema.Schema, tr schema.TypeRef, v *value.Value, ah atomHandler) ValidationErrors {
func resolveSchema(s *schema.Schema, tr schema.TypeRef, v value.Value, ah atomHandler) ValidationErrors {
a, ok := s.Resolve(tr)
if !ok {
return ah.errorf("schema error: no type found matching: %v", *tr.NamedType)
return errorf("schema error: no type found matching: %v", *tr.NamedType)
}
a = deduceAtom(a, v)
return handleAtom(a, tr, ah)
}
func deduceAtom(a schema.Atom, v *value.Value) schema.Atom {
// deduceAtom determines which of the possible types in atom 'atom' applies to value 'val'.
// If val is of a type allowed by atom, return a copy of atom with all other types set to nil.
// if val is nil, or is not of a type allowed by atom, just return the original atom,
// and validation will fail at a later stage. (with a more useful error)
func deduceAtom(atom schema.Atom, val value.Value) schema.Atom {
switch {
case v == nil:
case v.FloatValue != nil, v.IntValue != nil, v.StringValue != nil, v.BooleanValue != nil:
return schema.Atom{Scalar: a.Scalar}
case v.ListValue != nil:
return schema.Atom{List: a.List}
case v.MapValue != nil:
return schema.Atom{Map: a.Map}
case val == nil:
case val.IsFloat(), val.IsInt(), val.IsString(), val.IsBool():
if atom.Scalar != nil {
return schema.Atom{Scalar: atom.Scalar}
}
case val.IsList():
if atom.List != nil {
return schema.Atom{List: atom.List}
}
case val.IsMap():
if atom.Map != nil {
return schema.Atom{Map: atom.Map}
}
}
return a
return atom
}
func handleAtom(a schema.Atom, tr schema.TypeRef, ah atomHandler) ValidationErrors {
@@ -142,80 +150,53 @@ func handleAtom(a schema.Atom, tr schema.TypeRef, ah atomHandler) ValidationErro
name = "named type: " + *tr.NamedType
}
return ah.errorf("schema error: invalid atom: %v", name)
}
func (ef errorFormatter) validateScalar(t *schema.Scalar, v *value.Value, prefix string) (errs ValidationErrors) {
if v == nil {
return nil
}
if v.Null {
return nil
}
switch *t {
case schema.Numeric:
if v.FloatValue == nil && v.IntValue == nil {
// TODO: should the schema separate int and float?
return ef.errorf("%vexpected numeric (int or float), got %v", prefix, v)
}
case schema.String:
if v.StringValue == nil {
return ef.errorf("%vexpected string, got %v", prefix, v)
}
case schema.Boolean:
if v.BooleanValue == nil {
return ef.errorf("%vexpected boolean, got %v", prefix, v)
}
}
return nil
return errorf("schema error: invalid atom: %v", name)
}
// Returns the list, or an error. Reminder: nil is a valid list and might be returned.
func listValue(val value.Value) (*value.List, error) {
switch {
case val.Null:
func listValue(val value.Value) (value.List, error) {
if val.IsNull() {
// Null is a valid list.
return nil, nil
case val.ListValue != nil:
return val.ListValue, nil
default:
}
if !val.IsList() {
return nil, fmt.Errorf("expected list, got %v", val)
}
return val.AsList(), nil
}
// Returns the map, or an error. Reminder: nil is a valid map and might be returned.
func mapValue(val value.Value) (*value.Map, error) {
switch {
case val.Null:
func mapValue(val value.Value) (value.Map, error) {
if val == nil {
return nil, fmt.Errorf("expected map, got nil")
}
if val.IsNull() {
// Null is a valid map.
return nil, nil
case val.MapValue != nil:
return val.MapValue, nil
default:
}
if !val.IsMap() {
return nil, fmt.Errorf("expected map, got %v", val)
}
return val.AsMap(), nil
}
func keyedAssociativeListItemToPathElement(list *schema.List, index int, child value.Value) (fieldpath.PathElement, error) {
pe := fieldpath.PathElement{}
if child.Null {
if child.IsNull() {
// For now, the keys are required which means that null entries
// are illegal.
return pe, errors.New("associative list with keys may not have a null element")
}
if child.MapValue == nil {
if !child.IsMap() {
return pe, errors.New("associative list with keys may not have non-map elements")
}
keyMap := value.FieldList{}
for _, fieldName := range list.Keys {
var fieldValue value.Value
field, ok := child.MapValue.Get(fieldName)
if ok {
fieldValue = field.Value
if val, ok := child.AsMap().Get(fieldName); ok {
keyMap = append(keyMap, value.Field{Name: fieldName, Value: val})
} else {
// Treat keys as required.
return pe, fmt.Errorf("associative list with keys has an element that omits key field %q", fieldName)
}
keyMap = append(keyMap, value.Field{Name: fieldName, Value: fieldValue})
}
keyMap.Sort()
pe.Key = &keyMap
@@ -225,15 +206,15 @@ func keyedAssociativeListItemToPathElement(list *schema.List, index int, child v
func setItemToPathElement(list *schema.List, index int, child value.Value) (fieldpath.PathElement, error) {
pe := fieldpath.PathElement{}
switch {
case child.MapValue != nil:
case child.IsMap():
// TODO: atomic maps should be acceptable.
return pe, errors.New("associative list without keys has an element that's a map type")
case child.ListValue != nil:
case child.IsList():
// Should we support a set of lists? For the moment
// let's say we don't.
// TODO: atomic lists should be acceptable.
return pe, errors.New("not supported: associative list with lists as elements")
case child.Null:
case child.IsNull():
return pe, errors.New("associative list without keys has an element that's an explicit null")
default:
// We are a set type.

View File

@@ -17,18 +17,22 @@ limitations under the License.
package typed
import (
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"math"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
type mergingWalker struct {
errorFormatter
lhs *value.Value
rhs *value.Value
lhs value.Value
rhs value.Value
schema *schema.Schema
typeRef schema.TypeRef
// Current path that we are merging
path fieldpath.Path
// How to merge. Called after schema validation for all leaf fields.
rule mergeRule
@@ -37,7 +41,7 @@ type mergingWalker struct {
postItemHook mergeRule
// output of the merge operation (nil if none)
out *value.Value
out *interface{}
// internal housekeeping--don't set when constructing.
inLeaf bool // Set to true if we're in a "big leaf"--atomic map/list
@@ -54,29 +58,29 @@ type mergeRule func(w *mergingWalker)
var (
ruleKeepRHS = mergeRule(func(w *mergingWalker) {
if w.rhs != nil {
v := *w.rhs
v := w.rhs.Unstructured()
w.out = &v
} else if w.lhs != nil {
v := *w.lhs
v := w.lhs.Unstructured()
w.out = &v
}
})
)
// merge sets w.out.
func (w *mergingWalker) merge() (errs ValidationErrors) {
func (w *mergingWalker) merge(prefixFn func() string) (errs ValidationErrors) {
if w.lhs == nil && w.rhs == nil {
// check this condidition here instead of everywhere below.
return w.errorf("at least one of lhs and rhs must be provided")
return errorf("at least one of lhs and rhs must be provided")
}
a, ok := w.schema.Resolve(w.typeRef)
if !ok {
return w.errorf("schema error: no type found matching: %v", *w.typeRef.NamedType)
return errorf("schema error: no type found matching: %v", *w.typeRef.NamedType)
}
alhs := deduceAtom(a, w.lhs)
arhs := deduceAtom(a, w.rhs)
if alhs.Equals(arhs) {
if alhs.Equals(&arhs) {
errs = append(errs, handleAtom(arhs, w.typeRef, w)...)
} else {
w2 := *w
@@ -87,7 +91,7 @@ func (w *mergingWalker) merge() (errs ValidationErrors) {
if !w.inLeaf && w.postItemHook != nil {
w.postItemHook(w)
}
return errs
return errs.WithLazyPrefix(prefixFn)
}
// doLeaf should be called on leaves before descending into children, if there
@@ -105,8 +109,8 @@ func (w *mergingWalker) doLeaf() {
}
func (w *mergingWalker) doScalar(t *schema.Scalar) (errs ValidationErrors) {
errs = append(errs, w.validateScalar(t, w.lhs, "lhs: ")...)
errs = append(errs, w.validateScalar(t, w.rhs, "rhs: ")...)
errs = append(errs, validateScalar(t, w.lhs, "lhs: ")...)
errs = append(errs, validateScalar(t, w.rhs, "rhs: ")...)
if len(errs) > 0 {
return errs
}
@@ -130,7 +134,7 @@ func (w *mergingWalker) prepareDescent(pe fieldpath.PathElement, tr schema.TypeR
}
*w2 = *w
w2.typeRef = tr
w2.errorFormatter.descend(pe)
w2.path = append(w2.path, pe)
w2.lhs = nil
w2.rhs = nil
w2.out = nil
@@ -140,48 +144,56 @@ func (w *mergingWalker) prepareDescent(pe fieldpath.PathElement, tr schema.TypeR
func (w *mergingWalker) finishDescent(w2 *mergingWalker) {
// if the descent caused a realloc, ensure that we reuse the buffer
// for the next sibling.
w.errorFormatter = w2.errorFormatter.parent()
w.path = w2.path[:len(w2.path)-1]
*w.spareWalkers = append(*w.spareWalkers, w2)
}
func (w *mergingWalker) derefMap(prefix string, v *value.Value, dest **value.Map) (errs ValidationErrors) {
func (w *mergingWalker) derefMap(prefix string, v value.Value, dest *value.Map) (errs ValidationErrors) {
// taking dest as input so that it can be called as a one-liner with
// append.
if v == nil {
return nil
}
m, err := mapValue(*v)
m, err := mapValue(v)
if err != nil {
return w.prefixError(prefix, err)
return errorf("%v: %v", prefix, err)
}
*dest = m
return nil
}
func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs *value.List) (errs ValidationErrors) {
out := &value.List{}
func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs value.List) (errs ValidationErrors) {
rLen := 0
if rhs != nil {
rLen = rhs.Length()
}
lLen := 0
if lhs != nil {
lLen = lhs.Length()
}
out := make([]interface{}, 0, int(math.Max(float64(rLen), float64(lLen))))
// TODO: ordering is totally wrong.
// TODO: might as well make the map order work the same way.
// This is a cheap hack to at least make the output order stable.
rhsOrder := []fieldpath.PathElement{}
rhsOrder := make([]fieldpath.PathElement, 0, rLen)
// First, collect all RHS children.
var observedRHS fieldpath.PathElementValueMap
observedRHS := fieldpath.MakePathElementValueMap(rLen)
if rhs != nil {
observedRHS = fieldpath.MakePathElementValueMap(len(rhs.Items))
for i, child := range rhs.Items {
for i := 0; i < rhs.Length(); i++ {
child := rhs.At(i)
pe, err := listItemToPathElement(t, i, child)
if err != nil {
errs = append(errs, w.errorf("rhs: element %v: %v", i, err.Error())...)
errs = append(errs, errorf("rhs: element %v: %v", i, err.Error())...)
// If we can't construct the path element, we can't
// even report errors deeper in the schema, so bail on
// this element.
continue
}
if _, ok := observedRHS.Get(pe); ok {
errs = append(errs, w.errorf("rhs: duplicate entries for key %v", pe.String())...)
errs = append(errs, errorf("rhs: duplicate entries for key %v", pe.String())...)
}
observedRHS.Insert(pe, child)
rhsOrder = append(rhsOrder, pe)
@@ -189,32 +201,31 @@ func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs *value.List) (er
}
// Then merge with LHS children.
var observedLHS fieldpath.PathElementSet
observedLHS := fieldpath.MakePathElementSet(lLen)
if lhs != nil {
observedLHS = fieldpath.MakePathElementSet(len(lhs.Items))
for i, child := range lhs.Items {
for i := 0; i < lhs.Length(); i++ {
child := lhs.At(i)
pe, err := listItemToPathElement(t, i, child)
if err != nil {
errs = append(errs, w.errorf("lhs: element %v: %v", i, err.Error())...)
errs = append(errs, errorf("lhs: element %v: %v", i, err.Error())...)
// If we can't construct the path element, we can't
// even report errors deeper in the schema, so bail on
// this element.
continue
}
if observedLHS.Has(pe) {
errs = append(errs, w.errorf("lhs: duplicate entries for key %v", pe.String())...)
errs = append(errs, errorf("lhs: duplicate entries for key %v", pe.String())...)
continue
}
observedLHS.Insert(pe)
w2 := w.prepareDescent(pe, t.ElementType)
w2.lhs = &child
w2.lhs = value.Value(child)
if rchild, ok := observedRHS.Get(pe); ok {
w2.rhs = &rchild
w2.rhs = rchild
}
if newErrs := w2.merge(); len(newErrs) > 0 {
errs = append(errs, newErrs...)
} else if w2.out != nil {
out.Items = append(out.Items, *w2.out)
errs = append(errs, w2.merge(pe.String)...)
if w2.out != nil {
out = append(out, *w2.out)
}
w.finishDescent(w2)
}
@@ -226,45 +237,45 @@ func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs *value.List) (er
}
value, _ := observedRHS.Get(pe)
w2 := w.prepareDescent(pe, t.ElementType)
w2.rhs = &value
if newErrs := w2.merge(); len(newErrs) > 0 {
errs = append(errs, newErrs...)
} else if w2.out != nil {
out.Items = append(out.Items, *w2.out)
w2.rhs = value
errs = append(errs, w2.merge(pe.String)...)
if w2.out != nil {
out = append(out, *w2.out)
}
w.finishDescent(w2)
}
if len(out.Items) > 0 {
w.out = &value.Value{ListValue: out}
if len(out) > 0 {
i := interface{}(out)
w.out = &i
}
return errs
}
func (w *mergingWalker) derefList(prefix string, v *value.Value, dest **value.List) (errs ValidationErrors) {
func (w *mergingWalker) derefList(prefix string, v value.Value, dest *value.List) (errs ValidationErrors) {
// taking dest as input so that it can be called as a one-liner with
// append.
if v == nil {
return nil
}
l, err := listValue(*v)
l, err := listValue(v)
if err != nil {
return w.prefixError(prefix, err)
return errorf("%v: %v", prefix, err)
}
*dest = l
return nil
}
func (w *mergingWalker) doList(t *schema.List) (errs ValidationErrors) {
var lhs, rhs *value.List
var lhs, rhs value.List
w.derefList("lhs: ", w.lhs, &lhs)
w.derefList("rhs: ", w.rhs, &rhs)
// If both lhs and rhs are empty/null, treat it as a
// leaf: this helps preserve the empty/null
// distinction.
emptyPromoteToLeaf := (lhs == nil || len(lhs.Items) == 0) &&
(rhs == nil || len(rhs.Items) == 0)
emptyPromoteToLeaf := (lhs == nil || lhs.Length() == 0) && (rhs == nil || rhs.Length() == 0)
if t.ElementRelationship == schema.Atomic || emptyPromoteToLeaf {
w.doLeaf()
@@ -280,72 +291,68 @@ func (w *mergingWalker) doList(t *schema.List) (errs ValidationErrors) {
return errs
}
func (w *mergingWalker) visitMapItems(t *schema.Map, lhs, rhs *value.Map) (errs ValidationErrors) {
out := &value.Map{}
func (w *mergingWalker) visitMapItem(t *schema.Map, out map[string]interface{}, key string, lhs, rhs value.Value) (errs ValidationErrors) {
fieldType := t.ElementType
if sf, ok := t.FindField(key); ok {
fieldType = sf.Type
}
pe := fieldpath.PathElement{FieldName: &key}
w2 := w.prepareDescent(pe, fieldType)
w2.lhs = lhs
w2.rhs = rhs
errs = append(errs, w2.merge(pe.String)...)
if w2.out != nil {
out[key] = *w2.out
}
w.finishDescent(w2)
return errs
}
func (w *mergingWalker) visitMapItems(t *schema.Map, lhs, rhs value.Map) (errs ValidationErrors) {
out := map[string]interface{}{}
if lhs != nil {
for i := range lhs.Items {
litem := &lhs.Items[i]
fieldType := t.ElementType
if sf, ok := t.FindField(litem.Name); ok {
fieldType = sf.Type
}
w2 := w.prepareDescent(fieldpath.PathElement{FieldName: &litem.Name}, fieldType)
w2.lhs = &litem.Value
lhs.Iterate(func(key string, val value.Value) bool {
var rval value.Value
if rhs != nil {
if ritem, ok := rhs.Get(litem.Name); ok {
w2.rhs = &ritem.Value
if item, ok := rhs.Get(key); ok {
rval = item
defer rval.Recycle()
}
}
if newErrs := w2.merge(); len(newErrs) > 0 {
errs = append(errs, newErrs...)
} else if w2.out != nil {
out.Items = append(out.Items, value.Field{litem.Name, *w2.out})
}
w.finishDescent(w2)
}
errs = append(errs, w.visitMapItem(t, out, key, val, rval)...)
return true
})
}
if rhs != nil {
for j := range rhs.Items {
ritem := &rhs.Items[j]
rhs.Iterate(func(key string, val value.Value) bool {
if lhs != nil {
if _, ok := lhs.Get(ritem.Name); ok {
continue
if lhs.Has(key) {
return true
}
}
fieldType := t.ElementType
if sf, ok := t.FindField(ritem.Name); ok {
fieldType = sf.Type
}
w2 := w.prepareDescent(fieldpath.PathElement{FieldName: &ritem.Name}, fieldType)
w2.rhs = &ritem.Value
if newErrs := w2.merge(); len(newErrs) > 0 {
errs = append(errs, newErrs...)
} else if w2.out != nil {
out.Items = append(out.Items, value.Field{ritem.Name, *w2.out})
}
w.finishDescent(w2)
}
errs = append(errs, w.visitMapItem(t, out, key, nil, val)...)
return true
})
}
if len(out) > 0 {
i := interface{}(out)
w.out = &i
}
if len(out.Items) > 0 {
w.out = &value.Value{MapValue: out}
}
return errs
}
func (w *mergingWalker) doMap(t *schema.Map) (errs ValidationErrors) {
var lhs, rhs *value.Map
var lhs, rhs value.Map
w.derefMap("lhs: ", w.lhs, &lhs)
w.derefMap("rhs: ", w.rhs, &rhs)
// If both lhs and rhs are empty/null, treat it as a
// leaf: this helps preserve the empty/null
// distinction.
emptyPromoteToLeaf := (lhs == nil || len(lhs.Items) == 0) &&
(rhs == nil || len(rhs.Items) == 0)
emptyPromoteToLeaf := (lhs == nil || lhs.Length() == 0) && (rhs == nil || rhs.Length() == 0)
if t.ElementRelationship == schema.Atomic || emptyPromoteToLeaf {
w.doLeaf()

View File

@@ -20,8 +20,8 @@ import (
"fmt"
yaml "gopkg.in/yaml.v2"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// YAMLObject is an object encoded in YAML.
@@ -94,19 +94,33 @@ func (p ParseableType) IsValid() bool {
// FromYAML parses a yaml string into an object with the current schema
// and the type "typename" or an error if validation fails.
func (p ParseableType) FromYAML(object YAMLObject) (*TypedValue, error) {
v, err := value.FromYAML([]byte(object))
var v interface{}
err := yaml.Unmarshal([]byte(object), &v)
if err != nil {
return nil, err
}
return AsTyped(v, p.Schema, p.TypeRef)
return AsTyped(value.NewValueInterface(v), p.Schema, p.TypeRef)
}
// FromUnstructured converts a go interface to a TypedValue. It will return an
// FromUnstructured converts a go "interface{}" type, typically an
// unstructured object in Kubernetes world, to a TypedValue. It returns an
// error if the resulting object fails schema validation.
// The provided interface{} must be one of: map[string]interface{},
// map[interface{}]interface{}, []interface{}, int types, float types,
// string or boolean. Nested interface{} must also be one of these types.
func (p ParseableType) FromUnstructured(in interface{}) (*TypedValue, error) {
v, err := value.FromUnstructured(in)
return AsTyped(value.NewValueInterface(in), p.Schema, p.TypeRef)
}
// FromStructured converts a go "interface{}" type, typically an structured object in
// Kubernetes, to a TypedValue. It will return an error if the resulting object fails
// schema validation. The provided "interface{}" value must be a pointer so that the
// value can be modified via reflection. The provided "interface{}" may contain structs
// and types that are converted to Values by the jsonMarshaler interface.
func (p ParseableType) FromStructured(in interface{}) (*TypedValue, error) {
v, err := value.NewValueReflect(in)
if err != nil {
return nil, err
return nil, fmt.Errorf("error creating struct value reflector: %v", err)
}
return AsTyped(v, p.Schema, p.TypeRef)
}

View File

@@ -14,43 +14,44 @@ limitations under the License.
package typed
import (
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
type removingWalker struct {
value *value.Value
value value.Value
out interface{}
schema *schema.Schema
toRemove *fieldpath.Set
}
func removeItemsWithSchema(value *value.Value, toRemove *fieldpath.Set, schema *schema.Schema, typeRef schema.TypeRef) {
func removeItemsWithSchema(val value.Value, toRemove *fieldpath.Set, schema *schema.Schema, typeRef schema.TypeRef) value.Value {
w := &removingWalker{
value: value,
value: val,
schema: schema,
toRemove: toRemove,
}
resolveSchema(schema, typeRef, value, w)
resolveSchema(schema, typeRef, val, w)
return value.NewValueInterface(w.out)
}
// doLeaf should be called on leaves before descending into children, if there
// will be a descent. It modifies w.inLeaf.
func (w *removingWalker) doLeaf() ValidationErrors { return nil }
func (w *removingWalker) doScalar(t *schema.Scalar) ValidationErrors { return nil }
func (w *removingWalker) doScalar(t *schema.Scalar) ValidationErrors {
w.out = w.value.Unstructured()
return nil
}
func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) {
l := w.value.ListValue
l := w.value.AsList()
// If list is null, empty, or atomic just return
if l == nil || len(l.Items) == 0 || t.ElementRelationship == schema.Atomic {
if l == nil || l.Length() == 0 || t.ElementRelationship == schema.Atomic {
return nil
}
newItems := []value.Value{}
for i := range l.Items {
item := l.Items[i]
var newItems []interface{}
for i := 0; i < l.Length(); i++ {
item := l.At(i)
// Ignore error because we have already validated this list
pe, _ := listItemToPathElement(t, i, item)
path, _ := fieldpath.MakePath(pe)
@@ -58,23 +59,21 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) {
continue
}
if subset := w.toRemove.WithPrefix(pe); !subset.Empty() {
removeItemsWithSchema(&l.Items[i], subset, w.schema, t.ElementType)
item = removeItemsWithSchema(item, subset, w.schema, t.ElementType)
}
newItems = append(newItems, l.Items[i])
newItems = append(newItems, item.Unstructured())
}
l.Items = newItems
if len(l.Items) == 0 {
w.value.ListValue = nil
w.value.Null = true
if len(newItems) > 0 {
w.out = newItems
}
return nil
}
func (w *removingWalker) doMap(t *schema.Map) ValidationErrors {
m := w.value.MapValue
m := w.value.AsMap()
// If map is null, empty, or atomic just return
if m == nil || len(m.Items) == 0 || t.ElementRelationship == schema.Atomic {
if m == nil || m.Length() == 0 || t.ElementRelationship == schema.Atomic {
return nil
}
@@ -83,30 +82,26 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors {
fieldTypes[structField.Name] = structField.Type
}
newMap := &value.Map{}
for i := range m.Items {
item := m.Items[i]
pe := fieldpath.PathElement{FieldName: &item.Name}
newMap := map[string]interface{}{}
m.Iterate(func(k string, val value.Value) bool {
pe := fieldpath.PathElement{FieldName: &k}
path, _ := fieldpath.MakePath(pe)
fieldType := t.ElementType
if ft, ok := fieldTypes[item.Name]; ok {
if ft, ok := fieldTypes[k]; ok {
fieldType = ft
} else {
if w.toRemove.Has(path) {
continue
return true
}
}
if subset := w.toRemove.WithPrefix(pe); !subset.Empty() {
removeItemsWithSchema(&m.Items[i].Value, subset, w.schema, fieldType)
val = removeItemsWithSchema(val, subset, w.schema, fieldType)
}
newMap.Set(item.Name, m.Items[i].Value)
}
w.value.MapValue = newMap
if len(w.value.MapValue.Items) == 0 {
w.value.MapValue = nil
w.value.Null = true
newMap[k] = val.Unstructured()
return true
})
if len(newMap) > 0 {
w.out = newMap
}
return nil
}
func (*removingWalker) errorf(_ string, _ ...interface{}) ValidationErrors { return nil }

View File

@@ -0,0 +1,160 @@
/*
Copyright 2018 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 typed
import (
"sync"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
var tPool = sync.Pool{
New: func() interface{} { return &toFieldSetWalker{} },
}
func (tv TypedValue) toFieldSetWalker() *toFieldSetWalker {
v := tPool.Get().(*toFieldSetWalker)
v.value = tv.value
v.schema = tv.schema
v.typeRef = tv.typeRef
v.set = &fieldpath.Set{}
return v
}
func (v *toFieldSetWalker) finished() {
v.schema = nil
v.typeRef = schema.TypeRef{}
v.path = nil
v.set = nil
tPool.Put(v)
}
type toFieldSetWalker struct {
value value.Value
schema *schema.Schema
typeRef schema.TypeRef
set *fieldpath.Set
path fieldpath.Path
// Allocate only as many walkers as needed for the depth by storing them here.
spareWalkers *[]*toFieldSetWalker
}
func (v *toFieldSetWalker) prepareDescent(pe fieldpath.PathElement, tr schema.TypeRef) *toFieldSetWalker {
if v.spareWalkers == nil {
// first descent.
v.spareWalkers = &[]*toFieldSetWalker{}
}
var v2 *toFieldSetWalker
if n := len(*v.spareWalkers); n > 0 {
v2, *v.spareWalkers = (*v.spareWalkers)[n-1], (*v.spareWalkers)[:n-1]
} else {
v2 = &toFieldSetWalker{}
}
*v2 = *v
v2.typeRef = tr
v2.path = append(v2.path, pe)
return v2
}
func (v *toFieldSetWalker) finishDescent(v2 *toFieldSetWalker) {
// if the descent caused a realloc, ensure that we reuse the buffer
// for the next sibling.
v.path = v2.path[:len(v2.path)-1]
*v.spareWalkers = append(*v.spareWalkers, v2)
}
func (v *toFieldSetWalker) toFieldSet() ValidationErrors {
return resolveSchema(v.schema, v.typeRef, v.value, v)
}
func (v *toFieldSetWalker) doScalar(t *schema.Scalar) ValidationErrors {
v.set.Insert(v.path)
return nil
}
func (v *toFieldSetWalker) visitListItems(t *schema.List, list value.List) (errs ValidationErrors) {
for i := 0; i < list.Length(); i++ {
child := list.At(i)
pe, _ := listItemToPathElement(t, i, child)
v2 := v.prepareDescent(pe, t.ElementType)
v2.value = child
errs = append(errs, v2.toFieldSet()...)
v2.set.Insert(v2.path)
v.finishDescent(v2)
}
return errs
}
func (v *toFieldSetWalker) doList(t *schema.List) (errs ValidationErrors) {
list, _ := listValue(v.value)
if t.ElementRelationship == schema.Atomic {
v.set.Insert(v.path)
return nil
}
if list == nil {
return nil
}
errs = v.visitListItems(t, list)
return errs
}
func (v *toFieldSetWalker) visitMapItems(t *schema.Map, m value.Map) (errs ValidationErrors) {
m.Iterate(func(key string, val value.Value) bool {
pe := fieldpath.PathElement{FieldName: &key}
tr := t.ElementType
if sf, ok := t.FindField(key); ok {
tr = sf.Type
}
v2 := v.prepareDescent(pe, tr)
v2.value = val
errs = append(errs, v2.toFieldSet()...)
if _, ok := t.FindField(key); !ok {
v2.set.Insert(v2.path)
}
v.finishDescent(v2)
return true
})
return errs
}
func (v *toFieldSetWalker) doMap(t *schema.Map) (errs ValidationErrors) {
m, _ := mapValue(v.value)
if t.ElementRelationship == schema.Atomic {
v.set.Insert(v.path)
return nil
}
if m == nil {
return nil
}
errs = v.visitMapItems(t, m)
return errs
}

View File

@@ -21,9 +21,9 @@ import (
"strings"
"sync"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
// AsTyped accepts a value and a type and returns a TypedValue. 'v' must have
@@ -62,15 +62,15 @@ type TypedValue struct {
}
// AsValue removes the type from the TypedValue and only keeps the value.
func (tv TypedValue) AsValue() *value.Value {
return &tv.value
func (tv TypedValue) AsValue() value.Value {
return tv.value
}
// Validate returns an error with a list of every spec violation.
func (tv TypedValue) Validate() error {
w := tv.walker()
defer w.finished()
if errs := w.validate(); len(errs) != 0 {
if errs := w.validate(nil); len(errs) != 0 {
return errs
}
return nil
@@ -79,15 +79,12 @@ func (tv TypedValue) Validate() error {
// ToFieldSet creates a set containing every leaf field and item mentioned, or
// validation errors, if any were encountered.
func (tv TypedValue) ToFieldSet() (*fieldpath.Set, error) {
s := fieldpath.NewSet()
w := tv.walker()
w := tv.toFieldSetWalker()
defer w.finished()
w.leafFieldCallback = func(p fieldpath.Path) { s.Insert(p) }
w.nodeFieldCallback = func(p fieldpath.Path) { s.Insert(p) }
if errs := w.validate(); len(errs) != 0 {
if errs := w.toFieldSet(); len(errs) != 0 {
return nil, errs
}
return s, nil
return w.set, nil
}
// Merge returns the result of merging tv and pso ("partially specified
@@ -122,7 +119,7 @@ func (tv TypedValue) Compare(rhs *TypedValue) (c *Comparison, err error) {
c.Added.Insert(w.path)
} else if w.rhs == nil {
c.Removed.Insert(w.path)
} else if !w.rhs.Equals(*w.lhs) {
} else if !value.Equals(w.rhs, w.lhs) {
// TODO: Equality is not sufficient for this.
// Need to implement equality check on the value type.
c.Modified.Insert(w.path)
@@ -143,8 +140,7 @@ func (tv TypedValue) Compare(rhs *TypedValue) (c *Comparison, err error) {
// RemoveItems removes each provided list or map item from the value.
func (tv TypedValue) RemoveItems(items *fieldpath.Set) *TypedValue {
tv.value, _ = value.FromUnstructured(tv.value.ToUnstructured(true))
removeItemsWithSchema(&tv.value, items, tv.schema, tv.typeRef)
tv.value = removeItemsWithSchema(tv.value, items, tv.schema, tv.typeRef)
return &tv
}
@@ -162,11 +158,11 @@ func (tv TypedValue) NormalizeUnions(new *TypedValue) (*TypedValue, error) {
var errs ValidationErrors
var normalizeFn = func(w *mergingWalker) {
if w.rhs != nil {
v := *w.rhs
v := w.rhs.Unstructured()
w.out = &v
}
if err := normalizeUnions(w); err != nil {
errs = append(errs, w.error(err)...)
errs = append(errs, errorf(err.Error())...)
}
}
out, mergeErrs := merge(&tv, new, func(w *mergingWalker) {}, normalizeFn)
@@ -188,11 +184,11 @@ func (tv TypedValue) NormalizeUnionsApply(new *TypedValue) (*TypedValue, error)
var errs ValidationErrors
var normalizeFn = func(w *mergingWalker) {
if w.rhs != nil {
v := *w.rhs
v := w.rhs.Unstructured()
w.out = &v
}
if err := normalizeUnionsApply(w); err != nil {
errs = append(errs, w.error(err)...)
errs = append(errs, errorf(err.Error())...)
}
}
out, mergeErrs := merge(&tv, new, func(w *mergingWalker) {}, normalizeFn)
@@ -206,7 +202,7 @@ func (tv TypedValue) NormalizeUnionsApply(new *TypedValue) (*TypedValue, error)
}
func (tv TypedValue) Empty() *TypedValue {
tv.value = value.Value{Null: true}
tv.value = value.NewValueInterface(nil)
return &tv
}
@@ -216,12 +212,10 @@ var mwPool = sync.Pool{
func merge(lhs, rhs *TypedValue, rule, postRule mergeRule) (*TypedValue, error) {
if lhs.schema != rhs.schema {
return nil, errorFormatter{}.
errorf("expected objects with types from the same schema")
return nil, errorf("expected objects with types from the same schema")
}
if !lhs.typeRef.Equals(rhs.typeRef) {
return nil, errorFormatter{}.
errorf("expected objects of the same type, but got %v and %v", lhs.typeRef, rhs.typeRef)
if !lhs.typeRef.Equals(&rhs.typeRef) {
return nil, errorf("expected objects of the same type, but got %v and %v", lhs.typeRef, rhs.typeRef)
}
mw := mwPool.Get().(*mergingWalker)
@@ -238,14 +232,14 @@ func merge(lhs, rhs *TypedValue, rule, postRule mergeRule) (*TypedValue, error)
mwPool.Put(mw)
}()
mw.lhs = &lhs.value
mw.rhs = &rhs.value
mw.lhs = lhs.value
mw.rhs = rhs.value
mw.schema = lhs.schema
mw.typeRef = lhs.typeRef
mw.rule = rule
mw.postItemHook = postRule
errs := mw.merge()
errs := mw.merge(nil)
if len(errs) > 0 {
return nil, errs
}
@@ -254,10 +248,8 @@ func merge(lhs, rhs *TypedValue, rule, postRule mergeRule) (*TypedValue, error)
schema: lhs.schema,
typeRef: lhs.typeRef,
}
if mw.out == nil {
out.value = value.Value{Null: true}
} else {
out.value = *mw.out
if mw.out != nil {
out.value = value.NewValueInterface(*mw.out)
}
return out, nil
}

View File

@@ -20,8 +20,8 @@ import (
"fmt"
"strings"
"sigs.k8s.io/structured-merge-diff/schema"
"sigs.k8s.io/structured-merge-diff/value"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
func normalizeUnions(w *mergingWalker) error {
@@ -34,12 +34,12 @@ func normalizeUnions(w *mergingWalker) error {
return nil
}
old := &value.Map{}
if w.lhs != nil {
old = w.lhs.MapValue
var old value.Map
if w.lhs != nil && !w.lhs.IsNull() {
old = w.lhs.AsMap()
}
for _, union := range atom.Map.Unions {
if err := newUnion(&union).Normalize(old, w.rhs.MapValue, w.out.MapValue); err != nil {
if err := newUnion(&union).Normalize(old, w.rhs.AsMap(), value.NewValueInterface(*w.out).AsMap()); err != nil {
return err
}
}
@@ -56,14 +56,17 @@ func normalizeUnionsApply(w *mergingWalker) error {
return nil
}
old := &value.Map{}
if w.lhs != nil {
old = w.lhs.MapValue
var old value.Map
if w.lhs != nil && !w.lhs.IsNull() {
old = w.lhs.AsMap()
}
for _, union := range atom.Map.Unions {
if err := newUnion(&union).NormalizeApply(old, w.rhs.MapValue, w.out.MapValue); err != nil {
out := value.NewValueInterface(*w.out)
if err := newUnion(&union).NormalizeApply(old, w.rhs.AsMap(), out.AsMap()); err != nil {
return err
}
*w.out = out.Unstructured()
}
return nil
}
@@ -105,38 +108,38 @@ type discriminator struct {
name string
}
func (d *discriminator) Set(m *value.Map, v discriminated) {
func (d *discriminator) Set(m value.Map, v discriminated) {
if d == nil {
return
}
m.Set(d.name, value.StringValue(string(v)))
m.Set(d.name, value.NewValueInterface(string(v)))
}
func (d *discriminator) Get(m *value.Map) discriminated {
func (d *discriminator) Get(m value.Map) discriminated {
if d == nil || m == nil {
return ""
}
f, ok := m.Get(d.name)
val, ok := m.Get(d.name)
if !ok {
return ""
}
if f.Value.StringValue == nil {
if !val.IsString() {
return ""
}
return discriminated(*f.Value.StringValue)
return discriminated(val.AsString())
}
type fieldsSet map[field]struct{}
// newFieldsSet returns a map of the fields that are part of the union and are set
// in the given map.
func newFieldsSet(m *value.Map, fields []field) fieldsSet {
func newFieldsSet(m value.Map, fields []field) fieldsSet {
if m == nil {
return nil
}
set := fieldsSet{}
for _, f := range fields {
if subField, ok := m.Get(string(f)); ok && !subField.Value.Null {
if subField, ok := m.Get(string(f)); ok && !subField.IsNull() {
set.Add(f)
}
}
@@ -212,7 +215,7 @@ func newUnion(su *schema.Union) *union {
// clear removes all the fields in map that are part of the union, but
// the one we decided to keep.
func (u *union) clear(m *value.Map, f field) {
func (u *union) clear(m value.Map, f field) {
for _, fieldName := range u.f {
if field(fieldName) != f {
m.Delete(string(fieldName))
@@ -220,7 +223,7 @@ func (u *union) clear(m *value.Map, f field) {
}
}
func (u *union) Normalize(old, new, out *value.Map) error {
func (u *union) Normalize(old, new, out value.Map) error {
os := newFieldsSet(old, u.f)
ns := newFieldsSet(new, u.f)
diff := ns.Difference(os)
@@ -240,7 +243,7 @@ func (u *union) Normalize(old, new, out *value.Map) error {
return fmt.Errorf("multiple fields set without discriminator change: %v", ns)
}
// Update discriminiator if it needs to be deduced.
// Set discriminiator if it needs to be deduced.
if u.deduceInvalidDiscriminator && len(ns) == 1 {
u.d.Set(out, u.dn.toDiscriminated(*ns.One()))
}
@@ -248,7 +251,7 @@ func (u *union) Normalize(old, new, out *value.Map) error {
return nil
}
func (u *union) NormalizeApply(applied, merged, out *value.Map) error {
func (u *union) NormalizeApply(applied, merged, out value.Map) error {
as := newFieldsSet(applied, u.f)
if len(as) > 1 {
return fmt.Errorf("more than one field of union applied: %v", as)

View File

@@ -0,0 +1,190 @@
/*
Copyright 2018 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 typed
import (
"sync"
"sigs.k8s.io/structured-merge-diff/v3/fieldpath"
"sigs.k8s.io/structured-merge-diff/v3/schema"
"sigs.k8s.io/structured-merge-diff/v3/value"
)
var vPool = sync.Pool{
New: func() interface{} { return &validatingObjectWalker{} },
}
func (tv TypedValue) walker() *validatingObjectWalker {
v := vPool.Get().(*validatingObjectWalker)
v.value = tv.value
v.schema = tv.schema
v.typeRef = tv.typeRef
return v
}
func (v *validatingObjectWalker) finished() {
v.schema = nil
v.typeRef = schema.TypeRef{}
vPool.Put(v)
}
type validatingObjectWalker struct {
value value.Value
schema *schema.Schema
typeRef schema.TypeRef
// Allocate only as many walkers as needed for the depth by storing them here.
spareWalkers *[]*validatingObjectWalker
}
func (v *validatingObjectWalker) prepareDescent(tr schema.TypeRef) *validatingObjectWalker {
if v.spareWalkers == nil {
// first descent.
v.spareWalkers = &[]*validatingObjectWalker{}
}
var v2 *validatingObjectWalker
if n := len(*v.spareWalkers); n > 0 {
v2, *v.spareWalkers = (*v.spareWalkers)[n-1], (*v.spareWalkers)[:n-1]
} else {
v2 = &validatingObjectWalker{}
}
*v2 = *v
v2.typeRef = tr
return v2
}
func (v *validatingObjectWalker) finishDescent(v2 *validatingObjectWalker) {
// if the descent caused a realloc, ensure that we reuse the buffer
// for the next sibling.
*v.spareWalkers = append(*v.spareWalkers, v2)
}
func (v *validatingObjectWalker) validate(prefixFn func() string) ValidationErrors {
return resolveSchema(v.schema, v.typeRef, v.value, v).WithLazyPrefix(prefixFn)
}
func validateScalar(t *schema.Scalar, v value.Value, prefix string) (errs ValidationErrors) {
if v == nil {
return nil
}
if v.IsNull() {
return nil
}
switch *t {
case schema.Numeric:
if !v.IsFloat() && !v.IsInt() {
// TODO: should the schema separate int and float?
return errorf("%vexpected numeric (int or float), got %T", prefix, v)
}
case schema.String:
if !v.IsString() {
return errorf("%vexpected string, got %#v", prefix, v)
}
case schema.Boolean:
if !v.IsBool() {
return errorf("%vexpected boolean, got %v", prefix, v)
}
}
return nil
}
func (v *validatingObjectWalker) doScalar(t *schema.Scalar) ValidationErrors {
if errs := validateScalar(t, v.value, ""); len(errs) > 0 {
return errs
}
return nil
}
func (v *validatingObjectWalker) visitListItems(t *schema.List, list value.List) (errs ValidationErrors) {
observedKeys := fieldpath.MakePathElementSet(list.Length())
for i := 0; i < list.Length(); i++ {
child := list.At(i)
var pe fieldpath.PathElement
if t.ElementRelationship != schema.Associative {
pe.Index = &i
} else {
var err error
pe, err = listItemToPathElement(t, i, child)
if err != nil {
errs = append(errs, errorf("element %v: %v", i, err.Error())...)
// If we can't construct the path element, we can't
// even report errors deeper in the schema, so bail on
// this element.
return
}
if observedKeys.Has(pe) {
errs = append(errs, errorf("duplicate entries for key %v", pe.String())...)
}
observedKeys.Insert(pe)
}
v2 := v.prepareDescent(t.ElementType)
v2.value = child
errs = append(errs, v2.validate(pe.String)...)
v.finishDescent(v2)
}
return errs
}
func (v *validatingObjectWalker) doList(t *schema.List) (errs ValidationErrors) {
list, err := listValue(v.value)
if err != nil {
return errorf(err.Error())
}
if list == nil {
return nil
}
errs = v.visitListItems(t, list)
return errs
}
func (v *validatingObjectWalker) visitMapItems(t *schema.Map, m value.Map) (errs ValidationErrors) {
m.Iterate(func(key string, val value.Value) bool {
pe := fieldpath.PathElement{FieldName: &key}
tr := t.ElementType
if sf, ok := t.FindField(key); ok {
tr = sf.Type
} else if (t.ElementType == schema.TypeRef{}) {
errs = append(errs, errorf("field not declared in schema").WithPrefix(pe.String())...)
return false
}
v2 := v.prepareDescent(tr)
v2.value = val
// Giving pe.String as a parameter actually increases the allocations.
errs = append(errs, v2.validate(func() string { return pe.String() })...)
v.finishDescent(v2)
return true
})
return errs
}
func (v *validatingObjectWalker) doMap(t *schema.Map) (errs ValidationErrors) {
m, err := mapValue(v.value)
if err != nil {
return errorf(err.Error())
}
if m == nil {
return nil
}
errs = v.visitMapItems(t, m)
return errs
}

View File

@@ -4,12 +4,22 @@ go_library(
name = "go_default_library",
srcs = [
"doc.go",
"fastjson.go",
"unstructured.go",
"fields.go",
"jsontagutil.go",
"list.go",
"listreflect.go",
"listunstructured.go",
"map.go",
"mapreflect.go",
"mapunstructured.go",
"scalar.go",
"structreflect.go",
"value.go",
"valuereflect.go",
"valueunstructured.go",
],
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/value",
importpath = "sigs.k8s.io/structured-merge-diff/value",
importmap = "k8s.io/kubernetes/vendor/sigs.k8s.io/structured-merge-diff/v3/value",
importpath = "sigs.k8s.io/structured-merge-diff/v3/value",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/json-iterator/go:go_default_library",

View File

@@ -0,0 +1,97 @@
/*
Copyright 2019 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 value
import (
"sort"
"strings"
)
// Field is an individual key-value pair.
type Field struct {
Name string
Value Value
}
// FieldList is a list of key-value pairs. Each field is expectUpdated to
// have a different name.
type FieldList []Field
// Sort sorts the field list by Name.
func (f FieldList) Sort() {
if len(f) < 2 {
return
}
if len(f) == 2 {
if f[1].Name < f[0].Name {
f[0], f[1] = f[1], f[0]
}
return
}
sort.SliceStable(f, func(i, j int) bool {
return f[i].Name < f[j].Name
})
}
// Less compares two lists lexically.
func (f FieldList) Less(rhs FieldList) bool {
return f.Compare(rhs) == -1
}
// Compare compares two lists lexically. The result will be 0 if f==rhs, -1
// if f < rhs, and +1 if f > rhs.
func (f FieldList) Compare(rhs FieldList) int {
i := 0
for {
if i >= len(f) && i >= len(rhs) {
// Maps are the same length and all items are equal.
return 0
}
if i >= len(f) {
// F is shorter.
return -1
}
if i >= len(rhs) {
// RHS is shorter.
return 1
}
if c := strings.Compare(f[i].Name, rhs[i].Name); c != 0 {
return c
}
if c := Compare(f[i].Value, rhs[i].Value); c != 0 {
return c
}
// The items are equal; continue.
i++
}
}
// Equals returns true if the two fieldslist are equals, false otherwise.
func (f FieldList) Equals(rhs FieldList) bool {
if len(f) != len(rhs) {
return false
}
for i := range f {
if f[i].Name != rhs[i].Name {
return false
}
if !Equals(f[i].Value, rhs[i].Value) {
return false
}
}
return true
}

View File

@@ -0,0 +1,91 @@
/*
Copyright 2019 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 value
import (
"fmt"
"reflect"
"strings"
)
// TODO: This implements the same functionality as https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/runtime/converter.go#L236
// but is based on the highly efficient approach from https://golang.org/src/encoding/json/encode.go
func lookupJsonTags(f reflect.StructField) (name string, omit bool, inline bool, omitempty bool) {
tag := f.Tag.Get("json")
if tag == "-" {
return "", true, false, false
}
name, opts := parseTag(tag)
if name == "" {
name = f.Name
}
return name, false, opts.Contains("inline"), opts.Contains("omitempty")
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Chan, reflect.Func:
panic(fmt.Sprintf("unsupported type: %v", v.Type()))
}
return false
}
type tagOptions string
// parseTag splits a struct field's json tag into its name and
// comma-separated options.
func parseTag(tag string) (string, tagOptions) {
if idx := strings.Index(tag, ","); idx != -1 {
return tag[:idx], tagOptions(tag[idx+1:])
}
return tag, tagOptions("")
}
// Contains reports whether a comma-separated list of options
// contains a particular substr flag. substr must be surrounded by a
// string boundary or commas.
func (o tagOptions) Contains(optionName string) bool {
if len(o) == 0 {
return false
}
s := string(o)
for s != "" {
var next string
i := strings.Index(s, ",")
if i >= 0 {
s, next = s[:i], s[i+1:]
}
if s == optionName {
return true
}
s = next
}
return false
}

View File

@@ -0,0 +1,80 @@
/*
Copyright 2019 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 value
// List represents a list object.
type List interface {
// Length returns how many items can be found in the map.
Length() int
// At returns the item at the given position in the map. It will
// panic if the index is out of range.
At(int) Value
}
// ListEquals compares two lists lexically.
func ListEquals(lhs, rhs List) bool {
if lhs.Length() != rhs.Length() {
return false
}
for i := 0; i < lhs.Length(); i++ {
lv := lhs.At(i)
rv := rhs.At(i)
if !Equals(lv, rv) {
lv.Recycle()
rv.Recycle()
return false
}
lv.Recycle()
rv.Recycle()
}
return true
}
// ListLess compares two lists lexically.
func ListLess(lhs, rhs List) bool {
return ListCompare(lhs, rhs) == -1
}
// ListCompare compares two lists lexically. The result will be 0 if l==rhs, -1
// if l < rhs, and +1 if l > rhs.
func ListCompare(lhs, rhs List) int {
i := 0
for {
if i >= lhs.Length() && i >= rhs.Length() {
// Lists are the same length and all items are equal.
return 0
}
if i >= lhs.Length() {
// LHS is shorter.
return -1
}
if i >= rhs.Length() {
// RHS is shorter.
return 1
}
lv := lhs.At(i)
rv := rhs.At(i)
if c := Compare(lv, rv); c != 0 {
return c
}
lv.Recycle()
rv.Recycle()
// The items are equal; continue.
i++
}
}

View File

@@ -0,0 +1,42 @@
/*
Copyright 2019 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 value
import "reflect"
type listReflect struct {
Value reflect.Value
}
func (r listReflect) Length() int {
val := r.Value
return val.Len()
}
func (r listReflect) At(i int) Value {
val := r.Value
return mustWrapValueReflect(val.Index(i))
}
func (r listReflect) Unstructured() interface{} {
l := r.Length()
result := make([]interface{}, l)
for i := 0; i < l; i++ {
result[i] = r.At(i).Unstructured()
}
return result
}

View File

@@ -0,0 +1,27 @@
/*
Copyright 2019 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 value
type listUnstructured []interface{}
func (l listUnstructured) Length() int {
return len(l)
}
func (l listUnstructured) At(i int) Value {
return NewValueInterface(l[i])
}

View File

@@ -0,0 +1,113 @@
/*
Copyright 2019 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 value
import (
"sort"
"strings"
)
// Map represents a Map or go structure.
type Map interface {
// Set changes or set the value of the given key.
Set(key string, val Value)
// Get returns the value for the given key, if present, or (nil, false) otherwise.
Get(key string) (Value, bool)
// Has returns true if the key is present, or false otherwise.
Has(key string) bool
// Delete removes the key from the map.
Delete(key string)
// Equals compares the two maps, and return true if they are the same, false otherwise.
// Implementations can use MapEquals as a general implementation for this methods.
Equals(other Map) bool
// Iterate runs the given function for each key/value in the
// map. Returning false in the closure prematurely stops the
// iteration.
Iterate(func(key string, value Value) bool) bool
// Length returns the number of items in the map.
Length() int
}
// MapLess compares two maps lexically.
func MapLess(lhs, rhs Map) bool {
return MapCompare(lhs, rhs) == -1
}
// MapCompare compares two maps lexically.
func MapCompare(lhs, rhs Map) int {
lorder := make([]string, 0, lhs.Length())
lhs.Iterate(func(key string, _ Value) bool {
lorder = append(lorder, key)
return true
})
sort.Strings(lorder)
rorder := make([]string, 0, rhs.Length())
rhs.Iterate(func(key string, _ Value) bool {
rorder = append(rorder, key)
return true
})
sort.Strings(rorder)
i := 0
for {
if i >= len(lorder) && i >= len(rorder) {
// Maps are the same length and all items are equal.
return 0
}
if i >= len(lorder) {
// LHS is shorter.
return -1
}
if i >= len(rorder) {
// RHS is shorter.
return 1
}
if c := strings.Compare(lorder[i], rorder[i]); c != 0 {
return c
}
litem, _ := lhs.Get(lorder[i])
ritem, _ := rhs.Get(rorder[i])
if c := Compare(litem, ritem); c != 0 {
return c
}
litem.Recycle()
ritem.Recycle()
// The items are equal; continue.
i++
}
}
// MapEquals returns true if lhs == rhs, false otherwise. This function
// acts on generic types and should not be used by callers, but can help
// implement Map.Equals.
func MapEquals(lhs, rhs Map) bool {
if lhs.Length() != rhs.Length() {
return false
}
return lhs.Iterate(func(k string, v Value) bool {
vo, ok := rhs.Get(k)
if !ok {
return false
}
if !Equals(v, vo) {
vo.Recycle()
return false
}
vo.Recycle()
return true
})
}

View File

@@ -0,0 +1,107 @@
/*
Copyright 2019 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 value
import "reflect"
type mapReflect struct {
valueReflect
}
func (r mapReflect) Length() int {
val := r.Value
return val.Len()
}
func (r mapReflect) Get(key string) (Value, bool) {
mapKey := r.toMapKey(key)
val := r.Value.MapIndex(mapKey)
if !val.IsValid() {
return nil, false
}
return mustWrapValueReflectMapItem(&r.Value, &mapKey, val), val != reflect.Value{}
}
func (r mapReflect) Has(key string) bool {
var val reflect.Value
val = r.Value.MapIndex(r.toMapKey(key))
if !val.IsValid() {
return false
}
return val != reflect.Value{}
}
func (r mapReflect) Set(key string, val Value) {
r.Value.SetMapIndex(r.toMapKey(key), reflect.ValueOf(val.Unstructured()))
}
func (r mapReflect) Delete(key string) {
val := r.Value
val.SetMapIndex(r.toMapKey(key), reflect.Value{})
}
// TODO: Do we need to support types that implement json.Marshaler and are used as string keys?
func (r mapReflect) toMapKey(key string) reflect.Value {
val := r.Value
return reflect.ValueOf(key).Convert(val.Type().Key())
}
func (r mapReflect) Iterate(fn func(string, Value) bool) bool {
return eachMapEntry(r.Value, func(s string, value reflect.Value) bool {
mapVal := mustWrapValueReflect(value)
defer mapVal.Recycle()
return fn(s, mapVal)
})
}
func eachMapEntry(val reflect.Value, fn func(string, reflect.Value) bool) bool {
iter := val.MapRange()
for iter.Next() {
next := iter.Value()
if !next.IsValid() {
continue
}
if !fn(iter.Key().String(), next) {
return false
}
}
return true
}
func (r mapReflect) Unstructured() interface{} {
result := make(map[string]interface{}, r.Length())
r.Iterate(func(s string, value Value) bool {
result[s] = value.Unstructured()
return true
})
return result
}
func (r mapReflect) Equals(m Map) bool {
if r.Length() != m.Length() {
return false
}
// TODO: Optimize to avoid Iterate looping here by using r.Value.MapRange or similar if it improves performance.
return m.Iterate(func(key string, value Value) bool {
lhsVal, ok := r.Get(key)
if !ok {
return false
}
return Equals(lhsVal, value)
})
}

View File

@@ -0,0 +1,145 @@
/*
Copyright 2019 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 value
type mapUnstructuredInterface map[interface{}]interface{}
func (m mapUnstructuredInterface) Set(key string, val Value) {
m[key] = val.Unstructured()
}
func (m mapUnstructuredInterface) Get(key string) (Value, bool) {
if v, ok := m[key]; !ok {
return nil, false
} else {
return NewValueInterface(v), true
}
}
func (m mapUnstructuredInterface) Has(key string) bool {
_, ok := m[key]
return ok
}
func (m mapUnstructuredInterface) Delete(key string) {
delete(m, key)
}
func (m mapUnstructuredInterface) Iterate(fn func(key string, value Value) bool) bool {
for k, v := range m {
if ks, ok := k.(string); !ok {
continue
} else {
vv := NewValueInterface(v)
if !fn(ks, vv) {
vv.Recycle()
return false
}
vv.Recycle()
}
}
return true
}
func (m mapUnstructuredInterface) Length() int {
return len(m)
}
func (m mapUnstructuredInterface) Equals(other Map) bool {
if m.Length() != other.Length() {
return false
}
for k, v := range m {
ks, ok := k.(string)
if !ok {
return false
}
vo, ok := other.Get(ks)
if !ok {
return false
}
vv := NewValueInterface(v)
if !Equals(vv, vo) {
vv.Recycle()
vo.Recycle()
return false
}
vo.Recycle()
vv.Recycle()
}
return true
}
type mapUnstructuredString map[string]interface{}
func (m mapUnstructuredString) Set(key string, val Value) {
m[key] = val.Unstructured()
}
func (m mapUnstructuredString) Get(key string) (Value, bool) {
if v, ok := m[key]; !ok {
return nil, false
} else {
return NewValueInterface(v), true
}
}
func (m mapUnstructuredString) Has(key string) bool {
_, ok := m[key]
return ok
}
func (m mapUnstructuredString) Delete(key string) {
delete(m, key)
}
func (m mapUnstructuredString) Iterate(fn func(key string, value Value) bool) bool {
for k, v := range m {
vv := NewValueInterface(v)
if !fn(k, vv) {
vv.Recycle()
return false
}
vv.Recycle()
}
return true
}
func (m mapUnstructuredString) Length() int {
return len(m)
}
func (m mapUnstructuredString) Equals(other Map) bool {
if m.Length() != other.Length() {
return false
}
for k, v := range m {
vo, ok := other.Get(k)
if !ok {
return false
}
vv := NewValueInterface(v)
if !Equals(vv, vo) {
vo.Recycle()
vv.Recycle()
return false
}
vo.Recycle()
vv.Recycle()
}
return true
}

View File

@@ -0,0 +1,50 @@
/*
Copyright 2019 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 value
// Compare compares floats. The result will be 0 if lhs==rhs, -1 if f <
// rhs, and +1 if f > rhs.
func FloatCompare(lhs, rhs float64) int {
if lhs > rhs {
return 1
} else if lhs < rhs {
return -1
}
return 0
}
// IntCompare compares integers. The result will be 0 if i==rhs, -1 if i <
// rhs, and +1 if i > rhs.
func IntCompare(lhs, rhs int64) int {
if lhs > rhs {
return 1
} else if lhs < rhs {
return -1
}
return 0
}
// Compare compares booleans. The result will be 0 if b==rhs, -1 if b <
// rhs, and +1 if b > rhs.
func BoolCompare(lhs, rhs bool) int {
if lhs == rhs {
return 0
} else if lhs == false {
return -1
}
return 1
}

View File

@@ -0,0 +1,269 @@
/*
Copyright 2019 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 value
import (
"fmt"
"reflect"
"sync"
"sync/atomic"
)
// reflectStructCache keeps track of json tag related data for structs and fields to speed up reflection.
// TODO: This overlaps in functionality with the fieldCache in
// https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/runtime/converter.go#L57 but
// is more efficient at lookup by json field name. The logic should be consolidated. Only one copy of the cache needs
// to be kept for each running process.
var (
reflectStructCache = newStructCache()
)
type structCache struct {
// use an atomic and copy-on-write since there are a fixed (typically very small) number of structs compiled into any
// go program using this cache
value atomic.Value
// mu is held by writers when performing load/modify/store operations on the cache, readers do not need to hold a
// read-lock since the atomic value is always read-only
mu sync.Mutex
}
type structCacheMap map[reflect.Type]structCacheEntry
// structCacheEntry contains information about each struct field, keyed by json field name, that is expensive to
// compute using reflection.
type structCacheEntry map[string]*fieldCacheEntry
// Get returns true and fieldCacheEntry for the given type if the type is in the cache. Otherwise Get returns false.
func (c *structCache) Get(t reflect.Type) (map[string]*fieldCacheEntry, bool) {
entry, ok := c.value.Load().(structCacheMap)[t]
return entry, ok
}
// Set sets the fieldCacheEntry for the given type via a copy-on-write update to the struct cache.
func (c *structCache) Set(t reflect.Type, m map[string]*fieldCacheEntry) {
c.mu.Lock()
defer c.mu.Unlock()
currentCacheMap := c.value.Load().(structCacheMap)
if _, ok := currentCacheMap[t]; ok {
// Bail if the entry has been set while waiting for lock acquisition.
// This is safe since setting entries is idempotent.
return
}
newCacheMap := make(structCacheMap, len(currentCacheMap)+1)
for k, v := range currentCacheMap {
newCacheMap[k] = v
}
newCacheMap[t] = m
c.value.Store(newCacheMap)
}
func newStructCache() *structCache {
cache := &structCache{}
cache.value.Store(make(structCacheMap))
return cache
}
type fieldCacheEntry struct {
// isOmitEmpty is true if the field has the json 'omitempty' tag.
isOmitEmpty bool
// fieldPath is the field indices (see FieldByIndex) to lookup the value of
// a field in a reflect.Value struct. A path of field indices is used
// to support traversing to a field field in struct fields that have the 'inline'
// json tag.
fieldPath [][]int
}
func (f *fieldCacheEntry) getFieldFromStruct(structVal reflect.Value) reflect.Value {
// field might be field within 'inline' structs
for _, elem := range f.fieldPath {
structVal = structVal.FieldByIndex(elem)
}
return structVal
}
func getStructCacheEntry(t reflect.Type) structCacheEntry {
if hints, ok := reflectStructCache.Get(t); ok {
return hints
}
hints := map[string]*fieldCacheEntry{}
buildStructCacheEntry(t, hints, nil)
reflectStructCache.Set(t, hints)
return hints
}
func buildStructCacheEntry(t reflect.Type, infos map[string]*fieldCacheEntry, fieldPath [][]int) {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
jsonName, omit, isInline, isOmitempty := lookupJsonTags(field)
if omit {
continue
}
if isInline {
buildStructCacheEntry(field.Type, infos, append(fieldPath, field.Index))
continue
}
info := &fieldCacheEntry{isOmitEmpty: isOmitempty, fieldPath: append(fieldPath, field.Index)}
infos[jsonName] = info
}
}
type structReflect struct {
valueReflect
}
func (r structReflect) Length() int {
i := 0
eachStructField(r.Value, func(s string, value reflect.Value) bool {
i++
return true
})
return i
}
func (r structReflect) Get(key string) (Value, bool) {
if val, ok, _ := r.findJsonNameField(key); ok {
return mustWrapValueReflect(val), true
}
return nil, false
}
func (r structReflect) Has(key string) bool {
_, ok, _ := r.findJsonNameField(key)
return ok
}
func (r structReflect) Set(key string, val Value) {
fieldEntry, ok := getStructCacheEntry(r.Value.Type())[key]
if !ok {
panic(fmt.Sprintf("key %s may not be set on struct %T: field does not exist", key, r.Value.Interface()))
}
oldVal := fieldEntry.getFieldFromStruct(r.Value)
newVal := reflect.ValueOf(val.Unstructured())
r.update(fieldEntry, key, oldVal, newVal)
}
func (r structReflect) Delete(key string) {
fieldEntry, ok := getStructCacheEntry(r.Value.Type())[key]
if !ok {
panic(fmt.Sprintf("key %s may not be deleted on struct %T: field does not exist", key, r.Value.Interface()))
}
oldVal := fieldEntry.getFieldFromStruct(r.Value)
if oldVal.Kind() != reflect.Ptr && !fieldEntry.isOmitEmpty {
panic(fmt.Sprintf("key %s may not be deleted on struct: %T: value is neither a pointer nor an omitempty field", key, r.Value.Interface()))
}
r.update(fieldEntry, key, oldVal, reflect.Zero(oldVal.Type()))
}
func (r structReflect) update(fieldEntry *fieldCacheEntry, key string, oldVal, newVal reflect.Value) {
if oldVal.CanSet() {
oldVal.Set(newVal)
return
}
// map items are not addressable, so if a struct is contained in a map, the only way to modify it is
// to write a replacement fieldEntry into the map.
if r.ParentMap != nil {
if r.ParentMapKey == nil {
panic("ParentMapKey must not be nil if ParentMap is not nil")
}
replacement := reflect.New(r.Value.Type()).Elem()
fieldEntry.getFieldFromStruct(replacement).Set(newVal)
r.ParentMap.SetMapIndex(*r.ParentMapKey, replacement)
return
}
// This should never happen since NewValueReflect ensures that the root object reflected on is a pointer and map
// item replacement is handled above.
panic(fmt.Sprintf("key %s may not be modified on struct: %T: struct is not settable", key, r.Value.Interface()))
}
func (r structReflect) Iterate(fn func(string, Value) bool) bool {
return eachStructField(r.Value, func(s string, value reflect.Value) bool {
v := mustWrapValueReflect(value)
defer v.Recycle()
return fn(s, v)
})
}
func eachStructField(structVal reflect.Value, fn func(string, reflect.Value) bool) bool {
for jsonName, fieldCacheEntry := range getStructCacheEntry(structVal.Type()) {
fieldVal := fieldCacheEntry.getFieldFromStruct(structVal)
if fieldCacheEntry.isOmitEmpty && (safeIsNil(fieldVal) || isZero(fieldVal)) {
// omit it
continue
}
ok := fn(jsonName, fieldVal)
if !ok {
return false
}
}
return true
}
func (r structReflect) Unstructured() interface{} {
// Use number of struct fields as a cheap way to rough estimate map size
result := make(map[string]interface{}, r.Value.NumField())
r.Iterate(func(s string, value Value) bool {
result[s] = value.Unstructured()
return true
})
return result
}
func (r structReflect) Equals(m Map) bool {
if rhsStruct, ok := m.(structReflect); ok {
return reflect.DeepEqual(r.Value.Interface(), rhsStruct.Value.Interface())
}
if r.Length() != m.Length() {
return false
}
structCacheEntry := getStructCacheEntry(r.Value.Type())
return m.Iterate(func(s string, value Value) bool {
fieldCacheEntry, ok := structCacheEntry[s]
if !ok {
return false
}
lhsVal := fieldCacheEntry.getFieldFromStruct(r.Value)
return Equals(mustWrapValueReflect(lhsVal), value)
})
}
func (r structReflect) findJsonNameFieldAndNotEmpty(jsonName string) (reflect.Value, bool) {
structCacheEntry, ok := getStructCacheEntry(r.Value.Type())[jsonName]
if !ok {
return reflect.Value{}, false
}
fieldVal := structCacheEntry.getFieldFromStruct(r.Value)
omit := structCacheEntry.isOmitEmpty && (safeIsNil(fieldVal) || isZero(fieldVal))
return fieldVal, !omit
}
func (r structReflect) findJsonNameField(jsonName string) (val reflect.Value, ok bool, omitEmpty bool) {
structCacheEntry, ok := getStructCacheEntry(r.Value.Type())[jsonName]
if !ok {
return reflect.Value{}, false, false
}
fieldVal := structCacheEntry.getFieldFromStruct(r.Value)
return fieldVal, true, structCacheEntry.isOmitEmpty
}

View File

@@ -0,0 +1,315 @@
/*
Copyright 2018 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 value
import (
"bytes"
"fmt"
"io"
"strings"
jsoniter "github.com/json-iterator/go"
"gopkg.in/yaml.v2"
)
var (
readPool = jsoniter.NewIterator(jsoniter.ConfigCompatibleWithStandardLibrary).Pool()
writePool = jsoniter.NewStream(jsoniter.ConfigCompatibleWithStandardLibrary, nil, 1024).Pool()
)
// A Value corresponds to an 'atom' in the schema. It should return true
// for at least one of the IsXXX methods below, or the value is
// considered "invalid"
type Value interface {
// IsMap returns true if the Value is a Map, false otherwise.
IsMap() bool
// IsList returns true if the Value is a List, false otherwise.
IsList() bool
// IsBool returns true if the Value is a bool, false otherwise.
IsBool() bool
// IsInt returns true if the Value is a int64, false otherwise.
IsInt() bool
// IsFloat returns true if the Value is a float64, false
// otherwise.
IsFloat() bool
// IsString returns true if the Value is a string, false
// otherwise.
IsString() bool
// IsMap returns true if the Value is null, false otherwise.
IsNull() bool
// AsMap converts the Value into a Map (or panic if the type
// doesn't allow it).
AsMap() Map
// AsList converts the Value into a List (or panic if the type
// doesn't allow it).
AsList() List
// AsBool converts the Value into a bool (or panic if the type
// doesn't allow it).
AsBool() bool
// AsInt converts the Value into an int64 (or panic if the type
// doesn't allow it).
AsInt() int64
// AsFloat converts the Value into a float64 (or panic if the type
// doesn't allow it).
AsFloat() float64
// AsString converts the Value into a string (or panic if the type
// doesn't allow it).
AsString() string
// Recycle returns a value of this type that is no longer needed. The
// value shouldn't be used after this call.
Recycle()
// Unstructured converts the Value into an Unstructured interface{}.
Unstructured() interface{}
}
// FromJSON is a helper function for reading a JSON document.
func FromJSON(input []byte) (Value, error) {
return FromJSONFast(input)
}
// FromJSONFast is a helper function for reading a JSON document.
func FromJSONFast(input []byte) (Value, error) {
iter := readPool.BorrowIterator(input)
defer readPool.ReturnIterator(iter)
return ReadJSONIter(iter)
}
// ToJSON is a helper function for producing a JSon document.
func ToJSON(v Value) ([]byte, error) {
buf := bytes.Buffer{}
stream := writePool.BorrowStream(&buf)
defer writePool.ReturnStream(stream)
WriteJSONStream(v, stream)
b := stream.Buffer()
err := stream.Flush()
// Help jsoniter manage its buffers--without this, the next
// use of the stream is likely to require an allocation. Look
// at the jsoniter stream code to understand why. They were probably
// optimizing for folks using the buffer directly.
stream.SetBuffer(b[:0])
return buf.Bytes(), err
}
// ReadJSONIter reads a Value from a JSON iterator.
func ReadJSONIter(iter *jsoniter.Iterator) (Value, error) {
v := iter.Read()
if iter.Error != nil && iter.Error != io.EOF {
return nil, iter.Error
}
return NewValueInterface(v), nil
}
// WriteJSONStream writes a value into a JSON stream.
func WriteJSONStream(v Value, stream *jsoniter.Stream) {
stream.WriteVal(v.Unstructured())
}
// ToYAML marshals a value as YAML.
func ToYAML(v Value) ([]byte, error) {
return yaml.Marshal(v.Unstructured())
}
// Equals returns true iff the two values are equal.
func Equals(lhs, rhs Value) bool {
if lhs.IsFloat() || rhs.IsFloat() {
var lf float64
if lhs.IsFloat() {
lf = lhs.AsFloat()
} else if lhs.IsInt() {
lf = float64(lhs.AsInt())
} else {
return false
}
var rf float64
if rhs.IsFloat() {
rf = rhs.AsFloat()
} else if rhs.IsInt() {
rf = float64(rhs.AsInt())
} else {
return false
}
return lf == rf
}
if lhs.IsInt() {
if rhs.IsInt() {
return lhs.AsInt() == rhs.AsInt()
}
return false
} else if rhs.IsInt() {
return false
}
if lhs.IsString() {
if rhs.IsString() {
return lhs.AsString() == rhs.AsString()
}
return false
} else if rhs.IsString() {
return false
}
if lhs.IsBool() {
if rhs.IsBool() {
return lhs.AsBool() == rhs.AsBool()
}
return false
} else if rhs.IsBool() {
return false
}
if lhs.IsList() {
if rhs.IsList() {
return ListEquals(lhs.AsList(), rhs.AsList())
}
return false
} else if rhs.IsList() {
return false
}
if lhs.IsMap() {
if rhs.IsMap() {
return lhs.AsMap().Equals(rhs.AsMap())
}
return false
} else if rhs.IsMap() {
return false
}
if lhs.IsNull() {
if rhs.IsNull() {
return true
}
return false
} else if rhs.IsNull() {
return false
}
// No field is set, on either objects.
return true
}
// ToString returns a human-readable representation of the value.
func ToString(v Value) string {
if v.IsNull() {
return "null"
}
switch {
case v.IsFloat():
return fmt.Sprintf("%v", v.AsFloat())
case v.IsInt():
return fmt.Sprintf("%v", v.AsInt())
case v.IsString():
return fmt.Sprintf("%q", v.AsString())
case v.IsBool():
return fmt.Sprintf("%v", v.AsBool())
case v.IsList():
strs := []string{}
for i := 0; i < v.AsList().Length(); i++ {
strs = append(strs, ToString(v.AsList().At(i)))
}
return "[" + strings.Join(strs, ",") + "]"
case v.IsMap():
strs := []string{}
v.AsMap().Iterate(func(k string, v Value) bool {
strs = append(strs, fmt.Sprintf("%v=%v", k, ToString(v)))
return true
})
return strings.Join(strs, "")
}
// No field is set, on either objects.
return "{{undefined}}"
}
// Less provides a total ordering for Value (so that they can be sorted, even
// if they are of different types).
func Less(lhs, rhs Value) bool {
return Compare(lhs, rhs) == -1
}
// Compare provides a total ordering for Value (so that they can be
// sorted, even if they are of different types). The result will be 0 if
// v==rhs, -1 if v < rhs, and +1 if v > rhs.
func Compare(lhs, rhs Value) int {
if lhs.IsFloat() {
if !rhs.IsFloat() {
// Extra: compare floats and ints numerically.
if rhs.IsInt() {
return FloatCompare(lhs.AsFloat(), float64(rhs.AsInt()))
}
return -1
}
return FloatCompare(lhs.AsFloat(), rhs.AsFloat())
} else if rhs.IsFloat() {
// Extra: compare floats and ints numerically.
if lhs.IsInt() {
return FloatCompare(float64(lhs.AsInt()), rhs.AsFloat())
}
return 1
}
if lhs.IsInt() {
if !rhs.IsInt() {
return -1
}
return IntCompare(lhs.AsInt(), rhs.AsInt())
} else if rhs.IsInt() {
return 1
}
if lhs.IsString() {
if !rhs.IsString() {
return -1
}
return strings.Compare(lhs.AsString(), rhs.AsString())
} else if rhs.IsString() {
return 1
}
if lhs.IsBool() {
if !rhs.IsBool() {
return -1
}
return BoolCompare(lhs.AsBool(), rhs.AsBool())
} else if rhs.IsBool() {
return 1
}
if lhs.IsList() {
if !rhs.IsList() {
return -1
}
return ListCompare(lhs.AsList(), rhs.AsList())
} else if rhs.IsList() {
return 1
}
if lhs.IsMap() {
if !rhs.IsMap() {
return -1
}
return MapCompare(lhs.AsMap(), rhs.AsMap())
} else if rhs.IsMap() {
return 1
}
if lhs.IsNull() {
if !rhs.IsNull() {
return -1
}
return 0
} else if rhs.IsNull() {
return 1
}
// Invalid Value-- nothing is set.
return 0
}

View File

@@ -0,0 +1,319 @@
/*
Copyright 2019 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 value
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"sync"
)
var reflectPool = sync.Pool{
New: func() interface{} {
return &valueReflect{}
},
}
// NewValueReflect creates a Value backed by an "interface{}" type,
// typically an structured object in Kubernetes world that is uses reflection to expose.
// The provided "interface{}" value must be a pointer so that the value can be modified via reflection.
// The provided "interface{}" may contain structs and types that are converted to Values
// by the jsonMarshaler interface.
func NewValueReflect(value interface{}) (Value, error) {
if value == nil {
return NewValueInterface(nil), nil
}
v := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr {
// The root value to reflect on must be a pointer so that map.Set() and map.Delete() operations are possible.
return nil, fmt.Errorf("value provided to NewValueReflect must be a pointer")
}
return wrapValueReflect(nil, nil, v)
}
func wrapValueReflect(parentMap, parentMapKey *reflect.Value, value reflect.Value) (Value, error) {
// TODO: conversion of json.Marshaller interface types is expensive. This can be mostly optimized away by
// introducing conversion functions that do not require going through JSON and using those here.
if marshaler, ok := getMarshaler(value); ok {
return toUnstructured(marshaler, value)
}
value = dereference(value)
val := reflectPool.Get().(*valueReflect)
val.Value = value
val.ParentMap = parentMap
val.ParentMapKey = parentMapKey
return Value(val), nil
}
func mustWrapValueReflect(value reflect.Value) Value {
v, err := wrapValueReflect(nil, nil, value)
if err != nil {
panic(err)
}
return v
}
func mustWrapValueReflectMapItem(parentMap, parentMapKey *reflect.Value, value reflect.Value) Value {
v, err := wrapValueReflect(parentMap, parentMapKey, value)
if err != nil {
panic(err)
}
return v
}
func dereference(val reflect.Value) reflect.Value {
kind := val.Kind()
if (kind == reflect.Interface || kind == reflect.Ptr) && !safeIsNil(val) {
return val.Elem()
}
return val
}
type valueReflect struct {
ParentMap *reflect.Value
ParentMapKey *reflect.Value
Value reflect.Value
}
func (r valueReflect) IsMap() bool {
return r.isKind(reflect.Map, reflect.Struct)
}
func (r valueReflect) IsList() bool {
typ := r.Value.Type()
return typ.Kind() == reflect.Slice && !(typ.Elem().Kind() == reflect.Uint8)
}
func (r valueReflect) IsBool() bool {
return r.isKind(reflect.Bool)
}
func (r valueReflect) IsInt() bool {
// Uint64 deliberately excluded, see valueUnstructured.Int.
return r.isKind(reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8)
}
func (r valueReflect) IsFloat() bool {
return r.isKind(reflect.Float64, reflect.Float32)
}
func (r valueReflect) IsString() bool {
kind := r.Value.Kind()
if kind == reflect.String {
return true
}
if kind == reflect.Slice && r.Value.Type().Elem().Kind() == reflect.Uint8 {
return true
}
return false
}
func (r valueReflect) IsNull() bool {
return safeIsNil(r.Value)
}
func (r valueReflect) isKind(kinds ...reflect.Kind) bool {
kind := r.Value.Kind()
for _, k := range kinds {
if kind == k {
return true
}
}
return false
}
// TODO find a cleaner way to avoid panics from reflect.IsNil()
func safeIsNil(v reflect.Value) bool {
k := v.Kind()
switch k {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return v.IsNil()
}
return false
}
func (r valueReflect) AsMap() Map {
val := r.Value
switch val.Kind() {
case reflect.Struct:
return structReflect{r}
case reflect.Map:
return mapReflect{r}
default:
panic("value is not a map or struct")
}
}
func (r *valueReflect) Recycle() {
reflectPool.Put(r)
}
func (r valueReflect) AsList() List {
if r.IsList() {
return listReflect{r.Value}
}
panic("value is not a list")
}
func (r valueReflect) AsBool() bool {
if r.IsBool() {
return r.Value.Bool()
}
panic("value is not a bool")
}
func (r valueReflect) AsInt() int64 {
if r.isKind(reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8) {
return r.Value.Int()
}
if r.isKind(reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8) {
return int64(r.Value.Uint())
}
panic("value is not an int")
}
func (r valueReflect) AsFloat() float64 {
if r.IsFloat() {
return r.Value.Float()
}
panic("value is not a float")
}
func (r valueReflect) AsString() string {
kind := r.Value.Kind()
if kind == reflect.String {
return r.Value.String()
}
if kind == reflect.Slice && r.Value.Type().Elem().Kind() == reflect.Uint8 {
return base64.StdEncoding.EncodeToString(r.Value.Bytes())
}
panic("value is not a string")
}
func (r valueReflect) Unstructured() interface{} {
val := r.Value
switch {
case r.IsNull():
return nil
case val.Kind() == reflect.Struct:
return structReflect{r}.Unstructured()
case val.Kind() == reflect.Map:
return mapReflect{r}.Unstructured()
case r.IsList():
return listReflect{Value: r.Value}.Unstructured()
case r.IsString():
return r.AsString()
case r.IsInt():
return r.AsInt()
case r.IsBool():
return r.AsBool()
case r.IsFloat():
return r.AsFloat()
default:
panic(fmt.Sprintf("value of type %s is not a supported by value reflector", val.Type()))
}
}
// The below getMarshaler and toUnstructured functions are based on
// https://github.com/kubernetes/kubernetes/blob/40df9f82d0572a123f5ad13f48312978a2ff5877/staging/src/k8s.io/apimachinery/pkg/runtime/converter.go#L509
// and should somehow be consolidated with it
var marshalerType = reflect.TypeOf(new(json.Marshaler)).Elem()
func getMarshaler(v reflect.Value) (json.Marshaler, bool) {
// Check value receivers if v is not a pointer and pointer receivers if v is a pointer
if v.Type().Implements(marshalerType) {
return v.Interface().(json.Marshaler), true
}
// Check pointer receivers if v is not a pointer
if v.Kind() != reflect.Ptr && v.CanAddr() {
v = v.Addr()
if v.Type().Implements(marshalerType) {
return v.Interface().(json.Marshaler), true
}
}
return nil, false
}
var (
nullBytes = []byte("null")
trueBytes = []byte("true")
falseBytes = []byte("false")
)
func toUnstructured(marshaler json.Marshaler, sv reflect.Value) (Value, error) {
data, err := marshaler.MarshalJSON()
if err != nil {
return nil, err
}
switch {
case len(data) == 0:
return nil, fmt.Errorf("error decoding from json: empty value")
case bytes.Equal(data, nullBytes):
// We're done - we don't need to store anything.
return NewValueInterface(nil), nil
case bytes.Equal(data, trueBytes):
return NewValueInterface(true), nil
case bytes.Equal(data, falseBytes):
return NewValueInterface(false), nil
case data[0] == '"':
var result string
err := json.Unmarshal(data, &result)
if err != nil {
return nil, fmt.Errorf("error decoding string from json: %v", err)
}
return NewValueInterface(result), nil
case data[0] == '{':
result := make(map[string]interface{})
err := json.Unmarshal(data, &result)
if err != nil {
return nil, fmt.Errorf("error decoding object from json: %v", err)
}
return NewValueInterface(result), nil
case data[0] == '[':
result := make([]interface{}, 0)
err := json.Unmarshal(data, &result)
if err != nil {
return nil, fmt.Errorf("error decoding array from json: %v", err)
}
return NewValueInterface(result), nil
default:
var (
resultInt int64
resultFloat float64
err error
)
if err = json.Unmarshal(data, &resultInt); err == nil {
return NewValueInterface(resultInt), nil
}
if err = json.Unmarshal(data, &resultFloat); err == nil {
return NewValueInterface(resultFloat), nil
}
return nil, fmt.Errorf("error decoding number from json: %v", err)
}
}

View File

@@ -0,0 +1,177 @@
/*
Copyright 2018 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 value
import (
"fmt"
"sync"
)
var viPool = sync.Pool{
New: func() interface{} {
return &valueUnstructured{}
},
}
// NewValueInterface creates a Value backed by an "interface{}" type,
// typically an unstructured object in Kubernetes world.
// interface{} must be one of: map[string]interface{}, map[interface{}]interface{}, []interface{}, int types, float types,
// string or boolean. Nested interface{} must also be one of these types.
func NewValueInterface(v interface{}) Value {
vi := viPool.Get().(*valueUnstructured)
vi.Value = v
return Value(vi)
}
type valueUnstructured struct {
Value interface{}
}
func (v valueUnstructured) IsMap() bool {
if _, ok := v.Value.(map[string]interface{}); ok {
return true
}
if _, ok := v.Value.(map[interface{}]interface{}); ok {
return true
}
return false
}
func (v valueUnstructured) AsMap() Map {
if v.Value == nil {
panic("invalid nil")
}
switch t := v.Value.(type) {
case map[string]interface{}:
return mapUnstructuredString(t)
case map[interface{}]interface{}:
return mapUnstructuredInterface(t)
}
panic(fmt.Errorf("not a map: %#v", v))
}
func (v valueUnstructured) IsList() bool {
if v.Value == nil {
return false
}
_, ok := v.Value.([]interface{})
return ok
}
func (v valueUnstructured) AsList() List {
return listUnstructured(v.Value.([]interface{}))
}
func (v valueUnstructured) IsFloat() bool {
if v.Value == nil {
return false
} else if _, ok := v.Value.(float64); ok {
return true
} else if _, ok := v.Value.(float32); ok {
return true
}
return false
}
func (v valueUnstructured) AsFloat() float64 {
if f, ok := v.Value.(float32); ok {
return float64(f)
}
return v.Value.(float64)
}
func (v valueUnstructured) IsInt() bool {
if v.Value == nil {
return false
} else if _, ok := v.Value.(int); ok {
return true
} else if _, ok := v.Value.(int8); ok {
return true
} else if _, ok := v.Value.(int16); ok {
return true
} else if _, ok := v.Value.(int32); ok {
return true
} else if _, ok := v.Value.(int64); ok {
return true
} else if _, ok := v.Value.(uint); ok {
return true
} else if _, ok := v.Value.(uint8); ok {
return true
} else if _, ok := v.Value.(uint16); ok {
return true
} else if _, ok := v.Value.(uint32); ok {
return true
}
return false
}
func (v valueUnstructured) AsInt() int64 {
if i, ok := v.Value.(int); ok {
return int64(i)
} else if i, ok := v.Value.(int8); ok {
return int64(i)
} else if i, ok := v.Value.(int16); ok {
return int64(i)
} else if i, ok := v.Value.(int32); ok {
return int64(i)
} else if i, ok := v.Value.(uint); ok {
return int64(i)
} else if i, ok := v.Value.(uint8); ok {
return int64(i)
} else if i, ok := v.Value.(uint16); ok {
return int64(i)
} else if i, ok := v.Value.(uint32); ok {
return int64(i)
}
return v.Value.(int64)
}
func (v valueUnstructured) IsString() bool {
if v.Value == nil {
return false
}
_, ok := v.Value.(string)
return ok
}
func (v valueUnstructured) AsString() string {
return v.Value.(string)
}
func (v valueUnstructured) IsBool() bool {
if v.Value == nil {
return false
}
_, ok := v.Value.(bool)
return ok
}
func (v valueUnstructured) AsBool() bool {
return v.Value.(bool)
}
func (v valueUnstructured) IsNull() bool {
return v.Value == nil
}
func (v *valueUnstructured) Recycle() {
viPool.Put(v)
}
func (v valueUnstructured) Unstructured() interface{} {
return v.Value
}

View File

@@ -1,149 +0,0 @@
/*
Copyright 2019 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 value
import (
"bytes"
"fmt"
jsoniter "github.com/json-iterator/go"
)
var (
readPool = jsoniter.NewIterator(jsoniter.ConfigCompatibleWithStandardLibrary).Pool()
writePool = jsoniter.NewStream(jsoniter.ConfigCompatibleWithStandardLibrary, nil, 1024).Pool()
)
// FromJSONFast is a helper function for reading a JSON document
func FromJSONFast(input []byte) (Value, error) {
iter := readPool.BorrowIterator(input)
defer readPool.ReturnIterator(iter)
return ReadJSONIter(iter)
}
func ReadJSONIter(iter *jsoniter.Iterator) (Value, error) {
next := iter.WhatIsNext()
switch next {
case jsoniter.InvalidValue:
iter.ReportError("reading an object", "got invalid token")
return Value{}, iter.Error
case jsoniter.StringValue:
str := String(iter.ReadString())
return Value{StringValue: &str}, nil
case jsoniter.NumberValue:
number := iter.ReadNumber()
isFloat := false
for _, c := range number {
if c == 'e' || c == 'E' || c == '.' {
isFloat = true
break
}
}
if isFloat {
f, err := number.Float64()
if err != nil {
iter.ReportError("parsing as float", err.Error())
return Value{}, err
}
return Value{FloatValue: (*Float)(&f)}, nil
}
i, err := number.Int64()
if err != nil {
iter.ReportError("parsing as float", err.Error())
return Value{}, err
}
return Value{IntValue: (*Int)(&i)}, nil
case jsoniter.NilValue:
iter.ReadNil()
return Value{Null: true}, nil
case jsoniter.BoolValue:
b := Boolean(iter.ReadBool())
return Value{BooleanValue: &b}, nil
case jsoniter.ArrayValue:
list := &List{}
iter.ReadArrayCB(func(iter *jsoniter.Iterator) bool {
v, err := ReadJSONIter(iter)
if err != nil {
iter.Error = err
return false
}
list.Items = append(list.Items, v)
return true
})
return Value{ListValue: list}, iter.Error
case jsoniter.ObjectValue:
m := &Map{}
iter.ReadObjectCB(func(iter *jsoniter.Iterator, key string) bool {
v, err := ReadJSONIter(iter)
if err != nil {
iter.Error = err
return false
}
m.Items = append(m.Items, Field{Name: key, Value: v})
return true
})
return Value{MapValue: m}, iter.Error
default:
return Value{}, fmt.Errorf("unexpected object type %v", next)
}
}
// ToJSONFast is a helper function for producing a JSon document.
func (v *Value) ToJSONFast() ([]byte, error) {
buf := bytes.Buffer{}
stream := writePool.BorrowStream(&buf)
defer writePool.ReturnStream(stream)
v.WriteJSONStream(stream)
err := stream.Flush()
return buf.Bytes(), err
}
func (v *Value) WriteJSONStream(stream *jsoniter.Stream) {
switch {
case v.Null:
stream.WriteNil()
case v.FloatValue != nil:
stream.WriteFloat64(float64(*v.FloatValue))
case v.IntValue != nil:
stream.WriteInt64(int64(*v.IntValue))
case v.BooleanValue != nil:
stream.WriteBool(bool(*v.BooleanValue))
case v.StringValue != nil:
stream.WriteString(string(*v.StringValue))
case v.ListValue != nil:
stream.WriteArrayStart()
for i := range v.ListValue.Items {
if i > 0 {
stream.WriteMore()
}
v.ListValue.Items[i].WriteJSONStream(stream)
}
stream.WriteArrayEnd()
case v.MapValue != nil:
stream.WriteObjectStart()
for i := range v.MapValue.Items {
if i > 0 {
stream.WriteMore()
}
stream.WriteObjectField(v.MapValue.Items[i].Name)
v.MapValue.Items[i].Value.WriteJSONStream(stream)
}
stream.WriteObjectEnd()
default:
stream.Write([]byte("invalid_value"))
}
}

View File

@@ -1,234 +0,0 @@
/*
Copyright 2018 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 value
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
)
// FromYAML is a helper function for reading a YAML document; it attempts to
// preserve order of keys within maps/structs. This is as a convenience to
// humans keeping YAML documents, not because there is a behavior difference.
//
// Known bug: objects with top-level arrays don't parse correctly.
func FromYAML(input []byte) (Value, error) {
var decoded interface{}
if len(input) == 4 && string(input) == "null" {
// Special case since the yaml package doesn't accurately
// preserve this.
return Value{Null: true}, nil
}
// This attempts to enable order sensitivity; note the yaml package is
// broken for documents that have root-level arrays, hence the two-step
// approach. TODO: This is a horrific hack. Is it worth it?
var ms yaml.MapSlice
if err := yaml.Unmarshal(input, &ms); err == nil {
decoded = ms
} else if err := yaml.Unmarshal(input, &decoded); err != nil {
return Value{}, err
}
v, err := FromUnstructured(decoded)
if err != nil {
return Value{}, fmt.Errorf("failed to interpret (%v):\n%s", err, input)
}
return v, nil
}
// FromJSON is a helper function for reading a JSON document
func FromJSON(input []byte) (Value, error) {
var decoded interface{}
if err := json.Unmarshal(input, &decoded); err != nil {
return Value{}, err
}
v, err := FromUnstructured(decoded)
if err != nil {
return Value{}, fmt.Errorf("failed to interpret (%v):\n%s", err, input)
}
return v, nil
}
// FromUnstructured will convert a go interface to a Value.
// It's most commonly expected to be used with map[string]interface{} as the
// input. `in` must not have any structures with cycles in them.
// yaml.MapSlice may be used for order-preservation.
func FromUnstructured(in interface{}) (Value, error) {
if in == nil {
return Value{Null: true}, nil
}
switch t := in.(type) {
case map[interface{}]interface{}:
m := Map{}
for rawKey, rawVal := range t {
k, ok := rawKey.(string)
if !ok {
return Value{}, fmt.Errorf("key %#v: not a string", k)
}
v, err := FromUnstructured(rawVal)
if err != nil {
return Value{}, fmt.Errorf("key %v: %v", k, err)
}
m.Set(k, v)
}
return Value{MapValue: &m}, nil
case map[string]interface{}:
m := Map{}
for k, rawVal := range t {
v, err := FromUnstructured(rawVal)
if err != nil {
return Value{}, fmt.Errorf("key %v: %v", k, err)
}
m.Set(k, v)
}
return Value{MapValue: &m}, nil
case yaml.MapSlice:
m := Map{}
for _, item := range t {
k, ok := item.Key.(string)
if !ok {
return Value{}, fmt.Errorf("key %#v is not a string", item.Key)
}
v, err := FromUnstructured(item.Value)
if err != nil {
return Value{}, fmt.Errorf("key %v: %v", k, err)
}
m.Set(k, v)
}
return Value{MapValue: &m}, nil
case []interface{}:
l := List{}
for i, rawVal := range t {
v, err := FromUnstructured(rawVal)
if err != nil {
return Value{}, fmt.Errorf("index %v: %v", i, err)
}
l.Items = append(l.Items, v)
}
return Value{ListValue: &l}, nil
case int:
n := Int(t)
return Value{IntValue: &n}, nil
case int8:
n := Int(t)
return Value{IntValue: &n}, nil
case int16:
n := Int(t)
return Value{IntValue: &n}, nil
case int32:
n := Int(t)
return Value{IntValue: &n}, nil
case int64:
n := Int(t)
return Value{IntValue: &n}, nil
case uint:
n := Int(t)
return Value{IntValue: &n}, nil
case uint8:
n := Int(t)
return Value{IntValue: &n}, nil
case uint16:
n := Int(t)
return Value{IntValue: &n}, nil
case uint32:
n := Int(t)
return Value{IntValue: &n}, nil
case float32:
f := Float(t)
return Value{FloatValue: &f}, nil
case float64:
f := Float(t)
return Value{FloatValue: &f}, nil
case string:
return StringValue(t), nil
case bool:
return BooleanValue(t), nil
default:
return Value{}, fmt.Errorf("type unimplemented: %t", in)
}
}
// ToYAML is a helper function for producing a YAML document; it attempts to
// preserve order of keys within maps/structs. This is as a convenience to
// humans keeping YAML documents, not because there is a behavior difference.
func (v *Value) ToYAML() ([]byte, error) {
return yaml.Marshal(v.ToUnstructured(true))
}
// ToJSON is a helper function for producing a JSon document.
func (v *Value) ToJSON() ([]byte, error) {
return json.Marshal(v.ToUnstructured(false))
}
// ToUnstructured will convert the Value into a go-typed object.
// If preserveOrder is true, then maps will be converted to the yaml.MapSlice
// type. Otherwise, map[string]interface{} must be used-- this destroys
// ordering information and is not recommended if the result of this will be
// serialized. Other types:
// * list -> []interface{}
// * others -> corresponding go type, wrapped in an interface{}
//
// Of note, floats and ints will always come out as float64 and int64,
// respectively.
func (v *Value) ToUnstructured(preserveOrder bool) interface{} {
switch {
case v.FloatValue != nil:
f := float64(*v.FloatValue)
return f
case v.IntValue != nil:
i := int64(*v.IntValue)
return i
case v.StringValue != nil:
return string(*v.StringValue)
case v.BooleanValue != nil:
return bool(*v.BooleanValue)
case v.ListValue != nil:
out := []interface{}{}
for _, item := range v.ListValue.Items {
out = append(out, item.ToUnstructured(preserveOrder))
}
return out
case v.MapValue != nil:
m := v.MapValue
if preserveOrder {
ms := make(yaml.MapSlice, len(m.Items))
for i := range m.Items {
ms[i] = yaml.MapItem{
Key: m.Items[i].Name,
Value: m.Items[i].Value.ToUnstructured(preserveOrder),
}
}
return ms
}
// This case is unavoidably lossy.
out := map[string]interface{}{}
for i := range m.Items {
out[m.Items[i].Name] = m.Items[i].Value.ToUnstructured(preserveOrder)
}
return out
default:
fallthrough
case v.Null == true:
return nil
}
}

View File

@@ -1,538 +0,0 @@
/*
Copyright 2018 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 value
import (
"fmt"
"sort"
"strings"
)
// A Value is an object; it corresponds to an 'atom' in the schema.
type Value struct {
// Exactly one of the below must be set.
FloatValue *Float
IntValue *Int
StringValue *String
BooleanValue *Boolean
ListValue *List
MapValue *Map
Null bool // represents an explicit `"foo" = null`
}
// Equals returns true iff the two values are equal.
func (v Value) Equals(rhs Value) bool {
if v.FloatValue != nil || rhs.FloatValue != nil {
var lf float64
if v.FloatValue != nil {
lf = float64(*v.FloatValue)
} else if v.IntValue != nil {
lf = float64(*v.IntValue)
} else {
return false
}
var rf float64
if rhs.FloatValue != nil {
rf = float64(*rhs.FloatValue)
} else if rhs.IntValue != nil {
rf = float64(*rhs.IntValue)
} else {
return false
}
return lf == rf
}
if v.IntValue != nil {
if rhs.IntValue != nil {
return *v.IntValue == *rhs.IntValue
}
return false
}
if v.StringValue != nil {
if rhs.StringValue != nil {
return *v.StringValue == *rhs.StringValue
}
return false
}
if v.BooleanValue != nil {
if rhs.BooleanValue != nil {
return *v.BooleanValue == *rhs.BooleanValue
}
return false
}
if v.ListValue != nil {
if rhs.ListValue != nil {
return v.ListValue.Equals(rhs.ListValue)
}
return false
}
if v.MapValue != nil {
if rhs.MapValue != nil {
return v.MapValue.Equals(rhs.MapValue)
}
return false
}
if v.Null {
if rhs.Null {
return true
}
return false
}
// No field is set, on either objects.
return true
}
// Less provides a total ordering for Value (so that they can be sorted, even
// if they are of different types).
func (v Value) Less(rhs Value) bool {
return v.Compare(rhs) == -1
}
// Compare provides a total ordering for Value (so that they can be
// sorted, even if they are of different types). The result will be 0 if
// v==rhs, -1 if v < rhs, and +1 if v > rhs.
func (v Value) Compare(rhs Value) int {
if v.FloatValue != nil {
if rhs.FloatValue == nil {
// Extra: compare floats and ints numerically.
if rhs.IntValue != nil {
return v.FloatValue.Compare(Float(*rhs.IntValue))
}
return -1
}
return v.FloatValue.Compare(*rhs.FloatValue)
} else if rhs.FloatValue != nil {
// Extra: compare floats and ints numerically.
if v.IntValue != nil {
return Float(*v.IntValue).Compare(*rhs.FloatValue)
}
return 1
}
if v.IntValue != nil {
if rhs.IntValue == nil {
return -1
}
return v.IntValue.Compare(*rhs.IntValue)
} else if rhs.IntValue != nil {
return 1
}
if v.StringValue != nil {
if rhs.StringValue == nil {
return -1
}
return strings.Compare(string(*v.StringValue), string(*rhs.StringValue))
} else if rhs.StringValue != nil {
return 1
}
if v.BooleanValue != nil {
if rhs.BooleanValue == nil {
return -1
}
return v.BooleanValue.Compare(*rhs.BooleanValue)
} else if rhs.BooleanValue != nil {
return 1
}
if v.ListValue != nil {
if rhs.ListValue == nil {
return -1
}
return v.ListValue.Compare(rhs.ListValue)
} else if rhs.ListValue != nil {
return 1
}
if v.MapValue != nil {
if rhs.MapValue == nil {
return -1
}
return v.MapValue.Compare(rhs.MapValue)
} else if rhs.MapValue != nil {
return 1
}
if v.Null {
if !rhs.Null {
return -1
}
return 0
} else if rhs.Null {
return 1
}
// Invalid Value-- nothing is set.
return 0
}
type Int int64
type Float float64
type String string
type Boolean bool
// Compare compares integers. The result will be 0 if i==rhs, -1 if i <
// rhs, and +1 if i > rhs.
func (i Int) Compare(rhs Int) int {
if i > rhs {
return 1
} else if i < rhs {
return -1
}
return 0
}
// Compare compares floats. The result will be 0 if f==rhs, -1 if f <
// rhs, and +1 if f > rhs.
func (f Float) Compare(rhs Float) int {
if f > rhs {
return 1
} else if f < rhs {
return -1
}
return 0
}
// Compare compares booleans. The result will be 0 if b==rhs, -1 if b <
// rhs, and +1 if b > rhs.
func (b Boolean) Compare(rhs Boolean) int {
if b == rhs {
return 0
} else if b == false {
return -1
}
return 1
}
// Field is an individual key-value pair.
type Field struct {
Name string
Value Value
}
// FieldList is a list of key-value pairs. Each field is expected to
// have a different name.
type FieldList []Field
// Sort sorts the field list by Name.
func (f FieldList) Sort() {
if len(f) < 2 {
return
}
if len(f) == 2 {
if f[1].Name < f[0].Name {
f[0], f[1] = f[1], f[0]
}
return
}
sort.SliceStable(f, func(i, j int) bool {
return f[i].Name < f[j].Name
})
}
// Less compares two lists lexically.
func (f FieldList) Less(rhs FieldList) bool {
return f.Compare(rhs) == -1
}
// Less compares two lists lexically. The result will be 0 if f==rhs, -1
// if f < rhs, and +1 if f > rhs.
func (f FieldList) Compare(rhs FieldList) int {
i := 0
for {
if i >= len(f) && i >= len(rhs) {
// Maps are the same length and all items are equal.
return 0
}
if i >= len(f) {
// F is shorter.
return -1
}
if i >= len(rhs) {
// RHS is shorter.
return 1
}
if c := strings.Compare(f[i].Name, rhs[i].Name); c != 0 {
return c
}
if c := f[i].Value.Compare(rhs[i].Value); c != 0 {
return c
}
// The items are equal; continue.
i++
}
}
// List is a list of items.
type List struct {
Items []Value
}
// Equals compares two lists lexically.
func (l *List) Equals(rhs *List) bool {
if len(l.Items) != len(rhs.Items) {
return false
}
for i, lv := range l.Items {
if !lv.Equals(rhs.Items[i]) {
return false
}
}
return true
}
// Less compares two lists lexically.
func (l *List) Less(rhs *List) bool {
return l.Compare(rhs) == -1
}
// Compare compares two lists lexically. The result will be 0 if l==rhs, -1
// if l < rhs, and +1 if l > rhs.
func (l *List) Compare(rhs *List) int {
i := 0
for {
if i >= len(l.Items) && i >= len(rhs.Items) {
// Lists are the same length and all items are equal.
return 0
}
if i >= len(l.Items) {
// LHS is shorter.
return -1
}
if i >= len(rhs.Items) {
// RHS is shorter.
return 1
}
if c := l.Items[i].Compare(rhs.Items[i]); c != 0 {
return c
}
// The items are equal; continue.
i++
}
}
// Map is a map of key-value pairs. It represents both structs and maps. We use
// a list and a go-language map to preserve order.
//
// Set and Get helpers are provided.
type Map struct {
Items []Field
// may be nil; lazily constructed.
// TODO: Direct modifications to Items above will cause serious problems.
index map[string]int
// may be empty; lazily constructed.
// TODO: Direct modifications to Items above will cause serious problems.
order []int
}
func (m *Map) computeOrder() []int {
if len(m.order) != len(m.Items) {
m.order = make([]int, len(m.Items))
for i := range m.order {
m.order[i] = i
}
sort.SliceStable(m.order, func(i, j int) bool {
return m.Items[m.order[i]].Name < m.Items[m.order[j]].Name
})
}
return m.order
}
// Equals compares two maps lexically.
func (m *Map) Equals(rhs *Map) bool {
if len(m.Items) != len(rhs.Items) {
return false
}
for _, lfield := range m.Items {
rfield, ok := rhs.Get(lfield.Name)
if !ok {
return false
}
if !lfield.Value.Equals(rfield.Value) {
return false
}
}
return true
}
// Less compares two maps lexically.
func (m *Map) Less(rhs *Map) bool {
return m.Compare(rhs) == -1
}
// Compare compares two maps lexically.
func (m *Map) Compare(rhs *Map) int {
var noAllocL, noAllocR [2]int
var morder, rorder []int
// For very short maps (<2 elements) this permits us to avoid
// allocating the order array. We could make this accomodate larger
// maps, but 2 items should be enough to cover most path element
// comparisons, and at some point there will be diminishing returns.
// This has a large effect on the path element deserialization test,
// because everything is sorted / compared, but only once.
switch len(m.Items) {
case 0:
morder = noAllocL[0:0]
case 1:
morder = noAllocL[0:1]
case 2:
morder = noAllocL[0:2]
if m.Items[0].Name > m.Items[1].Name {
morder[0] = 1
} else {
morder[1] = 1
}
default:
morder = m.computeOrder()
}
switch len(rhs.Items) {
case 0:
rorder = noAllocR[0:0]
case 1:
rorder = noAllocR[0:1]
case 2:
rorder = noAllocR[0:2]
if rhs.Items[0].Name > rhs.Items[1].Name {
rorder[0] = 1
} else {
rorder[1] = 1
}
default:
rorder = rhs.computeOrder()
}
i := 0
for {
if i >= len(morder) && i >= len(rorder) {
// Maps are the same length and all items are equal.
return 0
}
if i >= len(morder) {
// LHS is shorter.
return -1
}
if i >= len(rorder) {
// RHS is shorter.
return 1
}
fa, fb := &m.Items[morder[i]], &rhs.Items[rorder[i]]
if c := strings.Compare(fa.Name, fb.Name); c != 0 {
return c
}
if c := fa.Value.Compare(fb.Value); c != 0 {
return c
}
// The items are equal; continue.
i++
}
}
// Get returns the (Field, true) or (nil, false) if it is not present
func (m *Map) Get(key string) (*Field, bool) {
if m.index == nil {
m.index = map[string]int{}
for i := range m.Items {
m.index[m.Items[i].Name] = i
}
}
f, ok := m.index[key]
if !ok {
return nil, false
}
return &m.Items[f], true
}
// Set inserts or updates the given item.
func (m *Map) Set(key string, value Value) {
if f, ok := m.Get(key); ok {
f.Value = value
return
}
m.Items = append(m.Items, Field{Name: key, Value: value})
i := len(m.Items) - 1
m.index[key] = i
m.order = nil
}
// Delete removes the key from the set.
func (m *Map) Delete(key string) {
items := []Field{}
for i := range m.Items {
if m.Items[i].Name != key {
items = append(items, m.Items[i])
}
}
m.Items = items
m.index = nil // Since the list has changed
m.order = nil
}
// StringValue returns s as a scalar string Value.
func StringValue(s string) Value {
s2 := String(s)
return Value{StringValue: &s2}
}
// IntValue returns i as a scalar numeric (integer) Value.
func IntValue(i int) Value {
i2 := Int(i)
return Value{IntValue: &i2}
}
// FloatValue returns f as a scalar numeric (float) Value.
func FloatValue(f float64) Value {
f2 := Float(f)
return Value{FloatValue: &f2}
}
// BooleanValue returns b as a scalar boolean Value.
func BooleanValue(b bool) Value {
b2 := Boolean(b)
return Value{BooleanValue: &b2}
}
// String returns a human-readable representation of the value.
func (v Value) String() string {
switch {
case v.FloatValue != nil:
return fmt.Sprintf("%v", *v.FloatValue)
case v.IntValue != nil:
return fmt.Sprintf("%v", *v.IntValue)
case v.StringValue != nil:
return fmt.Sprintf("%q", *v.StringValue)
case v.BooleanValue != nil:
return fmt.Sprintf("%v", *v.BooleanValue)
case v.ListValue != nil:
strs := []string{}
for _, item := range v.ListValue.Items {
strs = append(strs, item.String())
}
return "[" + strings.Join(strs, ",") + "]"
case v.MapValue != nil:
strs := []string{}
for _, i := range v.MapValue.Items {
strs = append(strs, fmt.Sprintf("%v=%v", i.Name, i.Value))
}
return "{" + strings.Join(strs, ";") + "}"
default:
fallthrough
case v.Null == true:
return "null"
}
}