add format printing to capabilities command
@@ -16,6 +16,7 @@ package cmd
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"sync"
@@ -24,6 +25,7 @@ import (
"github.com/openconfig/gnmi/proto/gnmi"
"github.com/openconfig/gnmi/proto/gnmi_ext"
"github.com/spf13/viper"
+ "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/encoding/prototext"
"github.com/spf13/cobra"
@@ -85,10 +87,46 @@ func printCapResponse(r *gnmi.CapabilityResponse, address string) {
if len(addresses) > 1 && !viper.GetBool("no-prefix") {
printPrefix = fmt.Sprintf("[%s] ", address)
}
- if viper.GetString("format") == "prototext" {
+ switch viper.GetString("format") {
+ case "protojson":
+ b, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(r)
+ if err != nil {
+ logger.Printf("error marshaling protojson msg: %v", err)
+ if !viper.GetBool("log") {
+ fmt.Printf("error marshaling protojson msg: %v\n", err)
+ }
+ return
+ }
+ fmt.Printf("%s\n", indent(printPrefix, string(b)))
+ return
+ case "prototext":
fmt.Printf("%s\n", indent(printPrefix, prototext.Format(r)))
return
+ case "json":
+ capRspMsg := capResponse{}
+
+ capRspMsg.Version = r.GetGNMIVersion()
+ for _, sm := range r.SupportedModels {
+ capRspMsg.SupportedModels = append(capRspMsg.SupportedModels,
+ supportedModels{
+ Name: sm.GetName(),
+ Organization: sm.GetOrganization(),
+ Version: sm.GetVersion(),
+ })
+ }
+ for _, se := range r.SupportedEncodings {
+ capRspMsg.Encodings = append(capRspMsg.Encodings, se.String())
}
+ b, err := json.MarshalIndent(capRspMsg, printPrefix, " ")
+ if err != nil {
+ logger.Printf("failed to marshal capabilities response: %v", err)
+ if !viper.GetBool("log") {
+ fmt.Printf("failed to marshal capabilities response: %v", err)
+ return
+ }
+ }
+ fmt.Println(string(b))
+ default:
fmt.Printf("%sgNMI version: %s\n", printPrefix, r.GNMIVersion)
if viper.GetBool("version") {
return
@@ -101,6 +139,7 @@ func printCapResponse(r *gnmi.CapabilityResponse, address string) {
for _, se := range r.SupportedEncodings {
fmt.Printf("%s - %s\n", printPrefix, se.String())
}
+ }
fmt.Println()
}
@@ -109,3 +148,14 @@ func init() {
capabilitiesCmd.Flags().BoolVarP(&printVersion, "version", "", false, "show gnmi version only")
viper.BindPFlag("capabilities-version", capabilitiesCmd.LocalFlags().Lookup("version"))
}
+
+type capResponse struct {
+ Version string `json:"version,omitempty"`
+ SupportedModels []supportedModels `json:"supported-models,omitempty"`
+ Encodings []string `json:"encodings,omitempty"`
+}
+type supportedModels struct {
+ Name string `json:"name,omitempty"`
+ Organization string `json:"organization,omitempty"`
+ Version string `json:"version,omitempty"`
+}
