在Go代码中如何访问最后一次提交的标识符?

huangapple go评论88阅读模式
英文:

How to access the last commit identifier in Go code?

问题

在Go代码中,有没有办法访问最后一次提交的标识符?我想用它来命名我代码生成的输出文件,这样我就可以找到与每个提交相关的输出。

我尝试找到解决方案,但似乎没有简单的解决办法。

英文:

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.

答案1

得分: 0

在Go代码中,有几种方法可以访问最后一次提交的标识符:

  1. Git命令:你可以使用git rev-parse HEAD命令获取最新提交的SHA-1哈希值。在Go中,你可以使用os/exec包执行这个命令,像这样:
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. 构建标志:另一种方法是在编译过程中使用-ldflags选项将提交哈希作为构建变量注入。你可以使用-X标志设置构建变量,后面跟着包路径和变量名。这是一个示例:
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
}

你可以使用-ldflags选项设置commitHash变量,像这样:

go build -ldflags "-X main.commitHash=`git rev-parse --short HEAD`"

这将在编译时将提交哈希注入到二进制文件中。

希望对你有所帮助!

英文:

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!

huangapple
  • 本文由 发表于 2023年6月22日 22:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76532734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定