yq/pkg/yqlib/delete_navigation_settings.go

66 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"
)
func DeleteNavigationSettings(lastBit string) NavigationSettings {
2019-12-27 21:51:54 +00:00
parser := NewPathParser()
2019-12-25 01:11:04 +00:00
return &NavigationSettingsImpl{
visitedNodes: []*VisitedNode{},
followAlias: func(node *yaml.Node, head string, tail []string, pathStack []interface{}) bool {
return false
},
autoCreateMap: func(node *yaml.Node, head string, tail []string, pathStack []interface{}) bool {
return true
},
visit: func(node *yaml.Node, head string, tail []string, pathStack []interface{}) error {
2019-12-27 21:51:54 +00:00
log.Debug("need to find and delete %v in here", lastBit)
2019-12-25 01:11:04 +00:00
DebugNode(node)
if node.Kind == yaml.SequenceNode {
newContent, errorDeleting := deleteFromArray(node.Content, lastBit)
if errorDeleting != nil {
return errorDeleting
}
node.Content = newContent
} else if node.Kind == yaml.MappingNode {
2019-12-27 21:51:54 +00:00
node.Content = deleteFromMap(parser, node.Content, pathStack, lastBit)
2019-12-25 01:11:04 +00:00
}
return nil
},
}
}
2019-12-27 21:51:54 +00:00
func deleteFromMap(pathParser PathParser, contents []*yaml.Node, pathStack []interface{}, lastBit string) []*yaml.Node {
newContents := make([]*yaml.Node, 0)
for index := 0; index < len(contents); index = index + 2 {
keyNode := contents[index]
valueNode := contents[index+1]
if pathParser.MatchesNextPathElement(keyNode, lastBit, []string{}, pathStack, keyNode.Value) == false {
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
func deleteFromArray(content []*yaml.Node, lastBit string) ([]*yaml.Node, error) {
2019-12-27 21:51:54 +00:00
if lastBit == "*" {
return make([]*yaml.Node, 0), nil
}
2019-12-25 01:11:04 +00:00
var index, err = strconv.ParseInt(lastBit, 10, 64) // nolint
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
}