go: 从git得到版本信息的脚本
一,脚本:
#!/bin/bash
gitTag=$(if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi)
echo $gitTag;
buildDate=$(TZ=Asia/Shanghai date +%Y-%m-%d\ %H:%M:%S)
echo $buildDate
gitCommit=$(git log --pretty=format:'%H' -n 1)
echo $gitCommit
gitBranch=$(git rev-parse --abbrev-ref HEAD)
echo $gitBranch
ldflags="-X main.gitTag=${gitTag} -X main.buildDate=${buildDate} -X main.gitBranch=${gitBranch} -X main.gitCommit=${gitCommit}"
echo $ldflags
go build -ldflags ${ldflags}
二,测试效果
$ ./build.sh
v1.0.2
2024-12-02 14:23:12
decffea369018dc5495e230fb6cace62cd233c32
master
-X main.gitTag=v1.0.2 -X main.buildDate=2024-12-02 14:23:12 -X main.gitBranch=master -X main.gitCommit=decffea369018dc5495e230fb6cace62cd233c32