yq/pkg/yqlib/treeops/operators.go

60 lines
1.6 KiB
Go
Raw Normal View History

2020-10-10 04:00:39 +00:00
package treeops
2020-10-11 00:45:20 +00:00
import (
2020-10-21 01:54:58 +00:00
"container/list"
2020-10-12 01:24:59 +00:00
"fmt"
2020-10-11 00:45:20 +00:00
"gopkg.in/yaml.v3"
)
2020-10-10 04:00:39 +00:00
2020-10-21 01:54:58 +00:00
type OperatorHandler func(d *dataTreeNavigator, matchingNodes *list.List, pathNode *PathTreeNode) (*list.List, error)
2020-10-10 04:00:39 +00:00
2020-10-21 01:54:58 +00:00
func PipeOperator(d *dataTreeNavigator, matchingNodes *list.List, pathNode *PathTreeNode) (*list.List, error) {
2020-10-10 04:00:39 +00:00
lhs, err := d.getMatchingNodes(matchingNodes, pathNode.Lhs)
if err != nil {
return nil, err
}
return d.getMatchingNodes(lhs, pathNode.Rhs)
}
2020-10-17 11:10:47 +00:00
func createBooleanCandidate(owner *CandidateNode, value bool) *CandidateNode {
valString := "true"
if !value {
valString = "false"
}
node := &yaml.Node{Kind: yaml.ScalarNode, Value: valString, Tag: "!!bool"}
return &CandidateNode{Node: node, Document: owner.Document, Path: owner.Path}
}
2020-10-21 01:54:58 +00:00
func nodeToMap(candidate *CandidateNode) *list.List {
elMap := list.New()
elMap.PushBack(candidate)
2020-10-16 01:29:26 +00:00
return elMap
}
2020-10-21 01:54:58 +00:00
func LengthOperator(d *dataTreeNavigator, matchMap *list.List, pathNode *PathTreeNode) (*list.List, error) {
2020-10-16 01:29:26 +00:00
log.Debugf("-- lengthOperation")
2020-10-21 01:54:58 +00:00
var results = list.New()
2020-10-12 01:24:59 +00:00
for el := matchMap.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
2020-10-16 01:29:26 +00:00
var length int
switch candidate.Node.Kind {
case yaml.ScalarNode:
length = len(candidate.Node.Value)
case yaml.MappingNode:
length = len(candidate.Node.Content) / 2
case yaml.SequenceNode:
length = len(candidate.Node.Content)
default:
length = 0
2020-10-12 01:24:59 +00:00
}
node := &yaml.Node{Kind: yaml.ScalarNode, Value: fmt.Sprintf("%v", length), Tag: "!!int"}
lengthCand := &CandidateNode{Node: node, Document: candidate.Document, Path: candidate.Path}
2020-10-21 01:54:58 +00:00
results.PushBack(lengthCand)
2020-10-12 01:24:59 +00:00
}
return results, nil
}