Skip to content

Commit a64eea3

Browse files
committed
Fixed bug in alternative op, dont evaluate RHS if LHS is truthy
1 parent a12c1a6 commit a64eea3

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed

pkg/yqlib/doc/operators/alternative-default-value.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,36 @@ will output
7979
cat
8080
```
8181

82+
## Update or create - entity exists
83+
This initialises `a` if it's not present
84+
85+
Given a sample.yml file of:
86+
```yaml
87+
a: 1
88+
```
89+
then
90+
```bash
91+
yq '(.a // (.a = 0)) += 1' sample.yml
92+
```
93+
will output
94+
```yaml
95+
a: 2
96+
```
97+
98+
## Update or create - entity does not exist
99+
This initialises `a` if it's not present
100+
101+
Given a sample.yml file of:
102+
```yaml
103+
b: camel
104+
```
105+
then
106+
```bash
107+
yq '(.a // (.a = 0)) += 1' sample.yml
108+
```
109+
will output
110+
```yaml
111+
b: camel
112+
a: 1
113+
```
114+

pkg/yqlib/operator_alternative.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,24 @@ package yqlib
22

33
func alternativeOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
44
log.Debugf("-- alternative")
5-
return crossFunction(d, context, expressionNode, alternativeFunc, true)
5+
prefs := crossFunctionPreferences{
6+
CalcWhenEmpty: true,
7+
Calculation: alternativeFunc,
8+
LhsResultValue: func(lhs *CandidateNode) (*CandidateNode, error) {
9+
if lhs == nil {
10+
return nil, nil
11+
}
12+
truthy, err := isTruthy(lhs)
13+
if err != nil {
14+
return nil, err
15+
}
16+
if truthy {
17+
return lhs, nil
18+
}
19+
return nil, nil
20+
},
21+
}
22+
return crossFunctionWithPrefs(d, context, expressionNode, prefs)
623
}
724

825
func alternativeFunc(d *dataTreeNavigator, context Context, lhs *CandidateNode, rhs *CandidateNode) (*CandidateNode, error) {

pkg/yqlib/operator_alternative_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ var alternativeOperatorScenarios = []expressionScenario{
8585
"D0, P[], (!!bool)::true\n",
8686
},
8787
},
88+
{
89+
description: "Update or create - entity exists",
90+
subdescription: "This initialises `a` if it's not present",
91+
expression: "(.a // (.a = 0)) += 1",
92+
document: `a: 1`,
93+
expected: []string{
94+
"D0, P[], (doc)::a: 2\n",
95+
},
96+
},
97+
{
98+
description: "Update or create - entity does not exist",
99+
subdescription: "This initialises `a` if it's not present",
100+
expression: "(.a // (.a = 0)) += 1",
101+
document: `b: camel`,
102+
expected: []string{
103+
"D0, P[], (!!map)::b: camel\na: 1\n",
104+
},
105+
},
88106
}
89107

90108
func TestAlternativeOperatorScenarios(t *testing.T) {

0 commit comments

Comments
 (0)