Skip to content

Commit 880397d

Browse files
authored
Refactored decoder responsibilities (#1402)
- improved comment handling - yaml decoder now responsible for leading content work around
1 parent 46c32f4 commit 880397d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+529
-329
lines changed

acceptance_tests/empty.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ EOL
99

1010
testEmptyEval() {
1111
X=$(./yq e test.yml)
12-
expected=$(cat test.yml)
12+
expected="# comment"
1313
assertEquals 0 $?
1414
assertEquals "$expected" "$X"
1515
}

cmd/constant.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package cmd
22

3-
var leadingContentPreProcessing = true
43
var unwrapScalar = true
54

65
var writeInplace = false

cmd/evaluate_all_command.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func evaluateAll(cmd *cobra.Command, args []string) (cmdError error) {
7575
return err
7676
}
7777

78-
decoder, err := configureDecoder()
78+
decoder, err := configureDecoder(true)
7979
if err != nil {
8080
return err
8181
}
@@ -109,13 +109,13 @@ func evaluateAll(cmd *cobra.Command, args []string) (cmdError error) {
109109
switch len(args) {
110110
case 0:
111111
if nullInput {
112-
err = yqlib.NewStreamEvaluator().EvaluateNew(processExpression(expression), printer, "")
112+
err = yqlib.NewStreamEvaluator().EvaluateNew(processExpression(expression), printer)
113113
} else {
114114
cmd.Println(cmd.UsageString())
115115
return nil
116116
}
117117
default:
118-
err = allAtOnceEvaluator.EvaluateFiles(processExpression(expression), args, printer, leadingContentPreProcessing, decoder)
118+
err = allAtOnceEvaluator.EvaluateFiles(processExpression(expression), args, printer, decoder)
119119
}
120120

121121
completedSuccessfully = err == nil

cmd/evalute_sequence_command.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func evaluateSequence(cmd *cobra.Command, args []string) (cmdError error) {
9797

9898
printer := yqlib.NewPrinter(encoder, printerWriter)
9999

100-
decoder, err := configureDecoder()
100+
decoder, err := configureDecoder(false)
101101
if err != nil {
102102
return err
103103
}
@@ -123,13 +123,13 @@ func evaluateSequence(cmd *cobra.Command, args []string) (cmdError error) {
123123
switch len(args) {
124124
case 0:
125125
if nullInput {
126-
err = streamEvaluator.EvaluateNew(processExpression(expression), printer, "")
126+
err = streamEvaluator.EvaluateNew(processExpression(expression), printer)
127127
} else {
128128
cmd.Println(cmd.UsageString())
129129
return nil
130130
}
131131
default:
132-
err = streamEvaluator.EvaluateFiles(processExpression(expression), args, printer, leadingContentPreProcessing, decoder)
132+
err = streamEvaluator.EvaluateFiles(processExpression(expression), args, printer, decoder)
133133
}
134134
completedSuccessfully = err == nil
135135

cmd/root.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ yq -P sample.json
5959
"naming conflicts with the default content name, directive name and proc inst prefix. If you need to keep " +
6060
"`+` please set that value explicityly with --xml-attribute-prefix.")
6161
}
62+
63+
//copy preference form global setting
64+
yqlib.ConfiguredYamlPreferences.UnwrapScalar = unwrapScalar
65+
66+
yqlib.ConfiguredYamlPreferences.PrintDocSeparators = !noDocSeparators
6267
},
6368
}
6469

@@ -97,7 +102,7 @@ yq -P sample.json
97102
rootCmd.PersistentFlags().BoolVarP(&forceNoColor, "no-colors", "M", false, "force print with no colors")
98103
rootCmd.PersistentFlags().StringVarP(&frontMatter, "front-matter", "f", "", "(extract|process) first input as yaml front-matter. Extract will pull out the yaml content, process will run the expression against the yaml content, leaving the remaining data intact")
99104
rootCmd.PersistentFlags().StringVarP(&forceExpression, "expression", "", "", "forcibly set the expression argument. Useful when yq argument detection thinks your expression is a file.")
100-
rootCmd.PersistentFlags().BoolVarP(&leadingContentPreProcessing, "header-preprocess", "", true, "Slurp any header comments and separators before processing expression.")
105+
rootCmd.PersistentFlags().BoolVarP(&yqlib.ConfiguredYamlPreferences.LeadingContentPreProcessing, "header-preprocess", "", true, "Slurp any header comments and separators before processing expression.")
101106

