Fixed length of null to be zero

This commit is contained in:
Mike Farah 2021-01-26 10:21:16 +11:00
parent 61f569aebb
commit 820a3320be
3 changed files with 43 additions and 1 deletions

View File

@ -16,6 +16,20 @@ will output
3 3
``` ```
## null length
Given a sample.yml file of:
```yaml
a: null
```
then
```bash
yq eval '.a | length' sample.yml
```
will output
```yaml
0
```
## Map length ## Map length
returns number of entries returns number of entries

View File

@ -17,7 +17,11 @@ func lengthOperator(d *dataTreeNavigator, matchMap *list.List, expressionNode *E
var length int var length int
switch targetNode.Kind { switch targetNode.Kind {
case yaml.ScalarNode: case yaml.ScalarNode:
if targetNode.Tag == "!!null" {
length = 0
} else {
length = len(targetNode.Value) length = len(targetNode.Value)
}
case yaml.MappingNode: case yaml.MappingNode:
length = len(targetNode.Content) / 2 length = len(targetNode.Content) / 2
case yaml.SequenceNode: case yaml.SequenceNode:

View File

@ -14,6 +14,30 @@ var lengthOperatorScenarios = []expressionScenario{
"D0, P[a], (!!int)::3\n", "D0, P[a], (!!int)::3\n",
}, },
}, },
{
description: "null length",
document: `{a: null}`,
expression: `.a | length`,
expected: []string{
"D0, P[a], (!!int)::0\n",
},
},
{
skipDoc: true,
document: `{a: ~}`,
expression: `.a | length`,
expected: []string{
"D0, P[a], (!!int)::0\n",
},
},
{
skipDoc: true,
document: `{a: key no exist}`,
expression: `.b | length`,
expected: []string{
"D0, P[b], (!!int)::0\n",
},
},
{ {
description: "Map length", description: "Map length",
subdescription: "returns number of entries", subdescription: "returns number of entries",