Last active
May 10, 2024 01:42
-
-
Save piotrpersona/ef4c5faaef07987d176d513e23cd9d0f to your computer and use it in GitHub Desktop.
Golang build ldflags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GIT_TAG="$( git describe --abbrev=0 )" | |
GIT_HASH="$( git rev-parse HEAD )" | |
BUILD_DATE="$( date +%F )" # Note: An ldflag cannot contain whitespace | |
REPO="github.com/user/repo" | |
OUTPUT_NAME="build-artifact" | |
PACKAGE="main.go" | |
read -r -d '' LDFLAGS << EOM | |
-X ${REPO}/cmd.gitVersionTag=${GIT_TAG} | |
-X ${REPO}/cmd.gitHash=${GIT_HASH} | |
-X ${REPO}/cmd.buildDate=${BUILD_DATE} | |
EOM | |
go build -ldflags "${LDFLAGS}" \ | |
-o "${GOPATH}/bin/${OUTPUT_NAME}" "${PACKAGE}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"fmt" | |
"github.com/spf13/cobra" | |
) | |
var gitHash, gitVersionTag, buildDate string | |
// versionCmd represents the version command | |
var versionCmd = &cobra.Command{ | |
Use: "version", | |
Short: "Display version", | |
Run: func(cmd *cobra.Command, args []string) { | |
fmt.Printf("version: %s\n", gitVersionTag) | |
fmt.Printf("hash: %s\n", gitHash) | |
fmt.Printf("build date: %s\n", buildDate) | |
}, | |
} | |
func init() { | |
rootCmd.AddCommand(versionCmd) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment