yq/pkg/yqlib/printer_writer.go

82 lines
1.8 KiB
Go
Raw Normal View History

2021-10-29 05:07:17 +00:00
package yqlib
import (
"bufio"
"fmt"
"io"
2021-10-29 09:49:06 +00:00
"os"
2021-10-29 22:56:47 +00:00
"gopkg.in/yaml.v3"
2021-10-29 05:07:17 +00:00
)
2021-10-29 09:49:06 +00:00
type PrinterWriter interface {
2021-10-29 22:56:47 +00:00
GetWriter(node *CandidateNode) (*bufio.Writer, error)
2021-10-29 05:07:17 +00:00
}
type singlePrinterWriter struct {
bufferedWriter *bufio.Writer
}
2021-10-29 09:49:06 +00:00
func NewSinglePrinterWriter(writer io.Writer) PrinterWriter {
2021-10-29 05:07:17 +00:00
return &singlePrinterWriter{
bufferedWriter: bufio.NewWriter(writer),
}
}
2021-10-29 22:56:47 +00:00
func (sp *singlePrinterWriter) GetWriter(node *CandidateNode) (*bufio.Writer, error) {
2021-10-29 05:07:17 +00:00
return sp.bufferedWriter, nil
}
type multiPrintWriter struct {
treeNavigator DataTreeNavigator
nameExpression *ExpressionNode
extension string
2021-10-29 22:56:47 +00:00
index int
2021-10-29 05:07:17 +00:00
}
2021-10-29 09:49:06 +00:00
func NewMultiPrinterWriter(expression *ExpressionNode, format PrinterOutputFormat) PrinterWriter {
extension := "yml"
switch format {
case JsonOutputFormat:
extension = "json"
case PropsOutputFormat:
extension = "properties"
}
return &multiPrintWriter{
nameExpression: expression,
extension: extension,
treeNavigator: NewDataTreeNavigator(),
2021-10-29 22:56:47 +00:00
index: 0,
2021-10-29 09:49:06 +00:00
}
}
2021-10-29 22:56:47 +00:00
func (sp *multiPrintWriter) GetWriter(node *CandidateNode) (*bufio.Writer, error) {
2021-10-29 05:07:17 +00:00
name := ""
2021-10-29 22:56:47 +00:00
indexVariableNode := yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: fmt.Sprintf("%v", sp.index)}
indexVariableCandidate := CandidateNode{Node: &indexVariableNode}
context := Context{MatchingNodes: node.AsList()}
context.SetVariable("index", indexVariableCandidate.AsList())
result, err := sp.treeNavigator.GetMatchingNodes(context, sp.nameExpression)
if err != nil {
return nil, err
2021-10-29 05:07:17 +00:00
}
2021-10-29 22:56:47 +00:00
if result.MatchingNodes.Len() > 0 {
name = result.MatchingNodes.Front().Value.(*CandidateNode).Node.Value
2021-10-29 05:07:17 +00:00
}
2021-10-29 22:56:47 +00:00
name = fmt.Sprintf("%v.%v", name, sp.extension)
2021-10-29 05:07:17 +00:00
2021-10-29 09:49:06 +00:00
f, err := os.Create(name)
if err != nil {
return nil, err
}
2021-10-29 22:56:47 +00:00
sp.index = sp.index + 1
2021-10-29 09:49:06 +00:00
return bufio.NewWriter(f), nil
2021-10-29 05:07:17 +00:00
}