yq/pkg/yqlib/operator_has.go
Mike Farah c6efd5519b Pass context through operators
Allows more sophisticated functionality
2021-02-11 10:58:40 +11:00

55 lines
1.5 KiB
Go

package yqlib
import (
"container/list"
"strconv"
yaml "gopkg.in/yaml.v3"
)
func hasOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
log.Debugf("-- hasOperation")
var results = list.New()
rhs, err := d.GetMatchingNodes(context, expressionNode.Rhs)
wanted := rhs.MatchingNodes.Front().Value.(*CandidateNode).Node
wantedKey := wanted.Value
if err != nil {
return Context{}, err
}
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
// grab the first value
candidateNode := unwrapDoc(candidate.Node)
var contents = candidateNode.Content
switch candidateNode.Kind {
case yaml.MappingNode:
candidateHasKey := false
for index := 0; index < len(contents) && !candidateHasKey; index = index + 2 {
key := contents[index]
if key.Value == wantedKey {
candidateHasKey = true
}
}
results.PushBack(createBooleanCandidate(candidate, candidateHasKey))
case yaml.SequenceNode:
candidateHasKey := false
if wanted.Tag == "!!int" {
var number, errParsingInt = strconv.ParseInt(wantedKey, 10, 64) // nolint
if errParsingInt != nil {
return Context{}, errParsingInt
}
candidateHasKey = int64(len(contents)) > number
}
results.PushBack(createBooleanCandidate(candidate, candidateHasKey))
default:
results.PushBack(createBooleanCandidate(candidate, false))
}
}
return context.ChildContext(results), nil
}