How can I get the current date in BUILD.bazel file

593 views Asked by At

I am new to bazel and facing the below issue while building my CPP code with bazel.

I want to pass the current date as one of the local defines in the below format.

date = < rule to get current date >

cc_lib( ... , local_define = [ "xyz = 28-11-2022"], )

how can I get the current date every time I run the bazel build? local_define = [ "xyz = date"],

I tried loading the python date but starlark doesn't have support for that.

1

There are 1 answers

1
ahumesky On

The usual way that bazel handles non-deterministic information in the build is using "build stamping", described here:

https://bazel.build/docs/user-manual#workspace-status

Bazel goes to great lengths to avoid non-determinism because it's bad for caching, so adding something like the current time to a build isn't straight forward. Using build stamping sometimes requires changing your program or generating files based on the status.txt files and incorporating those into your build. If defines are really needed, you can do that with something like this:

BUILD:

cc_binary(
  name = "main",
  srcs = ["main.c"],
  local_defines = ["DATE=\"$(DATE)\""],
)

main.c:

#include <stdio.h>

#ifndef DATE
#define DATE "none"
#endif

int main() {
  printf("date is %s\n", DATE);
  return 0;
}
$ bazel build main --define DATE="\\\"$(date)\\\""
INFO: Analyzed target //:main (37 packages loaded, 163 targets configured).
INFO: Found 1 target...
Target //:main up-to-date:
  bazel-bin/main
INFO: Elapsed time: 0.497s, Critical Path: 0.08s
INFO: 6 processes: 4 internal, 2 linux-sandbox.
INFO: Build completed successfully, 6 total actions

$ bazel-bin/main
date is Mon Nov 28 04:33:30 PM EST 2022

(All the escaping is necessary to allow for spaces in the date, but you might not need all that.)

Note that the --define DATE="\\\"$(date)\\\"" must be provided on the command line, and can't be put into a .bazelrc because .bazelrc isn't evaluated like the shell.