golang

为程序添加版本功能

Posted by Liangjf on May 27, 2019

为程序添加版本功能

选项解释

  • -v 用于获取可执行文件信息
  • -ldflags 指定参数替换
  • -X 指定命令行传参
  • main.gitTag 包名.参数名

编译

go build -v -ldflags "-X main.gitTag=1 -X main.gitCommit=2 -X main.gitTreeState=3 -X main.buildDate=4"

查看版本信息

  • 执行可执行程序 -v
  • xxxx -v

      F:\go_home\src\myselft\goVersion>goVersion.exe -v
      {
        "gitTaggitTag": "1",
        "gitCommit": "2",
        "gitTreeState": "3",
        "buildDate": "4",
        "goVersion": "go1.12.4",
        "compiler": "gc",
        "platform": "windows/amd64"
      }
    

shell脚本(Makefile)

versionDir = "demo/pkg/version"
gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi)
buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z)
gitCommit = $(shell git log --pretty=format:'%H' -n 1)
gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi)

ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}"

go build -v -ldflags ${ldflags} .

通过此脚本,可以获得版本信息有:build的时间,git commit的时间,git tag等