yq/pkg/yqlib/data_navigator.go

372 lines
12 KiB
Go
Raw Normal View History

package yqlib
2015-10-01 23:05:13 +00:00
import (
2019-12-08 04:37:30 +00:00
"bytes"
2015-10-01 23:05:13 +00:00
"strconv"
2019-12-15 07:24:23 +00:00
"strings"
logging "gopkg.in/op/go-logging.v1"
2019-12-06 04:57:46 +00:00
yaml "gopkg.in/yaml.v3"
2015-10-01 23:05:13 +00:00
)
type DataNavigator interface {
2019-12-09 02:44:53 +00:00
DebugNode(node *yaml.Node)
2019-12-12 09:47:22 +00:00
Get(rootNode *yaml.Node, path []string) (*yaml.Node, error)
2019-12-16 05:17:01 +00:00
Update(rootNode *yaml.Node, path []string, changesToApply *yaml.Node) error
2019-12-12 09:47:22 +00:00
Delete(rootNode *yaml.Node, path []string) error
2019-12-15 08:34:05 +00:00
GuessKind(tail []string, guess yaml.Kind) yaml.Kind
}
type navigator struct {
2019-12-16 09:38:55 +00:00
log *logging.Logger
followAliases bool
}
2019-12-15 07:24:23 +00:00
type VisitorFn func(*yaml.Node) error
2019-12-08 04:59:24 +00:00
2019-12-16 09:38:55 +00:00
func NewDataNavigator(l *logging.Logger, followAliases bool) DataNavigator {
2019-12-01 20:10:42 +00:00
return &navigator{
2019-12-16 09:38:55 +00:00
log: l,
followAliases: followAliases,
}
}
2019-12-06 04:57:46 +00:00
func (n *navigator) Get(value *yaml.Node, path []string) (*yaml.Node, error) {
2019-12-15 07:24:23 +00:00
matchingNodes := make([]*yaml.Node, 0)
n.Visit(value, path, func(matchedNode *yaml.Node) error {
matchingNodes = append(matchingNodes, matchedNode)
n.log.Debug("Matched")
n.DebugNode(matchedNode)
return nil
})
n.log.Debug("finished iterating, found %v matches", len(matchingNodes))
if len(matchingNodes) == 0 {
return nil, nil
} else if len(matchingNodes) == 1 {
return matchingNodes[0], nil
}
// make a new node
var newNode = yaml.Node{Kind: yaml.SequenceNode}
newNode.Content = matchingNodes
return &newNode, nil
2019-12-08 04:59:24 +00:00
}
2019-12-16 05:17:01 +00:00
func (n *navigator) Update(rootNode *yaml.Node, path []string, changesToApply *yaml.Node) error {
2019-12-15 07:24:23 +00:00
errorVisiting := n.Visit(rootNode, path, func(nodeToUpdate *yaml.Node) error {
2019-12-08 04:59:24 +00:00
n.log.Debug("going to update")
2019-12-09 02:44:53 +00:00
n.DebugNode(nodeToUpdate)
2019-12-08 04:59:24 +00:00
n.log.Debug("with")
2019-12-16 05:17:01 +00:00
n.DebugNode(changesToApply)
2019-12-08 04:59:24 +00:00
nodeToUpdate.Value = changesToApply.Value
nodeToUpdate.Tag = changesToApply.Tag
nodeToUpdate.Kind = changesToApply.Kind
nodeToUpdate.Style = changesToApply.Style
nodeToUpdate.Content = changesToApply.Content
nodeToUpdate.HeadComment = changesToApply.HeadComment
nodeToUpdate.LineComment = changesToApply.LineComment
nodeToUpdate.FootComment = changesToApply.FootComment
2019-12-15 07:24:23 +00:00
return nil
2019-12-08 04:59:24 +00:00
})
return errorVisiting
}
2019-12-15 08:34:05 +00:00
// TODO: refactor delete..
2019-12-12 09:47:22 +00:00
func (n *navigator) Delete(rootNode *yaml.Node, path []string) error {
lastBit, newTail := path[len(path)-1], path[:len(path)-1]
n.log.Debug("splitting path, %v", lastBit)
n.log.Debug("new tail, %v", newTail)
2019-12-15 07:24:23 +00:00
errorVisiting := n.Visit(rootNode, newTail, func(nodeToUpdate *yaml.Node) error {
2019-12-12 09:47:22 +00:00
n.log.Debug("need to find %v in here", lastBit)
n.DebugNode(nodeToUpdate)
2019-12-15 06:31:26 +00:00
original := nodeToUpdate.Content
2019-12-12 09:47:22 +00:00
if nodeToUpdate.Kind == yaml.SequenceNode {
var index, err = strconv.ParseInt(lastBit, 10, 64) // nolint
if err != nil {
2019-12-15 07:24:23 +00:00
return err
2019-12-12 09:47:22 +00:00
}
if index >= int64(len(nodeToUpdate.Content)) {
2019-12-15 07:24:23 +00:00
n.log.Debug("index %v is greater than content length %v", index, len(nodeToUpdate.Content))
return nil
2019-12-12 09:47:22 +00:00
}
nodeToUpdate.Content = append(original[:index], original[index+1:]...)
} else if nodeToUpdate.Kind == yaml.MappingNode {
2019-12-15 07:53:49 +00:00
// need to delete in reverse - otherwise the matching indexes
// become incorrect.
2019-12-15 07:52:37 +00:00
matchingIndices := make([]int, 0)
2019-12-16 10:09:23 +00:00
_, errorVisiting := n.visitMatchingEntries(nodeToUpdate.Content, lastBit, func(matchingNode []*yaml.Node, indexInMap int) error {
2019-12-15 07:52:37 +00:00
matchingIndices = append(matchingIndices, indexInMap)
n.log.Debug("matchingIndices %v", indexInMap)
2019-12-15 07:24:23 +00:00
return nil
})
2019-12-15 07:52:37 +00:00
n.log.Debug("delete matching indices now")
n.log.Debug("%v", matchingIndices)
2019-12-15 07:24:23 +00:00
if errorVisiting != nil {
return errorVisiting
2019-12-15 06:31:26 +00:00
}
2019-12-15 07:52:37 +00:00
for i := len(matchingIndices) - 1; i >= 0; i-- {
indexToDelete := matchingIndices[i]
n.log.Debug("deleting index %v, %v", indexToDelete, nodeToUpdate.Content[indexToDelete].Value)
nodeToUpdate.Content = append(nodeToUpdate.Content[:indexToDelete], nodeToUpdate.Content[indexToDelete+2:]...)
}
2019-12-15 07:24:23 +00:00
2019-12-12 09:47:22 +00:00
}
2019-12-15 07:24:23 +00:00
return nil
2019-12-12 09:47:22 +00:00
})
return errorVisiting
}
2019-12-15 07:24:23 +00:00
func (n *navigator) Visit(value *yaml.Node, path []string, visitor VisitorFn) error {
2019-12-06 04:57:46 +00:00
realValue := value
if realValue.Kind == yaml.DocumentNode {
2019-12-09 02:44:53 +00:00
n.log.Debugf("its a document! returning the first child")
2019-12-06 04:57:46 +00:00
realValue = value.Content[0]
}
2019-12-06 04:57:46 +00:00
if len(path) > 0 {
2019-12-06 05:36:42 +00:00
n.log.Debugf("diving into %v", path[0])
2019-12-09 02:44:53 +00:00
n.DebugNode(value)
2019-12-08 04:59:24 +00:00
return n.recurse(realValue, path[0], path[1:], visitor)
}
2019-12-08 04:59:24 +00:00
return visitor(realValue)
}
2019-12-15 08:34:05 +00:00
func (n *navigator) GuessKind(tail []string, guess yaml.Kind) yaml.Kind {
2019-12-06 04:57:46 +00:00
n.log.Debug("tail %v", tail)
2019-12-09 02:44:53 +00:00
if len(tail) == 0 && guess == 0 {
2019-12-08 04:37:30 +00:00
n.log.Debug("end of path, must be a scalar")
2019-12-06 04:57:46 +00:00
return yaml.ScalarNode
2019-12-09 02:44:53 +00:00
} else if len(tail) == 0 {
return guess
}
2019-12-09 02:44:53 +00:00
2019-12-06 04:57:46 +00:00
var _, errorParsingInt = strconv.ParseInt(tail[0], 10, 64)
2019-12-09 02:44:53 +00:00
if tail[0] == "+" || errorParsingInt == nil {
2019-12-06 04:57:46 +00:00
return yaml.SequenceNode
2017-04-17 22:53:27 +00:00
}
2019-12-09 02:57:38 +00:00
if tail[0] == "*" && (guess == yaml.SequenceNode || guess == yaml.MappingNode) {
2019-12-09 02:44:53 +00:00
return guess
}
2019-12-16 09:38:55 +00:00
if guess == yaml.AliasNode {
n.log.Debug("guess was an alias, okey doke.")
return guess
}
2019-12-16 10:09:23 +00:00
n.log.Debug("forcing a mapping node")
n.log.Debug("yaml.SequenceNode ?", guess == yaml.SequenceNode)
n.log.Debug("yaml.ScalarNode ?", guess == yaml.ScalarNode)
2019-12-06 04:57:46 +00:00
return yaml.MappingNode
2015-10-01 23:05:13 +00:00
}
2019-12-06 04:57:46 +00:00
func (n *navigator) getOrReplace(original *yaml.Node, expectedKind yaml.Kind) *yaml.Node {
2019-12-09 02:57:10 +00:00
if original.Kind != expectedKind {
2019-12-08 04:37:30 +00:00
n.log.Debug("wanted %v but it was %v, overriding", expectedKind, original.Kind)
2019-12-06 04:57:46 +00:00
return &yaml.Node{Kind: expectedKind}
2017-02-26 22:01:52 +00:00
}
2019-12-06 04:57:46 +00:00
return original
2015-10-01 23:05:13 +00:00
}
2019-12-09 02:44:53 +00:00
func (n *navigator) DebugNode(value *yaml.Node) {
2019-12-15 07:24:23 +00:00
if value == nil {
n.log.Debug("-- node is nil --")
} else if n.log.IsEnabledFor(logging.DEBUG) {
2019-12-08 04:37:30 +00:00
buf := new(bytes.Buffer)
encoder := yaml.NewEncoder(buf)
encoder.Encode(value)
encoder.Close()
n.log.Debug("Tag: %v", value.Tag)
n.log.Debug("%v", buf.String())
}
}
2019-12-15 07:24:23 +00:00
func (n *navigator) recurse(value *yaml.Node, head string, tail []string, visitor VisitorFn) error {
2019-12-16 09:38:55 +00:00
n.log.Debug("recursing, processing %v", head)
2019-12-06 04:57:46 +00:00
switch value.Kind {
case yaml.MappingNode:
n.log.Debug("its a map with %v entries", len(value.Content)/2)
2019-12-09 02:44:53 +00:00
if head == "*" {
2019-12-09 02:57:10 +00:00
return n.splatMap(value, tail, visitor)
2019-12-09 02:44:53 +00:00
}
2019-12-09 02:57:10 +00:00
return n.recurseMap(value, head, tail, visitor)
2019-12-06 04:57:46 +00:00
case yaml.SequenceNode:
2019-12-08 04:37:30 +00:00
n.log.Debug("its a sequence of %v things!, %v", len(value.Content))
2019-12-06 04:57:46 +00:00
if head == "*" {
2019-12-09 02:57:10 +00:00
return n.splatArray(value, tail, visitor)
2019-12-06 04:57:46 +00:00
} else if head == "+" {
2019-12-09 02:57:10 +00:00
return n.appendArray(value, tail, visitor)
}
return n.recurseArray(value, head, tail, visitor)
2019-12-16 09:38:55 +00:00
case yaml.AliasNode:
n.log.Debug("its an alias, followAliases: %v", n.followAliases)
n.DebugNode(value.Alias)
if n.followAliases == true {
return n.recurse(value.Alias, head, tail, visitor)
}
return nil
2019-12-09 02:57:10 +00:00
default:
2019-12-15 07:24:23 +00:00
return nil
2019-12-09 02:57:10 +00:00
}
}
2019-12-15 07:24:23 +00:00
func (n *navigator) splatMap(value *yaml.Node, tail []string, visitor VisitorFn) error {
2019-12-09 02:57:10 +00:00
for index, content := range value.Content {
if index%2 == 0 {
continue
2019-05-14 01:20:41 +00:00
}
2019-12-15 08:34:05 +00:00
content = n.getOrReplace(content, n.GuessKind(tail, content.Kind))
2019-12-15 07:24:23 +00:00
var err = n.Visit(content, tail, visitor)
2019-05-14 01:20:41 +00:00
if err != nil {
2019-12-15 07:24:23 +00:00
return err
2019-05-14 01:20:41 +00:00
}
2019-12-09 02:57:10 +00:00
}
2019-12-15 07:24:23 +00:00
return nil
2019-12-09 02:57:10 +00:00
}
2019-12-15 07:24:23 +00:00
func (n *navigator) recurseMap(value *yaml.Node, head string, tail []string, visitor VisitorFn) error {
2019-12-16 10:09:23 +00:00
visited, errorVisiting := n.visitMatchingEntries(value.Content, head, func(contents []*yaml.Node, indexInMap int) error {
contents[indexInMap+1] = n.getOrReplace(contents[indexInMap+1], n.GuessKind(tail, contents[indexInMap+1].Kind))
return n.Visit(contents[indexInMap+1], tail, visitor)
2019-12-15 07:24:23 +00:00
})
if errorVisiting != nil {
return errorVisiting
}
if visited {
return nil
2019-12-09 02:57:10 +00:00
}
2019-12-15 06:31:26 +00:00
//didn't find it, lets add it.
2019-12-09 02:57:10 +00:00
value.Content = append(value.Content, &yaml.Node{Value: head, Kind: yaml.ScalarNode})
2019-12-15 08:34:05 +00:00
mapEntryValue := yaml.Node{Kind: n.GuessKind(tail, 0)}
2019-12-09 02:57:10 +00:00
value.Content = append(value.Content, &mapEntryValue)
n.log.Debug("adding new node %v", value.Content)
return n.Visit(&mapEntryValue, tail, visitor)
}
2019-12-16 10:09:23 +00:00
// need to pass the node in, as it may be aliased
type mapVisitorFn func([]*yaml.Node, int) error
2019-12-15 07:24:23 +00:00
2019-12-22 04:33:54 +00:00
func (n *navigator) visitDirectMatchingEntries(contents []*yaml.Node, key string, visit mapVisitorFn) (bool, error) {
2019-12-15 07:24:23 +00:00
visited := false
2019-12-22 04:15:15 +00:00
for index := 0; index < len(contents); index = index + 2 {
2019-12-15 07:38:40 +00:00
content := contents[index]
2019-12-16 10:09:23 +00:00
n.log.Debug("index %v, checking %v, %v", index, content.Value, content.Tag)
2019-12-22 04:15:15 +00:00
if n.matchesKey(key, content.Value) {
n.log.Debug("found a match! %v", content.Value)
errorVisiting := visit(contents, index)
if errorVisiting != nil {
return visited, errorVisiting
}
visited = true
}
}
2019-12-22 04:33:54 +00:00
return visited, nil
}
2019-12-22 04:15:15 +00:00
2019-12-22 04:33:54 +00:00
func (n *navigator) visitMatchingEntries(contents []*yaml.Node, key string, visit mapVisitorFn) (bool, error) {
2019-12-22 04:15:15 +00:00
2019-12-22 04:33:54 +00:00
n.log.Debug("visitMatchingEntries %v in %v", key, contents)
// value.Content is a concatenated array of key, value,
// so keys are in the even indexes, values in odd.
// merge aliases are defined first, but we only want to traverse them
// if we don't find a match directly on this node first.
visited, errorVisitedDirectEntries := n.visitDirectMatchingEntries(contents, key, visit)
if errorVisitedDirectEntries != nil || visited == true || n.followAliases == false {
return visited, errorVisitedDirectEntries
}
2019-12-22 04:15:15 +00:00
// didnt find a match, lets check the aliases.
2019-12-22 04:33:54 +00:00
return n.visitAliases(contents, key, visit)
}
func (n *navigator) visitAliases(contents []*yaml.Node, key string, visit mapVisitorFn) (bool, error) {
2019-12-22 04:15:15 +00:00
// merge aliases are defined first, but we only want to traverse them
// if we don't find a match on this node first.
// traverse them backwards so that the last alias overrides the preceding.
2019-12-22 04:33:54 +00:00
// a node can either be
// an alias to one other node (e.g. <<: *blah)
// or a sequence of aliases (e.g. <<: [*blah, *foo])
n.log.Debug("checking for aliases")
2019-12-22 04:15:15 +00:00
for index := len(contents) - 2; index >= 0; index = index - 2 {
if contents[index+1].Kind == yaml.AliasNode {
2019-12-16 10:09:23 +00:00
valueNode := contents[index+1]
2019-12-22 04:15:15 +00:00
n.log.Debug("found an alias")
n.DebugNode(contents[index])
2019-12-16 10:09:23 +00:00
n.DebugNode(valueNode)
2019-12-22 04:33:54 +00:00
2019-12-16 10:09:23 +00:00
visitedAlias, errorInAlias := n.visitMatchingEntries(valueNode.Alias.Content, key, visit)
2019-12-22 04:33:54 +00:00
if visitedAlias == true || errorInAlias != nil {
return visitedAlias, errorInAlias
2019-12-22 04:15:15 +00:00
}
} else if contents[index+1].Kind == yaml.SequenceNode {
2019-12-22 04:35:16 +00:00
// could be an array of aliases...
2019-12-22 04:33:54 +00:00
visitedAliasSeq, errorVisitingAliasSeq := n.visitAliasSequence(contents[index+1].Content, key, visit)
if visitedAliasSeq == true || errorVisitingAliasSeq != nil {
return visitedAliasSeq, errorVisitingAliasSeq
2019-12-15 07:24:23 +00:00
}
2019-12-15 06:31:26 +00:00
}
2019-12-22 04:33:54 +00:00
}
n.log.Debug("nope no matching aliases found")
return false, nil
}
2019-12-22 04:15:15 +00:00
2019-12-22 04:33:54 +00:00
func (n *navigator) visitAliasSequence(possibleAliasArray []*yaml.Node, key string, visit mapVisitorFn) (bool, error) {
2019-12-22 04:35:16 +00:00
// need to search this backwards too, so that aliases defined last override the preceding.
2019-12-22 04:33:54 +00:00
for aliasIndex := len(possibleAliasArray) - 1; aliasIndex >= 0; aliasIndex = aliasIndex - 1 {
child := possibleAliasArray[aliasIndex]
if child.Kind == yaml.AliasNode {
n.log.Debug("found an alias")
n.DebugNode(child)
visitedAlias, errorInAlias := n.visitMatchingEntries(child.Alias.Content, key, visit)
if visitedAlias == true || errorInAlias != nil {
return visitedAlias, errorInAlias
}
}
2019-12-15 06:31:26 +00:00
}
2019-12-22 04:15:15 +00:00
return false, nil
2019-12-15 06:31:26 +00:00
}
2019-12-15 07:24:23 +00:00
func (n *navigator) matchesKey(key string, actual string) bool {
var prefixMatch = strings.TrimSuffix(key, "*")
if prefixMatch != key {
return strings.HasPrefix(actual, prefixMatch)
}
return actual == key
}
2019-12-09 02:57:10 +00:00
2019-12-15 07:24:23 +00:00
func (n *navigator) splatArray(value *yaml.Node, tail []string, visitor VisitorFn) error {
for _, childValue := range value.Content {
2019-12-09 02:57:10 +00:00
n.log.Debug("processing")
n.DebugNode(childValue)
2019-12-15 08:34:05 +00:00
childValue = n.getOrReplace(childValue, n.GuessKind(tail, childValue.Kind))
2019-12-15 07:24:23 +00:00
var err = n.Visit(childValue, tail, visitor)
2019-12-09 02:57:10 +00:00
if err != nil {
2019-12-15 07:24:23 +00:00
return err
2019-12-09 02:57:10 +00:00
}
}
2019-12-15 07:24:23 +00:00
return nil
2019-12-09 02:57:10 +00:00
}
2019-12-15 07:24:23 +00:00
func (n *navigator) appendArray(value *yaml.Node, tail []string, visitor VisitorFn) error {
2019-12-15 08:34:05 +00:00
var newNode = yaml.Node{Kind: n.GuessKind(tail, 0)}
2019-12-09 02:57:10 +00:00
value.Content = append(value.Content, &newNode)
n.log.Debug("appending a new node, %v", value.Content)
return n.Visit(&newNode, tail, visitor)
}
2019-12-15 07:24:23 +00:00
func (n *navigator) recurseArray(value *yaml.Node, head string, tail []string, visitor VisitorFn) error {
2019-12-09 02:57:10 +00:00
var index, err = strconv.ParseInt(head, 10, 64) // nolint
if err != nil {
2019-12-15 07:24:23 +00:00
return err
2019-12-09 02:57:10 +00:00
}
if index >= int64(len(value.Content)) {
2019-12-15 07:24:23 +00:00
return nil
}
2019-12-15 08:34:05 +00:00
value.Content[index] = n.getOrReplace(value.Content[index], n.GuessKind(tail, value.Content[index].Kind))
2019-12-09 02:57:10 +00:00
return n.Visit(value.Content[index], tail, visitor)
2019-05-14 01:20:41 +00:00
}