0

Is there any way to have access to the last commit's identifier in the go code? I'm going to use it for the naming the output files my code generates and in this way I can find outputs related to each commit.

I've tried to find a solution but it seems that there is no trivial solution for it.

  • You can probably leverage [go-git](https://pkg.go.dev/github.com/go-git/go-git/v5) to get the commit – joshmeranda Jun 22 '23 at 14:03
  • Can you describe exactly what you want to do? When you execute the code, there is no source, so there is no git commit to find. You need to inject any build information during the build process (some of which is done automatically, see https://stackoverflow.com/questions/15711780/go-how-to-add-git-revision-to-binaries-built/69611778#69611778) – JimB Jun 22 '23 at 14:04
  • you probably want `debug.ReadBuildInfo().[]Settings.Key == "vcs.revision"` – JBirdVegas Jun 22 '23 at 16:38

1 Answers1

0

There are a few ways to access the last commit's identifier in Go code:

  1. 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)
}
  1. 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!