2021-01-14 04:45:07 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/list"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
2021-11-23 22:57:35 +00:00
|
|
|
func getKeyOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
|
|
|
|
log.Debugf("-- getKeyOperator")
|
|
|
|
|
|
|
|
var results = list.New()
|
|
|
|
|
|
|
|
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
|
|
|
|
candidate := el.Value.(*CandidateNode)
|
|
|
|
|
|
|
|
results.PushBack(candidate.CreateReplacement(candidate.Key))
|
|
|
|
}
|
|
|
|
|
|
|
|
return context.ChildContext(results), nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
func keysOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
|
2021-01-14 04:45:07 +00:00
|
|
|
log.Debugf("-- keysOperator")
|
|
|
|
|
|
|
|
var results = list.New()
|
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
|
2021-01-14 04:45:07 +00:00
|
|
|
candidate := el.Value.(*CandidateNode)
|
|
|
|
node := unwrapDoc(candidate.Node)
|
|
|
|
var targetNode *yaml.Node
|
|
|
|
if node.Kind == yaml.MappingNode {
|
|
|
|
targetNode = getMapKeys(node)
|
|
|
|
} else if node.Kind == yaml.SequenceNode {
|
|
|
|
targetNode = getIndicies(node)
|
|
|
|
} else {
|
2021-02-02 07:17:59 +00:00
|
|
|
return Context{}, fmt.Errorf("Cannot get keys of %v, keys only works for maps and arrays", node.Tag)
|
2021-01-14 04:45:07 +00:00
|
|
|
}
|
|
|
|
|
2021-11-23 22:57:35 +00:00
|
|
|
result := candidate.CreateReplacement(targetNode)
|
2021-01-14 04:45:07 +00:00
|
|
|
results.PushBack(result)
|
|
|
|
}
|
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
return context.ChildContext(results), nil
|
2021-01-14 04:45:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func getMapKeys(node *yaml.Node) *yaml.Node {
|
|
|
|
contents := make([]*yaml.Node, 0)
|
|
|
|
for index := 0; index < len(node.Content); index = index + 2 {
|
|
|
|
contents = append(contents, node.Content[index])
|
|
|
|
}
|
|
|
|
return &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: contents}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getIndicies(node *yaml.Node) *yaml.Node {
|
|
|
|
var contents = make([]*yaml.Node, len(node.Content))
|
|
|
|
|
|
|
|
for index := range node.Content {
|
|
|
|
contents[index] = &yaml.Node{
|
|
|
|
Kind: yaml.ScalarNode,
|
|
|
|
Tag: "!!int",
|
|
|
|
Value: fmt.Sprintf("%v", index),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: contents}
|
|
|
|
}
|