2022-02-10 01:02:53 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2023-03-25 23:59:15 +00:00
|
|
|
"fmt"
|
2022-02-10 01:02:53 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type formatScenario struct {
|
|
|
|
input string
|
|
|
|
indent int
|
|
|
|
expression string
|
|
|
|
expected string
|
|
|
|
description string
|
|
|
|
subdescription string
|
|
|
|
skipDoc bool
|
|
|
|
scenarioType string
|
2022-11-02 10:41:39 +00:00
|
|
|
expectedError string
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
|
2022-11-02 10:41:39 +00:00
|
|
|
func processFormatScenario(s formatScenario, decoder Decoder, encoder Encoder) (string, error) {
|
2022-02-10 01:02:53 +00:00
|
|
|
var output bytes.Buffer
|
|
|
|
writer := bufio.NewWriter(&output)
|
|
|
|
|
|
|
|
if decoder == nil {
|
2022-10-28 03:16:46 +00:00
|
|
|
decoder = NewYamlDecoder(ConfiguredYamlPreferences)
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
log.Debugf("reading docs")
|
2022-02-10 01:02:53 +00:00
|
|
|
inputs, err := readDocuments(strings.NewReader(s.input), "sample.yml", 0, decoder)
|
|
|
|
if err != nil {
|
2022-11-02 10:41:39 +00:00
|
|
|
return "", err
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
log.Debugf("done reading the documents")
|
|
|
|
|
2022-02-10 01:02:53 +00:00
|
|
|
expression := s.expression
|
|
|
|
if expression == "" {
|
|
|
|
expression = "."
|
|
|
|
}
|
|
|
|
|
|
|
|
exp, err := getExpressionParser().ParseExpression(expression)
|
|
|
|
|
|
|
|
if err != nil {
|
2022-11-02 10:41:39 +00:00
|
|
|
return "", err
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
context, err := NewDataTreeNavigator().GetMatchingNodes(Context{MatchingNodes: inputs}, exp)
|
|
|
|
|
2023-10-18 01:11:53 +00:00
|
|
|
log.Debugf("Going to print: %v", NodesToString(context.MatchingNodes))
|
|
|
|
|
2022-02-10 01:02:53 +00:00
|
|
|
if err != nil {
|
2022-11-02 10:41:39 +00:00
|
|
|
return "", err
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
printer := NewPrinter(encoder, NewSinglePrinterWriter(writer))
|
|
|
|
err = printer.PrintResults(context.MatchingNodes)
|
|
|
|
if err != nil {
|
2022-11-02 10:41:39 +00:00
|
|
|
return "", err
|
2022-02-10 01:02:53 +00:00
|
|
|
}
|
|
|
|
writer.Flush()
|
|
|
|
|
2022-11-02 10:41:39 +00:00
|
|
|
return output.String(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustProcessFormatScenario(s formatScenario, decoder Decoder, encoder Encoder) string {
|
|
|
|
|
|
|
|
result, err := processFormatScenario(s, decoder, encoder)
|
|
|
|
if err != nil {
|
2023-03-25 23:59:15 +00:00
|
|
|
panic(fmt.Errorf("Bad scenario %v: %w", s.description, err))
|
2022-11-02 10:41:39 +00:00
|
|
|
}
|
|
|
|
return result
|
2022-02-10 01:02:53 +00:00
|
|
|
|
|
|
|
}
|