github.com/cosmos/cosmos-sdk@v0.50.10/version/command.go (about) 1 package version 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7 8 "github.com/spf13/cobra" 9 "sigs.k8s.io/yaml" 10 ) 11 12 const ( 13 flagLong = "long" 14 flagOutput = "output" 15 ) 16 17 // NewVersionCommand returns a CLI command to interactively print the application binary version information. 18 // Note: When seeking to add the extra info to the context 19 // The below can be added to the initRootCmd to include the extraInfo field 20 // 21 // cmdContext := context.WithValue(context.Background(), version.ContextKey{}, extraInfo) 22 // rootCmd.SetContext(cmdContext) 23 func NewVersionCommand() *cobra.Command { 24 cmd := &cobra.Command{ 25 Use: "version", 26 Short: "Print the application binary version information", 27 Args: cobra.NoArgs, 28 RunE: func(cmd *cobra.Command, _ []string) error { 29 verInfo := NewInfo() 30 31 if long, _ := cmd.Flags().GetBool(flagLong); !long { 32 fmt.Fprintln(cmd.OutOrStdout(), verInfo.Version) 33 return nil 34 } 35 36 // Extract and set extra information from the context 37 verInfo.ExtraInfo = extraInfoFromContext(cmd) 38 39 var ( 40 bz []byte 41 err error 42 ) 43 44 output, _ := cmd.Flags().GetString(flagOutput) 45 switch strings.ToLower(output) { 46 case "json": 47 bz, err = json.Marshal(verInfo) 48 49 default: 50 bz, err = yaml.Marshal(&verInfo) 51 } 52 53 if err != nil { 54 return err 55 } 56 57 fmt.Fprintln(cmd.OutOrStdout(), string(bz)) 58 return nil 59 }, 60 } 61 62 cmd.Flags().Bool(flagLong, false, "Print long version information") 63 cmd.Flags().StringP(flagOutput, "o", "text", "Output format (text|json)") 64 65 return cmd 66 } 67 68 func extraInfoFromContext(cmd *cobra.Command) ExtraInfo { 69 ctx := cmd.Context() 70 if ctx != nil { 71 extraInfo, ok := ctx.Value(ContextKey{}).(ExtraInfo) 72 if ok { 73 return extraInfo 74 } 75 } 76 return nil 77 }