英文:
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代码中,有几种方法可以访问最后一次提交的标识符:
- 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)
}
- 构建标志:另一种方法是在编译过程中使用
-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:
- 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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论