forked from hofstadter-io/hof
/
fmt.go
71 lines (55 loc) · 1.14 KB
/
fmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package cuetils
import (
"bytes"
"encoding/json"
"fmt"
"cuelang.org/go/cue"
"cuelang.org/go/cue/format"
"cuelang.org/go/encoding/yaml"
)
func FormatOutput(val cue.Value, format string) (string, error) {
switch format {
case "cue", "CUE":
return formatCue(val)
case "json":
return formatJson(val)
case "yml", "yaml":
return formatYaml(val)
default:
return "", fmt.Errorf("unknown output encoding %q", format)
}
}
func formatCue(val cue.Value) (string, error) {
syn := val.Syntax(
cue.Final(),
cue.ResolveReferences(true),
cue.Concrete(true),
cue.Definitions(false),
cue.Hidden(false),
cue.Optional(false),
cue.Attributes(false),
cue.Docs(false),
)
bs, err := format.Node(syn)
if err != nil {
return "", err
}
return string(bs), nil
}
func formatJson(val cue.Value) (string, error) {
var w bytes.Buffer
d := json.NewEncoder(&w)
d.SetIndent("", " ")
err := d.Encode(val)
if _, ok := err.(*json.MarshalerError); ok {
return "", err
}
return w.String(), nil
}
func formatYaml(val cue.Value) (string, error) {
bs, err := yaml.Encode(val)
if err != nil {
return "", err
}
return string(bs), nil
}