Add Absorb method to VarSet and DeepEqual to Var

This commit is contained in:
Jerome Brette
2019-07-06 08:54:42 -05:00
parent ffd95ef5a9
commit abc419b5f9
2 changed files with 55 additions and 3 deletions

View File

@@ -6,7 +6,6 @@ package target_test
import (
"encoding/base64"
"fmt"
"reflect"
"strings"
"testing"
@@ -334,7 +333,7 @@ vars:
t.Fatalf("unexpected size %d", len(vars))
}
for i := range vars[:2] {
if !reflect.DeepEqual(vars[i], someVars[i]) {
if !vars[i].DeepEqual(someVars[i]) {
t.Fatalf("unexpected var[%d]:\n %v\n %v", i, vars[i], someVars[i])
}
}
@@ -387,7 +386,7 @@ resources:
t.Fatalf("expected 4 vars, got %d", len(vars))
}
for i := range vars {
if !reflect.DeepEqual(vars[i], someVars[i]) {
if !vars[i].DeepEqual(someVars[i]) {
t.Fatalf("unexpected var[%d]:\n %v\n %v", i, vars[i], someVars[i])
}
}

View File

@@ -18,6 +18,7 @@ package types
import (
"fmt"
"reflect"
"sort"
"strings"
@@ -71,6 +72,19 @@ func (v *Var) defaulting() {
}
}
// VarEquals returns true if var a and b are Equals.
func (v Var) DeepEqual(other Var) bool {
v.ObjRef.GVK()
if v.FieldRef.FieldPath == "" {
v.FieldRef.FieldPath = "metadata.name"
}
other.ObjRef.GVK()
if other.FieldRef.FieldPath == "" {
other.FieldRef.FieldPath = "metadata.name"
}
return reflect.DeepEqual(v, other)
}
// VarSet is a set of Vars where no var.Name is repeated.
type VarSet struct {
set map[string]Var
@@ -135,6 +149,45 @@ func (vs *VarSet) Merge(v Var) error {
return nil
}
// AbsorbSet absorbs other vars with error on (name,value) collision.
func (vs *VarSet) AbsorbSet(incoming VarSet) error {
for _, v := range incoming.set {
vs.Absorb(v)
}
return nil
}
// AbsorbSlice absorbs a Var slice with error on (name,value) collision.
// Empty fields in incoming vars are defaulted.
func (vs *VarSet) AbsorbSlice(incoming []Var) error {
for _, v := range incoming {
if err := vs.Absorb(v); err != nil {
return err
}
}
return nil
}
// Absorb absorbs another Var with error on (name,value) collision.
// Empty fields in incoming Var is defaulted.
func (vs *VarSet) Absorb(v Var) error {
conflicting := vs.Get(v.Name)
if conflicting == nil {
// no conflict. The var is valid.
v.defaulting()
vs.set[v.Name] = v
return nil
}
if !v.DeepEqual(*conflicting) {
// two vars with the same name are pointing at two
// different resources.
return fmt.Errorf(
"var '%s' already encountered", v.Name)
}
return nil
}
// Contains is true if the set has the other var.
func (vs *VarSet) Contains(other Var) bool {
return vs.Get(other.Name) != nil