yq/pkg/yqlib/printer_writer.go

53 lines
1.1 KiB
Go
Raw Normal View History

2021-10-29 05:07:17 +00:00
package yqlib
import (
"bufio"
"fmt"
"io"
)
type printerWriter interface {
GetWriter(node *CandidateNode, index int) (*bufio.Writer, error)
}
type singlePrinterWriter struct {
bufferedWriter *bufio.Writer
}
func NewSinglePrinterWriter(writer io.Writer) printerWriter {
return &singlePrinterWriter{
bufferedWriter: bufio.NewWriter(writer),
}
}
func (sp *singlePrinterWriter) GetWriter(node *CandidateNode, i int) (*bufio.Writer, error) {
return sp.bufferedWriter, nil
}
type multiPrintWriter struct {
treeNavigator DataTreeNavigator
nameExpression *ExpressionNode
extension string
}
func (sp *multiPrintWriter) GetWriter(node *CandidateNode, index int) (*bufio.Writer, error) {
name := ""
if sp.nameExpression != nil {
context := Context{MatchingNodes: node.AsList()}
result, err := sp.treeNavigator.GetMatchingNodes(context, sp.nameExpression)
if err != nil {
return nil, err
}
if result.MatchingNodes.Len() > 0 {
name = result.MatchingNodes.Front().Value.(*CandidateNode).Node.Value
}
}
if name == "" {
name = fmt.Sprintf("%v.%v", index, sp.extension)
} else {
name = fmt.Sprintf("%v.%v", name, sp.extension)
}
}