Building with Bazel
Jul 8 2022 · Starlark, Bazel 5.1, Visual Studo Code 1.66
Part 1: Learning Bazel
08. Understand Bazel Rules
Leave a rating/review
Episode 8 - Understand Bazel Rules and Labels
Rules are an extremely important aspect Bazel. They allow us to write our own build functions, but more importantly than that, they allow us to build other languages. Out of the box, Bazel supports a handful of languages, but using custom rules, Bazel can be made to support any language.
In fact, on the Bazel Github page, you find a large listing of community hosted rules. Unfortunately, being community developed, support is not guaranteed. It all depends on the maintainer of the project. In my case, I ran into a major bug with one set of rules, but the project maintainer was incredibly helpful and he was able to put together a bug fix almost at once. That said, the maintainer didn’t work Google but rather, was an engineer at Lyft maintaining the repository. Also some language features may cause issues. For instance, I ran into direct issues compiling data bindings with Android. As is, I believe this is still an ongoing issue.
As mentioned, we use rules to create our own build functions as well as incorporate functions included with Bazel itself. We have native rules and language specific rules. The native rules aren’t specific to a programming language. They don’t need to be loaded and they are always available in your BUILD files. For example, the alias rule allows you to create another name for a rule.
Bazel also includes non-native rules that can be loaded using @bazel-tools. Okay - before we go into these non-native rules, what’s the deal with the @ sign.
This is what is known as a label. In this case it is the shorthand for the repository that contains the rules but we also use labels to refer to our build targets as you’ll see soon enough.
Following the label is the package. That is, the location inside the repository.
Finally we have the target itself which is where all the rules are listed. This is the file that contains all the rules. These are always bzl files.
When accessing rules, often times we’ll want to access a particular function. For instance, bazel tools provide a function called http_archive that allows us to download an archive at Github.
In our load statement, we pass in the rule, then we pass in the name of the function that we want to use. ha
Now we can use the http_archive symbol as a function. In this case, we’re using it to download the app rules. Now that you have a good idea about rules and labels, we’ll put them to work in the next episode by creating a singular workspace for our repo.