gobinaries icon indicating copy to clipboard operation
gobinaries copied to clipboard

Add support for using ldflags when building binary

Open montanaflynn opened this issue 4 years ago • 2 comments

Prerequisites

  • [x] I searched to see if the issue already exists.

Description

It would be quite useful to be able to add some 'ldflags` when building the binary. For example I usually add a version and commit hash variable to my programs which is updated when building rather than in the code. This is extremely useful for debugging.

An example of using ldflags to set the commit global variable:

go build -ldflags "-X github.com/a/b/main.commit=$(git rev-parse --short HEAD)" .

Other tools like goreleaser also set some flags by default and allow you to customize them as I do with my notify-cli tool. This makes it so when I run notify --version from a binary generated with goreleaser I get the following:

$ notify --version
Version: v0.0.8
Commit: a8982ead528a717a05415f5cef7d7448f5adc968

But with a binary from gobinaries:

$ notify --version
Version: unknown
Commit: unknown

I wonder if adding a config file like .gobinaries.yml with the flags you want to set would be something you would welcome, if so I could help with a PR.

montanaflynn avatar May 09 '20 09:05 montanaflynn

I see gobinaries actually already does use ldflags:

https://github.com/tj/gobinaries/blob/master/build/build.go#L155-L165

However it's not working for my project, maybe because it's in a subdirectory?

$ curl -sf https://gobinaries.com/montanaflynn/notify-cli/cmd/notify | sh
  ==> Downloading github.com/montanaflynn/notify-cli/cmd/notify@master
  ==> Resolved version master to v0.0.10
  ==> Downloading binary for darwin amd64
  ==> Installing notify to /usr/local/bin
  ==> Installation complete
$ notify --version
Version: unknown
Commit: unknown

When I use the same ldflags and build locally I do get the Version variable set correctly:

$ cd cmd/notify
$ go build -ldflags "-X main.version=test" .
$ ./notify --version
Version: test
Commit: unknown

montanaflynn avatar May 09 '20 10:05 montanaflynn

Hmm it worked fine for this project: https://github.com/tj/staticgen/blob/master/cmd/staticgen/main.go#L22, I haven't tested with others.

I'm definitely down for exposing more variables by default, but I'd like to avoid configuration if possible. For more complex builds it might be better to support pre-built binaries (issue #16 )

tj avatar May 11 '20 16:05 tj