0

I am trying to make my build configurable with a custom flag.

It should be possible to specify the flag value when I build, e.g.

bazel build //test:bundle --//:foo_flag=bar

Here is my build target definition (using rules_js):

load("@npm//:defs.bzl", "npm_link_all_packages")
load("@npm//test:webpack-cli/package_json.bzl", "bin")

npm_link_all_packages(
  name = "node_modules",
)

bin.webpack_cli(
  name = "bundle",
  outs = [
    "out/index.html",
    "out/main.js",
  ],
  args = [
    "--config",
    "webpack.config.js",
    "-o",
    "out",
  ],
  srcs = [
    "webpack.config.js",
    ":node_modules",
  ] + glob([
    "src/**/*.js",
  ]),
  chdir = package_name(),
  env = {
    # ?
  },
  visibility = [
    "//visibility:public",
  ],
)

What is unclear from the various Bazel examples is how to actually pass the flag to the rule.

I am looking for something like this:

# Invalid

  env = {
    "FOO": "$(value //:foo_flag)",
  },

How do I pass a flag in Bazel?

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

2 Answers2

0

To use the command-line flag, you want to use a config_setting() and then select() based on that.

config_setting(
  name = "foo_flag_set",
  flag_values = { "//:foo_flag": "bar" },
)

...

bin.webpack_cli(
  name = "bundle",
  ...
  env = select({
    ":foo_flag_set": {...},
    "//conditions:default": None,
  },
  ...
)

This might be the way to go, if you have a distinct set of values for your flag. Otherwise you might want to think about a --action_env flag.

lummax
  • 333
  • 8
  • I am currently using `--action_env` but that affects all genrules so is not ideal. Is there not a way to put the value of the flag into the `env`? It's surprising how difficult this is! – sdgfsdh Dec 03 '22 at 21:35
0

Set them with the --define flag. Values set like that will be expanded in any context that performs "Make" variable expansion. That looks like this:

bin.webpack_cli(
  name = "bundle",
  ...
  env = {
    "FOO": "$(FOO)",
  },
)

and then build with --define=FOO=bar.

I can't find the docs for bin.webpack_cli to confirm it does "Make" variable expansion in env, but most env attributes do so I'm assuming it does. For example rules_docker's container_layer.env mentions this in its documentation.

Brian Silverman
  • 3,085
  • 11
  • 13