概述
编译时注入 git 版本信息,有利于故障排查。
实例
代码中命令逻辑 util/common/vars.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const ( VERSION_CMD_LONG = "version" VERSION_CMD_SHORT = "v" VERSION_CMD_DESC_BRIEF = "show version info" )
var versionCmd = &cobra.Command{ Use: VERSION_CMD_LONG, Short: VERSION_CMD_DESC_BRIEF, Version: "v1.1", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("%s", BuildInfoSprinter()) }, }
func NewVersionCommand() *cobra.Command { return versionCmd }
func BuildInfoSprinter() string { return fmt.Sprintf("当前版本: %s\n当前分支: %s\n当前CommitId: %s\n构建时间: %s\n", common.Version, common.Release, common.CommitId, common.BuildTime) }
var ( Version string Release string CommitId string BuildTime string )
|
1 2 3 4 5 6 7
| paramsPath=$(shell go list -m)/util/common Release=$(shell git branch --show-current) CommitId=$(shell git rev-parse HEAD) VersionTag=$(shell git describe --tags) BuildFlags := "-X $(paramsPath).Version=$(VersionTag) -X $(paramsPath).Release=$(Release) -X $(paramsPath).CommitId=$(CommitId) -X $(paramsPath).BuildTime=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ') -w -s" -trimpath BuildFlagsForDev := "-X $(paramsPath).Version=$(VersionTag) -X $(paramsPath).Release=$(Release) -X $(paramsPath).CommitId=$(CommitId) -X $(paramsPath).BuildTime=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ')"
|