diff --git a/pkg/yqlib/doc/Add.md b/pkg/yqlib/doc/Add.md index e7fd6b26..e2cfa945 100644 --- a/pkg/yqlib/doc/Add.md +++ b/pkg/yqlib/doc/Add.md @@ -209,3 +209,15 @@ will output a: 4 ``` +## Add to null +Adding to null simply returns the rhs + +Running +```bash +yq eval --null-input 'null + "cat"' +``` +will output +```yaml +cat +``` + diff --git a/pkg/yqlib/operator_add.go b/pkg/yqlib/operator_add.go index d8ead709..90eafb0f 100644 --- a/pkg/yqlib/operator_add.go +++ b/pkg/yqlib/operator_add.go @@ -47,9 +47,14 @@ func add(d *dataTreeNavigator, lhs *CandidateNode, rhs *CandidateNode) (*Candida lhs.Node = unwrapDoc(lhs.Node) rhs.Node = unwrapDoc(rhs.Node) - target := lhs.CreateChild(nil, &yaml.Node{}) lhsNode := lhs.Node + if lhsNode.Tag == "!!null" { + return lhs.CreateChild(nil, rhs.Node), nil + } + + target := lhs.CreateChild(nil, &yaml.Node{}) + switch lhsNode.Kind { case yaml.MappingNode: return nil, fmt.Errorf("Maps not yet supported for addition") diff --git a/pkg/yqlib/operator_add_test.go b/pkg/yqlib/operator_add_test.go index d3001192..2d11f202 100644 --- a/pkg/yqlib/operator_add_test.go +++ b/pkg/yqlib/operator_add_test.go @@ -112,6 +112,14 @@ var addOperatorScenarios = []expressionScenario{ "D0, P[], (doc)::{a: 4}\n", }, }, + { + description: "Add to null", + subdescription: "Adding to null simply returns the rhs", + expression: `null + "cat"`, + expected: []string{ + "D0, P[], (!!str)::cat\n", + }, + }, } func TestAddOperatorScenarios(t *testing.T) { diff --git a/pkg/yqlib/operator_multiply_test.go b/pkg/yqlib/operator_multiply_test.go index 1794cec1..a9ef9ac9 100644 --- a/pkg/yqlib/operator_multiply_test.go +++ b/pkg/yqlib/operator_multiply_test.go @@ -144,6 +144,14 @@ b: "D0, P[a], (!!seq)::[{thing: two}]\n", }, }, + { + skipDoc: true, + document: `{a: {array: [1]}, b: {}}`, + expression: `.b *+ .a`, + expected: []string{ + "D0, P[b], (!!map)::{array: [1]}\n", + }, + }, { description: "Merge, appending arrays", document: `{a: {array: [1, 2, animal: dog], value: coconut}, b: {array: [3, 4, animal: cat], value: banana}}`,