Skip to content

Commit 76a24e6

Browse files
author
Yanqiang Miao
committed
Use protobuf/jsonpb instead of golang json in some cases
Signed-off-by: Yanqiang Miao <[email protected]>
1 parent 4e3c997 commit 76a24e6

File tree

3 files changed

+869
-6
lines changed

3 files changed

+869
-6
lines changed

cmd/crictl/container.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -458,10 +458,9 @@ func ContainerStatus(client pb.RuntimeServiceClient, ID, output string) error {
458458

459459
switch output {
460460
case "json":
461-
return outputJSON(r.Status)
462-
461+
return outputProtobufObjAsJSON(r.Status)
463462
case "yaml":
464-
return outputYAML(r.Status)
463+
return outputProtobufObjAsYAML(r.Status)
465464
}
466465

467466
// output in table format by default.
@@ -538,7 +537,6 @@ func ListContainers(client pb.RuntimeServiceClient, opts listOptions) error {
538537
switch opts.output {
539538
case "json":
540539
return outputJSON(r.Containers)
541-
542540
case "yaml":
543541
return outputYAML(r.Containers)
544542
}

cmd/crictl/util.go

+38-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import (
2424
"sort"
2525

2626
"github.com/ghodss/yaml"
27+
"github.com/golang/protobuf/jsonpb"
28+
"github.com/golang/protobuf/proto"
2729
"github.com/urfave/cli"
2830
"google.golang.org/grpc"
2931
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
@@ -178,8 +180,42 @@ func outputYAML(v interface{}) error {
178180
return nil
179181
}
180182

181-
func outputStatusInfo(status interface{}, info map[string]string, format string) error {
182-
statusByte, err := json.Marshal(status)
183+
func protobufObjectToJSON(obj proto.Message) (string, error) {
184+
jsonpbMarshaler := jsonpb.Marshaler{EmitDefaults: true, Indent: " "}
185+
marshaledJSON, err := jsonpbMarshaler.MarshalToString(obj)
186+
if err != nil {
187+
return "", err
188+
}
189+
190+
return marshaledJSON, nil
191+
}
192+
193+
func outputProtobufObjAsJSON(obj proto.Message) error {
194+
marshaledJSON, err := protobufObjectToJSON(obj)
195+
if err != nil {
196+
return err
197+
}
198+
199+
fmt.Println(marshaledJSON)
200+
return nil
201+
}
202+
203+
func outputProtobufObjAsYAML(obj proto.Message) error {
204+
marshaledJSON, err := protobufObjectToJSON(obj)
205+
if err != nil {
206+
return err
207+
}
208+
marshaledYAML, err := yaml.JSONToYAML([]byte(marshaledJSON))
209+
if err != nil {
210+
return err
211+
}
212+
213+
fmt.Println(string(marshaledYAML))
214+
return nil
215+
}
216+
217+
func outputStatusInfo(status proto.Message, info map[string]string, format string) error {
218+
statusByte, err := protobufObjectToJSON(status)
183219
if err != nil {
184220
return err
185221
}

0 commit comments

Comments
 (0)