yq/pkg/yqlib/lib.go

69 lines
1.6 KiB
Go
Raw Normal View History

package yqlib
import (
2019-12-06 05:36:42 +00:00
"fmt"
logging "gopkg.in/op/go-logging.v1"
2019-12-06 04:57:46 +00:00
yaml "gopkg.in/yaml.v3"
)
2019-12-06 05:36:42 +00:00
type UpdateCommand struct {
Command string
Path string
2019-12-16 05:17:01 +00:00
Value *yaml.Node
2019-12-06 05:36:42 +00:00
}
type YqLib interface {
2019-12-09 02:44:53 +00:00
DebugNode(node *yaml.Node)
2019-12-22 06:13:11 +00:00
Get(rootNode *yaml.Node, path string) ([]MatchingNode, error)
2019-12-06 05:36:42 +00:00
Update(rootNode *yaml.Node, updateCommand UpdateCommand) error
2019-12-16 05:17:01 +00:00
New(path string) yaml.Node
}
type lib struct {
navigator DataNavigator
2019-12-01 20:10:42 +00:00
parser PathParser
2019-12-06 05:36:42 +00:00
log *logging.Logger
}
func NewYqLib(l *logging.Logger) YqLib {
2019-12-01 20:10:42 +00:00
return &lib{
2019-12-16 09:38:55 +00:00
parser: NewPathParser(),
log: l,
}
}
2019-12-09 02:44:53 +00:00
func (l *lib) DebugNode(node *yaml.Node) {
2019-12-16 09:38:55 +00:00
navigator := NewDataNavigator(l.log, false)
navigator.DebugNode(node)
2019-12-09 02:44:53 +00:00
}
2019-12-22 06:13:11 +00:00
func (l *lib) Get(rootNode *yaml.Node, path string) ([]MatchingNode, error) {
var paths = l.parser.ParsePath(path)
2019-12-16 09:38:55 +00:00
navigator := NewDataNavigator(l.log, true)
return navigator.Get(rootNode, paths)
}
2019-12-16 05:17:01 +00:00
func (l *lib) New(path string) yaml.Node {
var paths = l.parser.ParsePath(path)
2019-12-16 09:38:55 +00:00
navigator := NewDataNavigator(l.log, false)
newNode := yaml.Node{Kind: navigator.GuessKind(paths, 0)}
2019-12-16 05:17:01 +00:00
return newNode
2019-12-15 08:34:05 +00:00
}
2019-12-06 05:36:42 +00:00
func (l *lib) Update(rootNode *yaml.Node, updateCommand UpdateCommand) error {
2019-12-16 09:38:55 +00:00
navigator := NewDataNavigator(l.log, false)
2019-12-06 05:36:42 +00:00
l.log.Debugf("%v to %v", updateCommand.Command, updateCommand.Path)
switch updateCommand.Command {
case "update":
var paths = l.parser.ParsePath(updateCommand.Path)
2019-12-16 09:38:55 +00:00
return navigator.Update(rootNode, paths, updateCommand.Value)
2019-12-06 05:36:42 +00:00
case "delete":
2019-12-12 09:47:22 +00:00
var paths = l.parser.ParsePath(updateCommand.Path)
2019-12-16 09:38:55 +00:00
return navigator.Delete(rootNode, paths)
2019-12-06 05:36:42 +00:00
default:
return fmt.Errorf("Unknown command %v", updateCommand.Command)
}
2019-12-01 20:10:42 +00:00
}