cue icon indicating copy to clipboard operation
cue copied to clipboard

encoding/yaml: encoder that receives an io.Writer

Open nyarly opened this issue 3 years ago • 3 comments

Building a Go tool emit multiple files, I need to be able to emit JSON and YAML based on CUE values.

For JSON, I have

func writeJSON(path string, v cue.Value) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	enc := json.NewEncoder(f)
	enc.SetIndent("", "    ")
	return enc.Encode(v)
}

(just using Go's encoding/json)

For YAML it's like

import "cuelang.org/go/pkg/encoding/yaml"

// notionally:
// function writeYAML(path string, v cue.Value) error {
// but I'm assembling from my code
str, err := yaml.Marshal(v)
if err != nil {
  return err
}
bs := []byte(str)
f, err := os.Create(path)
if err != nil {
	return err
}
defer f.Close()

_, err = f.Write(bs)	
}

It'd be great to have a streaming YAML encoder. I think encoding a string, converting to bytes, and then writing is probably not my biggest performance problem, but it couldn't hurt.

nyarly avatar Nov 01 '21 22:11 nyarly

@nyarly did you perhaps mean to reference https://pkg.go.dev/cuelang.org/[email protected]/encoding/yaml above? cuelang.org/go/pkg/encoding/yaml is definition of the builtin package encoding/yaml.

myitcv avatar Nov 03 '21 06:11 myitcv

I'd found the pkg implementation and was using that. The nice thing about using Encode is that it would be a []byte value already, so we can save a conversion.

Being able to stream the output remains a (perhaps only aesthetic) benefit.

nyarly avatar Nov 03 '21 18:11 nyarly

Indeed. The pattern from encoding/json of being able to create encoders/decoders that effectively wrap an io.{Reader,Writer} makes sense. Any such implementation would however live in the encoding/yaml package, not the builtin pkg/encoding/yaml.

myitcv avatar Nov 06 '21 08:11 myitcv