Search code examples
gitgogit-commit

How to access the last commit identifier in Go code?


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.


Solution

  • 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!