How to get git commit SHA inside BUILD.bazel?

Viewed 1690

My goal is to create a zip file that has a git commit SHA of the current HEAD in its name using Bazel.
I know there is a technique called Stamping, but I'm having a tough time wrapping my head around how I can use that for what I need.
I already have some code (rule) that creates the zip file that I need:

def go_binary_zip(name):
    go_binary(
        name = "{}_bin".format(name),
        embed = [":go_default_library"],
        goarch = "amd64",
        goos = "linux",
        visibility = ["//visibility:private"],
    )
    # How do I add the git commit SHA here?
    native.genrule(
        name = "{}_bin_archive".format(name),
        srcs = [":{}_bin".format(name)],
        outs = ["{}_bin.zip".format(name)],
        cmd = "$(location @bazel_tools//tools/zip:zipper/zipper) c $@ {}=$<".format(name),
        tools = ["@bazel_tools//tools/zip:zipper/zipper"],
        visibility = ["//visibility:public"],
    )

2 Answers

Getting the git commit SHA inside your macro or rule implementation isn't possible within bazel. Output paths are intended to be deterministic. You can get that information inside of a file that is available in a rule (see option 2 below.)

If your goal is to create a zip with the git commit SHA in the filename you you have a couple options.

  1. Write a script that runs outside of bazel to copy the zip from bazel into your workspace.

    #!/bin/bash
    bazel build //:example
    cp $(bazel info bazel-bin)/example.zip example-$(git rev-parse HEAD).zip
    
  2. Create a rule that uses stamping to generate a script file that you can run via bazel run to copy the archive for you. Inside your rule implementation you can access the stable-status.txt and volatile-status.txt files (documented here: https://docs.bazel.build/versions/master/user-manual.html#workspace_status) with ctx.info_file and ctx.version_file respectively.

    Do note that ctx.info_file and ctx.version_file are undocumented so it is unclear whether or not this API is stable or will be supported in the future (see github issue.)

Related