Ryan Burn
Ryan Burn

Reputation: 2316

How to reference environmental variables in WORKSPACE?

If a project has an external dependency to software that's installed locally and can't be managed with new_http_archive or new_git_repository because licensing or size issues prevent it from being downloaded, is there a way to have the path specified with new_local_repository use an environmental variable?

Looking at the comments on Issue #746, it looks like this was solved in some way. But I can't find any documentation on how to do it.

Upvotes: 3

Views: 11880

Answers (2)

László
László

Reputation: 4271

Looking at the comments on Issue #746, it looks like this was solved in some way. But I can't find any documentation on how to do it.

Thanks for checking for existing bugs! That bug is almost 2 years old though. Bazel has changed a ton since then.

For this problem, I think you should write your own repository rule in a .bzl file.

Repository rules are allowed to perform non-hermetic operations, read the environment, look at the whole filesystem, etc. Normal build rules are not, nor do they have access to the environment or the full filesystem.

Your repository rule should check the envvar's value and write a BUILD file that Bazel will use in the external repository that your rule created.

Look at my answer here for an example: Call llvm-config --prefix and use it in a BUILD rule

Upvotes: 2

rds
rds

Reputation: 26974

The preferred way in bazel is to place the tools in the source code repository too, because that's the only way to have reproducible builds.

However, I think you can use environment variables as part of an action and you can reference environment variables in rules.

I haven't tested, but I think the rule will look like this proprietary_tool.bzl:

def _proprietary_tool_impl(ctx):
    env = ctx.configuration.default_shell_env
    ctx.actions.run(
      inputs=ctx.attr.srcs,
      outputs=ctx.attr.out,
      executable=env['PROPRIETARY_TOOL_PATH'] + "/bin/tool",
    )

proprietary_tool = rule(
    implementation=_proprietary_tool_impl,
    attrs={}, # Add attributes needed by the proprietary tool
)

Upvotes: 0

Related Questions