debug.ReadBuildInfo Stamps CLI Version

debug.ReadBuildInfo reports the module path, Go version, and VCS revision so a CLI binary can print its own version information.

GoCli Tooling

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"runtime/debug"
)

func main() {
	info, ok := debug.ReadBuildInfo()
	if !ok {
		fmt.Println("build info unavailable")
		return
	}
	// the CLI stamps its own version from build info
	fmt.Println("module:", info.Main.Path)
	fmt.Println("go version:", info.GoVersion)
	if v := info.Main.Version; v != "" && v != "(devel)" {
		fmt.Println("version:", v)
	}
	var vcs, revision string
	for _, s := range info.Settings {
		switch s.Key {
		case "-ldflags":
			fmt.Println("ldflags:", s.Value)
		case "vcs":
			vcs = s.Value
		case "vcs.revision":
			revision = s.Value
		}
	}
	if vcs != "" && revision != "" {
		fmt.Printf("vcs: %s %s\n", vcs, revision)
	}
}

How the snippet works

Everything that executes sits inside the function main.

Repetition is confined to for _, s := range info.Settings — the rest of the file is straight-line.

Caveats

  • No install step: the snippet lives entirely inside the standard library.

Applying it

The signature doing the main work is func main()

Each step the file takes is announced in the output: build info unavailable, module:, go version:.

Statements that matter most here

for _, s := range info.Settings {
	switch s.Key {
	case "-ldflags":
		fmt.Println("ldflags:", s.Value)
	case "vcs":
		vcs = s.Value
	case "vcs.revision":
		revision = s.Value
	}
}

Interactive Tools for This Topic

FAQ

What does debug.ReadBuildInfo Stamps CLI Version print when run?
Invoke the file as-is — the `build info unavailable`, `module:`, `go version:` prefixes identify which step printed each line.