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 {
2021-12-30 04:39:40 +00:00
separator rune
2021-12-01 01:08:47 +00:00
}
2021-12-30 04:39:40 +00:00
func NewCsvEncoder(separator rune) Encoder {
return &csvEncoder{separator}
2021-12-01 01:08:47 +00:00
}
2021-12-30 04:39:40 +00:00
func (e *csvEncoder) CanHandleAliases() bool {
return false
}
func (e *csvEncoder) PrintDocumentSeparator(writer io.Writer) error {
2021-12-22 01:22:29 +00:00
return nil
}
2021-12-30 04:39:40 +00:00
func (e *csvEncoder) PrintLeadingContent(writer io.Writer, content string) error {
2021-12-22 01:22:29 +00:00
return nil
}
2021-12-30 04:39:40 +00:00
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
}
2021-12-30 04:39:40 +00:00
return csvWriter.Write(stringValues)
2021-12-02 01:11:15 +00:00
}
2021-12-30 04:39:40 +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 {
2021-12-30 04:39:40 +00:00
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)
}
2021-12-30 04:39:40 +00:00
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
}