yq/pkg/yqlib/encoder.go

56 lines
1.0 KiB
Go
Raw Normal View History

2020-01-10 11:01:59 +00:00
package yqlib
import (
"encoding/json"
"io"
yaml "gopkg.in/yaml.v3"
)
type Encoder interface {
Encode(node *yaml.Node) error
}
type yamlEncoder struct {
encoder *yaml.Encoder
}
2020-02-03 05:52:12 +00:00
func NewYamlEncoder(destination io.Writer, indent int) Encoder {
2020-01-10 11:01:59 +00:00
var encoder = yaml.NewEncoder(destination)
2020-02-03 05:52:12 +00:00
if indent < 0 {
indent = 0
}
encoder.SetIndent(indent)
2020-01-10 11:01:59 +00:00
return &yamlEncoder{encoder}
}
func (ye *yamlEncoder) Encode(node *yaml.Node) error {
return ye.encoder.Encode(node)
}
type jsonEncoder struct {
encoder *json.Encoder
}
2020-02-03 05:52:12 +00:00
func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder {
2020-01-10 11:01:59 +00:00
var encoder = json.NewEncoder(destination)
2020-02-03 05:52:12 +00:00
var indentString = ""
for index := 0; index < indent; index++ {
indentString = indentString + " "
}
2020-02-03 05:31:03 +00:00
if prettyPrint {
2020-02-03 05:52:12 +00:00
encoder.SetIndent("", indentString)
2020-02-03 05:31:03 +00:00
}
2020-01-10 11:01:59 +00:00
return &jsonEncoder{encoder}
}
func (je *jsonEncoder) Encode(node *yaml.Node) error {
var dataBucket interface{}
errorDecoding := node.Decode(&dataBucket)
if errorDecoding != nil {
return errorDecoding
}
return je.encoder.Encode(dataBucket)
}