matthias_buehlmann
matthias_buehlmann

Reputation: 5091

Bazel genrule: how to get absolute path to workspace directory?

I want to create a bazel gen-rule to create a header file that contains the current git commit hash:

# Generate "version_info.h"
cc_library(
    name = "version_info",
    srcs = [],
    hdrs = ["version_info.h"],
    visibility = ["//visibility:private"],
)

VERSION_INFO_H_BASH = """
#ifndef VERSION_INFO_H_
#define VERSION_INFO_H_

#define COMMIT_HASH "%s"

#endif  // VERSION_INFO_H_
"""

VERSION_INFO_H_PS = """
#ifndef VERSION_INFO_H_
#define VERSION_INFO_H_

#define COMMIT_HASH "{0}"

#endif  // VERSION_INFO_H_
"""

genrule(
    name = "generate_version_info",
    outs = ["version_info.h"],
    cmd_ps = ("cd what_comes_here; @'%s'@ -f \"$$(git.exe rev-parse HEAD)\" | Out-File $(OUTS)" % VERSION_INFO_H_PS),
    cmd = ("cd what_comes_here"; printf '%s' \"$$(git rev-parse HEAD)\ > $(OUTS)" % VERSION_INFO_H_BASH),
    visibility = ["//visibility:private"],
)

So far I haven't tested the linux version (cmd) but only on windows (cmd_ps) and it works, but the problem is that when powershell executes, it's not in the workspace directory (which is my git root). What do I need to replace what_comes_here with to first cd into the root of my workspace?

Upvotes: 3

Views: 3366

Answers (1)

Vertexwahn
Vertexwahn

Reputation: 8170

Make use of the workspace status feature of Bazel. An example can be found here.

Upvotes: 1

Related Questions