From d29af912cb3e64b6b75d5dd7df4ab69445d27c5b Mon Sep 17 00:00:00 2001 From: Andreas Berthoud Date: Sun, 6 Jun 2021 12:19:12 +0200 Subject: [PATCH] Add flavor_setting --- BUILD | 28 +++++++++++++++++++++++++--- README.md | 9 +++++++++ build_settings.bzl | 18 ++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 README.md create mode 100644 build_settings.bzl diff --git a/BUILD b/BUILD index 6b7fba8..c9819c0 100644 --- a/BUILD +++ b/BUILD @@ -2,6 +2,8 @@ load("@rules_python//python:defs.bzl", "py_binary") load("@rules_python//python:defs.bzl", "py_runtime_pair") load("@pip_requirements//:requirements.bzl", "requirement") +load("//:build_settings.bzl", "flavor") + py_runtime( name = "python37", interpreter_path = "/usr/local/bin/python3.7", @@ -25,14 +27,34 @@ toolchain( toolchain = ":py_runtime_pair", toolchain_type = "@rules_python//python:toolchain_type", ) + +flavor( + name = "favorite_flavor", + build_setting_default = "ORANGE" +) + +config_setting( + name = "apple_flavor_setting", + flag_values = { + ":favorite_flavor": "APPLE" + }, +) + +config_setting( + name = "banana_flavor_setting", + flag_values = { + ":favorite_flavor": "BANANA" + }, ) py_binary( name = "main", srcs = ["main.py"], - args = [ - "--cool", - ], + args = select({ + ":apple_flavor_setting": ["--red", "--green"], + ":banana_flavor_setting": ["--brown", "--curved=true"], + "//conditions:default": ["--orange"], + }), srcs_version = "PY3", deps = [ requirement("pyyaml"), diff --git a/README.md b/README.md new file mode 100644 index 0000000..a9de444 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Bazel playground + +## Play with ... + +- `bazel run main --//:favorite_flavor="BANANA"` +- `bazel run main --//:favorite_flavor="APPLE"` +- `bazel run main --//:favorite_flavor="ORANGE"` +- `bazel run main` + diff --git a/build_settings.bzl b/build_settings.bzl new file mode 100644 index 0000000..af1a146 --- /dev/null +++ b/build_settings.bzl @@ -0,0 +1,18 @@ +# https://docs.bazel.build/versions/2.1.0/skylark/config.html + +FlavorProvider = provider(fields = ['type']) + +flavors = ["APPLE", "BANANA", "ORANGE"] + +def _impl(ctx): + raw_flavor = ctx.build_setting_value + if raw_flavor not in flavors: + fail(str(ctx.label) + " build setting allowed to take values {" + + ", ".join(flavors) + "} but was set to unallowed value " + + raw_flavor) + return FlavorProvider(type = raw_flavor) + +flavor = rule( + implementation = _impl, + build_setting = config.string(flag = True) +)