2

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"],
    )

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Arash Outadi
  • 446
  • 7
  • 16

2 Answers2

2

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 at this link: 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.)

Chip Hogg
  • 1,570
  • 13
  • 14
Zaucy
  • 299
  • 3
  • 11
  • I'm going to try number 2, if I can figure it out based on the instructions I'll mark this as the correct answer. As it stands I'm still fairly confused to be honest. – Arash Outadi Mar 21 '21 at 18:07
  • If you don't mind a C++ dependency I wrote a utility library for this exact use case + more here: https://github.com/zaucy/bzlws/blob/master/docs/index.md (`bzlws_copy`) – Zaucy Jun 02 '21 at 04:20
0

You can use a git feature, which replace any occurence of $Id$ in files specified in a .gitattributes file https://stackoverflow.com/a/1792913/4638604.

slsy
  • 1,257
  • 8
  • 21