### Run Bazel Example Source: https://github.com/bazelbuild/examples/blob/main/bzlmod/01-depend_on_bazel_module/README.md Execute the Bazel example by navigating to the directory and running the 'bazel run main' command. Ensure GLOG_logtostderr is set for logging. ```bash GLOG_logtostderr=1 bazel run main ``` -------------------------------- ### Build Transition Example Source: https://github.com/bazelbuild/examples/blob/main/configurations/attaching_transitions_to_rules/README.md This command demonstrates how to build a target that utilizes a transition. Ensure you are in the correct directory before running. ```bash bazel build :tee ``` -------------------------------- ### Basic Transition Example Source: https://github.com/bazelbuild/examples/blob/main/configurations/read_attr_in_transition/README.md Run this command to see a transition that reads an attribute and applies a modification. ```bash bazel build :dont-do-transition # "value of some-string: abc" ``` ```bash bazel build :do-transition # "value of some-string: abc-transitioned" ``` -------------------------------- ### Build the C++ Binary Source: https://github.com/bazelbuild/examples/blob/main/cpp-tutorial/stage2/README.md Command to build the C++ binary example using Bazel. ```bash bazel build //main:hello-world ``` -------------------------------- ### Install libtinfo5 on Ubuntu Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/02-hello-cross/README.md Use this command to install the libtinfo5 shared library on Ubuntu 20.04 if you encounter errors related to its absence. ```bash apt update && apt install -y libtinfo5 ``` -------------------------------- ### Run cc_test Example Source: https://github.com/bazelbuild/examples/blob/main/configurations/cc_test/README.md Command to execute the test and view all output. This is used to verify the arguments passed to the test. ```bash bazel test :all --test_output=all ``` -------------------------------- ### Build Main Project with Alias Source: https://github.com/bazelbuild/examples/blob/main/configurations/auto_configured_builds/README.md Build the main project target after settings are read and flags are applied from `PROJECT.scl`. This demonstrates the initial project setup. ```sh $ bazel build //alias/project_main:main INFO: Reading project settings from //alias/project_main:PROJECT.scl. INFO: Applying flags from the config 'default_config' defined in //alias/project_main:PROJECT.scl: [--platforms=//:myplatform, --compilation_mode=opt, --@custom_flags//:project_flag="custom flag value"] INFO: Found 1 target... INFO: Build completed successfully, 1 total action ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/bazelbuild/examples/blob/main/frontend/react-webpack/README.md Run this command in the frontend folder to install project dependencies if you are not using Bazel for the Webpack build. ```shell pnpm i ``` -------------------------------- ### Setup Bazel for Vendored Dependencies Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/07-deps-vendor/README.md Configure `rules_rust` and `use_repo` in your `MODULE.bazel` file. No direct dependencies or `crate_universe` are declared at this stage. ```starlark module( name = "deps_vendored", version = "0.0.0", ) # https://github.com/bazel/rules_rust/releases bazel_dep(name = "rules_rust", version = "0.65.0") # Rust toolchain RUST_EDITION = "2024" RUST_VERSION = "1.85.0" rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") rust.toolchain( edition = RUST_EDITION, versions = [RUST_VERSION], ) use_repo(rust, "rust_toolchains") register_toolchains(@rust_toolchains//:all) # Rust dependencies; see thirdparty/BUILD.bazel ``` -------------------------------- ### Manage Runtime Data Dependencies with Runfiles Source: https://context7.com/bazelbuild/examples/llms.txt Examples demonstrating how to declare files needed at runtime using `ctx.runfiles`. This includes simple binaries, libraries with their own runfiles, and actions using tools with runfiles. ```BUILD load(":execute.bzl", "execute") load(":library.bzl", "runfiles_binary", "runfiles_library") load(":tool.bzl", "tool", "tool_user") # 1. Binary that needs a data file at runtime execute(name = "e", command = "cat $(location :data.txt)", data = [":data.txt"]) # 2. Library declares its own runtime requirements; binary inherits them runfiles_library(name = "lib", command = "cat $(location :data.txt)", data = [":data.txt"]) runfiles_binary(name = "bin", lib = ":lib") # 3. Build action that uses a tool with its own runfiles tool(name = "tool") tool_user(name = "tool_user", tool = ":tool") ``` ```bash bazel run //runfiles:e bazel run //runfiles:bin bazel build //runfiles:tool_user ``` -------------------------------- ### Run Non-Bazel Dev Server Source: https://github.com/bazelbuild/examples/blob/main/frontend/react-webpack/README.md Start the development server using the standard Webpack build process without Bazel. ```shell pnpm start ``` -------------------------------- ### Run Code Generation Example Source: https://github.com/bazelbuild/examples/blob/main/rules/generating_code/README.md Execute the code generation targets to see the output. These commands trigger the process of generating C++ and Python source files from an input text file. ```bash bazel run :p_maybe ``` ```bash bazel run :c_maybe ``` -------------------------------- ### Run Bazel Dev Server Source: https://github.com/bazelbuild/examples/blob/main/frontend/react-webpack/README.md Start the development server for the React Webpack application using Bazel's ibazel. ```shell ibazel run //react-webpack:dev_server ``` -------------------------------- ### Build a Simple Rust Binary with rules_rust Source: https://context7.com/bazelbuild/examples/llms.txt The most basic example of a Rust binary build using `rules_rust`. It defines a `rust_binary` target for a single source file. ```rust # rust-examples/01-hello-world/BUILD.bazel load("@rules_rust//rust:defs.bzl", "rust_binary") rust_binary( name = "bin", srcs = ["src/main.rs"], visibility = ["//visibility:public"], deps = [], ) ``` ```bash bazel build //01-hello-world:bin bazel run //01-hello-world:bin # Hello, World! ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/02-hello-cross/README.md Run this command in the terminal to install the Xcode Command Line Tools on macOS, which are often sufficient for development without the full Xcode package. ```bash xcode-select --install ``` -------------------------------- ### Show Genrule Variables Source: https://github.com/bazelbuild/examples/blob/main/make-variables/README.md Demonstrates predefined variables exclusively available to genrules. This example shows variables for genrules with multiple sources and outputs. ```bash $ bazel build //testapp:show_genrule_variables && cat bazel-bin/testapp/subdir/show_genrule_variables1.out SRCS: testapp/show_genrule_variables1.src testapp/show_genrule_variables2.src OUTS: bazel-out/x86-fastbuild/bin/testapp/subdir/show_genrule_variables1.out bazel-out/x86-fastbuild/bin/testapp/subdir/show_genrule_variables2.out RULEDIR: bazel-out/x86-fastbuild/bin/testapp @D (prefer RULEDIR to this): bazel-out/x86-fastbuild/bin/testapp * Because this genrule has multiple outputs, @D is the same as RULEDIR. ``` -------------------------------- ### Register Toolchains with Local Configuration Source: https://context7.com/bazelbuild/examples/llms.txt Register a custom toolchain discovered via a module extension for local host configuration. This example shows registering a local shell binary. ```python # bzlmod/04-local_config_and_register_toolchains/MODULE.bazel module(name = "example", version = "0.0.1") sh_config_ext = use_extension("//:local_config_sh.bzl", "my_sh_config_extension") use_repo(sh_config_ext, "my_local_config_sh") register_toolchains("@my_local_config_sh//:local_sh_toolchain") ``` -------------------------------- ### Defining a Build Setting Rule Source: https://github.com/bazelbuild/examples/blob/main/configurations/basic_build_setting/README.md Define a custom build setting rule, specifying its type, default value, and whether it can be set on the command line. This example defines the 'temperature' build setting. ```Starlark temperature = build_setting( build_setting.string(default = "HOT"), flagged_by = "//basic_build_setting:coffee-temp", ) ``` -------------------------------- ### Show Custom Starlark Variable Source: https://github.com/bazelbuild/examples/blob/main/make-variables/README.md Demonstrates how to define and use custom variables within Starlark code. This example shows a simple custom variable 'FOO' defined and accessed. ```bash $ bazel build //testapp:show_custom_var && cat bazel-bin/testapp/custom_var Target //testapp:show_custom_var up-to-date: bazel-bin/testapp/custom_var INFO: Build completed successfully, 2 total actions FOO is equal to bar! ``` -------------------------------- ### Astro Project Commands Source: https://github.com/bazelbuild/examples/blob/main/frontend/astro/README.md Common commands for managing an Astro project. Use `npm run dev` to start the local development server, `npm run build` to create a production build, and `npm run preview` to test the production build locally. ```bash npm run dev ``` ```bash npm run build ``` ```bash npm run preview ``` -------------------------------- ### Custom Starlark Rule: Run Shell Command Source: https://context7.com/bazelbuild/examples/llms.txt Execute a shell command as a build action using `ctx.actions.run_shell`. Inputs and outputs must be explicitly declared. This example demonstrates getting the byte count of a file and converting a file's content to uppercase. ```python # rules/shell_command/rules.bzl def _emit_size_impl(ctx): in_file = ctx.file.file out_file = ctx.actions.declare_file("%s.size" % ctx.attr.name) ctx.actions.run_shell( inputs = [in_file], outputs = [out_file], progress_message = "Getting size of %s" % in_file.short_path, command = "wc -c '%s' | awk '{print $1}' > '%s'" % (in_file.path, out_file.path), ) return [DefaultInfo(files = depset([out_file]))] emit_size = rule( implementation = _emit_size_impl, attrs = { "file": attr.label(mandatory = True, allow_single_file = True), }, ) def _convert_to_uppercase_impl(ctx): ctx.actions.run_shell( outputs = [ctx.outputs.output], inputs = [ctx.file.input], arguments = [ctx.file.input.path, ctx.outputs.output.path], command = "tr '[:lower:]' '[:upper:]' < \"$1\" > \"$2\"", ) convert_to_uppercase = rule( implementation = _convert_to_uppercase_impl, attrs = { "input": attr.label(allow_single_file = True, mandatory = True), "output": attr.output(), }, ) ``` ```python # rules/shell_command/BUILD load(":rules.bzl", "convert_to_uppercase", "emit_size") emit_size(name = "foo", file = "foo.txt") convert_to_uppercase(name = "make_uppercase", input = "foo.txt", output = "upper_foo.txt") ``` ```bash bazel build //shell_command:foo //shell_command:make_uppercase cat bazel-bin/shell_command/foo.size # byte count of foo.txt ``` -------------------------------- ### Build and Run Go Application Source: https://context7.com/bazelbuild/examples/llms.txt Commands to build the Go binary and run the `print_fortune` application. ```bash bazel build //:hello bazel run //stage2:print_fortune ``` -------------------------------- ### Build Multi-Architecture Binary Source: https://github.com/bazelbuild/examples/blob/main/configurations/multi_arch_binary/README.md Use this command to build a multi-architecture binary. Ensure you are in the directory containing the BUILD file. ```bash bazel build :foo ``` -------------------------------- ### Build and Inspect Fetched Books Source: https://github.com/bazelbuild/examples/blob/main/bzlmod/05-integrate_third_party_package_manager/README.md Run this command to build the 'check_books' target and then view the contents of the 'books' file, which lists the fetched book information. ```bash bazel build check_books ``` ```bash cat ./bazel-bin/books ``` -------------------------------- ### Build with Default Tool Source: https://github.com/bazelbuild/examples/blob/main/configurations/label_typed_build_setting/README.md Builds the `:my-toolbox` target using its default tool configuration. ```bash bazel build :my-toolbox ``` -------------------------------- ### Test Output Verification Source: https://github.com/bazelbuild/examples/blob/main/configurations/cc_test/README.md Example output from a test run, showing the arguments passed to the test executable. This verifies the functionality of the Starlark configuration and transitions. ```text ==================== Test output for //:my-test: ################################################################################ MYTEST ARGV[0]: .../bazel-out/k8-fastbuild-ST-54535d7cadf4/bin/my-test.runfiles/__main__/my-test MYTEST ARGV[1]: x MYTEST ARGV[2]: y MYTEST ARGV[3]: z MYTEST ARGV[4]: new arg ################################################################################ ================================================================================ ``` -------------------------------- ### Testing Select with Build Settings Source: https://github.com/bazelbuild/examples/blob/main/configurations/select_on_build_setting/README.md Run these commands to test the `select()` functionality with different build setting values. The output will change based on the `--//select_on_build_setting:season` flag. ```bash bazel build :harvest # => "We're harvesting apples!" ``` ```bash bazel build :harvest --//select_on_build_setting:season=summer # => "We're harvesting cherries!" ``` ```bash bazel build :harvest --//select_on_build_setting:season=fall # => "We're harvesting pumpkins!" ``` -------------------------------- ### Configure Rust Toolchain for Bazel Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Define the Rust toolchain for Bazel, specifying the edition and version. This setup is crucial for Rust projects managed by Bazel. ```starlark RUST_EDITION = "2024" RUST_VERSION = "1.85.0" rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") rust.toolchain( edition = RUST_EDITION, versions = [RUST_VERSION], ) use_repo(rust, "rust_toolchains") register_toolchains("@rust_toolchains//:all") # Custom Rust Prost toolchain register_toolchains("@//build/prost_toolchain") # Rust dependencies. See thirdparty/BUILD.bazel ``` -------------------------------- ### Run gRPC Server with Bazel Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Execute the gRPC server binary using Bazel. Ensure the Bazel environment is set up correctly. ```bash bazel run //grpc_server:bin ``` -------------------------------- ### Build gRPC Server with Optimization Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Compile the gRPC server binary with optimizations enabled using Bazel's '-c opt' flag. ```bash bazel build -c opt //grpc_server:bin ``` -------------------------------- ### Get Output Path with Bazel cquery Source: https://github.com/bazelbuild/examples/blob/main/cpp-tutorial/stage1/README.md Retrieve the output path of a built target using the `bazel cquery` command with `--output=files`. This is useful for scripting. ```bash bazel cquery --output=files //main:hello-world ``` -------------------------------- ### Build with Default Build Setting Source: https://github.com/bazelbuild/examples/blob/main/configurations/use_skylib_build_setting/README.md Run a Bazel build command to see the default output when a build setting is not explicitly provided. ```bash bazel build :ice-cream // => "flavor: strawberry" ``` -------------------------------- ### Configure LLVM Toolchain Extension Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/02-hello-cross/README.md Configure the LLVM toolchain extension to download and manage multiple LLVM distributions for different target architectures. This setup is crucial for cross-compilation. ```Starlark llvm = use_extension("@toolchains_llvm//toolchain/extensions:llvm.bzl", "llvm") lvm.toolchain( name = "llvm_toolchain", extra_llvm_distributions = { "LLVM-20.1.4-Linux-ARM64.tar.xz": "4de80a332eecb06bf55097fd3280e1c69ed80f222e5bdd556221a6ceee02721a", "LLVM-20.1.4-Linux-X64.tar.xz": "113b54c397adb2039fa45e38dc8107b9ec5a0baead3a3bac8ccfbb65b2340caa", "LLVM-20.1.4-macOS-ARM64.tar.xz": "debb43b7b364c5cf864260d84ba1b201d49b6460fe84b76eaa65688dfadf19d2", "clang+llvm-20.1.4-x86_64-pc-windows-msvc.tar.xz": "2b12ac1a0689e29a38a7c98c409cbfa83f390aea30c60b7a06e4ed73f82d2457", }, llvm_version = "20.1.4", ) lvm.sysroot( name = "llvm_toolchain", label = "@sysroot_linux_x64//:sysroot", targets = ["linux-x86_64"], ) lvm.sysroot( name = "llvm_toolchain", label = "@sysroot_linux_aarch64//:sysroot", targets = ["linux-aarch64"], ) use_repo(llvm, "llvm_toolchain") register_toolchains("@llvm_toolchain//:all") ``` -------------------------------- ### Run C++ Binary with Bazel Source: https://github.com/bazelbuild/examples/blob/main/third-party-dependencies/README.md Execute the main C++ binary target using Bazel. ```bash bazel run //:hello_world ``` -------------------------------- ### Specify Dev Dependencies Source: https://context7.com/bazelbuild/examples/llms.txt Mark dependencies or extension usages as dev-only using `dev_dependency = True` to prevent them from being inherited by downstream consumers. This example shows overriding a dev-only dependency. ```python # bzlmod/06-specify_dev_dependency/MODULE.bazel module(name = "example", version = "0.0.1") bazel_dep(name = "lib_a", version = "") local_path_override(module_name = "lib_a", path = "./lib_a") # bazel_skylib as a direct non-dev dependency of the root bazel_dep(name = "bazel_skylib", version = "1.7.1") # The librarian_extension manages "books" as repositories; # hamlet@2005.1 overrides lib_a's dev-only hamlet@1800.1 librarian_extension = use_extension("@librarian//:librarian.bzl", "librarian_extension") librarian_extension.book(name = "hamlet", edition = "1800.1") use_repo(librarian_extension, "hamlet") ``` -------------------------------- ### Show Path Variables Source: https://github.com/bazelbuild/examples/blob/main/make-variables/README.md Demonstrates predefined variables related to source and output file paths, including 'execpath', 'runfiles', and 'location'. ```bash $ bazel build //testapp:show_app_output && cat bazel-bin/testapp/app_output :app output paths execpath: bazel-out/host/bin/testapp/app runfiles: testapp/app location: bazel-out/host/bin/testapp/app source file paths execpath: testapp/empty.source runfiles: testapp/empty.source location: testapp/empty.source ``` -------------------------------- ### Build and Test Java Application Source: https://context7.com/bazelbuild/examples/llms.txt Commands to build the Java application and run its tests. ```bash bazel build //:java-maven bazel test //:tests ``` -------------------------------- ### Query Bazel Targets and Dependencies Source: https://context7.com/bazelbuild/examples/llms.txt These commands demonstrate how to use `bazel query` to find targets, inspect dependencies, and visualize the dependency graph. ```bash bazel query //... ``` ```bash bazel query "deps(//src/main/java/com/example/restaurant:cafe, 1)" ``` ```bash bazel query "rdeps(//..., //src/main/java/com/example/ingredients:ingredients)" ``` ```bash bazel query --output=graph "deps(//:runner)" | dot -Tpng > graph.png ``` -------------------------------- ### Run Optimized gRPC Server Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Execute the pre-compiled, optimized gRPC server binary using Bazel. ```bash bazel run -c opt //grpc_server:bin ``` -------------------------------- ### Define Rust Binary without Macro Dependencies Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/05-deps-cargo/README.md Configure a rust_binary target that does not rely on specific macros for dependency management. This setup is suitable for simpler binaries where direct dependency inclusion is sufficient. ```starlark rust_binary( name = "bin", srcs = ["src/main.rs"], deps = all_crate_deps(normal = True), ) ``` -------------------------------- ### Cross-Compile Rust Binary to Specific Platforms Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/02-hello-cross/README.md Configure Rust binary targets to cross-compile the same source file to different platforms by specifying the 'platform' attribute. This example shows targets for x86_64 and aarch64 Linux. ```Starlark load("@rules_rust//rust:defs.bzl", "rust_binary") rust_binary( name = "hello_world_x86_64", srcs = ["src/main.rs"], platform = "//build/platforms:linux-x86_64", deps = [], ) rust_binary( name = "hello_world_aarch64", srcs = ["src/main.rs"], platform = "//build/platforms:linux-aarch64", deps = [], ) ``` -------------------------------- ### Build the cc_binary Target Source: https://github.com/bazelbuild/examples/blob/main/cpp-tutorial/stage3/README.md Command to build the 'hello-world' binary target located in the 'main' package using Bazel. ```bash bazel build //main:hello-world ``` -------------------------------- ### Define Rust Test with Workspace Dependencies Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/05-deps-cargo/README.md Configure a rust_test target to use dependencies managed by the Cargo workspace. This example shows how to include normal and development dependencies, as well as proc-macro dependencies, for testing. ```starlark load("@crate_index//:defs.bzl", "aliases", "all_crate_deps") load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") rust_test( name = "unit_test", crate = ":lib", aliases = aliases( normal_dev = True, proc_macro_dev = True, ), deps = all_crate_deps( normal_dev = True, ), proc_macro_deps = all_crate_deps( proc_macro_dev = True, ), ) ``` -------------------------------- ### Build and Run Rust gRPC Client & Server Source: https://context7.com/bazelbuild/examples/llms.txt Builds a Rust gRPC server binary and its documentation tests. It includes dependencies on Tokio, Tonic, and generated proto bindings. ```bazel load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_doc", "rust_doc_test", "rust_test_suite") ust_binary( name = "bin", srcs = glob(["src/*.rs"]), crate_root = "src/main.rs", rustc_flags = select({ "//:release": ["-Clink-arg=-flto", "-Ccodegen-units=1", "-Cpanic=abort", "-Copt-level=3"], "//conditions:default": ["-Copt-level=0"], }), deps = [ "//proto_bindings:rust_proto", "@crates//:tokio", "@crates//:tonic", ], ) ust_doc(name = "server_doc", crate = ":bin") ust_doc_test(name = "server_doc_test", crate = ":bin") ust_test_suite( name = "demo_tests", srcs = glob(["tests/*_tests.rs"]), tags = ["unit"], deps = ["//proto_bindings:rust_proto"], ) ``` -------------------------------- ### Define Reusable Build Abstractions with Symbolic Macros Source: https://context7.com/bazelbuild/examples/llms.txt Illustrates symbolic macros using `macro()` for composable build logic. This example defines a `count_words` macro that generates a genrule and an internal letter frequency genrule. ```python # macros/word_counter/defs.bzl def _impl(name, visibility, srcs, out, _count_tool): native.genrule( name = name, visibility = visibility, # propagate caller's visibility to exported target outs = [out], tools = [_count_tool], srcs = srcs, cmd = "$(location %s) -n 5 $(SRCS) > $@" % str(_count_tool), ) # Internal target uses name-suffixing convention (not exported to caller) native.genrule( name = name + "_gen_letter_freq", visibility = ["//letter_metrics:__pkg__"], outs = [name + "_letter_freq"], tools = [_count_tool], srcs = srcs, cmd = "$(location %s) -l $(SRCS) > $@" % str(_count_tool), ) count_words = macro( implementation = _impl, attrs = { "srcs": attr.label_list(mandatory = True), "out": attr.output(mandatory = True), "_count_tool": attr.label(default = ":counter.py", configurable = False), }, ) # macros/main/BUILD.bazel load("//word_counter:defs.bzl", "count_words") load("//letter_metrics:defs.bzl", "gather_all_letter_frequencies", "generate_letter_frequencies") count_words( name = "hamlet", srcs = ["//data:hamlet.txt"], out = "hamlet_word_freq", visibility = ["//whatever:__pkg__"], ) # Finalizer macro: automatically aggregates all letter_frequency targets in the package gather_all_letter_frequencies(name = "auto_aggregate", out = "auto_aggregate_stats") ``` ```bash bazel build //main:hamlet bazel build //main:auto_aggregate ``` -------------------------------- ### Run gRPC Client with Bazel Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Execute the gRPC client binary using Bazel. This command initiates the client-side gRPC operations. ```bash bazel run //grpc_client:bin ``` -------------------------------- ### Configure External Crates with crates_repository Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/05-deps-cargo/README.md Use the crates_repository rule to ingest a Cargo.lock file and Cargo.toml manifests to generate Bazel dependencies. This setup allows Cargo.toml to be the single source of truth for your project's dependencies. ```starlark crate = use_extension("@rules_rust//crate_universe:extension.bzl", "crate") # # External crates crate.from_cargo( name = "crates", cargo_lockfile = "//:Cargo.lock", manifests = ["//:Cargo.toml"], ) use_repo(crate, "crates") ``` -------------------------------- ### Expected Build Output Source: https://github.com/bazelbuild/examples/blob/main/bzlmod/06-specify_dev_dependency/README.md This is the expected output after running the build command. It shows the Bazel Skylib version and the fetched editions of books, confirming the dev dependency behavior. ```text DEBUG: /examples/bzlmod/06-specify_dev_dependency/BUILD:3:6: Bazel Skylib version: 1.1.1 ... $ cat bazel-bin/books Book Name: hamlet Edition: 1800.1 Book Name: the_great_gatsby Edition: 2003.7 ``` -------------------------------- ### Generate Rust Bindings from Proto Files Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Use `proto_library` to define proto files and `rust_prost_library` to generate Rust bindings. Ensure your proto files are correctly referenced. ```starlark load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_rust_prost//:defs.bzl", "rust_prost_library") # Build proto files # https://bazel.github.io/rules_rust/rust_prost.html#rust_proto_library proto_library( name = "proto_bindings", srcs = [ "proto/helloworld.proto", ], ) # Generate Rust bindings from the generated proto files # https://bazelbuild.github.io/rules_rust/rust_prost.html#rust_prost_library rust_prost_library( name = "rust_proto", proto = ":proto_bindings", visibility = ["//visibility:public"], ) ``` -------------------------------- ### Build and Inspect Toolchain with Bzlmod Source: https://github.com/bazelbuild/examples/blob/main/bzlmod/04-local_config_and_register_toolchains/README.md Run this command to build the target and then inspect the generated result. Ensure the MY_SHELL_BIN_PATH environment variable is set before execution. ```bash MY_SHELL_BIN_PATH=/foo/bar/sh bazel build //:get_sh_path cat ./bazel-bin/result ``` -------------------------------- ### Build Java Binary with glob Source: https://context7.com/bazelbuild/examples/llms.txt Build a Java binary using `glob` to gather all source files in a directory tree. Ensure `default_visibility` is set appropriately. ```python # java-tutorial/BUILD load(@rules_java//java:defs.bzl, "java_binary") package(default_visibility = ["//visibility:public"]) java_binary( name = "ProjectRunner", srcs = glob(["src/main/java/com/example/*.java"]), ) ``` ```bash # java-tutorial/MODULE.bazel bazel_dep(name = "rules_java", version = "7.11.1") bazel build //:ProjectRunner bazel run //:ProjectRunner ``` -------------------------------- ### Project-wide settings with incompatible flag checks (default) Source: https://github.com/bazelbuild/examples/blob/main/configurations/auto_configured_builds/README.md Demonstrates the default behavior when using project settings with incompatible flag checks. Builds succeed with non-conflicting flags but fail if contradictory flags are provided. ```sh $ bazel build //compatible:all INFO: Reading project settings from //compatible:PROJECT.scl. INFO: Applying flags from the config 'default_config' defined in //compatible:PROJECT.scl: [--platforms=//:myplatform, --compilation_mode=opt, --@custom_flags//:project_flag="custom flag value"] INFO: Found 2 targets... INFO: Build completed successfully, 3 total actions ``` ```sh $ bazel build //compatible:all --copt=abc INFO: Reading project settings from //compatible:PROJECT.scl. WARNING: This build uses a project file (//compatible:PROJECT.scl), but also sets output-affecting flags in the command line or user bazelrc: ['--copt=abc']. Please consider removing these flags. INFO: Applying flags from the config 'default_config' defined in //compatible:PROJECT.scl: [--platforms=//:myplatform, --compilation_mode=opt, --@custom_flags//:project_flag="custom flag value"] INFO: Build completed successfully, 3 total actions ``` ```sh $ bazel build //compatible:all --compilation_mode=fastbuild INFO: Reading project settings from //compatible:PROJECT.scl. ERROR: Cannot parse options: This build uses a project file (//compatible:PROJECT.scl) that does not allow conflicting flags in the command line or user bazelrc. Found ['--compilation_mode=fastbuild']. Please remove these flags or disable project file resolution via --noenforce_project_configs. ERROR: Build did NOT complete successfully ``` -------------------------------- ### Test Containerized Application Source: https://github.com/bazelbuild/examples/blob/main/java-maven/README.md Verify that the container image works correctly within a container runtime. ```bash $ bazel test :container_test ``` -------------------------------- ### Build and Inspect City/Emoji Counts Source: https://github.com/bazelbuild/examples/blob/main/bzlmod/03-introduce_dependencies_with_module_extension/README.md Run this command to build the targets and then view the generated output files. ```bash bazel build //:city_count //:emoji_count cat bazel-bin/city_number bazel-bin/emoji_number ``` -------------------------------- ### Build with Specified Tool Source: https://github.com/bazelbuild/examples/blob/main/configurations/label_typed_build_setting/README.md Builds the `:my-toolbox` target, overriding the default tool with a specified label using a label-typed build setting. ```bash bazel build :my-toolbox --//label_typed_build_setting:tool=//label_typed_build_setting:screwdriver ``` -------------------------------- ### Build and Run gRPC Application Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/08-grpc-client-server/README.md Commands to build all targets, run tests, and execute the gRPC server and client applications using Bazel. ```shell bazel build //... bazel test //... Run the server: bazel run //grpc_server:bin Run the client: bazel run //grpc_client:bin ``` -------------------------------- ### Build Next.js Application with Bazel Source: https://github.com/bazelbuild/examples/blob/main/frontend/next.js/README.md Run this command to build the Next.js application using Bazel. The output will be located in `bazel-bin/next.js/.next`. ```bash pnpm run build bazel build //next.js:next ``` -------------------------------- ### Build OCI Container Image Source: https://context7.com/bazelbuild/examples/llms.txt Command to build the OCI container image. ```bash bazel build //:image ``` -------------------------------- ### Build with Non-Bazel Webpack Source: https://github.com/bazelbuild/examples/blob/main/frontend/react-webpack/README.md Run this command to build the project using the standard Webpack build process without Bazel. ```shell pnpm build ``` -------------------------------- ### Build with Bazel Source: https://github.com/bazelbuild/examples/blob/main/frontend/react-webpack/README.md Execute this command to build the React Webpack application using Bazel. ```shell bazel build //react-webpack/... ``` -------------------------------- ### Project-wide settings with strict flag checks (default) Source: https://github.com/bazelbuild/examples/blob/main/configurations/auto_configured_builds/README.md Illustrates strict flag checking for project-wide settings. Builds will fail if any flags differ from the project's defined settings, ensuring canonical flag usage. ```sh $ bazel build //strict:all INFO: Reading project settings from //strict:PROJECT.scl. INFO: Applying flags from the config 'default_config' defined in //strict:PROJECT.scl: [--platforms=//:myplatform, --compilation_mode=opt, --@custom_flags//:project_flag="custom flag value"] INFO: Found 2 targets... INFO: Build completed successfully, 3 total actions ``` ```sh $ bazel build //strict:all --copt=abc INFO: Reading project settings from //strict:PROJECT.scl. ERROR: Cannot parse options: This build uses a project file (//strict:PROJECT.scl) that does not allow output-affeccting flags in the command line or user bazelrc. Found ['--copt=abc']. Please remove these flags or disable project file resolution via --noenforce_project_configs. ERROR: Build did NOT complete successfully ``` -------------------------------- ### Attach Configuration Transitions to Rules Source: https://context7.com/bazelbuild/examples/llms.txt Illustrates how to define and attach Starlark configuration transitions to rule attributes. Transitions modify the build configuration for a target and its dependencies. ```bzl def _set_color_transition_impl(settings, attr): return {"//attaching_transitions_to_rules:color": attr.color} _set_color = transition( implementation = _set_color_transition_impl, inputs = [], outputs = ["//attaching_transitions_to_rules:color"], ) shirt = rule( implementation = _shirt_impl, attrs = { "color": attr.string(default = "white"), "back": attr.label(cfg = _set_color), "sleeve": attr.label(cfg = _set_color), }, ) ``` ```BUILD load("@bazel_skylib//rules:common_settings.bzl", "string_flag") load(":defs.bzl", "piece", "shirt") string_flag(name = "color", build_setting_default = "black") shirt(name = "tee", back = ":back", sleeve = ":sleeve") piece(name = "sleeve") piece(name = "back") ``` ```bash bazel build //attaching_transitions_to_rules:tee ``` -------------------------------- ### Custom Starlark Rule with ctx.actions.expand_template Source: https://context7.com/bazelbuild/examples/llms.txt Generates a source file from a template by substituting placeholder strings at build time. This is more efficient than building full content in memory. ```python # rules/expand_template/hello.bzl def hello(**kwargs): _hello(source_file = "{name}.cc".format(**kwargs), **kwargs) def _hello_impl(ctx): ctx.actions.expand_template( template = ctx.file._template, output = ctx.outputs.source_file, substitutions = {"{FIRSTNAME}": ctx.attr.firstname}, ) _hello = rule( implementation = _hello_impl, attrs = { "firstname": attr.string(mandatory = True), "_template": attr.label(default = ":hello.cc", allow_single_file = True), "source_file": attr.output(mandatory = True), }, ) # rules/expand_template/BUILD load("@rules_cc//cc:defs.bzl", "cc_binary") load(":hello.bzl", "hello") hello(name = "hello_john_src", firstname = "John") cc_binary(name = "hello", srcs = [":hello_john_src"]) ``` ```bash bazel run //expand_template:hello # Output: Hello John! ``` -------------------------------- ### Build Java Maven Application Source: https://github.com/bazelbuild/examples/blob/main/java-maven/README.md Use this command to build the Java application with Maven dependencies managed by Bazel. ```bash $ bazel build :java-maven ``` -------------------------------- ### Vendor Rust Dependencies Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/07-deps-vendor/README.md Run this command to download and store all Rust dependencies locally in the `thirdparty/crates` folder. This step is crucial before building any targets that rely on vendored crates. ```bash bazel run //thirdparty:crates_vendor ``` -------------------------------- ### OCI Image Build and Publish Workflow Source: https://github.com/bazelbuild/examples/blob/main/rust-examples/09-oci-container/README.md Integrates custom tagging, tar compression, OCI image building, and pushing to a registry. Ensure all necessary rules are loaded before defining targets. ```Starlark # Import all applicable rules. load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_doc", "rust_doc_test") load("@rules_pkg//pkg:tar.bzl", "pkg_tar") load("@rules_oci//oci:defs.bzl", "oci_image", "oci_push", "oci_image_index") # Import the custom image tag macro load("//:build/container.bzl", "build_sha265_tag") # 1) Compress the Rust binary to tar pkg_tar( name = "tar", srcs = [":bin"], ) # 2) Build container image # https://github.com/bazel-contrib/rules_oci/blob/main/docs/image.md oci_image( name = "image", base = "@distroless", tars = [":tar"], entrypoint = ["/bin"], exposed_ports = ["4242"], visibility = ["//visibility:public"], ) # 3) Build an unique and immutable image tag build_sha265_tag( name = "remote_tag", image = ":image", input = "image.json.sha256", output = "_tag.txt", ) # 4) Define a registry to publish the image # https://github.com/bazel-contrib/rules_oci/blob/main/docs/push.md) oci_push( name = "push", image = ":image", repository = "my.registry.com/rest-tokio", remote_tags = ":remote_tag", visibility = ["//visibility:public"], ) ``` -------------------------------- ### Show Predefined Variables Source: https://github.com/bazelbuild/examples/blob/main/make-variables/README.md Demonstrates predefined variables available to all Bazel rules. These variables are substituted in attributes marked as such. ```bash $ bazel build //testapp:show_predefined_variables && cat bazel-bin/testapp/show_predefined_variables.out COMPILATION_MODE: fastbuild BINDIR: bazel-out/x86-fastbuild/bin GENDIR: bazel-out/x86-fastbuild/bin TARGET_CPU: x86 ``` -------------------------------- ### C++ Multi-Package Build with Visibility Source: https://context7.com/bazelbuild/examples/llms.txt Split a project into two packages (`//main` and `//lib`) and manage cross-package dependencies using `visibility` declarations. ```python # cpp-tutorial/stage3/lib/BUILD load(@rules_cc//cc:cc_library.bzl, "cc_library") cc_library( name = "hello-time", srcs = ["hello-time.cc"], hdrs = ["hello-time.h"], visibility = ["//main:__pkg__"], # only visible to //main ) # cpp-tutorial/stage3/main/BUILD cc_binary( name = "hello-world", srcs = ["hello-world.cc"], deps = [ ":hello-greet", "//lib:hello-time", # cross-package dependency ], ) ``` ```bash bazel build //main:hello-world ```