2019-12-01 19:44:44 +00:00
|
|
|
package marshal
|
2019-11-23 03:52:29 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
yaml "github.com/mikefarah/yaml/v2"
|
|
|
|
errors "github.com/pkg/errors"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2019-12-01 19:44:44 +00:00
|
|
|
type YamlConverter interface {
|
|
|
|
YamlToString(context interface{}, trimOutput bool) (string, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type yamlConverter struct {}
|
|
|
|
|
|
|
|
func NewYamlConverter() YamlConverter {
|
|
|
|
return &yamlConverter{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (y *yamlConverter) YamlToString(context interface{}, trimOutput bool) (string, error) {
|
2019-11-23 03:52:29 +00:00
|
|
|
switch context := context.(type) {
|
|
|
|
case string:
|
|
|
|
return context, nil
|
|
|
|
default:
|
2019-12-01 19:44:44 +00:00
|
|
|
return y.marshalContext(context, trimOutput)
|
2019-11-23 03:52:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-01 19:44:44 +00:00
|
|
|
func (y *yamlConverter) marshalContext(context interface{}, trimOutput bool) (string, error) {
|
2019-11-23 03:52:29 +00:00
|
|
|
out, err := yaml.Marshal(context)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return "", errors.Wrap(err, "error printing yaml")
|
|
|
|
}
|
|
|
|
|
|
|
|
outStr := string(out)
|
|
|
|
// trim the trailing new line as it's easier for a script to add
|
|
|
|
// it in if required than to remove it
|
|
|
|
if trimOutput {
|
|
|
|
return strings.Trim(outStr, "\n "), nil
|
|
|
|
}
|
|
|
|
return outStr, nil
|
|
|
|
}
|