102107
rootCmd.PersistentFlags().StringVarP(&splitFileExp, "split-exp", "s", "", "print each result (or doc) into a file named (exp). [exp] argument must return a string. You can use $index in the expression as the result counter.")
103108
rootCmd.PersistentFlags().StringVarP(&splitFileExpFile, "split-exp-file", "", "", "Use a file to specify the split-exp expression.")

cmd/utils.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ func initCommand(cmd *cobra.Command, args []string) (string, []string, error) {
5656
return expression, args, nil
5757
}
5858

59-
func configureDecoder() (yqlib.Decoder, error) {
59+
func configureDecoder(evaluateTogether bool) (yqlib.Decoder, error) {
6060
yqlibInputFormat, err := yqlib.InputFormatFromString(inputFormat)
6161
if err != nil {
6262
return nil, err
@@ -73,8 +73,9 @@ func configureDecoder() (yqlib.Decoder, error) {
7373
case yqlib.TSVObjectInputFormat:
7474
return yqlib.NewCSVObjectDecoder('\t'), nil
7575
}
76-
77-
return yqlib.NewYamlDecoder(), nil
76+
prefs := yqlib.ConfiguredYamlPreferences
77+
prefs.EvaluateTogether = evaluateTogether
78+
return yqlib.NewYamlDecoder(prefs), nil
7879
}
7980

8081
func configurePrinterWriter(format yqlib.PrinterOutputFormat, out io.Writer) (yqlib.PrinterWriter, error) {
@@ -105,7 +106,7 @@ func configureEncoder(format yqlib.PrinterOutputFormat) yqlib.Encoder {
105106
case yqlib.TSVOutputFormat:
106107
return yqlib.NewCsvEncoder('\t')
107108
case yqlib.YamlOutputFormat:
108-
return yqlib.NewYamlEncoder(indent, colorsEnabled, !noDocSeparators, unwrapScalar)
109+
return yqlib.NewYamlEncoder(indent, colorsEnabled, yqlib.ConfiguredYamlPreferences)
109110
case yqlib.XMLOutputFormat:
110111
return yqlib.NewXMLEncoder(indent, yqlib.ConfiguredXMLPreferences)
111112
}

examples/empty-no-comment.yaml

Whitespace-only changes.

pkg/yqlib/all_at_once_evaluator.go

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88

99
// A yaml expression evaluator that runs the expression once against all files/nodes in memory.
1010
type Evaluator interface {
11-
EvaluateFiles(expression string, filenames []string, printer Printer, leadingContentPreProcessing bool, decoder Decoder) error
11+
EvaluateFiles(expression string, filenames []string, printer Printer, decoder Decoder) error
1212

1313
// EvaluateNodes takes an expression and one or more yaml nodes, returning a list of matching candidate nodes
1414
EvaluateNodes(expression string, nodes ...*yaml.Node) (*list.List, error)
@@ -46,21 +46,16 @@ func (e *allAtOnceEvaluator) EvaluateCandidateNodes(expression string, inputCand
4646
return context.MatchingNodes, nil
4747
}
4848

49-
func (e *allAtOnceEvaluator) EvaluateFiles(expression string, filenames []string, printer Printer, leadingContentPreProcessing bool, decoder Decoder) error {
49+
func (e *allAtOnceEvaluator) EvaluateFiles(expression string, filenames []string, printer Printer, decoder Decoder) error {
5050
fileIndex := 0
51-
firstFileLeadingContent := ""
5251

5352
var allDocuments = list.New()
5453
for _, filename := range filenames {
55-
reader, leadingContent, err := readStream(filename, fileIndex == 0 && leadingContentPreProcessing)
54+
reader, err := readStream(filename)
5655
if err != nil {
5756
return err
5857
}
5958

60-
if fileIndex == 0 {
61-
firstFileLeadingContent = leadingContent
62-
}
63-
6459
fileDocuments, err := readDocuments(reader, filename, fileIndex, decoder)
6560
if err != nil {
6661
return err
@@ -75,11 +70,9 @@ func (e *allAtOnceEvaluator) EvaluateFiles(expression string, filenames []string
7570
Filename: "",
7671
Node: &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Tag: "!!null", Kind: yaml.ScalarNode}}},
7772
FileIndex: 0,
78-
LeadingContent: firstFileLeadingContent,
73+
LeadingContent: "",
7974
}
8075
allDocuments.PushBack(candidateNode)
81-
} else {
82-
allDocuments.Front().Value.(*CandidateNode).LeadingContent = firstFileLeadingContent
8376
}
8477

8578
matches, err := e.EvaluateCandidateNodes(expression, allDocuments)

pkg/yqlib/csv_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,13 @@ var csvScenarios = []formatScenario{
136136
func testCSVScenario(t *testing.T, s formatScenario) {
137137
switch s.scenarioType {
138138
case "encode-csv":
139-
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(), NewCsvEncoder(',')), s.description)
139+
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(ConfiguredYamlPreferences), NewCsvEncoder(',')), s.description)
140140
case "encode-tsv":
141-
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(), NewCsvEncoder('\t')), s.description)
141+
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewYamlDecoder(ConfiguredYamlPreferences), NewCsvEncoder('\t')), s.description)
142142
case "decode-csv-object":
143-
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewCSVObjectDecoder(','), NewYamlEncoder(2, false, true, true)), s.description)
143+
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewCSVObjectDecoder(','), NewYamlEncoder(2, false, ConfiguredYamlPreferences)), s.description)
144144
case "decode-tsv-object":
145-
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewCSVObjectDecoder('\t'), NewYamlEncoder(2, false, true, true)), s.description)
145+
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewCSVObjectDecoder('\t'), NewYamlEncoder(2, false, ConfiguredYamlPreferences)), s.description)
146146
case "roundtrip-csv":
147147
test.AssertResultWithContext(t, s.expected, processFormatScenario(s, NewCSVObjectDecoder(','), NewCsvEncoder(',')), s.description)
148148
default:
@@ -171,7 +171,7 @@ func documentCSVDecodeObjectScenario(w *bufio.Writer, s formatScenario, formatTy
171171
}
172172

