我正在使用git标签在go程序中注入(inject)版本,例如在Makefile中:

VERSION = $(shell git describe --always --dirty)

github_pki: main.go
    CGO_ENABLED=0 GOOS=linux \
      go build -a \
          -ldflags="-X main.version=$(VERSION)" \
        -installsuffix cgo -o $@ $<

其中versionmain.go中定义为:
var version = "undefined"

使用make效果很好,但使用go getgo build时效果不好。有没有办法在不使用外部构建系统的情况下(即使用ldflags/go build)使此go get工作?

最佳答案

issue 22147 cmd/go : Make it easier to embed compiled git SHA into binary 中,您现在可以(在Go 1.12 +,2019年第一季度,2年后)使用依赖项的替代方法(尚未在主程序中使用)。

因此,您仍然需要-ldflags来记录源的版本。
而不是记录依赖项的版本:现在可用。



// BuildInfo represents the build information read from the running binary.

type BuildInfo struct {
    Path string    // The main package path
    Main Module    // The main module information
    Deps []*Module // Module dependencies
}

// ReadBuildInfo returns the build information embedded in the running binary.
   The information is available only in binaries built with module support.

func ReadBuildInfo() (info *BuildInfo, ok bool)

这来自commit 45e9c55:



您可以在issue 26404: "cmd/go: export module information for binaries programmatically"中看到它

package main

import (
    "log"
    "runtime/debug"

    "github.com/kr/pretty"
)

func main() {
    bi, ok := debug.ReadBuildInfo()
    if !ok {
        log.Fatal("!ok")
    }
    pretty.Println(bi)
}

你得到:

&debug.BuildInfo{
    Path: "foo.to/v",
    Main: debug.Module{
        Path:    "foo.to/v",
        Version: "(devel)",
        Sum:     "",
        Replace: (*debug.Module)(nil),
    },
    Deps: {
        &debug.Module{
            Path:    "github.com/kr/pretty",
            Version: "v0.1.0",
            Sum:     "h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=",
            Replace: (*debug.Module)(nil),
        },
        &debug.Module{
            Path:    "github.com/kr/text",
            Version: "v0.1.0",
            Sum:     "h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=",
            Replace: (*debug.Module)(nil),
        },
    },
}



因此,主要问题仍然存在:issues/29814 " cmd/go : use version control to discover the main module's version? "



Go 1.13(2019年第三季度)包括:

关于git - 使用git从git获得动态版本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38087256/

10-11 22:47
查看更多