changed handling of empty values

This commit is contained in:
Natasha Sarkar
2020-11-06 11:42:17 -08:00
parent 9f06376ab2
commit 73d91dda6e
2 changed files with 9 additions and 39 deletions

View File

@@ -48,6 +48,7 @@ func (a ElementAppender) Filter(rn *RNode) (*RNode, error) {
// not designed for this purpose. To append an element, please use ElementAppender.
// To replace, set the key-value pair and a non-nil Element.
// To delete, set the key-value pair and leave the Element as nil.
// Every key must have a corresponding value.
type ElementSetter struct {
Kind string `yaml:"kind,omitempty"`
@@ -78,9 +79,6 @@ func (e ElementSetter) Filter(rn *RNode) (*RNode, error) {
if len(e.Keys) == 0 {
e.Keys = append(e.Keys, "")
}
if len(e.Values) == 0 {
e.Values = append(e.Values, "")
}
if err := ErrorIfInvalid(rn, SequenceNode); err != nil {
return nil, err
@@ -103,16 +101,16 @@ func (e ElementSetter) Filter(rn *RNode) (*RNode, error) {
continue
}
if len(e.Keys) > len(e.Values) {
return nil, fmt.Errorf("cannot have more keys than values")
}
// check if this is the element we are matching
var val *RNode
var err error
found := true
for j := range e.Keys {
val, err = newNode.Pipe(FieldMatcher{Name: e.Keys[j], StringValue: e.Values[j]})
if j >= len(e.Values) {
val, err = newNode.Pipe(FieldMatcher{Name: e.Keys[j], StringValue: ""})
} else {
val, err = newNode.Pipe(FieldMatcher{Name: e.Keys[j], StringValue: e.Values[j]})
}
if err != nil {
return nil, err
}
@@ -123,7 +121,9 @@ func (e ElementSetter) Filter(rn *RNode) (*RNode, error) {
}
if !found {
// not the element we are looking for, keep it in the Content
newContent = append(newContent, elem)
if len(e.Values) > 0 {
newContent = append(newContent, elem)
}
continue
}
matchingElementFound = true

View File

@@ -132,22 +132,6 @@ func TestElementSetter(t *testing.T) {
_, err = node.Pipe(ElementSetter{Keys: []string{"a"}})
assert.EqualError(t, err, "wrong Node Kind for expected: MappingNode was ScalarNode: value: {scalarValue}")
node = MustParse(`
- a: b
- c: d
`)
// {a: b} is removed since the value is omitted and only key is used
// to match and no Element specified.
rn, err = node.Pipe(ElementSetter{Keys: []string{"a"}})
assert.NoError(t, err)
assert.Nil(t, rn)
assert.Equal(t, `- c: d
`, assertNoErrorString(t)(node.String()))
node = MustParse(`
- a: b
- c: d
`)
// Return error because ElementSetter will assume all elements are scalar when
// there is only value provided.
_, err = node.Pipe(ElementSetter{Values: []string{"b"}})
@@ -342,20 +326,6 @@ func TestElementSetterMultipleKeys(t *testing.T) {
- e: f
- g: h
`, assertNoErrorString(t)(node.String()))
node = orig.Copy()
// Should return an error
// keys and values are not the same length
newElement = NewMapRNode(&map[string]string{
"g": "h",
})
rn, err = node.Pipe(ElementSetter{
Keys: []string{"a", "c"},
Values: []string{"b"},
Element: newElement.YNode(),
})
assert.Error(t, err)
assert.Nil(t, rn)
}
func TestElementMatcherWithNoValue(t *testing.T) {