golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.34k stars 17.71k forks source link

cmd/go: enable injection of build version info #59019

Closed deitch closed 1 year ago

deitch commented 1 year ago

This is somewhat related to #44469

I compile a binary with go. I distribute it. go, in its helpfulness, includes lots of information about modules and their versions, e.g. from dlv:

$ go version -m ./dlv
./dlv: go1.20.1
    path    github.com/go-delve/delve/cmd/dlv
    mod github.com/go-delve/delve   (devel)
    dep github.com/cosiner/argv v0.1.0  h1:BVDiEL32lwHukgJKP87btEPenzrrHUjajs/8yzaqcXg=
    dep github.com/cpuguy83/go-md2man/v2    v2.0.0  h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM=
    dep github.com/derekparker/trie v0.0.0-20221213183930-4c74548207f4
    dep github.com/go-delve/liner   v1.2.3-0.20220127212407-d32d89dd2a5d    h1:pxjSLshkZJGLVm0wv20f/H0oTWiq/egkoJQ2ja6LEvo=
    dep github.com/google/go-dap    v0.6.0  h1:Y1RHGUtv3R8y6sXq2dtGRMYrFB2hSqyFVws7jucrzX4=
    dep github.com/hashicorp/golang-lru v0.5.4  h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc=
        ...

Except for the module itself, which just shows (devel).

The compiled binary carries with it all of its dependency version and source information, but only package name for the root module itself. This makes it of much less usefulness for sbom and software supply-chain and provenance tools.

The build process populates BuildInfo, but leaves the version blank.

I recall seeing a discussion earlier about not wanting to depend on external tools; I get that. It might even be a good enough start if there were a "hook" that let you add that information, whether a flag or even the usual -X something=v1.2.3 (although calculating if it is a tag or a pseudo-version and what that is also appears not to be in an obviously exposed package).

  1. Ideal: go build figures out, "I am running in a git repo at a specific commit, I will figure out my version or pseudo-version and put it in"
  2. Below: go build provides an option to do it, something like --module-version=auto (to auto-populate) or --module-version=v1.2.3
  3. Below: it provides a -X flag that can be used, e.g. -ldflags '-X runtime.BuildInfo.Version=v1.2.3', although that leaves it on the user to figure out what that version or pseudo-version is
seankhliao commented 1 year ago

Duplicate of #50603

deitch commented 1 year ago

Dang that was quick. Thanks @seankhliao .

I would have just commented on that issue, but so hard to find. GitHub needs better search.