1= Go Version 2 3image::https://travis-ci.org/christopherhein/go-version.svg?branch=master[link="https://travis-ci.org/christopherhein/go-version"] 4 5This package gives allows you to use https://github.com/spf13/cobra and 6https://github.com/goreleaser/goreleaser together to output your version in a 7simple way. Supporting multiple flags for mutating the output. 8 9== Usage 10 11To use this package you will need to create `cobra` command for version such as 12this. 13 14[source,go] 15---- 16package main 17 18import ( 19 "fmt" 20 goversion "go.hein.dev/go-version" 21 "github.com/spf13/cobra" 22) 23 24var ( 25 shortened = false 26 version = "dev" 27 commit = "none" 28 date = "unknown" 29 output = "json" 30 versionCmd = &cobra.Command{ 31 Use: "version", 32 Short: "Version will output the current build information", 33 Long: ``, 34 Run: func(_ *cobra.Command, _ []string) { 35 resp := goVersion.FuncWithOutput(shortened, version, commit, date, output) 36 fmt.Print(resp) 37 return 38 }, 39 } 40) 41 42func init() { 43 versionCmd.Flags().BoolVarP(&shortened, "short", "s", false, "Print just the version number.") 44 versionCmd.Flags().StringVarP(&output, "output", "o", "json", "Output format. One of 'yaml' or 'json'.") 45 rootCmd.AddCommand(versionCmd) 46} 47---- 48 49When you do this then you can pass in these flags at build time. _If you'd like 50more control of the output you can change the `Run` function to something more 51like this. 52 53[source,go] 54---- 55Run: func(_ *cobra.Command, _ []string) { 56 var response string 57 versionOutput := New(version, commit, date) 58 59 if shortened { 60 response = versionOutput.ToShortened() 61 } else { 62 response = versionOutput.ToJSON() 63 } 64 fmt.Printf("%+v", response) 65 return 66}, 67---- 68 69[source,shell] 70---- 71go build -ldflags "-X main.commit=<SOMEHASH> -X main.date=<SOMEDATE>" 72---- 73 74This then gives your CLI the ability to use this for the JSON output: 75 76[source,shell] 77---- 78$ ./my-cli version 79{"Version":"dev","Commit":"<SOMEHASH>","Date":"<SOMEDATE>"} 80---- 81 82Or to make this human readable you could use: 83 84[source,shell] 85---- 86$ ./my-cli -s 87 88Version: dev 89Commit: <SOMEHASH> 90Date: <SOMEDATE> 91---- 92 93== Testing 94 95To run the test suite all you need to do is run. 96 97[source,shell] 98---- 99go test -v ./... 100---- 101 102== Contributing 103 104If you want to contribute check out 105https://github.com/christopherhein/go-version/blob/master/CONTRIBUTING.adoc 106