编译 Go 程序时加入 git commit 等额外信息

在编译 Go 程序的时候如何加入一些额外的信息,比如 当前最新的 commit sha,编译的 go version 之类的

通过 go build -ldflags "-X importpath.name=value’ " 赋值字符串value给指定包importpath中的变量name

-ldflags 会将后边的参数传递给 go tool link 链接器
go tool link 的 -X 会将字符串赋值给指定包中变量,格式是 importpath.name=value

// main.go
package main

import "fmt"

var (
    Author string
    GoVersion   string
)

func main() {
    fmt.Printf("Author: %s\n", Author)
    fmt.Printf("GoVersion: %s\n", Date)
}

可以赋值多个变量

$ go build -ldflags "-X 'main.Author=iceber' -X 'main.GoVersion=`go version`'" main.go
$ ./main
Author: iceber
GoVersion: go version go1.13.4 darwin/amd64

赋值其他包中的变量

$ go build -ldflags "-X 'github.com/Iceber/test/pkg/build.GitCommitSha=`git log --pretty=format:%h`'" .

分享一下获取 git commit sha 的方法

获取一行 commit sha + commit message

# 显示一行简洁的信息 sha 和 message
$ git log --pretty=oneline -1
1b956f133ba1de1d53f76461d6d1b625b303f29d fix

使用 abbrev-commit flag 可以获取前 7 位 commit sha

$ git log --pretty=oneline --abbrev-commit -1
1b956f13 fix

直接使用 oneline flag

$ git log --oneline -1
1b956f13 fix

如果只显示 sha 怎么办呢

$ git log --pretty=format:'%h' -1
1b956f13

需要使用 pretty format
%h 可以打印缩短的 sha
%H 打印完整 sha
%s 打印 commit message

详细可以参考 git log 输出格式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值