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-log

This 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.

Written by Jamie Tanna's profile image Jamie Tanna on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

This blog post is 100% human-written, and has nothing derived from LLMs (be it code, editorial support or prose).

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.