2020-12-01 04:06:54 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
yaml "gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
func sortKeysOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
|
2020-12-01 04:06:54 +00:00
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
|
2020-12-01 04:06:54 +00:00
|
|
|
candidate := el.Value.(*CandidateNode)
|
2021-05-16 04:00:30 +00:00
|
|
|
rhs, err := d.GetMatchingNodes(context.SingleReadonlyChildContext(candidate), expressionNode.Rhs)
|
2020-12-01 04:06:54 +00:00
|
|
|
if err != nil {
|
2021-02-02 07:17:59 +00:00
|
|
|
return Context{}, err
|
2020-12-01 04:06:54 +00:00
|
|
|
}
|
|
|
|
|
2021-02-02 07:17:59 +00:00
|
|
|
for childEl := rhs.MatchingNodes.Front(); childEl != nil; childEl = childEl.Next() {
|
2021-01-12 23:00:51 +00:00
|
|
|
node := unwrapDoc(childEl.Value.(*CandidateNode).Node)
|
2020-12-01 04:06:54 +00:00
|
|
|
if node.Kind == yaml.MappingNode {
|
|
|
|
sortKeys(node)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2021-02-02 07:17:59 +00:00
|
|
|
return Context{}, err
|
2020-12-01 04:06:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2021-02-02 07:17:59 +00:00
|
|
|
return context, nil
|
2020-12-01 04:06:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func sortKeys(node *yaml.Node) {
|
|
|
|
keys := make([]string, len(node.Content)/2)
|
|
|
|
keyBucket := map[string]*yaml.Node{}
|
|
|
|
valueBucket := map[string]*yaml.Node{}
|
|
|
|
var contents = node.Content
|
|
|
|
for index := 0; index < len(contents); index = index + 2 {
|
|
|
|
key := contents[index]
|
|
|
|
value := contents[index+1]
|
|
|
|
keys[index/2] = key.Value
|
|
|
|
keyBucket[key.Value] = key
|
|
|
|
valueBucket[key.Value] = value
|
|
|
|
}
|
|
|
|
sort.Strings(keys)
|
|
|
|
sortedContent := make([]*yaml.Node, len(node.Content))
|
|
|
|
for index := 0; index < len(keys); index = index + 1 {
|
|
|
|
keyString := keys[index]
|
|
|
|
sortedContent[index*2] = keyBucket[keyString]
|
|
|
|
sortedContent[1+(index*2)] = valueBucket[keyString]
|
|
|
|
}
|
|
|
|
node.Content = sortedContent
|
|
|
|
}
|