yq/pkg/yqlib/treeops/candidate_node.go

85 lines
2.2 KiB
Go
Raw Normal View History

2020-10-13 01:51:37 +00:00
package treeops
import (
"fmt"
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
type CandidateNode struct {
Node *yaml.Node // the actual node
Path []interface{} /// the path we took to get to this node
Document uint // the document index of this node
}
func (n *CandidateNode) GetKey() string {
2020-10-17 11:10:47 +00:00
return fmt.Sprintf("%v - %v - %v", n.Document, n.Path, n.Node.Value)
2020-10-13 01:51:37 +00:00
}
2020-10-16 01:29:26 +00:00
// updates this candidate from the given candidate node
func (n *CandidateNode) UpdateFrom(other *CandidateNode) {
2020-10-19 05:36:46 +00:00
n.UpdateAttributesFrom(other)
2020-10-16 01:29:26 +00:00
n.Node.Content = other.Node.Content
n.Node.Value = other.Node.Value
2020-10-19 05:14:29 +00:00
}
func (n *CandidateNode) UpdateAttributesFrom(other *CandidateNode) {
2020-10-19 05:36:46 +00:00
if n.Node.Kind != other.Node.Kind {
// clear out the contents when switching to a different type
// e.g. map to array
n.Node.Content = make([]*yaml.Node, 0)
n.Node.Value = ""
}
2020-10-16 01:29:26 +00:00
n.Node.Kind = other.Node.Kind
n.Node.Tag = other.Node.Tag
n.Node.Style = other.Node.Style
2020-10-19 05:14:29 +00:00
n.Node.FootComment = other.Node.FootComment
n.Node.HeadComment = other.Node.HeadComment
n.Node.LineComment = other.Node.LineComment
2020-10-16 01:29:26 +00:00
}
2020-10-13 01:51:37 +00:00
func (n *CandidateNode) PathStackToString() string {
return mergePathStackToString(n.Path)
}
func mergePathStackToString(pathStack []interface{}) string {
var sb strings.Builder
for index, path := range pathStack {
switch path.(type) {
case int, int64:
// if arrayMergeStrategy == AppendArrayMergeStrategy {
// sb.WriteString("[+]")
// } else {
sb.WriteString(fmt.Sprintf("[%v]", path))
// }
default:
s := fmt.Sprintf("%v", path)
var _, errParsingInt = strconv.ParseInt(s, 10, 64) // nolint
hasSpecial := strings.Contains(s, ".") || strings.Contains(s, "[") || strings.Contains(s, "]") || strings.Contains(s, "\"")
hasDoubleQuotes := strings.Contains(s, "\"")
wrappingCharacterStart := "\""
wrappingCharacterEnd := "\""
if hasDoubleQuotes {
wrappingCharacterStart = "("
wrappingCharacterEnd = ")"
}
if hasSpecial || errParsingInt == nil {
sb.WriteString(wrappingCharacterStart)
}
sb.WriteString(s)
if hasSpecial || errParsingInt == nil {
sb.WriteString(wrappingCharacterEnd)
}
}
if index < len(pathStack)-1 {
sb.WriteString(".")
}
}
return sb.String()
}