There are a few ways to access the last commit's identifier in Go code:
- Git command: You can use
git rev-parse HEAD
command to get the SHA-1 hash of the latest commit. In Go, you can execute this command by using the os/exec package like this:
package main
import (
"fmt"
"os/exec"
)
func main() {
out, err := exec.Command("git", "rev-parse", "HEAD").Output()
if err != nil {
fmt.Println(err)
}
commitHash := string(out)
fmt.Println(commitHash)
}
- Build flags: Another way is to use the
-ldflags
option during compilation to inject the commit hash as a build variable. You can set a build variable using the -X
flag followed by the package path and the variable name. Here's an example:
package main
import (
"fmt"
)
var commitHash string
func main() {
fmt.Println(commitHash)
}
// SetCommitHash sets the commit hash during compilation using -ldflags.
// go build -ldflags "-X main.commitHash=`git rev-parse --short HEAD`"
func SetCommitHash(hash string) {
commitHash = hash
}
You can set the commitHash
variable using the -ldflags
option like this:
go build -ldflags "-X main.commitHash=`git rev-parse --short HEAD`"
This will inject the commit hash into the binary at compile time.
I hope this helps!