forked from mikefarah/yq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer_writer.go
81 lines (64 loc) · 1.78 KB
/
printer_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package yqlib
import (
"bufio"
"fmt"
"io"
"os"
"gopkg.in/yaml.v3"
)
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),
}
}
func (sp *singlePrinterWriter) GetWriter(node *CandidateNode) (*bufio.Writer, error) {
return sp.bufferedWriter, nil
}
type multiPrintWriter struct {
treeNavigator DataTreeNavigator
nameExpression *ExpressionNode
extension string
index int
}
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(),
index: 0,
}
}
func (sp *multiPrintWriter) GetWriter(node *CandidateNode) (*bufio.Writer, error) {
name := ""
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
}
if result.MatchingNodes.Len() > 0 {
name = result.MatchingNodes.Front().Value.(*CandidateNode).Node.Value
}
name = fmt.Sprintf("%v.%v", name, sp.extension)
f, err := os.Create(name)
if err != nil {
return nil, err
}
sp.index = sp.index + 1
return bufio.NewWriter(f), nil
}