github.com/iter8-tools/iter8@v1.1.2/cmd/version.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  
     7  	"github.com/iter8-tools/iter8/base"
     8  	"github.com/spf13/cobra"
     9  )
    10  
    11  // versionDesc is the description of the version command
    12  var versionDesc = `
    13  Print the version of Iter8 CLI.
    14  
    15  	$ iter8 version
    16  
    17  The output may look as follows:
    18  
    19  	$ cmd.BuildInfo{Version:"v0.13.0", GitCommit:"f24e86f3d3eceb02eabbba54b40af2c940f55ad5", GoVersion:"go1.19.3"}
    20  
    21  In the sample output shown above:
    22  
    23  - Version is the semantic version of the Iter8 CLI.
    24  - GitCommit is the SHA hash for the commit that this version was built from.
    25  - GoVersion is the version of Go that was used to compile Iter8 CLI.
    26  `
    27  
    28  var (
    29  	// gitCommit is the git sha1
    30  	gitCommit = ""
    31  )
    32  
    33  // BuildInfo describes the compile time information.
    34  type BuildInfo struct {
    35  	// Version is the semantic version
    36  	Version string `json:"version,omitempty"`
    37  	// GitCommit is the git sha1.
    38  	GitCommit string `json:"git_commit,omitempty"`
    39  	// GoVersion is the version of the Go compiler used to compile Iter8.
    40  	GoVersion string `json:"go_version,omitempty"`
    41  }
    42  
    43  // newVersionCmd creates the version command
    44  func newVersionCmd() *cobra.Command {
    45  	var short bool
    46  	// versionCmd represents the version command
    47  	cmd := &cobra.Command{
    48  		Use:           "version",
    49  		Short:         "Print Iter8 CLI version",
    50  		Long:          versionDesc,
    51  		SilenceErrors: true,
    52  		RunE: func(_ *cobra.Command, _ []string) error {
    53  			v := getBuildInfo()
    54  			if short {
    55  				if len(v.GitCommit) >= 7 {
    56  					fmt.Printf("%s+g%s", base.Version, v.GitCommit[:7])
    57  					fmt.Println()
    58  					return nil
    59  				}
    60  				fmt.Println(base.Version)
    61  				return nil
    62  			}
    63  			fmt.Printf("%#v", v)
    64  			fmt.Println()
    65  			return nil
    66  		},
    67  	}
    68  	addShortFlag(cmd, &short)
    69  	return cmd
    70  }
    71  
    72  // get returns build info
    73  func getBuildInfo() BuildInfo {
    74  	v := BuildInfo{
    75  		Version:   base.Version,
    76  		GitCommit: gitCommit,
    77  		GoVersion: runtime.Version(),
    78  	}
    79  	return v
    80  }
    81  
    82  // addShortFlag adds the short flag to the version command
    83  func addShortFlag(cmd *cobra.Command, shortPtr *bool) {
    84  	cmd.Flags().BoolVar(shortPtr, "short", false, "print abbreviated version info")
    85  	cmd.Flags().Lookup("short").NoOptDefVal = "true"
    86  }