### Start InstantSearch Source: https://github.com/bazelbuild/bazel-website/blob/master/search2.html Starts the Algolia InstantSearch instance, initiating the search process and rendering the configured widgets. ```javascript search.start(); ``` -------------------------------- ### Markdown Formatting Example Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/docs-style.md Illustrates the recommended Markdown formatting for documentation, including line wrapping and link usage. ```markdown Where possible, use Markdown instead of HTML in your files. Follow the [GitHub Markdown Syntax Guide](https://guides.github.com/features/mastering-markdown/#syntax) for recommended Markdown style. ``` -------------------------------- ### Example of Output Path Without CPU Source: https://github.com/bazelbuild/bazel-website/blob/master/roadmaps/2018/configuration.md This example shows an output path for a Java class that does not include the CPU architecture. This change aims to improve multiplatform build times and cross-build cacheability. ```text bazel-out/ppc-fastbuild/PlatformIndependentModule.class ``` -------------------------------- ### Skylark Macro for Java Setup Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2015-07-02-skylark-remote-repositories.md This macro defines bindings and a local repository for Java development. It's used to simplify the setup of Java toolchains and related targets. ```python def setup_java(): native.new_local_repository(name = “jdk-local”, path = “/usr/share/java/jdk8”, build_file = “jdk.BUILD”) for target in ["jni_header", "jni_md_header", "langtools", "bootclasspath", "extdir", "toolchain", "jdk", "java", "javac", "jar"]: native.bind(name=target, actual="@%s//:%s" % (name, target)) native.bind(name="jni_md_header-linux", actual="@%s//:jni_md_header" % name) native.bind(name="jni_md_header-darwin", actual="@%s//:jni_md_header" % name) ``` -------------------------------- ### Basic Shell Command Example Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/docs-style.md Use code blocks for commands that users are expected to copy and execute. Separate commands from their output into distinct blocks. ```shell ... ``` -------------------------------- ### Example Usage of Label-keyed String Dictionary Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2017-03-03-label-keyed-string-dict-type.md Demonstrates defining flag rules, setting configuration based on labels, and using select statements with label-keyed flag values. ```Starlark flag_rule( name = "beep", values = ["boop", "bop", "bump"], default = "bump" ) config_setting( name = "beep#boop", flag_values = { ":beep": "boop" } ) transition_rule( name = "configuration", deps = [ ":lib" ], sets_flags = { ":beep": "boop" } ) library_rule( name = "lib" deps = select({ ":beep#boop": [":boop_dep"], "//conditions:default": [":other_dep"] }) ) ``` -------------------------------- ### Build Bazel Binary Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/getting_started.md Builds the Bazel binary using an existing Bazel installation. The resulting binary is located at `bazel-bin/src/bazel`. ```bash bazel build //src:bazel ``` -------------------------------- ### Test Bazel Chocolatey Package Installation Source: https://github.com/bazelbuild/bazel-website/blob/master/maintaining/windows-chocolatey-maintenance.md Tests the installation of the Bazel Chocolatey package. This script should install the package cleanly and provide further instructions. It assumes a web server is running locally on port 8000 to serve the package files. ```powershell choco uninstall bazel # should remove bazel from the system ``` -------------------------------- ### Inline Code Formatting Example Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/docs-style.md Use inline code styling for filenames, directories, and paths to distinguish them from regular text. This improves readability and clarity. ```text bazel help ``` -------------------------------- ### Test Bazel Scoop Installation Source: https://github.com/bazelbuild/bazel-website/blob/master/maintaining/windows-scoop-maintenance.md Uninstall, install, and verify the Bazel Scoop package. This is used to test changes made to the bazel.json file. ```bash scoop uninstall bazel scoop install bazel bazel version bazel something_else ``` -------------------------------- ### Set Install Link Based on OS Source: https://github.com/bazelbuild/bazel-website/blob/master/index.html This JavaScript code snippet dynamically sets the download link for Bazel installation based on the user's operating system. It checks for Windows, macOS, and Linux environments. ```javascript var installBtn = document.getElementById("btn-install"); if (navigator.appVersion.indexOf("Win") != -1) { installBtn.href = "{{ site.docs_site_url }}/install-windows.html"; } else if (navigator.appVersion.indexOf("Mac") != -1) { installBtn.href = "{{ site.docs_site_url }}/install-os-x.html"; } else if (navigator.appVersion.indexOf("Linux") != -1) { installBtn.href = "{{ site.docs_site_url }}/install-ubuntu.html"; } ``` -------------------------------- ### Native Provider Declaration Example Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/declared-providers.md A hypothetical Java implementation demonstrating how to declare a Skylark provider natively using annotations. ```java /** * Hypothetical implementation of Skylark provider value (result of * provider(..) function. */ class SkylarkProviderValue extends SkylarkValue { ... /** * Creates a SkylarkProviderValue for a native provider * `native` must be annotated with @SkylarkProvider annotation. * Field accessors and constructor function appear magically. */ static SkylarkProviderValue forNative(Class native) { ... } } @SkylarkProvider(builder = Builder.class) // A class with this annotation can be used as provider declaration class rustProvider implements TransitiveInfoProvider { @SkylarkProviderField(doc = ...) // Skylark name is 'defines' String getDefines() { ... } @SkylarkProviderField(doc = ...) // Skylark name is 'transitive_deps' NestedSet getTransitiveDeps() { ... } @SkylarkProviderField(doc = ...) // Not allowed, the set of types exposed to Skylark is restricted DottedVersion getVersion() { ... } // Automatically used to provide an implementation for // construction function. static class Builder { // a setter for 'defines' field, based on name. void setDefines(String defines) { ... } // a setter for 'transitive_deps' field, based on name. void setTransitiveDeps(...) {...} rustProvider build() { ... } } } ``` -------------------------------- ### Declare Target Platforms for Rules Source: https://github.com/bazelbuild/bazel-website/blob/master/roadmaps/2018/configuration.md Example of how to specify target platforms for rules in a BUILD file. This allows rules to declare which machines they can build on. ```sh $ cat a/BUILD cc_binary(name = "app_for_linux", platforms = ["//platforms:linux"]) cc_binary(name = "app_for_mac", platforms = ["//platforms:mac"]) $ bazel build //a:all # No command line flags! ``` -------------------------------- ### Clone Bazel Repository Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/getting_started.md Clone the official Bazel Git repository from GitHub to start contributing. ```bash git clone https://github.com/bazelbuild/bazel.git ``` -------------------------------- ### Bazel Build Error Example Source: https://github.com/bazelbuild/bazel-website/blob/master/404.md This snippet shows a typical error message from Bazel when attempting to build a target that does not exist. It highlights the 'ERROR: no such page' message and the 'BUILD file not found' reason. ```bash $ bazel build :what-you-were-looking-for ............... ERROR: no such page ':what-you-were-looking-for': BUILD file not found on package path. INFO: Elapsed time: 0.567s ``` -------------------------------- ### Example of a 'sandwich' rule dependency structure Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2016-08-04-extensibility-for-native-rules.md Illustrates a common scenario where a Skylark rule ('bread_library') needs to interact with a native rule ('java_library') in a dependency chain. ```python bread_library(name = "top", …) java_library(name = "meat", deps = [":top", …], …) bread_library(name = "bottom", deps = [":meat", …]) ``` -------------------------------- ### Generate BUILD File and Toolchain Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2015-03-06-bazel-init.md This function generates a BUILD file for a JDK, sets up a local repository, and defines a Java toolchain. It also installs necessary build jars. ```python def generate_method(attrs): scratch_file("BUILD.jdk", """ Content of the jdk BUILD file. """) # Create binding using local_repository. This should not lie in # the WORKSPACE file but in a separate WORKSPACE file in the hidden # directory. local_repository(name = "jdk", path = attrs.jdk_path, build_file = "BUILD.jdk") bind("@jdk//jdk", "jdk") # also add a filegroup("jdk", "//external:jdk") java_toolchain(name = "toolchain", source = attrs.java_version, target = attrs.java_version) # The magic __BAZEL_*__ variable could be set so we don’t # redownload the repository if possible. This install_target # should leverage the work already done on remote repositories. # This should build and copy the result into the tools directory with # The corresponding exports_files now. install_target(__BAZEL_REPOSITORY__, __BAZEL_VERSION__, "//src/java_tools/buildjar:JavaBuilder_deploy.jar") install_target(__BAZEL_REPOSITORY__, __BAZEL_VERSION__, "//src/java_tools/buildjar:JavaBuilder_deploy.jar") copy("https://ijar_url", "ijar") ``` -------------------------------- ### Execute a command and get its output Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2016-02-16-cpp-autoconf.md The `execute` method runs a command and returns its standard output, standard error, and return code. This is useful for detecting compiler types or gathering compiler flags. ```python exec_result = execute(["gcc", "...", "-v"]) print(exec_result.stdout) ``` -------------------------------- ### Correcting invalid label format in Bazel deps Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2016-05-23-beautiful-error-messages.md This example addresses an error related to invalid label formats in the 'deps' attribute. It shows how to fix labels that incorrectly start with a slash by suggesting the correct format with double slashes. ```python cc_library( name = "name", deps = ["/test/foo.cc"], ) ``` ```text ERROR: /path/BUILD:1:1: //test:name: invalid label '/test/foo.cc' in element 0 of attribute 'srcs' in 'cc_library' rule: invalid target name '/test/foo.cc': target names may not start with '/' ``` ```text ERROR: /path/BUILD:3:13: Invalid label '/test:foo.cc' in deps. Labels relative to the root start with //. Did you mean '//test:foo.cc'? deps = ["/test:foo.cc"], ^------------- "//test:foo.cc" ``` -------------------------------- ### Initialize Algolia InstantSearch Source: https://github.com/bazelbuild/bazel-website/blob/master/search2.html Initializes the InstantSearch instance with application ID, API key, index name, and search parameters. Use this to set up the search client. ```javascript var search = instantsearch({ appId: 'BH4D9OD16A', apiKey: '8e0152321e991cc72635d18bfd059bf1', indexName: 'bazel', urlSync: true, searchParameters: { hitsPerPage: 10 } }); ``` -------------------------------- ### Declaring a Provider with Documentation and Fields Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/declared-providers.md Illustrates how to declare a provider with associated documentation and a list of its fields. Extra undeclared fields are disallowed if 'fields' is present. ```python rust_provider = provider( doc = "This provider contains Rust information ...", fields = ["defines", "transitive_deps"] ) ``` -------------------------------- ### Build Bazel on Windows Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/getting_started.md Compile the Bazel project from source on Windows systems using the Bazel build tool. Specify an output directory for the executable. ```bash cd bazel bazel --output_user_root=c:\tmp build //src:bazel.exe ``` -------------------------------- ### Returning Legacy Providers Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/declared-providers.md Demonstrates returning providers using legacy simple names in the return struct. This also works for default providers like 'files' and 'runfiles'. ```python def _impl(ctx): ... return struct( legacy_provider = struct(...), files = set(...), providers = [rust]) ``` -------------------------------- ### Negate a Search Term Source: https://github.com/bazelbuild/bazel-website/blob/master/browse-and-search-user-guide.md Use the '-' prefix to negate a term from the search results. This example searches for 'hello' but excludes 'world'. ```text hello -world ``` -------------------------------- ### Build with all targets Source: https://github.com/bazelbuild/bazel-website/blob/master/roadmaps/2019/configuration.md Build all targets without needing specific command-line flags. This demonstrates the 'just works' philosophy for multi-platform builds. ```bash $ bazel build :all ``` -------------------------------- ### Build All Targets Source: https://github.com/bazelbuild/bazel-website/blob/master/roadmaps/configuration.md Command to build all targets in the project. This is the desired end-state for Bazel builds. ```bash bazel build //:all ``` -------------------------------- ### Returning Declared and Legacy Providers Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/declared-providers.md Shows how to return a declared provider both directly and with a simple name, facilitating migration from old to new rule styles. ```python def _impl(ctx): ... return struct(rust = rust, providers = [rust]) ``` -------------------------------- ### Mutability Example in Skylark Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/saner-skylark-sets.md Demonstrates how lists, tuples, and structs can be mutable if they contain mutable elements like lists. Only immutable structs are allowed in sets. ```python l = [27, 42, 30] # This list is mutable (inside a function definition) t = (l, 42) # This tuple is mutable, since l can be modified s = struct(field = l) # This struct is mutable, since l can be modified ``` -------------------------------- ### Declaring a Provider with Fields as a Dictionary Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/declared-providers.md Shows how to declare a provider where the 'fields' argument is a dictionary, mapping field names to their documentation strings. ```python rust_provider = provider( doc = "This provider contains Rust information ...", fields = { "defines": "doc for define", "transitive_deps": "doc for transitive deps, }) ``` -------------------------------- ### Build Bazel Distribution Archive Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/getting_started.md Creates a distribution archive of Bazel, which is useful for rebuilding Bazel when making modifications. This archive is then used with the `compile.sh` script. ```bash bazel build //:bazel-distfile ``` -------------------------------- ### Escape Special Characters Source: https://github.com/bazelbuild/bazel-website/blob/master/browse-and-search-user-guide.md Use a backslash '\' to escape special characters like '.', '\', or '('. This example escapes parentheses in a function name search. ```text run\(\) ``` -------------------------------- ### Filter Search by Language Source: https://github.com/bazelbuild/bazel-website/blob/master/browse-and-search-user-guide.md Use the 'lang:' filter to perform an exact match by file language. This example searches for 'test' within Java files. ```text lang:java test ``` -------------------------------- ### Build Bazel on Linux/macOS Source: https://github.com/bazelbuild/bazel-website/blob/master/basics/getting_started.md Compile the Bazel project from source on Linux or macOS systems using the Bazel build tool itself. This command builds the main Bazel binary. ```bash cd bazel bazel build //src:bazel ``` -------------------------------- ### Define Parameterized Aspect and Rule Source: https://github.com/bazelbuild/bazel-website/blob/master/designs/skylark/parameterized-aspects.md This example demonstrates how to define a parameterized aspect with a limited set of API versions and a rule that uses this aspect with a custom parameter extractor. ```python SUPPORTED_API_VERSIONS = ["1","2","3"] def _py_aspect_attrs(api_version): if api_version = "1": return { '_protoc' : attr.label(default = "//tools/protoc:v1") } else if api_version == "2": …. def _py_aspect_impl(target, ctx, params): if params.api_version == "1": …. py_proto_aspect = aspect(implementation = _py_aspect_impl, # params declare all aspect parameters with all possible values params = { 'api_version' : set(SUPPORTED_API_VERSIONS) }, attr_aspects = ['deps'], # rhs of attrs can still be dictionary if no dependencies on params attrs = _py_aspect_attrs, ) # Can be omitted, see below. def _py_proto_library_parameter_extractor(py_api_version, some_other_attr): return { 'api_version' : str(py_api_version), } py_proto_library = rule(implementation = _py_proto_library_impl, attrs = { 'py_api_version' : attr.int() 'deps': attr.label_list(aspect = py_proto_aspect, # Can be omitted: the default extractor # just strs all rule attributes with the same # names as aspect parameters. aspect_parameter_extractor = _py_proto_library_parameter_extractor, ), 'some_other_attr' : attr.string(), } ) ```