Bazel custom rule example. Aug 28, 2024 · Simplify rules using context variables.


Bazel custom rule example Suppose you have the following target:. http_archive supports a list of urls as mirrors, and git_repository supports only a single remote. Examples This example writes the list of the labels in the transitive closure of the specified target to a file. However, this structure helps you avoid introducing unnecessary complication in complex builds. Through these it is possible to access information such as all transitive headers or libraries to link. This makes it possible to: define custom flags for your project, obsoleting the need for --define write transitions to configure deps in different configurations than their parents (such as --compilation Documentation for rules_python is at https://rules-python. In the wild: rules _ k8s For example, consider rules_k8s, the Kubernetes rules for Bazel. , then return a DefaultInfo provider (along with _blah_provider) and set the files field to the transitive closure of files. 3 · 8. Examples: Suppose you need to have a debian package for your custom rules. Example awesome-bazel A curated list of Bazel rules, tooling and resources. Oct 30, 2025 · Such rules are restricted in capabilities (for example, the size of their dependency tree is limited), so transitions created using this function are limited in potential scope as compared to transitions created using transition(). Oct 30, 2025 · Be mindful of introducing custom constraints, all users of your rules will use them to perform platform specific logic in their BUILD files (for example, using selects). You can refine the solution if you want a different set of files when the rule is in a data attribute Oct 30, 2025 · A rule defines a series of actions that Bazel performs on inputs to produce a set of outputs, which are referenced in providers returned by the rule's implementation function. Examples: Suppose the current repository contains the source code for a chat program, rooted at the directory ~/chat-app. 2 · 8. cpp source files (inputs). Run g++ on the source files (action). Migrating from the bundled rules The core rules are currently available in Bazel as built-in symbols, but this form is deprecated. An external repository is a rule that can be used only in the WORKSPACE file and enables non-hermetic operation at the loading phase of Bazel. jar extension. srcs, cc_binary. In this article, we'll walk through the process of configuring our simple set of rules to use toolchains. To add a new plugin, you can generally follow the pattern seen in the multiple language examples in this repository; simpler languages such as C++ are Nov 13, 2024 · A simple Bazel Query in practice In the following chapter, we will use TARGET_PATTERN syntax to demonstrate how Bazel queries work. They can be used to depend on third-party libraries (such as Maven Oct 30, 2025 · We recommend that you name your sh_binary() rules after the name of the script minus the extension (e. Aug 31, 2020 · 1 I'm working on a problem in which I only want to create a particular rule if a certain Bazel config has been specified (via '--config'). Suppose you have the following target: Dec 7, 2019 · Bazel can isolate a build from the host system using platforms and toolchains. By following these best practices, you can write efficient and readable Bazel rules that make your build system more scalable and maintainable. . Implementing Starlark rules that depend on C++ rules and/or that C++ rules can depend on Most C++ rules provide CcInfo, a provider containing CompilationContext and LinkingContext. Apr 17, 2018 · You can't easily create a filegroup like that, but you can still achieve what you want. Return the DefaultInfo provider with the executable output and other files to make available at This page covers how to create repository rules and provides examples for more details. Suppose you have the following target: Nov 13, 2020 · When I first started writing custom Bazel rules, I often created separate rules for the build and run commands in Bazel. If you want to use the rule in genrule. Then you can add to your WORKSPACE file: Oct 30, 2025 · This page describes the toolchain framework, which is a way for rule authors to decouple their rule logic from platform-based selection of tools. An external repository is a directory tree, containing source files usable in a Bazel build, which is generated on demand by running its corresponding repo rule. This repository aims to follow semantic versioning. The example will be using new_http_repository because it's a common use case, but the procedure for new_local_repository and all the other types is similar. attr. The depset constructor accepts a list of elements ("direct") and a list of other depsets ("transitive"), and returns a depset representing a set http_jar(name, auth_patterns, canonical_id, downloaded_file_name, integrity, netrc, sha256, url, urls) Downloads a jar from a URL and makes it available as java_import Downloaded files must have a . I am incrementally porting us up to newer versions. Example This defines a toolchain type for a custom rule. Such tests are called "analysis tests" and are currently the best option for testing the inner Aug 28, 2024 · Simplify rules using context variables. This can be used, for example, for a multiplatform library that automatically chooses the appropriate implementation for the architecture, or for a feature-configurable binary that can be customized at build time. Bazel augments the core language with numerous build-related functions such as glob, genrule, java_binary, and so on. For example, a C++ binary rule might: Aug 9, 2017 · Notably, gocode, the autocompletion engine used by vim-go and VSCode, when running in bzl (Bazel) lookup mode seems to expect to find generated sources in bazel-genfiles/, not bazel-bin/, and therefore fails. js tools and building JavaScript projects - aspect-build/rules_js Mar 21, 2021 · Bazel allows several ways to define rules in a workspace. As a rule writer, you must consider not only the user Oct 30, 2025 · A rule defines a series of actions that Bazel performs on inputs to produce a set of outputs, which are referenced in providers returned by the rule's implementation function. This page describes the recommended, native, and non-native Bazel rules. Remember to keep your rules concise, focused, and well High-performance Bazel rules for running Node. Define input and output files using rule attributes. Net By using this ruleset instead of MSBuild you gain the Bazel promise of {Fast, Correct} - Choose two This document will not enumerate all the possible gains that Bazel can bring and instead it's recommended to take a look at the Bazel documentation for a primer on Bazel. This was a mistake. Much of Bazel's strength comes from the ability to define new rules that can be used by others. Oct 30, 2025 · There are several different approaches to testing Starlark code in Bazel. #!/bin/zsh) Example For a simple shell script with no dependencies and some data files: Nov 5, 2025 · This rule defines a new type of toolchain -- a simple target that represents a class of tools that serve the same role for different platforms. A rule defines a series of actions that Bazel performs on inputs to produce a set of outputs, which are referenced in providers returned by the rule's implementation function. deb. For example, a C++ binary rule might: Take a set of . They are data structures used to pass information between rules, and we'll need them to gather information about dependencies. sh); the rule name and the file name must be distinct. Oct 30, 2025 · Bazel users are accustomed to rules that create executables, and rule authors can follow a common set of patterns to extend this to "custom verbs". bzl for checking the analysis-time behavior of rules, such as their actions and providers. data, etc. Examples There are a number of examples in the examples/ folder and larger examples in the bazel-examples repository using rules_ts such as jest, react, angular. dep[DataInfo] Create a new Provider using the provider function. automatically build //my:android_app Oct 30, 2025 · A complete working example can be found in the rules_cc examples. It includes how to define build settings and provides examples. Their implementation is subject to Bazel's backward compatibility policy. Suppose you have the following target: Nov 8, 2019 · For many rules, the value of the args attribute isn't embedded into the output binary, but in your rule implementation you can read ctx. For example, I once wrote rules that looked something like: Examples for Bazel. See the Toolchains page for more details. Each external repository rule creates its own workspace, with its own BUILD files and artifacts. bzl: def _impl(repository_ctx): repository_ctx. Return the DefaultInfo provider with the executable output and other files to make available at Bazel augments the core language with numerous build-related functions such as glob, genrule, java_binary, and so on. It is recommended to read the rules and platforms pages before continuing. Examples live in the examples directory. Bazel users are accustomed to rules that create executables, and rule authors can follow a common set of patterns to extend this to "custom verbs". If you want to do anything more complicated, for example add support for a new programming language, consider creating a rule. The core rules are stable. Bazel supports projects in multiple languages and builds outputs for multiple platforms. A complete working example can be found in the rules_cc examples. Net This ruleset is a alternative to using MSBuild with . In this article, we are focusing on genrule, the easiest way to create a custom rule (with some limitations). Examples This documentation is an example of sphinxdocs rules and the rest of the components have examples in the examples directory. The empty rule To create your first rule, create the file foo. See How to contribute for information on our development workflow. Oct 30, 2025 · Bazel augments the core language with numerous build-related functions such as glob, genrule, java_binary, and so on. These examples will show you how to navigate and understand the build targets within a project's structure. Jul 11, 2024 · The genquery's output is ordered using --order_output=full in order to enforce deterministic output. Keep rules concise and focused on a single task. Repos can be defined in a multitude of ways, but ultimately, each repo is defined by invoking a repo rule, just as build targets are defined by Oct 30, 2025 · DataInfo = provider() def _rule_impl(ctx) ctx. Testing rules Skylib has a test framework called unittest. Bazel rules for . How do I modify my rule to save the output to bazel-genfiles/ instead of bazel-bin/? My rule is equivalent to the example in rules_go: Apr 24, 2025 · A step-by-step guide to building, testing, and packaging a Python library with Bazel and the rules_python core library. com/package. readthedocs. The above rules will use the default C++ toolchain to compile. Rules A rule defines a series of actions that Bazel performs on inputs to produce a set of outputs. They are an essential element of rule processing. In fact, Bazel Queries are a perfect tool to demonstrate how Mar 29, 2018 · Introduction This page explains how to use a custom prebuilt C/C++ toolchain contained in an external repository. io and in the Bazel Build Encyclopedia. Bazel queries and TARGET_PATTERN Target Pattern is a syntax used to specify a set of targets. Rules give you more control and flexibility. For additional information, please refer to the documentation. This page gathers the current best practices and frameworks by use case. 0 · 7. It uses a human-readable, high-level build language. See the Bazel and Starlark documentation for more details, and the Rules SIG template as a starting point for new rulesets. --compilation_mode=opt or --cpu=arm) bake better defaults into rules (e. Contribute to bazelbuild/examples development by creating an account on GitHub. View the Project on GitHub jin/awesome-bazel Awesome Bazel {Fast, Correct} - Choose two Bazel is an open-source build and test tool similar to Make, Maven, and Gradle. Motivation Let's first Oct 30, 2025 · This page covers how to define repository rules and provides examples for more details. Instead, we rely on bazel run: the workhorse for tasks we want to have side effects. I want this rule to only execute in a certain configuration (optimized, --compilation_mode=opt) and not run (or be a no-op PA Jul 31, 2018 · Bazel lets you write rules in Starlark to support new languages. This makes it possible to: define custom flags for your project, obsoleting the need for --define write transitions to configure deps in different configurations than their parents (e. Nov 9, 2019 · In this article, we'll define a repository rule that downloads a Go toolchain and generates a custom build file. From Bazel’s perspective, g++ and the standard C++ libraries are also inputs to this rule. It needs to depend on an SSL library which is available from May 25, 2018 · Most language rules will want to define their own – see @io_bazel_rules_go//go/toolchain:toolchains. This package is available from http://example. 11 and have a bunch of build infrastructure that works around former limitations in Bazel. We have been using Bazel since 0. 3 days ago · Git repository rules depend on system git(1) whereas the HTTP downloader is built into Bazel and has no system dependencies. srcs, filegroup. Oct 30, 2025 · This page covers the benefits and basic usage of Starlark configurations, Bazel's API for customizing how your project builds. 1 · 8. bzl for an example of custom values for the built-in settings. Oct 30, 2025 · Configurable attributes, commonly known as select(), is a Bazel feature that lets users toggle the values of build rule attributes at the command line. Configurations Starlark configuration is Bazel’s API for customizing how your project builds. g. 7 Aug 15, 2018 · We'll define a go_library rule, which can be depended on by other libraries and binaries. Bazel rules are highly structured, and learning this structure takes time. Recommended rules Here is a selection of recommended rules: Android C / C++ Docker/OCI Go Haskell Java JavaScript / NodeJS The heart of Bazel is the Starlark language, a Pythonic configuration language that developers can use to define custom build rules. If you'd like an example added, you can fund a Feature Request. Oct 30, 2025 · Depsets are a specialized data structure for efficiently collecting data across a target’s transitive dependencies. As a rule writer, you must consider not only the user Oct 30, 2025 · Bazel users are accustomed to rules that create executables, and rule authors can follow a common set of patterns to extend this to "custom verbs". Jun 13, 2023 · Conclusion I hope that this text, and the example explain how you can use the make build rule in bazel yourself. Custom Plugins ¶ Custom plugins are supported by rules_proto_grpc, through the use of the proto_plugin Starlark rule to create a plugin target in a BUILD file and by then creating a rule that uses proto_compile_impl with the new plugin. execu I have a custom test rule that validates the size of a produced binary. The Bazel community maintains this repository. Oct 30, 2025 · sha256, url, urls) Downloads a file from a URL and makes it available to be used as a file group. The name of the output file is the name of the rule. Oct 30, 2025 · The bazel test command respects this sort of organization: For an invocation like bazel test //some/test:suite, Bazel first enumerates all test targets transitively included by the //some/test:suite target (we call this "test_suite expansion"), then Bazel builds and tests those targets. This time, we'll cover writing a simple rule that compiles and links a Go binary from sources. Examples for Bazel. This lets us avoid depending on the host toolchain, which aids reproducibility and make remote execution possible. cpp files (the inputs) Run g++ on them (the action) Return an executable file (the output). When this is done, the rules will be almost completely independent from the host system. 4 · 8. Bazel supports Oct 30, 2025 · Macros are suitable for simple tasks. Oct 30, 2025 · Bazel augments the core language with numerous build-related functions such as glob, genrule, java_binary, and so on. Oct 30, 2025 · The Bazel ecosystem has a growing and evolving set of rules to support popular languages and packages. Oct 30, 2025 · This page covers how to create repository rules and provides examples for more details. sh_binary respects shebangs, so any available interpreter may be used (eg. The easiest way to create a macro that resizes an image is to use a genrule: Oct 31, 2025 · Bazel Reference Build encyclopedia Send feedback Python Rules On this page Rules py_binary Arguments py_library Arguments py_test Arguments py_runtime Report an issue open_in_new View source open_in_new Nightly · 8. Sep 10, 2017 · I'm pretty lost trying to create a custom repository rule pypi. The bazel examples didn’t quite help me understand the mechanisms at play here, so I wrote this explanation up in hope it is useful to someone in the future. This page covers why toolchains are needed, how to define and use them, and how Bazel selects an appropriate toolchain based on platform constraints. We'll also cover structs, providers, and depsets. The defining feature of depset is its time- and space-efficient union operation. bzl: Bazel Rules This directory contains examples of Bazel rules. Bazel users are accustomed to rules that create executables, and rule authors can follow a common set of patterns to extend this to “custom verbs”. bzl: Writing rules for Windows Example rules Distributing rules Share your custom rules to your project or the Bazel community. args and put that into the output binary / output wrapper as needed. Learn about Bazel's release model, latest releases, and compatibility policies. With Starlark, you gain full control over your build processes, enabling you to adapt Bazel to your unique project requirements.