yq/pkg/yqlib/operator_length.go

40 lines
943 B
Go
Raw Normal View History

package yqlib
import (
"container/list"
"fmt"
yaml "gopkg.in/yaml.v3"
)
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)
2021-01-12 23:00:51 +00:00
targetNode := unwrapDoc(candidate.Node)
var length int
switch targetNode.Kind {
case yaml.ScalarNode:
2021-01-25 23:21:16 +00:00
if targetNode.Tag == "!!null" {
length = 0
} else {
length = len(targetNode.Value)
}
case yaml.MappingNode:
length = len(targetNode.Content) / 2
case yaml.SequenceNode:
length = len(targetNode.Content)
default:
length = 0
}
node := &yaml.Node{Kind: yaml.ScalarNode, Value: fmt.Sprintf("%v", length), Tag: "!!int"}
2021-11-23 22:57:35 +00:00
result := candidate.CreateReplacement(node)
results.PushBack(result)
}
return context.ChildContext(results), nil
}