yq/pkg/yqlib/operator_length.go

37 lines
853 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)
2023-04-08 10:17:13 +00:00
targetNode := candidate.unwrapDocument()
var length int
switch targetNode.Kind {
2023-04-08 10:17:13 +00:00
case ScalarNode:
2021-01-25 23:21:16 +00:00
if targetNode.Tag == "!!null" {
length = 0
} else {
length = len(targetNode.Value)
}
2023-04-08 10:17:13 +00:00
case MappingNode:
length = len(targetNode.Content) / 2
2023-04-08 10:17:13 +00:00
case SequenceNode:
length = len(targetNode.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
}