yq/pkg/yqlib/operator_length.go

36 lines
805 B
Go
Raw Normal View History

package yqlib
import (
"container/list"
"fmt"
)
func lengthOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
log.Debugf("-- lengthOperation")
var results = list.New()
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
var length int
2023-06-07 17:45:42 +00:00
switch candidate.Kind {
2023-04-08 10:17:13 +00:00
case ScalarNode:
2023-06-07 17:45:42 +00:00
if candidate.Tag == "!!null" {
2021-01-25 23:21:16 +00:00
length = 0
} else {
2023-06-07 17:45:42 +00:00
length = len(candidate.Value)
2021-01-25 23:21:16 +00:00
}
2023-04-08 10:17:13 +00:00
case MappingNode:
2023-06-07 17:45:42 +00:00
length = len(candidate.Content) / 2
2023-04-08 10:17:13 +00:00
case SequenceNode:
2023-06-07 17:45:42 +00:00
length = len(candidate.Content)
default:
length = 0
}
2023-04-08 11:27:47 +00:00
result := candidate.CreateReplacement(ScalarNode, "!!int", fmt.Sprintf("%v", length))
results.PushBack(result)
}
return context.ChildContext(results), nil
}