mirror of
https://github.com/mikefarah/yq.git
synced 2026-03-10 15:54:26 +00:00
Adds a new CLI flag that enables compact sequence indentation where '- ' is
considered part of the indentation. This leverages the CompactSeqIndent()
method from the underlying go.yaml.in/yaml/v4 library.
Example output with --yaml-compact-seq-indent:
parent:
items:
- one
- two
Instead of the default:
parent:
items:
- one
- two
Closes #1841
81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package yqlib
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"strings"
|
|
|
|
"go.yaml.in/yaml/v4"
|
|
)
|
|
|
|
type yamlEncoder struct {
|
|
prefs YamlPreferences
|
|
}
|
|
|
|
func NewYamlEncoder(prefs YamlPreferences) Encoder {
|
|
return &yamlEncoder{prefs}
|
|
}
|
|
|
|
func (ye *yamlEncoder) CanHandleAliases() bool {
|
|
return true
|
|
}
|
|
|
|
func (ye *yamlEncoder) PrintDocumentSeparator(writer io.Writer) error {
|
|
return PrintYAMLDocumentSeparator(writer, ye.prefs.PrintDocSeparators)
|
|
}
|
|
|
|
func (ye *yamlEncoder) PrintLeadingContent(writer io.Writer, content string) error {
|
|
return PrintYAMLLeadingContent(writer, content, ye.prefs.PrintDocSeparators, ye.prefs.ColorsEnabled)
|
|
}
|
|
|
|
func (ye *yamlEncoder) Encode(writer io.Writer, node *CandidateNode) error {
|
|
log.Debug("encoderYaml - going to print %v", NodeToString(node))
|
|
// Detect line ending style from LeadingContent
|
|
lineEnding := "\n"
|
|
if strings.Contains(node.LeadingContent, "\r\n") {
|
|
lineEnding = "\r\n"
|
|
}
|
|
if node.Kind == ScalarNode && ye.prefs.UnwrapScalar {
|
|
valueToPrint := node.Value
|
|
if node.LeadingContent == "" || valueToPrint != "" {
|
|
valueToPrint = valueToPrint + lineEnding
|
|
}
|
|
return writeString(writer, valueToPrint)
|
|
}
|
|
|
|
destination := writer
|
|
tempBuffer := bytes.NewBuffer(nil)
|
|
if ye.prefs.ColorsEnabled {
|
|
destination = tempBuffer
|
|
}
|
|
|
|
var encoder = yaml.NewEncoder(destination)
|
|
|
|
encoder.SetIndent(ye.prefs.Indent)
|
|
if ye.prefs.CompactSequenceIndent {
|
|
encoder.CompactSeqIndent()
|
|
}
|
|
|
|
target, err := node.MarshalYAML()
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
trailingContent := target.FootComment
|
|
target.FootComment = ""
|
|
|
|
if err := encoder.Encode(target); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := ye.PrintLeadingContent(destination, trailingContent); err != nil {
|
|
return err
|
|
}
|
|
|
|
if ye.prefs.ColorsEnabled {
|
|
return colorizeAndPrint(tempBuffer.Bytes(), writer)
|
|
}
|
|
return nil
|
|
}
|