2021-10-29 03:14:39 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
2022-06-23 04:31:04 +00:00
|
|
|
"regexp"
|
2021-10-29 03:14:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type PrinterWriter interface {
|
|
|
|
GetWriter(node *CandidateNode) (*bufio.Writer, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type singlePrinterWriter struct {
|
|
|
|
bufferedWriter *bufio.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSinglePrinterWriter(writer io.Writer) PrinterWriter {
|
|
|
|
return &singlePrinterWriter{
|
|
|
|
bufferedWriter: bufio.NewWriter(writer),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-11 02:17:34 +00:00
|
|
|
func (sp *singlePrinterWriter) GetWriter(_ *CandidateNode) (*bufio.Writer, error) {
|
2021-10-29 03:14:39 +00:00
|
|
|
return sp.bufferedWriter, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type multiPrintWriter struct {
|
|
|
|
treeNavigator DataTreeNavigator
|
|
|
|
nameExpression *ExpressionNode
|
|
|
|
extension string
|
|
|
|
index int
|
|
|
|
}
|
|
|
|
|
2024-02-24 03:58:11 +00:00
|
|
|
func NewMultiPrinterWriter(expression *ExpressionNode, format *PrinterOutputFormat) PrinterWriter {
|
2021-10-29 03:14:39 +00:00
|
|
|
extension := "yml"
|
|
|
|
|
|
|
|
switch format {
|
2022-02-07 00:55:55 +00:00
|
|
|
case JSONOutputFormat:
|
2021-10-29 03:14:39 +00:00
|
|
|
extension = "json"
|
|
|
|
case PropsOutputFormat:
|
|
|
|
extension = "properties"
|
|
|
|
}
|
|
|
|
|
|
|
|
return &multiPrintWriter{
|
|
|
|
nameExpression: expression,
|
|
|
|
extension: extension,
|
|
|
|
treeNavigator: NewDataTreeNavigator(),
|
|
|
|
index: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sp *multiPrintWriter) GetWriter(node *CandidateNode) (*bufio.Writer, error) {
|
|
|
|
name := ""
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
indexVariableNode := CandidateNode{Kind: ScalarNode, Tag: "!!int", Value: fmt.Sprintf("%v", sp.index)}
|
2021-10-29 03:14:39 +00:00
|
|
|
|
|
|
|
context := Context{MatchingNodes: node.AsList()}
|
2023-10-18 01:11:53 +00:00
|
|
|
context.SetVariable("index", indexVariableNode.AsList())
|
2021-10-29 03:14:39 +00:00
|
|
|
result, err := sp.treeNavigator.GetMatchingNodes(context, sp.nameExpression)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if result.MatchingNodes.Len() > 0 {
|
2023-10-18 01:11:53 +00:00
|
|
|
name = result.MatchingNodes.Front().Value.(*CandidateNode).Value
|
2021-10-29 03:14:39 +00:00
|
|
|
}
|
2022-06-23 04:31:04 +00:00
|
|
|
var extensionRegexp = regexp.MustCompile(`\.[a-zA-Z0-9]+$`)
|
|
|
|
if !extensionRegexp.MatchString(name) {
|
|
|
|
name = fmt.Sprintf("%v.%v", name, sp.extension)
|
|
|
|
}
|
2021-10-29 03:14:39 +00:00
|
|
|
|
|
|
|
f, err := os.Create(name)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
sp.index = sp.index + 1
|
|
|
|
|
|
|
|
return bufio.NewWriter(f), nil
|
|
|
|
|
|
|
|
}
|