yq/pkg/yqlib/encoder_csv.go

71 lines
1.6 KiB
Go
Raw Normal View History

2021-12-01 01:08:47 +00:00
package yqlib
import (
"encoding/csv"
"fmt"
"io"
yaml "gopkg.in/yaml.v3"
)
type csvEncoder struct {
separator rune
2021-12-01 01:08:47 +00:00
}
func NewCsvEncoder(separator rune) Encoder {
return &csvEncoder{separator}
2021-12-01 01:08:47 +00:00
}
func (e *csvEncoder) CanHandleAliases() bool {
return false
}
func (e *csvEncoder) PrintDocumentSeparator(writer io.Writer) error {
return nil
}
func (e *csvEncoder) PrintLeadingContent(writer io.Writer, content string) error {
return nil
}
func (e *csvEncoder) encodeRow(csvWriter *csv.Writer, contents []*yaml.Node) error {
2021-12-02 01:11:15 +00:00
stringValues := make([]string, len(contents))
for i, child := range contents {
if child.Kind != yaml.ScalarNode {
return fmt.Errorf("csv encoding only works for arrays of scalars (string/numbers/booleans), child[%v] is a %v", i, child.Tag)
}
stringValues[i] = child.Value
}
return csvWriter.Write(stringValues)
2021-12-02 01:11:15 +00:00
}
func (e *csvEncoder) Encode(writer io.Writer, originalNode *yaml.Node) error {
csvWriter := csv.NewWriter(writer)
csvWriter.Comma = e.separator
2021-12-01 01:08:47 +00:00
// node must be a sequence
node := unwrapDoc(originalNode)
if node.Kind != yaml.SequenceNode {
2021-12-02 01:11:15 +00:00
return fmt.Errorf("csv encoding only works for arrays, got: %v", node.Tag)
} else if len(node.Content) == 0 {
return nil
}
if node.Content[0].Kind == yaml.ScalarNode {
return e.encodeRow(csvWriter, node.Content)
2021-12-01 01:08:47 +00:00
}
for i, child := range node.Content {
2021-12-02 01:11:15 +00:00
if child.Kind != yaml.SequenceNode {
2021-12-01 01:08:47 +00:00
return fmt.Errorf("csv encoding only works for arrays of scalars (string/numbers/booleans), child[%v] is a %v", i, child.Tag)
}
err := e.encodeRow(csvWriter, child.Content)
2021-12-02 01:11:15 +00:00
if err != nil {
return err
}
2021-12-01 01:08:47 +00:00
}
2021-12-02 01:11:15 +00:00
return nil
2021-12-01 01:08:47 +00:00
}