github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/cmd/gosbom/cli/version.go (about) 1 package cli 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "log" 7 "os" 8 9 "github.com/nextlinux/gosbom/cmd/gosbom/cli/options" 10 "github.com/nextlinux/gosbom/internal" 11 "github.com/nextlinux/gosbom/internal/config" 12 "github.com/nextlinux/gosbom/internal/version" 13 "github.com/spf13/cobra" 14 "github.com/spf13/viper" 15 ) 16 17 func Version(v *viper.Viper, _ *config.Application) *cobra.Command { 18 o := &options.VersionOptions{} 19 cmd := &cobra.Command{ 20 Use: "version", 21 Short: "show the version", 22 RunE: func(cmd *cobra.Command, args []string) error { 23 return printVersion(o.Output) 24 }, 25 } 26 27 err := o.AddFlags(cmd, v) 28 if err != nil { 29 log.Fatal(err) 30 } 31 32 return cmd 33 } 34 35 func printVersion(output string) error { 36 versionInfo := version.FromBuild() 37 38 switch output { 39 case "text": 40 fmt.Println("Application: ", internal.ApplicationName) 41 fmt.Println("Version: ", versionInfo.Version) 42 fmt.Println("JsonSchemaVersion: ", internal.JSONSchemaVersion) 43 fmt.Println("BuildDate: ", versionInfo.BuildDate) 44 fmt.Println("GitCommit: ", versionInfo.GitCommit) 45 fmt.Println("GitDescription: ", versionInfo.GitDescription) 46 fmt.Println("Platform: ", versionInfo.Platform) 47 fmt.Println("GoVersion: ", versionInfo.GoVersion) 48 fmt.Println("Compiler: ", versionInfo.Compiler) 49 50 case "json": 51 enc := json.NewEncoder(os.Stdout) 52 enc.SetEscapeHTML(false) 53 enc.SetIndent("", " ") 54 err := enc.Encode(&struct { 55 version.Version 56 Application string `json:"application"` 57 }{ 58 Version: versionInfo, 59 Application: internal.ApplicationName, 60 }) 61 if err != nil { 62 fmt.Printf("failed to show version information: %+v\n", err) 63 os.Exit(1) 64 } 65 default: 66 fmt.Printf("unsupported output format: %s\n", output) 67 os.Exit(1) 68 } 69 70 return nil 71 }