LoginSignup
0
0

More than 1 year has passed since last update.

【Golang】Gitコミットのrevision番号(commit id)を取得するには

Posted at

Go 1.18以降でBuildInfoを使う場合

BuildInfoのSettingsにある"vcs.revision"を取得。

main.go
package main

import (
	"fmt"
	"runtime/debug"
)

func main() {
	var rev string
	info, _ := debug.ReadBuildInfo()
	for _, s := range info.Settings {
		if s.Key == "vcs.revision" {
			rev = s.Value
		}
	 }
	fmt.Printf("revision: %s\n", rev)
}
$ go mod init sample 
$ git init && git add . && git commit -m 'initial commit'
$ go build . && ./sample
revision: bd486152ad205a33a1ec87c1122e3e20bda577aa

Go 1.18より前でBuildInfoを使わない場合

Gitコマンドを叩き、CombinedOutputで標準出力を取得。.gitディレクトリがあれば取得できます。

main.go
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("git", "show", "--no-patch", "--format=%H")
	out, _ := cmd.CombinedOutput()
	fmt.Printf("revision: %s\n", out)
}
$ go mod init sample 
$ git init && git add . && git commit -m 'initial commit'
$ go build . && ./sample
revision: 680ec96a84debf616fd3f339e9b55b0897ac1b9c

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0