173173
writeOrPanic(w, fmt.Sprintf("```yaml\n%v```\n\n",
174-
processFormatScenario(s, NewCSVObjectDecoder(separator), NewYamlEncoder(s.indent, false, true, true))),
174+
processFormatScenario(s, NewCSVObjectDecoder(separator), NewYamlEncoder(s.indent, false, ConfiguredYamlPreferences))),
175175
)
176176
}
177177

@@ -203,7 +203,7 @@ func documentCSVEncodeScenario(w *bufio.Writer, s formatScenario, formatType str
203203
}
204204

205205
writeOrPanic(w, fmt.Sprintf("```%v\n%v```\n\n", formatType,
206-
processFormatScenario(s, NewYamlDecoder(), NewCsvEncoder(separator))),
206+
processFormatScenario(s, NewYamlDecoder(ConfiguredYamlPreferences), NewCsvEncoder(separator))),
207207
)
208208
}
209209

pkg/yqlib/decoder.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ package yqlib
33
import (
44
"fmt"
55
"io"
6-
7-
yaml "gopkg.in/yaml.v3"
86
)
97

108
type InputFormat uint
@@ -20,8 +18,8 @@ const (
2018
)
2119

2220
type Decoder interface {
23-
Init(reader io.Reader)
24-
Decode(node *yaml.Node) error
21+
Init(reader io.Reader) error
22+
Decode() (*CandidateNode, error)
2523
}
2624

2725
func InputFormatFromString(format string) (InputFormat, error) {

0 commit comments

Comments
 (0)