Skip to content

Commit

Permalink
add example of using a skylib build setting (bazelbuild#166)
Browse files Browse the repository at this point in the history
Work towards bazelbuild#154
  • Loading branch information
juliexxia authored May 15, 2020
1 parent 87d283e commit 20c3823
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion rules/WORKSPACE
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ http_archive(
sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44",
)
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()

bazel_skylib_workspace()
17 changes: 17 additions & 0 deletions rules/starlark_configurations/use_skylib_build_setting/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# We don't actually need an external repo to define Starlark settings. But
# Skylib provides convenience macros that reduce boilerplate, so we'll use that
# here.
#
# See https://docs.bazel.build/versions/master/skylark/config.html and
# https://github.com/bazelbuild/bazel-skylib) for more info.

load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
load(":defs.bzl", "dessert")

# This can be set on the command line by setting
# //starlark_configurations/use_skylib_build_setting:flavor=<flavor>.
# We declare here that its default value is "strawberry".
string_flag(name = "flavor", build_setting_default = "strawberry")

# A rule that depends on `:flavor`which means it can read its value.
dessert(name = "ice-cream")
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
This is an example of how to use and read the pre-defined build
settings in the `bazel_skylib` repo.

To test it out, cd into this directory and run the following:

```
$ bazel build :ice-cream // => "flavor: strawberry"
$ bazel build :ice-cream --//starlark_configurations/use_skylib_build_settings:flavor=rocky-road => "flavor: rocky-road"
```
17 changes: 17 additions & 0 deletions rules/starlark_configurations/use_skylib_build_setting/defs.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Load the provider of the pre-made settings defined in bazel_skylib
load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")

def _impl(ctx):
# Access the value of --//starlark_configurations/use_skylib_build_setting:flavor for the target.
print("flavor: " + ctx.attr._flavor[BuildSettingInfo].value)
return []

dessert = rule(
implementation = _impl,
attrs = {
# Depend on the build setting so that we can access it in the rule implementation.
# Use a private attribute (one that is prefixed with "_") so that target writers
# can't override the value.
"_flavor": attr.label(default = ":flavor"),
},
)

0 comments on commit 20c3823

Please sign in to comment.