yq/pkg/yqlib/delete_navigation_strategy.go

67 lines
2.0 KiB
Go
Raw Normal View History

2019-12-25 01:11:04 +00:00
package yqlib
import (
"strconv"
yaml "gopkg.in/yaml.v3"
)
2019-12-28 07:19:37 +00:00
func DeleteNavigationStrategy(pathElementToDelete string) NavigationStrategy {
2019-12-27 21:51:54 +00:00
parser := NewPathParser()
2019-12-28 07:19:37 +00:00
return &NavigationStrategyImpl{
visitedNodes: []*NodeContext{},
followAlias: func(nodeContext NodeContext) bool {
2019-12-25 01:11:04 +00:00
return false
},
2019-12-28 07:19:37 +00:00
autoCreateMap: func(nodeContext NodeContext) bool {
2019-12-25 01:11:04 +00:00
return true
},
2019-12-28 07:19:37 +00:00
visit: func(nodeContext NodeContext) error {
node := nodeContext.Node
log.Debug("need to find and delete %v in here", pathElementToDelete)
2019-12-25 01:11:04 +00:00
DebugNode(node)
if node.Kind == yaml.SequenceNode {
2019-12-28 07:19:37 +00:00
newContent, errorDeleting := deleteFromArray(node.Content, pathElementToDelete)
2019-12-25 01:11:04 +00:00
if errorDeleting != nil {
return errorDeleting
}
node.Content = newContent
} else if node.Kind == yaml.MappingNode {
2019-12-28 07:19:37 +00:00
node.Content = deleteFromMap(parser, node.Content, nodeContext.PathStack, pathElementToDelete)
2019-12-25 01:11:04 +00:00
}
return nil
},
}
}
2019-12-28 07:19:37 +00:00
func deleteFromMap(pathParser PathParser, contents []*yaml.Node, pathStack []interface{}, pathElementToDelete string) []*yaml.Node {
2019-12-27 21:51:54 +00:00
newContents := make([]*yaml.Node, 0)
for index := 0; index < len(contents); index = index + 2 {
keyNode := contents[index]
valueNode := contents[index+1]
2019-12-28 07:19:37 +00:00
if pathParser.MatchesNextPathElement(NodeContext{keyNode, pathElementToDelete, []string{}, pathStack}, keyNode.Value) == false {
2019-12-27 21:51:54 +00:00
log.Debug("adding node %v", keyNode.Value)
newContents = append(newContents, keyNode, valueNode)
} else {
log.Debug("skipping node %v", keyNode.Value)
}
}
return newContents
}
2019-12-25 01:11:04 +00:00
2019-12-28 07:19:37 +00:00
func deleteFromArray(content []*yaml.Node, pathElementToDelete string) ([]*yaml.Node, error) {
2019-12-27 21:51:54 +00:00
2019-12-28 07:19:37 +00:00
if pathElementToDelete == "*" {
2019-12-27 21:51:54 +00:00
return make([]*yaml.Node, 0), nil
}
2019-12-28 07:19:37 +00:00
var index, err = strconv.ParseInt(pathElementToDelete, 10, 64) // nolint
2019-12-25 01:11:04 +00:00
if err != nil {
return content, err
}
if index >= int64(len(content)) {
log.Debug("index %v is greater than content length %v", index, len(content))
return content, nil
}
return append(content[:index], content[index+1:]...), nil
}