-
Notifications
You must be signed in to change notification settings - Fork 1
/
yaml_proto.go
64 lines (52 loc) · 1.15 KB
/
yaml_proto.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
package printers
import (
"encoding/json"
"fmt"
"io"
"os"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"sigs.k8s.io/yaml"
)
// ProtoYAMLPrinter prints data of type proto.Message in YAML format
type ProtoYAMLPrinter struct {
out io.Writer
fallback bool
}
func NewProtoYAMLPrinter() *ProtoYAMLPrinter {
return &ProtoYAMLPrinter{
out: os.Stdout,
}
}
func (p *ProtoYAMLPrinter) WithOut(out io.Writer) *ProtoYAMLPrinter {
p.out = out
return p
}
func (p *ProtoYAMLPrinter) WithFallback(fallback bool) *ProtoYAMLPrinter {
p.fallback = fallback
return p
}
func (p *ProtoYAMLPrinter) Print(data any) error {
msg, ok := data.(proto.Message)
if !ok {
if p.fallback {
return NewYAMLPrinter().WithOut(p.out).Print(data)
}
return fmt.Errorf("unable to marshal proto message because given data is not of type proto.Message")
}
intermediate, err := protojson.Marshal(msg)
if err != nil {
return err
}
var r any
err = json.Unmarshal(intermediate, &r)
if err != nil {
return err
}
content, err := yaml.Marshal(r)
if err != nil {
return err
}
fmt.Fprintf(p.out, "%s", string(content))
return nil
}