Allowing Nix packages to override your version in Go

When folks build Nix packages, it usually builds them from the source code itself, not in a Git checkout.
This means that when you're building tools that use the Git checkout to determine what version of the code you're running - like I'd detailed in Getting a --version flag for Cobra CLIs in Go - this doesn't actually work for Nix users, as there's no .git to look for.
This is something we'd hit in the past with oapi-codegen, where we exposed a new option that could be configured by someone building the project.
If you're using tools like goreleaser, you can take advantage of a fairly common practice in the Go community, to use the main.version ldflag.
This means that someone building your tool can run i.e.
go build -ldflags='-X main.version=1.2.3' ./cmd/renovate-pretty-logThis requires a few code changes to make this work.
Firstly, in the main package for your tool, you need to expose a version variable, which will then be provided by -X main.version:
package main
// ...
var (
// version the release version of this tool. Automagically populated by GoReleaser, or someone building with `go build -ldflags='-X main.version=1.2.3' ...`
version = "dev"
)Then, when determining the version either through runtime/debug or Carlana's versioninfo module, check if that main.version is set, and if so, let it take precedence.
For instance:
package cmd
import "runtime/debug"
func ToolVersion(mainVersion string) string {
if mainVersion != "dev" && mainVersion != "" {
return mainVersion
}
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" {
return info.Main.Version
}
return ""
}This then means that any packager (Nix or otherwise!) can specify a custom version, or we fall back to the Git repo's information.