github.com/kastenhq/syft@v0.0.0-20230821225854-0710af25cdbe/cmd/syft/cli/version.go (about)

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