yq/pkg/yqlib/encoder_csv.go

58 lines
1.3 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 {
destination csv.Writer
}
func NewCsvEncoder(destination io.Writer, separator rune) Encoder {
csvWriter := *csv.NewWriter(destination)
csvWriter.Comma = separator
return &csvEncoder{csvWriter}
}
2021-12-02 01:11:15 +00:00
func (e *csvEncoder) encodeRow(contents []*yaml.Node) error {
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 e.destination.Write(stringValues)
}
2021-12-01 01:08:47 +00:00
func (e *csvEncoder) Encode(originalNode *yaml.Node) error {
// 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(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-02 01:11:15 +00:00
err := e.encodeRow(child.Content)
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
}