Rules_go: How to add the ldflags " -X main.BuildTime=`date -u '+%Y-%m-%d_%I:%M:%S%p'`" ?

Created on 2 Mar 2017  路  2Comments  路  Source: bazelbuild/rules_go

How to implement the same function as

go build -ldflags " -X main.BuildTime=date -u '+%Y-%m-%d_%I:%M:%S%p' -X main.Version=git rev-parse HEAD" ?

I add both the two arguments to the 'ldflags' in def.bzl, but it doesn't work.

Most helpful comment

For anyone trying to do this now, the current instructions are at https://github.com/bazelbuild/rules_go/blob/master/go/core.rst#defines-and-stamping. The linkstamp attribute was deprecated and removed some time ago.

All 2 comments

You can do this with the new link stamping functionality. See the documentation for the linkstamp attribute for go_binary. Also see the example in examples/stamped_bin.

Basically, you will need to create a script that prints information you want to put in the link stamp. Let's call it status.sh. It will look something like this (not tested):

#!/bin/bash

echo BuildTime $(date -u '+%Y-%m-%d_%I:%M:%S%p')
echo Version $(git rev-parse HEAD)

Add the linkstamp attribute to the go_binary rule in your BUILD file. You'll specify the package where these values should be set.

go_binary(
    ...
    linkstamp = "main",
)

Run Bazel with your status script (the "./" is important):

$ bazel build --workspace_status_command=./status.sh :my_binary

Bazel will turn the output of the status script into -X flags passed to the linker.

I plan to add support for custom link options in the future (see #217), but that will only support static options in BUILD files.

For anyone trying to do this now, the current instructions are at https://github.com/bazelbuild/rules_go/blob/master/go/core.rst#defines-and-stamping. The linkstamp attribute was deprecated and removed some time ago.

Was this page helpful?
0 / 5 - 0 ratings