Skip to content

cmd/go: Make it easier to embed compiled git SHA into binary #22147

Closed
@kevinburke

Description

@kevinburke

If I compile Go from source and run go version, I get output like this:

go version devel +475d92ba4d Thu Oct 5 10:50:18 2017 +0000 darwin/amd64

I would love to get the same output in my programs. Specifically, I'm trying to debug a reported error in a program I wrote and it would be a lot easier if I knew which SHA they were running.

It's easy in the Go build tool because it can specify what code runs during the build process. From findgoversion():

	// Otherwise, use Git.
	// What is the current branch?
	branch := chomp(run(goroot, CheckExit, "git", "rev-parse", "--abbrev-ref", "HEAD"))

	// What are the tags along the current branch?
	tag := "devel"
	precise := false

	// If we're on a release branch, use the closest matching tag
	// that is on the release branch (and not on the master branch).
	if strings.HasPrefix(branch, "release-branch.") {
		tag, precise = branchtag(branch)
	}

	if !precise {
		// Tag does not point at HEAD; add hash and date to version.
		tag += chomp(run(goroot, CheckExit, "git", "log", "-n", "1", "--format=format: +%h %cd", "HEAD"))
	}

I have options for replicating this behavior, none very good:

  • Use linker flags: This blog post describes compiling Go with -ldflags -X in such a way that you can embed the SHA at compile time. https://medium.com/@joshroppo/setting-go-1-5-variables-at-compile-time-for-versioning-5b30a965d33e

    I can do this of course, but I'm not sure it's feasible or possible to ask all of my users to remember to do this when they compile my program. I can add a Make target or something to automate the instructions but that's something they have to remember to do too.

    I could release compiled libraries but that's infeasible in a company environment where tip is changing rapidly and users are used to compiling from source.

  • Tag a new release every time I add a commit to the program. I wrote this tool to do that: github.com/Shyp/bump_version. Generally though it's not practical to tag every single commit, the same reason there aren't tags for every commit between Go 1.8.3 and Go 1.9.0.

It would be nice if there was some API for detecting or automatically embedding the git SHA in the binary so I can access it at runtime, and print it out when users of my program run <mybinary> version or <mybinary> env, the same way the Go team found this information useful and found a way to embed it while the program was being compiled.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions