github.com/lyraproj/hiera@v1.0.0-rc4/hiera/render.go (about) 1 package hiera 2 3 import ( 4 "io" 5 6 "github.com/tada/catch" 7 8 "github.com/tada/catch/pio" 9 10 "github.com/lyraproj/dgo/dgo" 11 "github.com/lyraproj/dgo/streamer" 12 "github.com/lyraproj/dgo/typ" 13 "github.com/lyraproj/dgo/util" 14 "github.com/lyraproj/dgo/vf" 15 "github.com/lyraproj/dgoyaml/yaml" 16 "github.com/lyraproj/hiera/api" 17 ) 18 19 // RenderName is the name of the option value that describes how to render output 20 type RenderName string 21 22 const ( 23 // YAML render output in YAML 24 YAML = RenderName(`yaml`) 25 // JSON render output in JSON 26 JSON = RenderName(`json`) 27 // Binary render output as binary data 28 Binary = RenderName(`binary`) 29 // Text render output as plain text 30 Text = RenderName(`s`) 31 ) 32 33 // Render renders a value on a writer using a specified RenderName 34 func Render(s api.Session, renderAs RenderName, value dgo.Value, out io.Writer) { 35 // Convert value to rich data format without references 36 dedupStream := func(value dgo.Value, consumer streamer.Consumer) { 37 opts := streamer.DefaultOptions() 38 opts.DedupLevel = streamer.NoDedup 39 ser := streamer.New(s.AliasMap(), opts) 40 ser.Stream(value, consumer) 41 } 42 43 switch renderAs { 44 case JSON: 45 if value.Equals(vf.Nil) { 46 pio.WriteString(out, "null\n") 47 } else { 48 dedupStream(value, streamer.JSON(out)) 49 pio.WriteByte(out, '\n') 50 } 51 52 case YAML: 53 if value.Equals(vf.Nil) { 54 pio.WriteString(out, "\n") 55 } else { 56 dc := streamer.DataCollector() 57 dedupStream(value, dc) 58 bs, err := yaml.Marshal(dc.Value()) 59 if err != nil { 60 panic(err) 61 } 62 pio.WriteString(out, string(bs)) 63 } 64 case Binary: 65 bi := vf.New(typ.Binary, value).(dgo.Binary) 66 _, err := out.Write(bi.GoBytes()) 67 if err != nil { 68 panic(err) 69 } 70 case Text: 71 util.Fprintln(out, value) 72 default: 73 panic(catch.Error(`unknown rendering '%s'`, renderAs)) 74 } 75 }