bazel-lib-2.22.5/000077500000000000000000000000001513125663600134535ustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/000077500000000000000000000000001513125663600150105ustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/bazelrc/000077500000000000000000000000001513125663600164325ustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/bazelrc/.gitignore000066400000000000000000000000151513125663600204160ustar00rootroot00000000000000user.bazelrc bazel-lib-2.22.5/.aspect/bazelrc/BUILD.bazel000066400000000000000000000012651513125663600203140ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_file") exports_files(glob([ "*.bazelrc", "*.md", ])) # `usage.md` & `intro.md` are also used for [docsite](https://docs.aspect.build/guides/bazelrc) # content which is why they are separated into individual md files genrule( name = "gen_readme_md", srcs = glob(["*.md"]), outs = ["_README.md"], cmd = """ cat .aspect/bazelrc/intro.md > $@ echo '' >> $@ cat .aspect/bazelrc/usage.md >> $@ echo '' >> $@ cat .aspect/bazelrc/automatic_updates.md >> $@ """, ) write_source_file( name = "update_readme_md", in_file = "_README.md", out_file = "README.md", ) bazel-lib-2.22.5/.aspect/bazelrc/README.md000066400000000000000000000050171513125663600177140ustar00rootroot00000000000000# Aspect bazelrc presets The `.bazelrc` files found here are the source-of-truth for our recommended Bazel presets. ## Using Aspect bazelrc presets in your project The `.bazelrc` file can get large, fast. Some settings don't apply everywhere - some options are appropriate only on CI, and some vary depending on the version of Bazel you use or languages used. Bazel rc files can contain `import` statements, which allow you to organize the content better. To use these presets in your project, simply vendor the `*.bazelrc` files from https://github.com/bazel-contrib/bazel-lib/tree/main/.aspect/bazelrc into the `.aspect/bazelrc` folder in your repository and `import` them in your `.bazelrc` file. For example, ```python title=".bazelrc" # Import Aspect bazelrc presets import %workspace%/.aspect/bazelrc/bazel6.bazelrc import %workspace%/.aspect/bazelrc/convenience.bazelrc import %workspace%/.aspect/bazelrc/correctness.bazelrc import %workspace%/.aspect/bazelrc/debug.bazelrc import %workspace%/.aspect/bazelrc/javascript.bazelrc import %workspace%/.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/.aspect/bazelrc/user.bazelrc ``` ## Automatic updates A convenient way to automatically keep your vendored copy up-to-date is to use the `write_aspect_bazelrc_presets` rule in `.aspect/bazelrc/BUILD.bazel`: ```python title=".aspect/bazelrc/BUILD.bazel" "Aspect bazelrc presets; see https://docs.aspect.build/guides/bazelrc" load("@aspect_bazel_lib//lib:bazelrc_presets.bzl", "write_aspect_bazelrc_presets") write_aspect_bazelrc_presets(name = "update_aspect_bazelrc_presets") ``` When `@aspect_bazel_lib` is upgraded in your `WORKSPACE.bazel` or your `MODULE.bazel` file, a `diff_test` stamped out by `write_aspect_bazelrc_presets` will fail if your vendored copy is out-of-date and print the Bazel command to run to update it. For example, `bazel run //.aspect/bazelrc:update_aspect_bazelrc_presets`. See the [bazelrc](https://github.com/aspect-build/bazel-examples/blob/main/bazelrc/.aspect/bazelrc/BUILD.bazel) example in our [bazel-examples](https://github.com/aspect-build/bazel-examples) repository for a working example. bazel-lib-2.22.5/.aspect/bazelrc/automatic_updates.md000066400000000000000000000017511513125663600224730ustar00rootroot00000000000000## Automatic updates A convenient way to automatically keep your vendored copy up-to-date is to use the `write_aspect_bazelrc_presets` rule in `.aspect/bazelrc/BUILD.bazel`: ```python title=".aspect/bazelrc/BUILD.bazel" "Aspect bazelrc presets; see https://docs.aspect.build/guides/bazelrc" load("@aspect_bazel_lib//lib:bazelrc_presets.bzl", "write_aspect_bazelrc_presets") write_aspect_bazelrc_presets(name = "update_aspect_bazelrc_presets") ``` When `@aspect_bazel_lib` is upgraded in your `WORKSPACE.bazel` or your `MODULE.bazel` file, a `diff_test` stamped out by `write_aspect_bazelrc_presets` will fail if your vendored copy is out-of-date and print the Bazel command to run to update it. For example, `bazel run //.aspect/bazelrc:update_aspect_bazelrc_presets`. See the [bazelrc](https://github.com/aspect-build/bazel-examples/blob/main/bazelrc/.aspect/bazelrc/BUILD.bazel) example in our [bazel-examples](https://github.com/aspect-build/bazel-examples) repository for a working example. bazel-lib-2.22.5/.aspect/bazelrc/bazel6.bazelrc000066400000000000000000000076471513125663600211770ustar00rootroot00000000000000# Not using common here because https://github.com/bazelbuild/bazel/pull/18609 was added in Bazel 6.3.0 # Speed up all builds by not checking if external repository files have been modified. # Docs: https://github.com/bazelbuild/bazel/blob/1af61b21df99edc2fc66939cdf14449c2661f873/src/main/java/com/google/devtools/build/lib/bazel/repository/RepositoryOptions.java#L244 build --noexperimental_check_external_repository_files fetch --noexperimental_check_external_repository_files query --noexperimental_check_external_repository_files # Directories used by sandboxed non-worker execution may be reused to avoid unnecessary setup costs. # Save time on Sandbox creation and deletion when many of the same kind of action run during the # build. # Docs: https://bazel.build/reference/command-line-reference#flag--reuse_sandbox_directories build --reuse_sandbox_directories # Avoid this flag being enabled by remote_download_minimal or remote_download_toplevel # See https://meroton.com/blog/bazel-6-errors-build-without-the-bytes/ build --noexperimental_action_cache_store_output_metadata # Speed up all builds by not checking if output files have been modified. Lets you make changes to # the output tree without triggering a build for local debugging. For example, you can modify # [rules_js](https://github.com/aspect-build/rules_js) 3rd party npm packages in the output tree # when local debugging. # Docs: https://github.com/bazelbuild/bazel/blob/1af61b21df99edc2fc66939cdf14449c2661f873/src/main/java/com/google/devtools/build/lib/pkgcache/PackageOptions.java#L185 # NB: This flag is in bazel6.bazelrc as when used in Bazel 7 is has been observed to break # "build without the bytes" --remote_download_outputs=toplevel. See https://github.com/bazel-contrib/bazel-lib/pull/711 # for more info. build --noexperimental_check_output_files fetch --noexperimental_check_output_files query --noexperimental_check_output_files # Don't apply `--noremote_upload_local_results` and `--noremote_accept_cached` to the disk cache. # If you have both `--noremote_upload_local_results` and `--disk_cache`, then this fixes a bug where # Bazel doesn't write to the local disk cache as it treats as a remote cache. # Docs: https://bazel.build/reference/command-line-reference#flag--incompatible_remote_results_ignore_disk # NB: This flag is in bazel6.bazelrc because it became a no-op in Bazel 7 and has been removed # in Bazel 8. build --incompatible_remote_results_ignore_disk # Propagate tags from a target declaration to the actions' execution requirements. # Ensures that tags applied in your BUILD file, like `tags=["no-remote"]` # get propagated to actions created by the rule. # Without this option, you rely on rules authors to manually check the tags you passed # and apply relevant ones to the actions they create. # See https://github.com/bazelbuild/bazel/issues/8830 for details. # Docs: https://bazel.build/reference/command-line-reference#flag--experimental_allow_tags_propagation build --experimental_allow_tags_propagation fetch --experimental_allow_tags_propagation query --experimental_allow_tags_propagation # Do not build runfiles symlink forests for external repositories under # `.runfiles/wsname/external/repo` (in addition to `.runfiles/repo`). This reduces runfiles & # sandbox creation times & prevents accidentally depending on this feature which may flip to off by # default in the future. Note, some rules may fail under this flag, please file issues with the rule # author. # Docs: https://bazel.build/reference/command-line-reference#flag--legacy_external_runfiles build --nolegacy_external_runfiles # The maximum number of attempts to retry a download error. # Using the default value from Bazel 8. # Docs: https://bazel.build/reference/command-line-reference#common_options-flag--experimental_repository_downloader_retries build --experimental_repository_downloader_retries=5 fetch --experimental_repository_downloader_retries=5 query --experimental_repository_downloader_retries=5 bazel-lib-2.22.5/.aspect/bazelrc/bazel7.bazelrc000066400000000000000000000043711513125663600211670ustar00rootroot00000000000000# Speed up all builds by not checking if external repository files have been modified. # Docs: https://github.com/bazelbuild/bazel/blob/1af61b21df99edc2fc66939cdf14449c2661f873/src/main/java/com/google/devtools/build/lib/bazel/repository/RepositoryOptions.java#L244 common --noexperimental_check_external_repository_files # Don't report when the root module's lower bound for a dependency happens to be less than the resolved version. # This is expected and should NOT prompt an engineer to update our lower bound to match. # WARNING: For repository 'aspect_bazel_lib', the root module requires module version aspect_bazel_lib@1.30.2, # but got aspect_bazel_lib@1.31.2 in the resolved dependency graph. common --check_direct_dependencies=off # Directories used by sandboxed non-worker execution may be reused to avoid unnecessary setup costs. # Save time on Sandbox creation and deletion when many of the same kind of action run during the # build. # Docs: https://bazel.build/reference/command-line-reference#flag--reuse_sandbox_directories common --reuse_sandbox_directories # Do not build runfiles symlink forests for external repositories under # `.runfiles/wsname/external/repo` (in addition to `.runfiles/repo`). This reduces runfiles & # sandbox creation times & prevents accidentally depending on this feature which may flip to off by # default in the future. Note, some rules may fail under this flag, please file issues with the rule # author. # Docs: https://bazel.build/reference/command-line-reference#flag--legacy_external_runfiles common --nolegacy_external_runfiles # The maximum number of attempts to retry if the build encountered a transient remote cache error that would otherwise fail the build. # Using the same value here than what is the default in Bazel 8 to help with https://github.com/bazelbuild/bazel/issues/22387 # Docs: https://bazel.build/reference/command-line-reference#build-flag--experimental_remote_cache_eviction_retries common --experimental_remote_cache_eviction_retries=5 # The maximum number of attempts to retry a download error. # Using the default value from Bazel 8. # Docs: https://bazel.build/reference/command-line-reference#common_options-flag--experimental_repository_downloader_retries common --experimental_repository_downloader_retries=5 bazel-lib-2.22.5/.aspect/bazelrc/bazel8.bazelrc000066400000000000000000000000501513125663600211560ustar00rootroot00000000000000# No Bazel 8 specific flag presets yet. bazel-lib-2.22.5/.aspect/bazelrc/ci.bazelrc000066400000000000000000000066211513125663600203760ustar00rootroot00000000000000# Set this flag to enable re-tries of failed tests on CI. # When any test target fails, try one or more times. This applies regardless of whether the "flaky" # tag appears on the target definition. # This is a tradeoff: legitimately failing tests will take longer to report, # but we can paper over flaky tests that pass most of the time. # The alternative is to mark every flaky test with the `flaky = True` attribute, but this requires # the buildcop to make frequent code edits. # Not recommended for local builds so that the flakiness is observed during development and thus # is more likely to get fixed. # Note that when passing after the first attempt, Bazel will give a special "FLAKY" status. # Docs: https://bazel.build/docs/user-manual#flaky-test-attempts test --flaky_test_attempts=2 # Announce all announces command options read from the bazelrc file(s) when starting up at the # beginning of each Bazel invocation. This is very useful on CI to be able to inspect what Bazel rc # settings are being applied on each run. # Docs: https://bazel.build/docs/user-manual#announce-rc common --announce_rc # Add a timestamp to each message generated by Bazel specifying the time at which the message was # displayed. # Docs: https://bazel.build/docs/user-manual#show-timestamps common --show_timestamps # Only show progress every 60 seconds on CI. # We want to find a compromise between printing often enough to show that the build isn't stuck, # but not so often that we produce a long log file that requires a lot of scrolling. # https://bazel.build/reference/command-line-reference#flag--show_progress_rate_limit common --show_progress_rate_limit=60 # Use cursor controls in screen output. # Docs: https://bazel.build/docs/user-manual#curses common --curses=yes # Use colors to highlight output on the screen. Set to `no` if your CI does not display colors. # Docs: https://bazel.build/docs/user-manual#color common --color=yes # The terminal width in columns. Configure this to override the default value based on what your CI system renders. # Docs: https://github.com/bazelbuild/bazel/blob/1af61b21df99edc2fc66939cdf14449c2661f873/src/main/java/com/google/devtools/build/lib/runtime/UiOptions.java#L151 common --terminal_columns=143 ###################################### # Generic remote cache configuration # ###################################### # Only download remote outputs of top level targets to the local machine. # Docs: https://bazel.build/reference/command-line-reference#flag--remote_download_toplevel common --remote_download_toplevel # The maximum amount of time to wait for remote execution and cache calls. # https://bazel.build/reference/command-line-reference#flag--remote_timeout common --remote_timeout=3600 # Upload locally executed action results to the remote cache. # Docs: https://bazel.build/reference/command-line-reference#flag--remote_upload_local_results common --remote_upload_local_results # Fall back to standalone local execution strategy if remote execution fails. If the grpc remote # cache connection fails, it will fail the build, add this so it falls back to the local cache. # Docs: https://bazel.build/reference/command-line-reference#flag--remote_local_fallback common --remote_local_fallback # Fixes builds hanging on CI that get the TCP connection closed without sending RST packets. # Docs: https://bazel.build/reference/command-line-reference#flag--grpc_keepalive_time common --grpc_keepalive_time=30s bazel-lib-2.22.5/.aspect/bazelrc/convenience.bazelrc000066400000000000000000000030771513125663600223010ustar00rootroot00000000000000# Attempt to build & test every target whose prerequisites were successfully built. # Docs: https://bazel.build/docs/user-manual#keep-going common --keep_going # Output test errors to stderr so users don't have to `cat` or open test failure log files when test # fail. This makes the log noisier in exchange for reducing the time-to-feedback on test failures for # users. # Docs: https://bazel.build/docs/user-manual#test-output common --test_output=errors # Show the output files created by builds that requested more than one target. This helps users # locate the build outputs in more cases # Docs: https://bazel.build/docs/user-manual#show-result common --show_result=20 # Bazel picks up host-OS-specific config lines from bazelrc files. For example, if the host OS is # Linux and you run bazel build, Bazel picks up lines starting with build:linux. Supported OS # identifiers are `linux`, `macos`, `windows`, `freebsd`, and `openbsd`. Enabling this flag is # equivalent to using `--config=linux` on Linux, `--config=windows` on Windows, etc. # Docs: https://bazel.build/reference/command-line-reference#flag--enable_platform_specific_config common --enable_platform_specific_config # Output a heap dump if an OOM is thrown during a Bazel invocation # (including OOMs due to `--experimental_oom_more_eagerly_threshold`). # The dump will be written to `/.heapdump.hprof`. # You may need to configure CI to capture this artifact and upload for later use. # Docs: https://bazel.build/reference/command-line-reference#flag--heap_dump_on_oom common --heap_dump_on_oom bazel-lib-2.22.5/.aspect/bazelrc/correctness.bazelrc000066400000000000000000000102761513125663600223360ustar00rootroot00000000000000# Do not upload locally executed action results to the remote cache. # This should be the default for local builds so local builds cannot poison the remote cache. # It should be flipped to `--remote_upload_local_results` on CI # by using `--bazelrc=.aspect/bazelrc/ci.bazelrc`. # Docs: https://bazel.build/reference/command-line-reference#flag--remote_upload_local_results common --noremote_upload_local_results # Don't allow network access for build actions in the sandbox. # Ensures that you don't accidentally make non-hermetic actions/tests which depend on remote # services. # Developers should tag targets with `tags=["requires-network"]` to opt-out of the enforcement. # Docs: https://bazel.build/reference/command-line-reference#flag--sandbox_default_allow_network common --sandbox_default_allow_network=false # Warn if a test's timeout is significantly longer than the test's actual execution time. # Bazel's default for test_timeout is medium (5 min), but most tests should instead be short (1 min). # While a test's timeout should be set such that it is not flaky, a test that has a highly # over-generous timeout can hide real problems that crop up unexpectedly. # For instance, a test that normally executes in a minute or two should not have a timeout of # ETERNAL or LONG as these are much, much too generous. # Docs: https://bazel.build/docs/user-manual#test-verbose-timeout-warnings common --test_verbose_timeout_warnings # Allow the Bazel server to check directory sources for changes. Ensures that the Bazel server # notices when a directory changes, if you have a directory listed in the srcs of some target. # Recommended when using # [copy_directory](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/copy_directory.md) and # [rules_js](https://github.com/aspect-build/rules_js) since npm package are source directories # inputs to copy_directory actions. # Docs: https://bazel.build/reference/command-line-reference#flag--host_jvm_args startup --host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1 # Allow exclusive tests to run in the sandbox. Fixes a bug where Bazel doesn't enable sandboxing for # tests with `tags=["exclusive"]`. # Docs: https://bazel.build/reference/command-line-reference#flag--incompatible_exclusive_test_sandboxed common --incompatible_exclusive_test_sandboxed # Use a static value for `PATH` and does not inherit `LD_LIBRARY_PATH`. Doesn't let environment # variables like `PATH` sneak into the build, which can cause massive cache misses when they change. # Use `--action_env=ENV_VARIABLE` if you want to inherit specific environment variables from the # client, but note that doing so can prevent cross-user caching if a shared cache is used. # Docs: https://bazel.build/reference/command-line-reference#flag--incompatible_strict_action_env common --incompatible_strict_action_env # Do not automatically create `__init__.py` files in the runfiles of Python targets. Fixes the wrong # default that comes from Google's internal monorepo by using `__init__.py` to delimit a Python # package. Precisely, when a `py_binary` or `py_test` target has `legacy_create_init` set to `auto (the # default), it is treated as false if and only if this flag is set. See # https://github.com/bazelbuild/bazel/issues/10076. # Docs: https://bazel.build/reference/command-line-reference#flag--incompatible_default_to_explicit_init_py common --incompatible_default_to_explicit_init_py # Set default value of `allow_empty` to `False` in `glob()`. This prevents a common mistake when # attempting to use `glob()` to match files in a subdirectory that is opaque to the current package # because it contains a BUILD file. See https://github.com/bazelbuild/bazel/issues/8195. # Docs: https://bazel.build/reference/command-line-reference#flag--incompatible_disallow_empty_glob common --incompatible_disallow_empty_glob # Always download coverage files for tests from the remote cache. By default, coverage files are not # downloaded on test result cache hits when --remote_download_minimal is enabled, making it impossible # to generate a full coverage report. # Docs: https://bazel.build/reference/command-line-reference#flag--experimental_fetch_all_coverage_outputs # ditching remote cache results common --experimental_fetch_all_coverage_outputs bazel-lib-2.22.5/.aspect/bazelrc/debug.bazelrc000066400000000000000000000014071513125663600210660ustar00rootroot00000000000000############################################################ # Use `bazel test --config=debug` to enable these settings # ############################################################ # Stream stdout/stderr output from each test in real-time. # Docs: https://bazel.build/docs/user-manual#test-output common:debug --test_output=streamed # Run one test at a time. # Docs: https://bazel.build/reference/command-line-reference#flag--test_strategy common:debug --test_strategy=exclusive # Prevent long running tests from timing out. # Docs: https://bazel.build/docs/user-manual#test-timeout common:debug --test_timeout=9999 # Always run tests even if they have cached results. # Docs: https://bazel.build/docs/user-manual#cache-test-results common:debug --nocache_test_results bazel-lib-2.22.5/.aspect/bazelrc/intro.md000066400000000000000000000001651513125663600201110ustar00rootroot00000000000000# Aspect bazelrc presets The `.bazelrc` files found here are the source-of-truth for our recommended Bazel presets. bazel-lib-2.22.5/.aspect/bazelrc/java.bazelrc000066400000000000000000000024131513125663600207170ustar00rootroot00000000000000# Aspect recommended Bazel flags when using rules_java and rules_jvm_external # Pin java versions to desired language level # See https://bazel.build/docs/bazel-and-java#java-versions # and https://en.wikipedia.org/wiki/Java_version_history # What version of Java are the source files in this repo? # See https://bazel.build/docs/user-manual#java-language-version common --java_language_version=17 # The Java language version used to build tools that are executed during a build # See https://bazel.build/docs/user-manual#tool-java-language-version common --tool_java_language_version=17 # The version of JVM to use to execute the code and run the tests. # NB: The default value is local_jdk which is non-hermetic. # See https://bazel.build/docs/user-manual#java-runtime-version common --java_runtime_version=remotejdk_17 # The version of JVM used to execute tools that are needed during a build. # See https://bazel.build/docs/user-manual#tool-java-runtime-version common --tool_java_runtime_version=remotejdk_17 # Repository rules, such as rules_jvm_external: put Bazel's JDK on the path. # Avoids non-hermeticity from dependency on a JAVA_HOME pointing at a system JDK # see https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk bazel-lib-2.22.5/.aspect/bazelrc/javascript.bazelrc000066400000000000000000000014431513125663600221460ustar00rootroot00000000000000# Aspect recommended Bazel flags when using Aspect's JavaScript rules: https://github.com/aspect-build/rules_js # Docs for Node.js flags: https://nodejs.org/en/docs/guides/debugging-getting-started/#command-line-options # Support for debugging Node.js tests. Use bazel run with `--config=debug` to turn on the NodeJS # inspector agent. The node process will break before user code starts and wait for the debugger to # connect. Pass the --inspect-brk option to all tests which enables the node inspector agent. See # https://nodejs.org/de/docs/guides/debugging-getting-started/#command-line-options for more # details. # Docs: https://nodejs.org/en/docs/guides/debugging-getting-started/#command-line-options run:debug -- --node_options=--inspect-brk common:debug --test_env=NODE_OPTIONS=--inspect-brk bazel-lib-2.22.5/.aspect/bazelrc/local/000077500000000000000000000000001513125663600175245ustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/bazelrc/local/bazel7.bazelrc000077700000000000000000000000001513125663600252122../bazel7.bazelrcustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/bazelrc/performance.bazelrc000066400000000000000000000021071513125663600222770ustar00rootroot00000000000000# Directories used by sandboxed non-worker execution may be reused to avoid unnecessary setup costs. # Save time on Sandbox creation and deletion when many of the same kind of action run during the # build. # No longer experimental in Bazel 6: https://github.com/bazelbuild/bazel/commit/c1a95501a5611878e5cc43a3cc531f2b9e47835b # Docs: https://bazel.build/reference/command-line-reference#flag--reuse_sandbox_directories common --experimental_reuse_sandbox_directories # Avoid creating a runfiles tree for binaries or tests until it is needed. # Docs: https://bazel.build/reference/command-line-reference#flag--build_runfile_links # See https://github.com/bazelbuild/bazel/issues/6627 # # This may break local workflows that `build` a binary target, then run the resulting program # outside of `bazel run`. In those cases, the script will need to call # `bazel build --build_runfile_links //my/binary:target` and then execute the resulting program. common --nobuild_runfile_links # Needed prior to Bazel 8; see # https://github.com/bazelbuild/bazel/issues/20577 coverage --build_runfile_links bazel-lib-2.22.5/.aspect/bazelrc/usage.md000066400000000000000000000026571513125663600200720ustar00rootroot00000000000000## Using Aspect bazelrc presets in your project The `.bazelrc` file can get large, fast. Some settings don't apply everywhere - some options are appropriate only on CI, and some vary depending on the version of Bazel you use or languages used. Bazel rc files can contain `import` statements, which allow you to organize the content better. To use these presets in your project, simply vendor the `*.bazelrc` files from https://github.com/bazel-contrib/bazel-lib/tree/main/.aspect/bazelrc into the `.aspect/bazelrc` folder in your repository and `import` them in your `.bazelrc` file. For example, ```python title=".bazelrc" # Import Aspect bazelrc presets import %workspace%/.aspect/bazelrc/bazel6.bazelrc import %workspace%/.aspect/bazelrc/convenience.bazelrc import %workspace%/.aspect/bazelrc/correctness.bazelrc import %workspace%/.aspect/bazelrc/debug.bazelrc import %workspace%/.aspect/bazelrc/javascript.bazelrc import %workspace%/.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/.aspect/bazelrc/user.bazelrc ``` bazel-lib-2.22.5/.aspect/cli/000077500000000000000000000000001513125663600155575ustar00rootroot00000000000000bazel-lib-2.22.5/.aspect/cli/config.yaml000066400000000000000000000001371513125663600177110ustar00rootroot00000000000000lint: aspects: - //tools/lint:linters.bzl%vale - //tools/lint:linters.bzl%shellcheck bazel-lib-2.22.5/.bazelignore000066400000000000000000000000341513125663600157520ustar00rootroot00000000000000# nested modules docs/ e2e/ bazel-lib-2.22.5/.bazeliskrc000066400000000000000000000001311513125663600156000ustar00rootroot00000000000000BAZELISK_BASE_URL=https://static.aspect.build/aspect USE_BAZEL_VERSION=aspect/2024.34.43 bazel-lib-2.22.5/.bazelrc000066400000000000000000000045111513125663600150770ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/.aspect/bazelrc/convenience.bazelrc import %workspace%/.aspect/bazelrc/correctness.bazelrc import %workspace%/.aspect/bazelrc/debug.bazelrc import %workspace%/.aspect/bazelrc/javascript.bazelrc import %workspace%/.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### common --enable_platform_specific_config # For testing our --stamp behavior. # Normally users would use a --workspace_status_command with a script that calls `git describe`. common --embed_label=v1.2.3 # Mock versioning command to test the --stamp behavior common --workspace_status_command="echo BUILD_SCM_VERSION 1.2.3" # For releasing, use --workspace_status_command and stamp # before adding more flags to the release config make sure it does not # affect the hashes of /tools. See tools/release.bzl for opt transition # add appropriate commandline transition there to match the configuration. common:release -c opt # Don’t want to push a rules author to update their deps if not needed. # https://bazel.build/reference/command-line-reference#flag--check_direct_dependencies # https://bazelbuild.slack.com/archives/C014RARENH0/p1691158021917459?thread_ts=1691156601.420349&cid=C014RARENH0 common --check_direct_dependencies=off # Make sure we don't regress this. common --incompatible_auto_exec_groups # Symlinks are pretty much required on windows so enable by default startup --windows_enable_symlinks # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # This option fixes 20 tests on Windows but I am reluctant to enable it as it would be # better for this library to be tested with runfiles off (it is a performance drain on windows). # common:windows --enable_runfiles # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/.bazelversion000066400000000000000000000000061513125663600161530ustar00rootroot000000000000008.3.1 bazel-lib-2.22.5/.bcr/000077500000000000000000000000001513125663600142775ustar00rootroot00000000000000bazel-lib-2.22.5/.bcr/metadata.template.json000066400000000000000000000007711513125663600205710ustar00rootroot00000000000000{ "homepage": "https://docs.aspect.build/rules/aspect_bazel_lib", "maintainers": [ { "name": "Alex Eagle", "email": "alex@aspect.build", "github": "alexeagle" }, { "name": "Derek Cormier", "email": "derek@aspect.build", "github": "kormide" }, { "name": "Jason Bedard", "email": "jason@aspect.build", "github": "jbedard" } ], "repository": ["github:bazel-contrib/bazel-lib"], "versions": [], "yanked_versions": {} } bazel-lib-2.22.5/.bcr/patches/000077500000000000000000000000001513125663600157265ustar00rootroot00000000000000bazel-lib-2.22.5/.bcr/patches/go_dev_dep.patch000066400000000000000000000016201513125663600210410ustar00rootroot00000000000000diff --git a/MODULE.bazel b/MODULE.bazel index e63fa5b..9d78a88 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -52,26 +52,26 @@ use_repo(host, "aspect_bazel_lib_host") bazel_dep( name = "gazelle", version = "0.40.0", - # In released versions: dev_dependency = True + dev_dependency = True, ) bazel_dep( name = "rules_go", version = "0.55.0", repo_name = "io_bazel_rules_go", - # In released versions: dev_dependency = True + dev_dependency = True, ) go_sdk = use_extension( "@io_bazel_rules_go//go:extensions.bzl", "go_sdk", - # In released versions: dev_dependency = True + dev_dependency = True, ) go_sdk.from_file(go_mod = "//:go.mod") go_deps = use_extension( "@gazelle//:extensions.bzl", "go_deps", - # In released versions: dev_dependency = True + dev_dependency = True, ) go_deps.from_file(go_mod = "//:go.mod") use_repo( bazel-lib-2.22.5/.bcr/presubmit.yml000066400000000000000000000004541513125663600170370ustar00rootroot00000000000000bcr_test_module: module_path: "e2e/smoke" matrix: platform: ["debian10", "macos", "ubuntu2004", "windows"] bazel: - 7.x - 8.x tasks: run_tests: name: "Run test module" platform: ${{ platform }} bazel: ${{ bazel }} test_targets: - "//..." bazel-lib-2.22.5/.bcr/source.template.json000066400000000000000000000002551513125663600203060ustar00rootroot00000000000000{ "integrity": "**leave this alone**", "strip_prefix": "{REPO}-{VERSION}", "url": "https://github.com/{OWNER}/{REPO}/releases/download/{TAG}/bazel-lib-{TAG}.tar.gz" } bazel-lib-2.22.5/.editorconfig000066400000000000000000000000541513125663600161270ustar00rootroot00000000000000[*.sh] indent_style = space indent_size = 2 bazel-lib-2.22.5/.gitattributes000066400000000000000000000013041513125663600163440ustar00rootroot00000000000000# In code review, collapse generated files docs/*.md linguist-generated=true docs/jq.md linguist-generated=false docs/tar.md linguist-generated=false docs/yq.md linguist-generated=false ################################# # Configuration for 'git archive' # see https://git-scm.com/docs/git-archive#ATTRIBUTES # Omit folders that users don't need, making the distribution artifact smaller lib/tests export-ignore # Omit the .bazeliskrc file for the smoke test that runs on the Bazel Central # Registry ci because we test on Windows but do not publish Aspect CLI Windows # binaries. e2e/smoke/.bazeliskrc export-ignore # Substitution for the _VERSION_PRIVATE placeholder tools/version.bzl export-subst bazel-lib-2.22.5/.github/000077500000000000000000000000001513125663600150135ustar00rootroot00000000000000bazel-lib-2.22.5/.github/workflows/000077500000000000000000000000001513125663600170505ustar00rootroot00000000000000bazel-lib-2.22.5/.github/workflows/ci.bazelrc000066400000000000000000000004121513125663600210040ustar00rootroot00000000000000# Directories caches by GitHub actions common:local --disk_cache=~/.cache/bazel-disk-cache common --repository_cache=~/.cache/bazel-repository-cache # Debug where options came from common --announce_rc # Keep bazel stdout readable in logs common --noshow_progress bazel-lib-2.22.5/.github/workflows/ci.yaml000066400000000000000000000165111513125663600203330ustar00rootroot00000000000000name: CI # Controls when the action will run. on: # Triggers the workflow on push or pull request events but only for the main branch push: branches: [main, 1.x, 2.x] pull_request: branches: [main, 1.x, 2.x] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: concurrency: # Cancel previous actions from the same PR or branch except 'main' branch. # See https://docs.github.com/en/actions/using-jobs/using-concurrency and https://docs.github.com/en/actions/learn-github-actions/contexts for more info. group: concurrency-group::${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}${{ github.ref_name == 'main' && format('::{0}', github.run_id) || ''}} cancel-in-progress: ${{ github.ref_name != 'main' }} env: HEAD_REF: ${{ github.head_ref }} jobs: # Prepares dynamic test matrix values matrix-prep: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - id: bazel-version name: Prepare 'bazel-version' matrix axis run: | v=$(head -n 1 .bazelversion) m=${v::1} a=( "major:$m, version:\"$v\"" "major:7, version:\"7.4.1\"" "major:6, version:\"6.5.0\"" ) printf -v j '{%s},' "${a[@]}" echo "res=[${j%,}]" | tee -a $GITHUB_OUTPUT - id: os name: Prepare 'os' matrix axis run: | a=( ubuntu, macos, windows ) printf -v j '"%s",' "${a[@]}" echo "res=[${j%,}]" | tee -a $GITHUB_OUTPUT outputs: bazel-version: ${{ steps.bazel-version.outputs.res }} os: ${{ steps.os.outputs.res }} test: runs-on: ${{ matrix.os }}-latest needs: - matrix-prep strategy: fail-fast: false matrix: bazel-version: ${{ fromJSON(needs.matrix-prep.outputs.bazel-version) }} bzlmod: [1, 0] os: ${{ fromJSON(needs.matrix-prep.outputs.os) }} folder: - "." - "e2e/copy_action" - "e2e/copy_to_directory" - "e2e/coreutils" - "e2e/external_copy_to_directory" - "e2e/smoke" - "e2e/write_source_files" exclude: # Root workspace is bzlmod-only - folder: . bzlmod: 0 # Don't test MacOS and Windows against secondary bazel version to minimize minutes (billed at 10X and 2X respectively) # https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#included-storage-and-minutes - os: macos bazel-version: major: 6 - os: windows bazel-version: major: 6 # Reduce size of the test matrix: # Don't run workspace tests with Bazel 8 # Don't run bzlmod tests with Bazel 6 - bazel-version: major: 8 bzlmod: 0 - bazel-version: major: 6 bzlmod: 1 # TODO: green up root Workspace on MacOS - folder: . os: macos include: - folder: docs bzlmod: 1 os: ubuntu bazel-version: major: 8 version: 8.1.1 steps: - uses: actions/checkout@v4 - name: Mount bazel caches uses: actions/cache@v4 with: path: | ~/.cache/bazel-disk-cache ~/.cache/bazel-repository-cache key: bazel-cache-${{ matrix.bazel-version.version }}-${{ matrix.bzlmod }}-${{ matrix.os }}-${{ matrix.folder }}-${{ hashFiles('.bazelrc', '.bazelversion', '.bazeliskrc', '**/BUILD', '**/BUILD.bazel', '**/*.bzl', 'WORKSPACE', 'WORKSPACE.bazel', 'WORKSPACE.bzlmod', 'MODULE.bazel') }} restore-keys: bazel-cache-${{ matrix.bazel-version.version }}-${{ matrix.bzlmod }}-${{ matrix.os }}-${{ matrix.folder }}- - name: Configure Bazel version working-directory: ${{ matrix.folder }} shell: bash run: | # Overwrite the .bazelversion instead of using USE_BAZEL_VERSION so that Bazelisk # still bootstraps Aspect CLI from configuration in .bazeliskrc. Aspect CLI will # then use .bazelversion to determine which Bazel version to use. echo "${{ matrix.bazel-version.version }}" > .bazelversion # Delete all the version specific bazelrc files that are used for local development # since the version we're testing against is dynamic. These are just symlinks and the # root .bazelrc brings these in with try-imports. In this CI workflows, we explicitly # bring in the version specific bazelrc file with --bazelrc when we invoke bazel. rm ${GITHUB_WORKSPACE//\\/\/}/.aspect/bazelrc/local/*.bazelrc # TODO: remove this block once we have Aspect CLI Windows releases - name: Don't use Aspect CLI on Windows if: matrix.os == 'windows' working-directory: ${{ matrix.folder }} shell: bash run: rm -f .bazeliskrc - name: bazel test //... working-directory: ${{ matrix.folder }} shell: bash run: | bazel \ --bazelrc=${GITHUB_WORKSPACE//\\/\/}/.aspect/bazelrc/bazel${{ matrix.bazel-version.major }}.bazelrc \ --bazelrc=${GITHUB_WORKSPACE//\\/\/}/.aspect/bazelrc/ci.bazelrc \ --bazelrc=${GITHUB_WORKSPACE//\\/\/}/.github/workflows/ci.bazelrc \ test \ --test_tag_filters=-skip-on-bazel${{ matrix.bazel-version.major }} \ --build_tag_filters=-skip-on-bazel${{ matrix.bazel-version.major }} \ --enable_bzlmod=${{ matrix.bzlmod }} \ //... - name: Integration tests # Don't run integration tests on Windows since they are bash scripts and Windows runs Powershell if: matrix.folder == '.' && matrix.os != 'windows' && matrix.bazel-version.major != '6' # Find all shell scripts within e2e, echo the filename, execute, fail on error run: find e2e/*.sh -maxdepth 1 -type f -exec sh -c 'echo "\n\n------------------------------- $0 -------------------------------" && BZLMOD_FLAG=${{ steps.set_bzlmod_flag.outputs.bzlmod_flag }} "$0" || kill $PPID' \{\} \; - name: Verify bcr patches if: matrix.folder == '.' && matrix.bzlmod == '1' && matrix.os == 'ubuntu' && matrix.bazel-version.major != '6' run: patch --dry-run -p1 < .bcr/patches/*.patch pre-commit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pre-commit/action@v3.0.1 # For branch protection settings, this job provides a "stable" name that can be used to gate PR merges # on "all matrix jobs were successful". conclusion: needs: [test, pre-commit] runs-on: ubuntu-latest if: always() steps: - uses: technote-space/workflow-conclusion-action@45ce8e0eb155657ab8ccf346ade734257fd196a5 # v3.0.3 # Note: possible conclusion values: # https://github.com/technote-space/workflow-conclusion-action/blob/main/src/constant.ts - name: report success if: ${{ env.WORKFLOW_CONCLUSION == 'success' }} working-directory: /tmp run: echo ${{ env.WORKFLOW_CONCLUSION }} && exit 0 - name: report failure if: ${{ env.WORKFLOW_CONCLUSION == 'failure' }} working-directory: /tmp run: echo ${{ env.WORKFLOW_CONCLUSION }} && exit 1 bazel-lib-2.22.5/.github/workflows/conventional-commits.yml000066400000000000000000000005101513125663600237370ustar00rootroot00000000000000name: Verify PR title/description on: pull_request_target: types: - opened - edited - synchronize permissions: pull-requests: read jobs: check: runs-on: ubuntu-latest steps: - uses: amannn/action-semantic-pull-request@v5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} bazel-lib-2.22.5/.github/workflows/integrity.jq000066400000000000000000000012761513125663600214300ustar00rootroot00000000000000# JQ filter to transform sha256 files to a value we can read from starlark. # NB: the sha256 files are expected to be newline-terminated. # # Input looks like # 48552e399a1f2ab97e62ca7fce5783b6214e284330c7555383f43acf82446636 unpack-linux-aarch64\nfd265552bfd236efef519f81ce783322a50d8d7ab5af5d08a713e519cedff87f unpack-linux-x86_64\n # # Output should look like # { # "unpack-linux-aarch64": "48552e399a1f2ab97e62ca7fce5783b6214e284330c7555383f43acf82446636", # "unpack-linux-x86_64": "fd265552bfd236efef519f81ce783322a50d8d7ab5af5d08a713e519cedff87f" # } . # Don't end with an empty object | rtrimstr("\n") | split("\n") | map( split(" ") | {"key": .[1], "value": .[0]} ) | from_entries bazel-lib-2.22.5/.github/workflows/new_issue.yaml000066400000000000000000000022461513125663600217410ustar00rootroot00000000000000name: New issue on: issues: types: - opened - reopened jobs: new_issue: runs-on: ubuntu-latest permissions: issues: write steps: # https://docs.github.com/en/actions/managing-issues-and-pull-requests/adding-labels-to-issues - uses: actions/github-script@v7 with: script: | github.rest.issues.addLabels({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, labels: ["untriaged"] }) # https://docs.github.com/en/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects#adding-an-item-to-a-project - run: | gh api graphql -f query="mutation { addProjectV2ItemById(input: {projectId: \"$PROJECT_ID\" contentId: \"$CONTENT_ID\"}) { item { id } } }" env: GITHUB_TOKEN: ${{ secrets.GH_PROJECTS_RW_TOKEN }} OWNER: ${{ github.repository_owner }} REPO: ${{ github.event.repository.name }} CONTENT_ID: ${{ github.event.issue.node_id }} PROJECT_ID: PVT_kwDOA6IKMs4ALj2o # Aspect OSS Bazel Rules bazel-lib-2.22.5/.github/workflows/publish.yaml000066400000000000000000000022401513125663600214000ustar00rootroot00000000000000# Publish new releases to Bazel Central Registry. name: Publish on: # Run the publish workflow after a successful release # Will be triggered from the release.yaml workflow workflow_call: inputs: tag_name: required: true type: string secrets: BCR_PUBLISH_TOKEN: required: true # In case of problems, let release engineers retry by manually dispatching # the workflow from the GitHub UI workflow_dispatch: inputs: tag_name: description: a tag pointing to the commit being published required: true type: string jobs: publish: uses: bazel-contrib/publish-to-bcr/.github/workflows/publish.yaml@v0.2.3 with: tag_name: ${{ inputs.tag_name }} # GitHub repository which is a fork of the upstream where the Pull Request will be opened. registry_fork: bazel-contrib/bazel-central-registry draft: false permissions: attestations: write contents: write id-token: write secrets: # Necessary to push to the BCR fork, and to open a pull request against a registry publish_token: ${{ secrets.publish_token || secrets.BCR_PUBLISH_TOKEN }} bazel-lib-2.22.5/.github/workflows/release.yml000066400000000000000000000036061513125663600212200ustar00rootroot00000000000000# Cut a release whenever a new tag is pushed to the repo. # You should use an annotated tag, like `git tag -a v1.2.3` # and put the release notes into the commit message for the tag. name: Release on: # Can be triggered from the tag.yaml workflow workflow_call: inputs: tag_name: required: true type: string # In case of problems, let release engineers retry by manually dispatching # the workflow from the GitHub UI workflow_dispatch: inputs: tag_name: required: true type: string # Or, developers can manually push a tag from their clone push: tags: - "v*.*.*" permissions: id-token: write attestations: write contents: write jobs: build: # Go cross-compilation works from linux -> any platform runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build Go Binaries env: # NB: this variable is read by tools/release/copy_release_artifacts.sh # and must match the path in release_prep.sh under RELEASED_BINARY_INTEGRITY DEST: binaries run: | rm -rf ${{ env.DEST }} mkdir -p ${{ env.DEST }} bazel --bazelrc=.github/workflows/ci.bazelrc \ run --config=release //tools/release:copy_release_artifacts - uses: actions/upload-artifact@v4 with: name: go-binaries path: binaries/ retention-days: 1 release: needs: build uses: bazel-contrib/.github/.github/workflows/release_ruleset.yaml@v7.2.3 with: release_files: | go-binaries/* bazel-lib-*.tar.gz prerelease: false tag_name: ${{ inputs.tag_name || github.ref_name }} publish: needs: release uses: ./.github/workflows/publish.yaml with: tag_name: ${{ inputs.tag_name || github.ref_name }} secrets: BCR_PUBLISH_TOKEN: ${{ secrets.BCR_PUBLISH_TOKEN }} bazel-lib-2.22.5/.github/workflows/release_prep.sh000077500000000000000000000054701513125663600220630ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail # Argument provided by reusable workflow caller, see # https://github.com/bazel-contrib/.github/blob/d197a6427c5435ac22e56e33340dff912bc9334e/.github/workflows/release_ruleset.yaml#L72 TAG=$1 # The prefix is chosen to match what GitHub generates for source archives # This guarantees that users can easily switch from a released artifact to a source archive # with minimal differences in their code (e.g. strip_prefix remains the same) PREFIX="bazel-lib-${TAG:1}" ARCHIVE="bazel-lib-$TAG.tar.gz" ARCHIVE_TMP=$(mktemp) # NB: configuration for 'git archive' is in /.gitattributes git archive --format=tar --prefix=${PREFIX}/ ${TAG} >$ARCHIVE_TMP ############ # Patch up the archive to have integrity hashes for built binaries that we downloaded in the GHA workflow. # Now that we've run `git archive` we are free to pollute the working directory. # Delete the placeholder file tar --file $ARCHIVE_TMP --delete ${PREFIX}/tools/integrity.bzl mkdir -p ${PREFIX}/tools cat >${PREFIX}/tools/integrity.bzl <$ARCHIVE SHA=$(shasum -a 256 $ARCHIVE | awk '{print $1}') cat < Read more about bzlmod: ## Using WORKSPACE Paste this snippet into your \`WORKSPACE\` file: \`\`\`starlark load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "aspect_bazel_lib", sha256 = "${SHA}", strip_prefix = "${PREFIX}", url = "https://github.com/bazel-contrib/bazel-lib/releases/download/${TAG}/${ARCHIVE}", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "aspect_bazel_lib_register_toolchains") # Required bazel-lib dependencies aspect_bazel_lib_dependencies() # Required rules_shell dependencies load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") rules_shell_dependencies() rules_shell_toolchains() # Register bazel-lib toolchains aspect_bazel_lib_register_toolchains() # Create the host platform repository transitively required by bazel-lib load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@platforms//host:extension.bzl", "host_platform_repo") maybe( host_platform_repo, name = "host_platform", ) \`\`\` EOF bazel-lib-2.22.5/.github/workflows/tag.yaml000066400000000000000000000030241513125663600205060ustar00rootroot00000000000000# Tag a new release # This is easier than having to run manual `git` operations on a local clone. # It also runs on a schedule so we don't leave commits unreleased indefinitely # (avoiding users having to ping "hey could someone cut a release"). name: Tag a Release on: # Allow devs to tag manually through the GitHub UI. # For example after landing a fix that customers are waiting for. workflow_dispatch: # Run at 2PM UTC (7AM PST) on the 2nd and 17th of each month. # This is a trade-off between making too many releases, # which overwhelms BCR maintainers and over-notifies users, # and releasing too infrequently which delays delivery of bugfixes and features. schedule: - cron: "0 14 2,17 * *" jobs: tag: permissions: contents: write # allow create tag runs-on: ubuntu-latest outputs: new-tag: ${{ steps.ccv.outputs.new-tag }} new-tag-version: ${{steps.ccv.outputs.new-tag-version}} steps: - uses: actions/checkout@v4 with: # Need enough history to find the prior release tag fetch-depth: 0 - name: Bump tag if necessary id: ccv uses: smlx/ccv@7318e2f25a52dcd550e75384b84983973251a1f8 # v0.10.0 release: needs: tag uses: ./.github/workflows/release.yml with: tag_name: ${{ needs.tag.outputs.new-tag-version }} if: needs.tag.outputs.new-tag == 'true' && needs.tag.outputs.new-tag-version-type != 'major' secrets: inherit permissions: contents: write attestations: write id-token: write bazel-lib-2.22.5/.gitignore000066400000000000000000000014721513125663600154470ustar00rootroot00000000000000bazel-* .bazelrc.user test-out/ .idea/ .ijwb/ .vscode .DS_Store # Bazel's MODULE lockfile isn't ready to check in yet as of Bazel 7.1. # Do allow for it to be created, however, since it gives a performance boost for local development. # [Store resolved repository attributes in the Bzlmod lockfile](https://github.com/bazelbuild/bazel/issues/19026) # [MODULE.bazel.lock file contains user specific paths](https://github.com/bazelbuild/bazel/issues/19621) # [Consider skipping bazel_tools@_ from lockfile](https://github.com/bazelbuild/bazel/issues/19971) # [MODULE.bazel.lock file "reads through" already-locked package manager](https://github.com/bazelbuild/bazel/issues/20272) # [moduleFileHash in MODULE.bazel.lock causes frequent Git merge conflicts](https://github.com/bazelbuild/bazel/issues/20369) MODULE.bazel.lock bazel-lib-2.22.5/.pre-commit-config.yaml000066400000000000000000000026501513125663600177370ustar00rootroot00000000000000# See CONTRIBUTING.md for instructions. # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks # Commitizen runs in commit-msg stage # but we don't want to run the other hooks on commit messages default_stages: [pre-commit] repos: # Check formatting and lint for starlark code - repo: https://github.com/keith/pre-commit-buildifier rev: 8.0.3 hooks: - id: buildifier - id: buildifier-lint # Enforce that commit messages allow for later changelog generation - repo: https://github.com/commitizen-tools/commitizen rev: v4.8.2 hooks: # Requires that commitizen is already installed - id: commitizen stages: [commit-msg] - repo: https://github.com/pre-commit/mirrors-prettier rev: v3.1.0 hooks: - id: prettier - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: check-added-large-files - id: check-byte-order-marker - id: check-case-conflict - id: check-symlinks - id: destroyed-symlinks - id: end-of-file-fixer exclude: &exclude_pattern "^(docs|e2e|lib/tests)/" - id: mixed-line-ending - id: trailing-whitespace - repo: https://github.com/crate-ci/typos rev: v1.32.0 hooks: - id: typos exclude: | (?x)^( lib/private/yq_toolchain.bzl| lib/tests/glob_match_test.bzl ) bazel-lib-2.22.5/.prettierignore000066400000000000000000000002671513125663600165230ustar00rootroot00000000000000.circleci/config.yml docs/*.md e2e/*/docs.md lib/lib/tests/write_source_files/*.js lib/lib/tests/write_source_files/subdir/*.js lib/lib/tests/write_source_files/subdir/subsubdir/*.js bazel-lib-2.22.5/.shellcheckrc000066400000000000000000000003201513125663600161010ustar00rootroot00000000000000# Turn on warnings for unquoted variables with safe values enable=quote-safe-variables # Turn on warnings for unassigned uppercase variables enable=check-unassigned-uppercase #enable=require-variable-braces bazel-lib-2.22.5/.typos.toml000066400000000000000000000001451513125663600156040ustar00rootroot00000000000000[default.extend-identifiers] MODULEs = "MODULEs" # Else it becomes MODULEEs HashiCorp = "HashiCorp" bazel-lib-2.22.5/.vale.ini000066400000000000000000000007401513125663600151620ustar00rootroot00000000000000# Configuration for https://Vale.sh # See https://vale.sh/docs/topics/config/ StylesPath = tools/lint/vale IgnoredScopes = code # Tell Vale to look in tools/lint/vale/config/vocabularies/engineering Vocab = engineering [*.md] BlockIgnores = ```[a-z]*\n.*?\n``` BasedOnStyles = Vale, Google # Reduce levels to make silo error-free. # TODO(alex): consider promoting some to error Google.Exclamation = warning Google.Quotes = warning Vale.Spelling = warning Vale.Terms = warning bazel-lib-2.22.5/BUILD.bazel000066400000000000000000000077521513125663600153440ustar00rootroot00000000000000load("@aspect_bazel_lib//:bzl_library.bzl", "bzl_library") load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin") load("@aspect_bazel_lib_host//:defs.bzl", "host") load("@bazel_skylib//rules:copy_file.bzl", "copy_file") load("@bazel_skylib//rules:write_file.bzl", "write_file") load("@buildifier_prebuilt//:rules.bzl", "buildifier") load("@gazelle//:def.bzl", "DEFAULT_LANGUAGES", "gazelle", "gazelle_binary") load("//lib:diff_test.bzl", "diff_test") load("//lib:testing.bzl", "assert_contains") load("//lib:write_source_files.bzl", "write_source_files") exports_files([".shellcheckrc"]) # gazelle:prefix github.com/bazel-contrib/bazel-lib gazelle_binary( name = "gazelle_bin", languages = select({ # TODO: under bzlmod we get go linking errors when adding # the skylib gazelle plugin. # https://github.com/bazelbuild/rules_go/issues/1877 "@aspect_bazel_lib//lib:bzlmod": DEFAULT_LANGUAGES, "//conditions:default": DEFAULT_LANGUAGES + [ "@bazel_skylib_gazelle_plugin//bzl", ], }), ) gazelle( name = "gazelle", gazelle = "gazelle_bin", mode = "fix", ) gazelle( name = "gazelle.check", gazelle = "gazelle_bin", mode = "diff", ) gazelle( name = "gazelle_update_repos", args = [ "-build_file_proto_mode=disable_global", "-from_file=go.mod", "-to_macro=deps.bzl%go_dependencies", "-prune", ], command = "update-repos", ) buildifier( name = "buildifier", exclude_patterns = ["./.git/*"], lint_mode = "fix", mode = "fix", tags = ["manual"], # tag as manual so windows ci does not build it by default ) buildifier( name = "buildifier.check", exclude_patterns = ["./.git/*"], lint_mode = "warn", mode = "diff", tags = ["manual"], # tag as manual so windows ci does not build it by default ) alias( name = "format", actual = "//tools/format", tags = ["manual"], # tag as manual so windows ci does not build it by default ) # write_source_files() to a git ignored subdirectory of the root genrule( name = "write_source_file_root", outs = ["write_source_file-root_directory/test.txt"], cmd = "mkdir -p $$(dirname $@) && echo 'test' > $@", visibility = ["//visibility:private"], ) write_source_files( name = "write_source_file_root-test", diff_test = False, files = { "test-out/dist/write_source_file_root-test/test.txt": ":write_source_file_root", "test-out/dist/write_source_file_root-test_b/test.txt": ":write_source_file_root", }, ) # Test case: diff_test with a file in a directory prefixed with "external" # stamped in the root package write_file( name = "file_in_external_prefixed_dir", out = "external-dir/foo.txt", content = ["foo"], ) copy_file( name = "copy_of_file_in_external_prefixed_dir", src = "external-dir/foo.txt", out = "foo_copy.txt", ) diff_test( name = "case_file_has_external_prefix", file1 = "external-dir/foo.txt", file2 = "foo_copy.txt", ) assert_contains( name = "bazel_version_test", actual = ".bazelversion", expected = str(host.bazel_version), # TODO: Enable this for windows target_compatible_with = [] if host.bazel_version.startswith("7") and not host.is_windows else ["@platforms//:incompatible"], ) bzl_library( name = "bzl_library", srcs = ["bzl_library.bzl"], deps = ["@bazel_skylib//:bzl_library"], ) bzl_library( name = "deps", srcs = ["deps.bzl"], visibility = ["//visibility:public"], deps = [ "@bazel_tools//tools/build_defs/repo:cache.bzl", "@bazel_tools//tools/build_defs/repo:http.bzl", "@gazelle//:deps", ], ) # Place the .vale.ini file in bazel-bin so the relative path it contains # StylesPath = tools/lint/vale # will work when it's run as an action. copy_to_bin( name = ".vale_ini", srcs = [".vale.ini"], visibility = ["//visibility:public"], ) filegroup( name = "markdown_files", srcs = glob(["*.md"]), tags = ["markdown"], ) bazel-lib-2.22.5/CONTRIBUTING.md000066400000000000000000000030101513125663600156760ustar00rootroot00000000000000# How to contribute ## Formatting Starlark files should be formatted by Buildifier. We suggest using a pre-commit hook to automate this. First [install pre-commit](https://pre-commit.com/#installation) (>= v3.2.0), then run ```shell pre-commit install ``` Otherwise later tooling on CI may yell at you about formatting/linting violations. ## Updating BUILD files Some targets are generated from sources. Currently this is just the `bzl_library` targets. Run `bazel run //:gazelle` to keep them up to date. ## Using this as a development dependency of other rules You'll commonly find that you develop in another WORKSPACE, such as some other ruleset that depends on bazel_lib, or in a nested WORKSPACE in the integration_tests folder. To always tell Bazel to use this directory rather than some release artifact or a version fetched from the internet, run this from this directory: ```sh OVERRIDE="--override_repository=bazel_lib=$(pwd)/bazel_lib" echo "build $OVERRIDE" >> ~/.bazelrc echo "query $OVERRIDE" >> ~/.bazelrc ``` This means that any usage of `@aspect_bazel_lib` on your system will point to this folder. ## Releasing 1. Make sure your git state is at the right place (something like `git fetch; git checkout origin/main`) 1. Determine the next release version, following semver (could automate in the future from changelog) 1. `git tag -a v1.2.3` (will open an editor to put release notes) 1. `git push --tags` 1. Watch the automation run on GitHub actions 1. Update the release page with auto-generated release notes bazel-lib-2.22.5/LICENSE000066400000000000000000000236761513125663600144760ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS bazel-lib-2.22.5/MODULE.bazel000066400000000000000000000065421513125663600154660ustar00rootroot00000000000000"aspect-build/bazel-lib" module( name = "aspect_bazel_lib", bazel_compatibility = [">=6.5.0"], compatibility_level = 1, ) # Lower-bounds (minimum) versions for direct runtime dependencies bazel_dep(name = "bazel_features", version = "1.9.0") bazel_dep(name = "bazel_skylib", version = "1.8.1") bazel_dep(name = "platforms", version = "0.0.10") bazel_dep(name = "stardoc", version = "0.7.1") bazel_dep(name = "rules_shell", version = "0.4.1") # Depend on our own renamed module, providing back-compat to make migration easier. # See https://github.com/aspect-build/rules_lint/pull/666 as an example where it's needed, # because JS actions often rely on action deduplication. bazel_dep(name = "bazel_lib", version = "3.0.0") # TODO(3.0): remove this back-compat bazel_dep(name = "jq.bzl", version = "0.1.0") bazel_dep(name = "yq.bzl", version = "0.1.1") bazel_dep(name = "tar.bzl", version = "0.5.1") bazel_lib_toolchains = use_extension("@aspect_bazel_lib//lib:extensions.bzl", "toolchains") bazel_lib_toolchains.copy_directory() bazel_lib_toolchains.copy_to_directory() bazel_lib_toolchains.jq() bazel_lib_toolchains.yq() bazel_lib_toolchains.coreutils() bazel_lib_toolchains.tar() bazel_lib_toolchains.zstd() bazel_lib_toolchains.expand_template() bazel_lib_toolchains.bats() use_repo(bazel_lib_toolchains, "bats_toolchains", "bsd_tar_toolchains", "copy_directory_toolchains", "copy_to_directory_toolchains", "coreutils_toolchains", "expand_template_toolchains", "jq", "jq_toolchains", "yq", "yq_toolchains", "zstd_toolchains") register_toolchains( "@copy_directory_toolchains//:all", "@copy_to_directory_toolchains//:all", "@jq_toolchains//:all", "@yq_toolchains//:all", "@coreutils_toolchains//:all", "@expand_template_toolchains//:all", "@bats_toolchains//:all", "@bsd_tar_toolchains//:all", "@zstd_toolchains//:all", ) ####### Dev dependencies ######## # To allow /tools to be built from source # NOTE: when publishing to BCR, we patch this to be dev_dependency, as we publish pre-built binaries # along with our releases. bazel_dep( name = "gazelle", version = "0.40.0", # In released versions: dev_dependency = True ) bazel_dep( name = "rules_go", version = "0.55.0", repo_name = "io_bazel_rules_go", # In released versions: dev_dependency = True ) go_sdk = use_extension( "@io_bazel_rules_go//go:extensions.bzl", "go_sdk", # In released versions: dev_dependency = True ) go_sdk.from_file(go_mod = "//:go.mod") go_deps = use_extension( "@gazelle//:extensions.bzl", "go_deps", # In released versions: dev_dependency = True ) go_deps.from_file(go_mod = "//:go.mod") use_repo( go_deps, "com_github_bmatcuk_doublestar_v4", "org_golang_x_exp", "org_golang_x_sys", ) host = use_extension("@aspect_bazel_lib//lib:extensions.bzl", "host", dev_dependency = True) host.host() use_repo(host, "aspect_bazel_lib_host") host_platform = use_extension("@platforms//host:extension.bzl", "host_platform") use_repo(host_platform, "host_platform") bazel_dep(name = "bazel_skylib_gazelle_plugin", version = "1.5.0", dev_dependency = True) bazel_dep(name = "buildifier_prebuilt", version = "6.4.0", dev_dependency = True) bazel_dep(name = "external_test_repo", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "external_test_repo", path = "./lib/tests/external_test_repo", ) bazel-lib-2.22.5/README.md000066400000000000000000000075551513125663600147460ustar00rootroot00000000000000# Bazel helpers library Base Starlark libraries and basic Bazel rules which are useful for constructing rulesets and BUILD files. This module depends on [bazel-skylib](https://github.com/bazelbuild/bazel-skylib). In theory all these utilities could be upstreamed to bazel-skylib, but the declared scope of that project is narrow and it's very difficult to get anyone's attention to review PRs there. ## Installation Installation instructions are included on each release: To use a commit rather than a release, you can point at any SHA of the repo. However, this adds more "dev dependencies", as you'll have to build our helper programs (such as `copy_to_directory`, `expand_template`) from their Go sources rather than download pre-built binaries. For example to use commit `abc123` in `MODULE.bazel`: ``` # Automatically picks up new Go dev dependencies git_override( module_name = "aspect_bazel_lib", commit = "abc123", remote = "git@github.com:aspect-build/bazel-lib.git", ) ``` Or in `WORKSPACE`: 1. Replace `url = "https://github.com/bazel-contrib/bazel-lib/releases/download/v0.1.0/bazel-lib-v0.1.0.tar.gz"` with a GitHub-provided source archive like `url = "https://github.com/bazel-contrib/bazel-lib/archive/abc123.tar.gz"` 1. Replace `strip_prefix = "bazel-lib-0.1.0"` with `strip_prefix = "bazel-lib-abc123"` 1. Update the `sha256`. The easiest way to do this is to comment out the line, then Bazel will print a message with the correct value. 1. `load("@aspect_bazel_lib//:deps.bzl", "go_dependencies")` and then call `go_dependencies()` > Note that GitHub source archives don't have a strong guarantee on the sha256 stability, see > # Public API ## Copying files - [copy_directory](docs/copy_directory.md) Copies directories to another package. - [copy_file](docs/copy_file.md) Copies files to another package. - [copy_to_bin](docs/copy_to_bin.md) Copies a source file to output tree at the same workspace-relative path. - [copy_to_directory](docs/copy_to_directory.md) Copies and arranges files and directories into a new directory. - [write_source_files](docs/write_source_files.md) Write to one or more files or folders in the source tree. Stamp out tests that ensure the sources exist and are up to date. ## Manipulating paths - [directory_path](docs/directory_path.md) Provide a label to reference some path within a directory, via DirectoryPathInfo. - [output_files](docs/output_files.md) Forwards a subset of the files (via the DefaultInfo provider) from a given target's DefaultInfo or OutputGroupInfo. ## Writing rules - [expand_make_vars](docs/expand_make_vars.md) Perform make variable and location substitutions in strings.. - [expand_template](docs/expand_template.md) Substitute templates with make variables, location resolves, stamp variables, and arbitrary strings. - [paths](docs/paths.md) Useful path resolution methods. - [transitions](docs/transitions.md) Transition sources to a provided platform. - [lists](docs/lists.md) Functional-style helpers for working with list data structures. - [utils](docs/utils.md) Various utils for labels and globs. - [params_file](docs/params_file.md) Generate encoded params file from a list of arguments. - [repo_utils](docs/repo_utils.md) Useful methods for repository rule implementations. - [run_binary](docs/run_binary.md) Like skylib's run_binary but adds directory output support. - [stamping](docs/stamping.md) Support version stamping in custom rules. - [base64](docs/base64.md) Starlark Base64 encoder & decoder. ## Testing - [bats_test](docs/bats.md): A test runner for the [Bash Automated Testing System](https://github.com/bats-core/bats-core). ## Generating documentation - [docs](docs/docs.md) Rules for generating docs and stamping tests to ensure they are up to date. bazel-lib-2.22.5/WORKSPACE.bazel000066400000000000000000000002121513125663600160230ustar00rootroot00000000000000# Placeholder indicating the root of a Bazel Workspace, needed only so this repo can be tested against # Bazel 6 without --enable_bzlmod. bazel-lib-2.22.5/bzl_library.bzl000066400000000000000000000064311513125663600165030ustar00rootroot00000000000000"""A library rule and macro for grouping Starlark sources. Drop-in replacement for bzl_library in bazel_skylib, with exceptions: - We support .bzl and .star extensions, while bzl_library accepts .bzl and .scl. """ load("@bazel_skylib//:bzl_library.bzl", "StarlarkLibraryInfo") def _bzl_library_impl(ctx): deps_files = [x.files for x in ctx.attr.deps] all_files = depset(ctx.files.srcs, order = "postorder", transitive = deps_files) if not ctx.files.srcs and not deps_files: fail("bzl_library rule '%s' has no srcs or deps" % ctx.label) return [ # All dependent files should be listed in both `files` and in `runfiles`; # this ensures that a `bzl_library` can be referenced as `data` from # a separate program, or from `tools` of a genrule(). DefaultInfo( files = all_files, runfiles = ctx.runfiles(transitive_files = all_files), ), # Interop with @bazel_skylib//:bzl_library StarlarkLibraryInfo( srcs = ctx.files.srcs, transitive_srcs = all_files, ), ] bzl_library_rule = rule( implementation = _bzl_library_impl, attrs = { "srcs": attr.label_list( allow_files = [".bzl", ".star"], ), "deps": attr.label_list( allow_files = [".bzl", ".star"], ), }, doc = """Creates a logical collection of Starlark .bzl and .star files.""", ) def bzl_library(name, srcs = [], deps = [], **kwargs): """Wrapper for bzl_library. Args: name: name srcs: List of `.bzl` and `.star` files that are processed to create this target. deps: List of other `bzl_library` or `filegroup` targets that are required by the Starlark files listed in `srcs`. **kwargs: additional arguments for the bzl_library rule. """ # buildifier: disable=unused-variable _ = kwargs.pop("compatible_with", None) _ = kwargs.pop("exec_compatible_with", None) _ = kwargs.pop("features", None) _ = kwargs.pop("target_compatible_with", None) bzl_library_rule( name = name, srcs = srcs, deps = deps, compatible_with = [], exec_compatible_with = [], features = [], target_compatible_with = [], **kwargs ) # validate that public API docs have correct deps, by running the doc extractor over them. # TODO(alexeagle): it would be better to attach this as a validation action in the bzl_library_rule # but there's no tool available for that since the Java implementation code is only exposed as a # native Bazel rule. # See bazelbuild/bazel-skylib#568 if hasattr(native, "starlark_doc_extract") and "/private" not in native.package_name(): extract_targets = [] for i, src in enumerate(srcs): extract_target = "{}.doc_extract{}".format(name, i if i > 0 else "") native.starlark_doc_extract( name = extract_target, src = src, deps = deps, testonly = True, visibility = ["//visibility:private"], ) extract_targets.append(extract_target) native.filegroup( name = "{}.docs-as-proto".format(name), srcs = extract_targets, testonly = True, ) bazel-lib-2.22.5/deps.bzl000066400000000000000000000110531513125663600151170ustar00rootroot00000000000000"""This module contains the project repository dependencies. """ load("@gazelle//:deps.bzl", "go_repository") def go_dependencies(): """The Go dependencies. """ go_repository( name = "com_github_bazelbuild_rules_go", build_file_proto_mode = "disable_global", importpath = "github.com/bazelbuild/rules_go", sum = "h1:+ozpngVAW67pCAwfhepaXSSrG3yHcj8K9hNAxSYBno4=", version = "v0.52.0", ) go_repository( name = "com_github_bmatcuk_doublestar_v4", build_file_proto_mode = "disable_global", importpath = "github.com/bmatcuk/doublestar/v4", sum = "h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0CXv75Q=", version = "v4.7.1", ) go_repository( name = "com_github_gogo_protobuf", build_file_proto_mode = "disable_global", importpath = "github.com/gogo/protobuf", sum = "h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=", version = "v1.3.2", ) go_repository( name = "com_github_golang_mock", build_file_proto_mode = "disable_global", importpath = "github.com/golang/mock", sum = "h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U=", version = "v1.7.0-rc.1", ) go_repository( name = "com_github_golang_protobuf", build_file_proto_mode = "disable_global", importpath = "github.com/golang/protobuf", sum = "h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=", version = "v1.5.3", ) go_repository( name = "com_github_google_go_cmp", build_file_proto_mode = "disable_global", importpath = "github.com/google/go-cmp", sum = "h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=", version = "v0.6.0", ) go_repository( name = "com_github_pmezard_go_difflib", build_file_proto_mode = "disable_global", importpath = "github.com/pmezard/go-difflib", sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=", version = "v1.0.0", ) go_repository( name = "org_golang_google_genproto", build_file_proto_mode = "disable_global", importpath = "google.golang.org/genproto", sum = "h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=", version = "v0.0.0-20200526211855-cb27e3aa2013", ) go_repository( name = "org_golang_google_grpc", build_file_proto_mode = "disable_global", importpath = "google.golang.org/grpc", sum = "h1:pnP7OclFFFgFi4VHQDQDaoXUVauOFyktqTsqqgzFKbc=", version = "v1.40.1", ) go_repository( name = "org_golang_google_grpc_cmd_protoc_gen_go_grpc", build_file_proto_mode = "disable_global", importpath = "google.golang.org/grpc/cmd/protoc-gen-go-grpc", sum = "h1:rNBFJjBCOgVr9pWD7rs/knKL4FRTKgpZmsRfV214zcA=", version = "v1.3.0", ) go_repository( name = "org_golang_google_protobuf", build_file_proto_mode = "disable_global", importpath = "google.golang.org/protobuf", sum = "h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=", version = "v1.31.0", ) go_repository( name = "org_golang_x_exp", build_file_proto_mode = "disable_global", importpath = "golang.org/x/exp", sum = "h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=", version = "v0.0.0-20240823005443-9b4947da3948", ) go_repository( name = "org_golang_x_mod", build_file_proto_mode = "disable_global", importpath = "golang.org/x/mod", sum = "h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=", version = "v0.20.0", ) go_repository( name = "org_golang_x_net", build_file_proto_mode = "disable_global", importpath = "golang.org/x/net", sum = "h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=", version = "v0.26.0", ) go_repository( name = "org_golang_x_sync", build_file_proto_mode = "disable_global", importpath = "golang.org/x/sync", sum = "h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=", version = "v0.8.0", ) go_repository( name = "org_golang_x_sys", build_file_proto_mode = "disable_global", importpath = "golang.org/x/sys", sum = "h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=", version = "v0.29.0", ) go_repository( name = "org_golang_x_text", build_file_proto_mode = "disable_global", importpath = "golang.org/x/text", sum = "h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=", version = "v0.16.0", ) bazel-lib-2.22.5/docs/000077500000000000000000000000001513125663600144035ustar00rootroot00000000000000bazel-lib-2.22.5/docs/.bazelrc000066400000000000000000000005051513125663600160260ustar00rootroot00000000000000# Never Compile protoc Again # Don't build protoc from the cc_binary, it's slow and spammy when cache miss common --per_file_copt=external/.*protobuf.*@--PROTOBUF_WAS_NOT_SUPPOSED_TO_BE_BUILT common --host_per_file_copt=external/.*protobuf.*@--PROTOBUF_WAS_NOT_SUPPOSED_TO_BE_BUILT common --java_runtime_version=remotejdk_11 bazel-lib-2.22.5/docs/.bazelversion000066400000000000000000000000061513125663600171030ustar00rootroot000000000000008.3.1 bazel-lib-2.22.5/docs/BUILD.bazel000066400000000000000000000066761513125663600163000ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:docs.bzl", "update_docs") load(":defs.bzl", "stardoc_with_diff_test") stardoc_with_diff_test( name = "copy_file", bzl_library_target = "@aspect_bazel_lib//lib:copy_file", ) stardoc_with_diff_test( name = "copy_directory", bzl_library_target = "@aspect_bazel_lib//lib:copy_directory", ) stardoc_with_diff_test( name = "copy_to_directory", bzl_library_target = "@aspect_bazel_lib//lib:copy_to_directory", ) stardoc_with_diff_test( name = "copy_to_bin", bzl_library_target = "@aspect_bazel_lib//lib:copy_to_bin", ) stardoc_with_diff_test( name = "docs", bzl_library_target = "@aspect_bazel_lib//lib:docs", tags = ["some_random_tag_for_testing_pr746_regression"], ) stardoc_with_diff_test( name = "diff_test", bzl_library_target = "@aspect_bazel_lib//lib:diff_test", ) stardoc_with_diff_test( name = "expand_make_vars", bzl_library_target = "@aspect_bazel_lib//lib:expand_make_vars", ) stardoc_with_diff_test( name = "expand_template", bzl_library_target = "@aspect_bazel_lib//lib:expand_template", ) stardoc_with_diff_test( name = "params_file", bzl_library_target = "@aspect_bazel_lib//lib:params_file", ) stardoc_with_diff_test( name = "paths", bzl_library_target = "@aspect_bazel_lib//lib:paths", ) stardoc_with_diff_test( name = "lists", bzl_library_target = "@aspect_bazel_lib//lib:lists", ) stardoc_with_diff_test( name = "utils", bzl_library_target = "@aspect_bazel_lib//lib:utils", ) stardoc_with_diff_test( name = "write_source_files", bzl_library_target = "@aspect_bazel_lib//lib:write_source_files", ) stardoc_with_diff_test( name = "directory_path", bzl_library_target = "@aspect_bazel_lib//lib:directory_path", ) stardoc_with_diff_test( name = "output_files", bzl_library_target = "@aspect_bazel_lib//lib:output_files", ) stardoc_with_diff_test( name = "run_binary", bzl_library_target = "@aspect_bazel_lib//lib:run_binary", ) stardoc_with_diff_test( name = "transitions", bzl_library_target = "@aspect_bazel_lib//lib:transitions", ) stardoc_with_diff_test( name = "repo_utils", bzl_library_target = "@aspect_bazel_lib//lib:repo_utils", ) stardoc_with_diff_test( name = "glob_match", bzl_library_target = "@aspect_bazel_lib//lib:glob_match", ) stardoc_with_diff_test( name = "host_repo", bzl_library_target = "@aspect_bazel_lib//lib:host_repo", ) stardoc_with_diff_test( name = "platform_utils", bzl_library_target = "@aspect_bazel_lib//lib:platform_utils", ) stardoc_with_diff_test( name = "stamping", bzl_library_target = "@aspect_bazel_lib//lib:stamping", ) stardoc_with_diff_test( name = "testing", bzl_library_target = "@aspect_bazel_lib//lib:testing", ) stardoc_with_diff_test( name = "base64", bzl_library_target = "@aspect_bazel_lib//lib:base64", ) stardoc_with_diff_test( name = "repositories", bzl_library_target = "@aspect_bazel_lib//lib:repositories", ) stardoc_with_diff_test( name = "bazelrc_presets", bzl_library_target = "@aspect_bazel_lib//lib:bazelrc_presets", ) stardoc_with_diff_test( name = "strings", bzl_library_target = "@aspect_bazel_lib//lib:strings", ) stardoc_with_diff_test( name = "bats", bzl_library_target = "@aspect_bazel_lib//lib:bats", ) stardoc_with_diff_test( name = "resource_sets", bzl_library_target = "@aspect_bazel_lib//lib:resource_sets", ) update_docs(name = "update") bazel-lib-2.22.5/docs/MODULE.bazel000066400000000000000000000012571513125663600164140ustar00rootroot00000000000000"Dependencies for building docs with stardoc" bazel_dep(name = "aspect_bazel_lib", version = "0.0.0") bazel_dep(name = "rules_java", version = "8.11.0") bazel_dep(name = "platforms", version = "0.0.11") bazel_dep(name = "stardoc", version = "0.7.1") local_path_override( module_name = "aspect_bazel_lib", path = "..", ) http_jar = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_jar") http_jar( name = "stardoc-prebuilt", integrity = "sha256-jDi5ITmziwwiHCsfd8v0UOoraWXIAfICIll+wbpg/vE=", # NB: version matches the stardoc load above urls = ["https://github.com/alexeagle/stardoc-prebuilt/releases/download/v0.7.1/renderer_deploy.jar"], ) bazel-lib-2.22.5/docs/base64.md000066400000000000000000000017751513125663600160230ustar00rootroot00000000000000 Utility functions for encoding and decoding strings with base64. See https://en.wikipedia.org/wiki/Base64. ## base64.decode
load("@aspect_bazel_lib//lib:base64.bzl", "base64")

base64.decode(data)
Decode a base64 encoded string. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | data | base64-encoded string | none | **RETURNS** A string containing the decoded data ## base64.encode
load("@aspect_bazel_lib//lib:base64.bzl", "base64")

base64.encode(data)
Base64 encode a string. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | data | string to encode | none | **RETURNS** The base64-encoded string bazel-lib-2.22.5/docs/bats.md000066400000000000000000000033131513125663600156560ustar00rootroot00000000000000 A test rule that invokes the [Bash Automated Testing System](https://github.com/bats-core/bats-core). For example, a `bats_test` target containing a single .bat and basic configuration: ```starlark bats_test( name = "my_test", size = "small", srcs = [ "my_test.bats", ], data = [ "data.bin", ], env = { "DATA_PATH": "$(location :data.bin)", }, args = ["--timing"], ) ``` ## bats_test
load("@aspect_bazel_lib//lib:bats.bzl", "bats_test")

bats_test(name, srcs, data, env)
**ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | srcs | Test files | List of labels | optional | `[]` | | data | Runtime dependencies of the test. | List of labels | optional | `[]` | | env | Environment variables of the action.

Subject to [$(location)](https://bazel.build/reference/be/make-variables#predefined_label_variables) and ["Make variable"](https://bazel.build/reference/be/make-variables) substitution. | Dictionary: String -> String | optional | `{}` | bazel-lib-2.22.5/docs/bazelrc_presets.md000066400000000000000000000025771513125663600201270ustar00rootroot00000000000000 'Presets' for bazelrc See https://docs.aspect.build/guides/bazelrc ## write_aspect_bazelrc_presets
load("@aspect_bazel_lib//lib:bazelrc_presets.bzl", "write_aspect_bazelrc_presets")

write_aspect_bazelrc_presets(name, presets, **kwargs)
Keeps your vendored copy of Aspect recommended `.bazelrc` presets up-to-date. This macro uses a [write_source_files](https://docs.aspect.build/rules/aspect_bazel_lib/docs/write_source_files) rule under the hood to keep your presets up-to-date. By default all presets are vendored but this list can be customized using the `presets` attribute. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | a unique name for this target | none | | presets | a list of preset names to keep up-to-date | `["bazel6", "bazel7", "ci", "convenience", "correctness", "debug", "java", "javascript", "performance"]` | | kwargs | Additional arguments to pass to `write_source_files` | none | bazel-lib-2.22.5/docs/copy_directory.md000066400000000000000000000123161513125663600177660ustar00rootroot00000000000000 A rule that copies a directory to another place. The rule uses a precompiled binary to perform the copy, so no shell is required. ## Preserving modification times `copy_directory` and `copy_to_directory` have a `preserve_mtime` attribute, however there are two caveats to consider when using this feature: 1. Remote Execution / Caching: These layers will reset the modify time and are incompatible with this feature. To avoid these failures the [no-remote tag](https://bazel.build/reference/be/common-definitions) can be added. 2. Caching: Changes to only the modified time will not re-trigger cached actions. This can be worked around by using a clean build when these types of changes occur. For tests the [external tag](https://bazel.build/reference/be/common-definitions) can be used but this will result in tests never being cached. ## copy_directory
load("@aspect_bazel_lib//lib:copy_directory.bzl", "copy_directory")

copy_directory(name, src, out, hardlink, **kwargs)
Copies a directory to another location. This rule uses a precompiled binary to perform the copy, so no shell is required. If using this rule with source directories, it is recommended that you use the `--host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1` startup option so that changes to files within source directories are detected. See https://github.com/bazelbuild/bazel/commit/c64421bc35214f0414e4f4226cc953e8c55fa0d2 for more context. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the rule. | none | | src | The directory to make a copy of. Can be a source directory or TreeArtifact. | none | | out | Path of the output directory, relative to this package. | none | | hardlink | Controls when to use hardlinks to files instead of making copies.

Creating hardlinks is much faster than making copies of files with the caveat that hardlinks share file permissions with their source.

Since Bazel removes write permissions on files in the output tree after an action completes, hardlinks to source files within source directories is not recommended since write permissions will be inadvertently removed from sources files.

- "auto": hardlinks are used if src is a tree artifact already in the output tree - "off": files are always copied - "on": hardlinks are always used (not recommended) | `"auto"` | | kwargs | further keyword arguments, e.g. `visibility` | none | ## copy_directory_bin_action
load("@aspect_bazel_lib//lib:copy_directory.bzl", "copy_directory_bin_action")

copy_directory_bin_action(ctx, src, dst, copy_directory_bin, copy_directory_toolchain, hardlink,
                          verbose, preserve_mtime)
Factory function that creates an action to copy a directory from src to dst using a tool binary. The tool binary will typically be the `@aspect_bazel_lib//tools/copy_directory` `go_binary` either built from source or provided by a toolchain. This helper is used by the copy_directory rule. It is exposed as a public API so it can be used within other rule implementations. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | src | The source directory to copy. | none | | dst | The directory to copy to. Must be a TreeArtifact. | none | | copy_directory_bin | Copy to directory tool binary. | none | | copy_directory_toolchain | The toolchain type for Auto Exec Groups. The default is probably what you want. | `"@aspect_bazel_lib//lib:copy_directory_toolchain_type"` | | hardlink | Controls when to use hardlinks to files instead of making copies.

See copy_directory rule documentation for more details. | `"auto"` | | verbose | print verbose logs to stdout | `False` | | preserve_mtime | preserve the modified time from the source. See the caveats above about interactions with remote execution and caching. | `False` | bazel-lib-2.22.5/docs/copy_file.md000066400000000000000000000105121513125663600166750ustar00rootroot00000000000000 A rule that copies a file to another place. `native.genrule()` is sometimes used to copy files (often wishing to rename them). The `copy_file` rule does this with a simpler interface than genrule. This rule uses a hermetic uutils/coreutils `cp` binary, no shell is required. This fork of bazel-skylib's copy_file adds `DirectoryPathInfo` support and allows multiple `copy_file` rules in the same package. ## copy_file
load("@aspect_bazel_lib//lib:copy_file.bzl", "copy_file")

copy_file(name, src, out, is_executable, allow_symlink, **kwargs)
Copies a file or directory to another location. `native.genrule()` is sometimes used to copy files (often wishing to rename them). The 'copy_file' rule does this with a simpler interface than genrule. This rule uses a hermetic uutils/coreutils `cp` binary, no shell is required. If using this rule with source directories, it is recommended that you use the `--host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1` startup option so that changes to files within source directories are detected. See https://github.com/bazelbuild/bazel/commit/c64421bc35214f0414e4f4226cc953e8c55fa0d2 for more context. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the rule. | none | | src | A Label. The file to make a copy of. (Can also be the label of a rule that generates a file.) | none | | out | Path of the output file, relative to this package. | none | | is_executable | A boolean. Whether to make the output file executable. When True, the rule's output can be executed using `bazel run` and can be in the srcs of binary and test rules that require executable sources. WARNING: If `allow_symlink` is True, `src` must also be executable. | `False` | | allow_symlink | A boolean. Whether to allow symlinking instead of copying. When False, the output is always a hard copy. When True, the output *can* be a symlink, but there is no guarantee that a symlink is created (i.e., at the time of writing, we don't create symlinks on Windows). Set this to True if you need fast copying and your tools can handle symlinks (which most UNIX tools can). | `False` | | kwargs | further keyword arguments, e.g. `visibility` | none | ## copy_file_action
load("@aspect_bazel_lib//lib:copy_file.bzl", "copy_file_action")

copy_file_action(ctx, src, dst, dir_path)
Factory function that creates an action to copy a file from src to dst. If src is a TreeArtifact, dir_path must be specified as the path within the TreeArtifact to the file to copy. This helper is used by copy_file. It is exposed as a public API so it can be used within other rule implementations. To use `copy_file_action` in your own rules, you need to include the toolchains it uses in your rule definition. For example: ```starlark load("@bazel_lib//lib:copy_file.bzl", "COPY_FILE_TOOLCHAINS") my_rule = rule( ..., toolchains = COPY_FILE_TOOLCHAINS, ) ``` Additionally, you must ensure that the coreutils toolchain is has been registered in your WORKSPACE if you are not using bzlmod: ```starlark load("@bazel_lib//lib:repositories.bzl", "register_coreutils_toolchains") register_coreutils_toolchains() ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | src | The source file to copy or TreeArtifact to copy a single file out of. | none | | dst | The destination file. | none | | dir_path | If src is a TreeArtifact, the path within the TreeArtifact to the file to copy. | `None` | bazel-lib-2.22.5/docs/copy_to_bin.md000066400000000000000000000076271513125663600172450ustar00rootroot00000000000000 A rule that copies source files to the output tree. This rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe command (fc.exe) on Windows (no Bash is required). Originally authored in rules_nodejs https://github.com/bazel-contrib/rules_nodejs/blob/8b5d27400db51e7027fe95ae413eeabea4856f8e/internal/common/copy_to_bin.bzl ## copy_file_to_bin_action
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_file_to_bin_action")

copy_file_to_bin_action(ctx, file)
Factory function that creates an action to copy a file to the output tree. File are copied to the same workspace-relative path. The resulting files is returned. If the file passed in is already in the output tree is then it is returned without a copy action. To use `copy_file_to_bin_action` in your own rules, you need to include the toolchains it uses in your rule definition. For example: ```starlark load("@bazel_lib//lib:copy_to_bin.bzl", "COPY_FILE_TO_BIN_TOOLCHAINS") my_rule = rule( ..., toolchains = COPY_FILE_TO_BIN_TOOLCHAINS, ) ``` Additionally, you must ensure that the coreutils toolchain is has been registered in your WORKSPACE if you are not using bzlmod: ```starlark load("@bazel_lib//lib:repositories.bzl", "register_coreutils_toolchains") register_coreutils_toolchains() ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | file | The file to copy. | none | **RETURNS** A File in the output tree. ## copy_files_to_bin_actions
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_files_to_bin_actions")

copy_files_to_bin_actions(ctx, files)
Factory function that creates actions to copy files to the output tree. Files are copied to the same workspace-relative path. The resulting list of files is returned. If a file passed in is already in the output tree is then it is added directly to the result without a copy action. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | files | List of File objects. | none | **RETURNS** List of File objects in the output tree. ## copy_to_bin
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin")

copy_to_bin(name, srcs, **kwargs)
Copies a source file to output tree at the same workspace-relative path. e.g. `/path/to/file -> /bazel-out//bin/path/to/file` If a file passed in is already in the output tree is then it is added directly to the DefaultInfo provided by the rule without a copy. This is useful to populate the output folder with all files needed at runtime, even those which aren't outputs of a Bazel rule. This way you can run a binary in the output folder (execroot or runfiles_root) without that program needing to rely on a runfiles helper library or be aware that files are divided between the source tree and the output tree. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the rule. | none | | srcs | A list of labels. File(s) to copy. | none | | kwargs | further keyword arguments, e.g. `visibility` | none | bazel-lib-2.22.5/docs/copy_to_directory.md000066400000000000000000000417331513125663600204750ustar00rootroot00000000000000 Copy files and directories to an output directory. ## copy_to_directory
load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory")

copy_to_directory(name, srcs, out, add_directory_to_runfiles, allow_overwrites,
                  exclude_srcs_packages, exclude_srcs_patterns, hardlink,
                  include_external_repositories, include_srcs_packages, include_srcs_patterns,
                  preserve_mtime, replace_prefixes, root_paths, verbose)
Copies files and directories to an output directory. Files and directories can be arranged as needed in the output directory using the `root_paths`, `include_srcs_patterns`, `exclude_srcs_patterns` and `replace_prefixes` attributes. Filters and transformations are applied in the following order: 1. `include_external_repositories` 2. `include_srcs_packages` 3. `exclude_srcs_packages` 4. `root_paths` 5. `include_srcs_patterns` 6. `exclude_srcs_patterns` 7. `replace_prefixes` For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. Glob patterns are supported. Standard wildcards (globbing patterns) plus the `**` doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns. **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | srcs | Files and/or directories or targets that provide `DirectoryPathInfo` to copy into the output directory. | List of labels | optional | `[]` | | out | Path of the output directory, relative to this package.

If not set, the name of the target is used. | String | optional | `""` | | add_directory_to_runfiles | Whether to add the outputted directory to the target's runfiles. | Boolean | optional | `True` | | allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice.

The order of srcs matters as the last copy of a particular file will win when overwriting. Performance of copy_to_directory will be slightly degraded when allow_overwrites is True since copies cannot be parallelized out as they are calculated. Instead all copy paths must be calculated before any copies can be started. | Boolean | optional | `False` | | exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory.

Files in srcs are not copied to the output directory if the Bazel package of the file matches one of the patterns specified.

Forward slashes (`/`) should be used as path separators. A first character of `"."` will be replaced by the target's package path.

Files that have do not have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Globs are supported (see rule docstring above). | List of strings | optional | `[]` | | exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory.

Files in srcs are not copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified.

Forward slashes (`/`) should be used as path separators.

Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Globs are supported (see rule docstring above). | List of strings | optional | `[]` | | hardlink | Controls when to use hardlinks to files instead of making copies.

Creating hardlinks is much faster than making copies of files with the caveat that hardlinks share file permissions with their source.

Since Bazel removes write permissions on files in the output tree after an action completes, hardlinks to source files are not recommended since write permissions will be inadvertently removed from sources files.

- `auto`: hardlinks are used for generated files already in the output tree - `off`: all files are copied - `on`: hardlinks are used for all files (not recommended) | String | optional | `"auto"` | | include_external_repositories | List of external repository names (with glob support) to include in the output directory.

Files from external repositories are only copied into the output directory if the external repository they come from matches one of the external repository patterns specified or if they are in the same external repository as this target.

When copied from an external repository, the file path in the output directory defaults to the file's path within the external repository. The external repository name is _not_ included in that path.

For example, the following copies `@external_repo//path/to:file` to `path/to/file` within the output directory.

copy_to_directory(
    name = "dir",
    include_external_repositories = ["external_*"],
    srcs = ["@external_repo//path/to:file"],
)


Files that come from matching external are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. The external repository name of the file from an external repository is not included in the output directory path and is considered in subsequent filters and transformations.

Globs are supported (see rule docstring above). | List of strings | optional | `[]` | | include_srcs_packages | List of Bazel packages (with glob support) to include in output directory.

Files in srcs are only copied to the output directory if the Bazel package of the file matches one of the patterns specified.

Forward slashes (`/`) should be used as path separators. A first character of `"."` will be replaced by the target's package path.

Defaults to `["**"]` which includes sources from all packages.

Files that have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Globs are supported (see rule docstring above). | List of strings | optional | `["**"]` | | include_srcs_patterns | List of paths (with glob support) to include in output directory.

Files in srcs are only copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified.

Forward slashes (`/`) should be used as path separators.

Defaults to `["**"]` which includes all sources.

Files that have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Globs are supported (see rule docstring above). | List of strings | optional | `["**"]` | | preserve_mtime | If True, the last modified time of copied files is preserved. See the [caveats on copy_directory](/docs/copy_directory.md#preserving-modification-times) about interactions with remote execution and caching. | Boolean | optional | `False` | | replace_prefixes | Map of paths prefixes (with glob support) to replace in the output directory path when copying files.

If the output directory path for a file starts with or fully matches a a key in the dict then the matching portion of the output directory path is replaced with the dict value for that key. The final path segment matched can be a partial match of that segment and only the matching portion will be replaced. If there are multiple keys that match, the longest match wins.

Forward slashes (`/`) should be used as path separators.

Replace prefix transformation are the final step in the list of filters and transformations. The final output path of a file being copied into the output directory is determined at this step.

Globs are supported (see rule docstring above). | Dictionary: String -> String | optional | `{}` | | root_paths | List of paths (with glob support) that are roots in the output directory.

If any parent directory of a file being copied matches one of the root paths patterns specified, the output directory path will be the path relative to the root path instead of the path relative to the file's workspace. If there are multiple root paths that match, the longest match wins.

Matching is done on the parent directory of the output file path so a trailing '**' glob patterm will match only up to the last path segment of the dirname and will not include the basename. Only complete path segments are matched. Partial matches on the last segment of the root path are ignored.

Forward slashes (`/`) should be used as path separators.

A `"."` value expands to the target's package path (`ctx.label.package`).

Defaults to `["."]` which results in the output directory path of files in the target's package and and sub-packages are relative to the target's package and files outside of that retain their full workspace relative paths.

Globs are supported (see rule docstring above). | List of strings | optional | `["."]` | | verbose | If true, prints out verbose logs to stdout | Boolean | optional | `False` | ## copy_to_directory_bin_action
load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory_bin_action")

copy_to_directory_bin_action(ctx, name, dst, copy_to_directory_bin, copy_to_directory_toolchain,
                             files, targets, root_paths, include_external_repositories,
                             include_srcs_packages, exclude_srcs_packages, include_srcs_patterns,
                             exclude_srcs_patterns, replace_prefixes, allow_overwrites, hardlink,
                             preserve_mtime, verbose)
Factory function to copy files to a directory using a tool binary. The tool binary will typically be the `@aspect_bazel_lib//tools/copy_to_directory` `go_binary` either built from source or provided by a toolchain. This helper is used by copy_to_directory. It is exposed as a public API so it can be used within other rule implementations where additional_files can also be passed in. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | name | Name of target creating this action used for config file generation. | none | | dst | The directory to copy to. Must be a TreeArtifact. | none | | copy_to_directory_bin | Copy to directory tool binary. | none | | copy_to_directory_toolchain | The toolchain type for Auto Exec Groups. The default is probably what you want. | `"@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"` | | files | List of files to copy into the output directory. | `[]` | | targets | List of targets that provide `DirectoryPathInfo` to copy into the output directory. | `[]` | | root_paths | List of paths that are roots in the output directory.

See copy_to_directory rule documentation for more details. | `["."]` | | include_external_repositories | List of external repository names to include in the output directory.

See copy_to_directory rule documentation for more details. | `[]` | | include_srcs_packages | List of Bazel packages to include in output directory.

See copy_to_directory rule documentation for more details. | `["**"]` | | exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory.

See copy_to_directory rule documentation for more details. | `[]` | | include_srcs_patterns | List of paths (with glob support) to include in output directory.

See copy_to_directory rule documentation for more details. | `["**"]` | | exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory.

See copy_to_directory rule documentation for more details. | `[]` | | replace_prefixes | Map of paths prefixes to replace in the output directory path when copying files.

See copy_to_directory rule documentation for more details. | `{}` | | allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice.

See copy_to_directory rule documentation for more details. | `False` | | hardlink | Controls when to use hardlinks to files instead of making copies.

See copy_to_directory rule documentation for more details. | `"auto"` | | preserve_mtime | If true, preserve the modified time from the source. | `False` | | verbose | If true, prints out verbose logs to stdout | `False` | ## copy_to_directory_lib.impl
load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory_lib")

copy_to_directory_lib.impl(ctx)
**PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx |

-

| none | bazel-lib-2.22.5/docs/defs.bzl000066400000000000000000000003721513125663600160370ustar00rootroot00000000000000"Override default renderer" load("@aspect_bazel_lib//lib:docs.bzl", _swdt = "stardoc_with_diff_test") def stardoc_with_diff_test(name, **kwargs): _swdt( name = name, renderer = "//tools:stardoc_renderer", **kwargs ) bazel-lib-2.22.5/docs/diff_test.md000066400000000000000000000033731513125663600167020ustar00rootroot00000000000000 A test rule that compares two binary files or two directories. Similar to `bazel-skylib`'s [`diff_test`](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/diff_test.bzl) but also supports comparing directories. The rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe command (fc.exe) on Windows (no Bash is required). See also: [rules_diff](https://gitlab.arm.com/bazel/rules_diff) ## diff_test
load("@aspect_bazel_lib//lib:diff_test.bzl", "diff_test")

diff_test(name, file1, file2, diff_args, size, **kwargs)
A test that compares two files. The test succeeds if the files' contents match. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | The name of the test rule. | none | | file1 | Label of the file to compare to file2. | none | | file2 | Label of the file to compare to file1, or a list of strings which are the lines to expect file1 to contain. | none | | diff_args | Arguments to pass to the `diff` command. (Ignored on Windows) | `[]` | | size | standard attribute for tests | `"small"` | | kwargs | The common attributes for tests. | none | bazel-lib-2.22.5/docs/directory_path.md000066400000000000000000000107141513125663600177500ustar00rootroot00000000000000 Rule and corresponding provider that joins a label pointing to a TreeArtifact with a path nested within that directory ## directory_path
load("@aspect_bazel_lib//lib:directory_path.bzl", "directory_path")

directory_path(name, directory, path)
Provide DirectoryPathInfo to reference some path within a directory. Otherwise there is no way to give a Bazel label for it. **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | directory | a TreeArtifact (ctx.actions.declare_directory) | Label | required | | | path | path relative to the directory | String | required | | ## DirectoryPathInfo
load("@aspect_bazel_lib//lib:directory_path.bzl", "DirectoryPathInfo")

DirectoryPathInfo(directory, path)
Joins a label pointing to a TreeArtifact with a path nested within that directory. **FIELDS** | Name | Description | | :------------- | :------------- | | directory | a TreeArtifact (ctx.actions.declare_directory) | | path | path relative to the directory | ## make_directory_path
load("@aspect_bazel_lib//lib:directory_path.bzl", "make_directory_path")

make_directory_path(name, directory, path, **kwargs)
Helper function to generate a directory_path target and return its label. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | unique name for the generated `directory_path` target | none | | directory | `directory` attribute passed to generated `directory_path` target | none | | path | `path` attribute passed to generated `directory_path` target | none | | kwargs | parameters to pass to generated `output_files` target | none | **RETURNS** The label `name` ## make_directory_paths
load("@aspect_bazel_lib//lib:directory_path.bzl", "make_directory_paths")

make_directory_paths(name, dict, **kwargs)
Helper function to convert a dict of directory to path mappings to directory_path targets and labels. For example, ``` make_directory_paths("my_name", { "//directory/artifact:target_1": "file/path", "//directory/artifact:target_2": ["file/path1", "file/path2"], }) ``` generates the targets, ``` directory_path( name = "my_name_0", directory = "//directory/artifact:target_1", path = "file/path" ) directory_path( name = "my_name_1", directory = "//directory/artifact:target_2", path = "file/path1" ) directory_path( name = "my_name_2", directory = "//directory/artifact:target_2", path = "file/path2" ) ``` and the list of targets is returned, ``` [ "my_name_0", "my_name_1", "my_name_2", ] ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | The target name to use for the generated targets & labels.

The names are generated as zero-indexed `name + "_" + i` | none | | dict | The dictionary of directory keys to path or path list values. | none | | kwargs | additional parameters to pass to each generated target | none | **RETURNS** The label of the generated `directory_path` targets named `name + "_" + i` bazel-lib-2.22.5/docs/docs.md000066400000000000000000000042341513125663600156600ustar00rootroot00000000000000 Public API for docs helpers ## stardoc_with_diff_test
load("@aspect_bazel_lib//lib:docs.bzl", "stardoc_with_diff_test")

stardoc_with_diff_test(name, bzl_library_target, **kwargs)
Creates a stardoc target that can be auto-detected by update_docs to write the generated doc to the source tree and test that it's up to date. This is helpful for minimizing boilerplate in repos with lots of stardoc targets. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | the name of the stardoc file to be written to the current source directory (.md will be appended to the name). Call bazel run on this target to update the file. | none | | bzl_library_target | the label of the `bzl_library` target to generate documentation for | none | | kwargs | additional attributes passed to the stardoc() rule, such as for overriding the templates | none | ## update_docs
load("@aspect_bazel_lib//lib:docs.bzl", "update_docs")

update_docs(name, **kwargs)
Stamps an executable run for writing all stardocs declared with stardoc_with_diff_test to the source tree. This is to be used in tandem with `stardoc_with_diff_test()` to produce a convenient workflow for generating, testing, and updating all doc files as follows: ``` bash # on CI cd docs; bazel test :all # if it's out-of-date, then cd docs; bazel run update ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | the name of executable target | `"update"` | | kwargs | Other common named parameters such as `tags` or `visibility` | none | bazel-lib-2.22.5/docs/expand_make_vars.md000066400000000000000000000110121513125663600202270ustar00rootroot00000000000000 Public API for expanding variables ## expand_locations
load("@aspect_bazel_lib//lib:expand_make_vars.bzl", "expand_locations")

expand_locations(ctx, input, targets)
Expand location templates. Expands all `$(execpath ...)`, `$(rootpath ...)` and deprecated `$(location ...)` templates in the given string by replacing with the expanded path. Expansion only works for labels that point to direct dependencies of this rule or that are explicitly listed in the optional argument targets. See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_label_variables. Use `$(rootpath)` and `$(rootpaths)` to expand labels to the runfiles path that a built binary can use to find its dependencies. This path is of the format: - `./file` - `path/to/file` - `../external_repo/path/to/file` Use `$(execpath)` and `$(execpaths)` to expand labels to the execroot (where Bazel runs build actions). This is of the format: - `./file` - `path/to/file` - `external/external_repo/path/to/file` - `/path/to/file` - `/external/external_repo/path/to/file` The deprecated `$(location)` and `$(locations)` expansions returns either the execpath or rootpath depending on the context. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | context | none | | input | String to be expanded | none | | targets | List of targets for additional lookup information. | `[]` | **RETURNS** The expanded path or the original path **DEPRECATED** Use vanilla `ctx.expand_location(input, targets = targets)` instead ## expand_variables
load("@aspect_bazel_lib//lib:expand_make_vars.bzl", "expand_variables")

expand_variables(ctx, s, outs, inputs, attribute_name)
Expand make variables and substitute like genrule does. Bazel [pre-defined variables](https://bazel.build/reference/be/make-variables#predefined_variables) are expanded however only `$@`, `$(@D)` and `$(RULEDIR)` of [pre-defined genrule variables](https://bazel.build/reference/be/make-variables#predefined_genrule_variables) are supported. This function is the same as ctx.expand_make_variables with the additional genrule-like substitutions of: - `$<`: The input file if it is a single file. Else triggers a build error. - `$@`: The output file if it is a single file. Else triggers a build error. - `$(@D)`: The output directory. If there is only one file name in outs, this expands to the directory containing that file. If there is only one directory in outs, this expands to the single output directory. If there are multiple files, this instead expands to the package's root directory in the bin tree, even if all generated files belong to the same subdirectory! - `$(RULEDIR)`: The output directory of the rule, that is, the directory corresponding to the name of the package containing the rule under the bin tree. - `$(BUILD_FILE_PATH)`: ctx.build_file_path - `$(VERSION_FILE)`: ctx.version_file.path - `$(INFO_FILE)`: ctx.info_file.path - `$(TARGET)`: ctx.label - `$(WORKSPACE)`: ctx.workspace_name See https://docs.bazel.build/versions/main/be/general.html#genrule.cmd and https://docs.bazel.build/versions/main/be/make-variables.html#predefined_genrule_variables for more information of how these special variables are expanded. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | starlark rule context | none | | s | expression to expand | none | | outs | declared outputs of the rule, for expanding references to outputs | `[]` | | inputs | declared inputs of the rule, for expanding references to inputs | `[]` | | attribute_name | name of the attribute containing the expression. Used for error reporting. | `"args"` | **RETURNS** `s` with the variables expanded bazel-lib-2.22.5/docs/expand_template.md000066400000000000000000000122731513125663600201040ustar00rootroot00000000000000 Public API for expand template ## expand_template_rule
load("@aspect_bazel_lib//lib:expand_template.bzl", "expand_template_rule")

expand_template_rule(name, data, out, is_executable, stamp, stamp_substitutions, substitutions,
                     template)
Template expansion This performs a simple search over the template file for the keys in substitutions, and replaces them with the corresponding values. Values may also use location templates as documented in [expand_locations](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/expand_make_vars.md#expand_locations) as well as [configuration variables](https://docs.bazel.build/versions/main/skylark/lib/ctx.html#var) such as `$(BINDIR)`, `$(TARGET_CPU)`, and `$(COMPILATION_MODE)` as documented in [expand_variables](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/expand_make_vars.md#expand_variables). **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | data | List of targets for additional lookup information. | List of labels | optional | `[]` | | out | Where to write the expanded file.

If the `template` is a source file, then `out` defaults to be named the same as the template file and outputted to the same workspace-relative path. In this case there will be no pre-declared label for the output file. It can be referenced by the target label instead. This pattern is similar to `copy_to_bin` but with substitutions on the copy.

Otherwise, `out` defaults to `[name].txt`. | Label | optional | `None` | | is_executable | Whether to mark the output file as executable. | Boolean | optional | `False` | | stamp | Whether to encode build information into the output. Possible values:

- `stamp = 1`: Always stamp the build information into the output, even in [--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. This setting should be avoided, since it is non-deterministic. It potentially causes remote cache misses for the target and any downstream actions that depend on the result. - `stamp = 0`: Never stamp, instead replace build information by constant values. This gives good build result caching. - `stamp = -1`: Embedding of build information is controlled by the [--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag. Stamped targets are not rebuilt unless their dependencies change. | Integer | optional | `-1` | | stamp_substitutions | Mapping of strings to substitutions.

There are overlaid on top of substitutions when stamping is enabled for the target.

Substitutions can contain $(execpath :target) and $(rootpath :target) expansions, $(MAKEVAR) expansions and {{STAMP_VAR}} expansions when stamping is enabled for the target. | Dictionary: String -> String | optional | `{}` | | substitutions | Mapping of strings to substitutions.

Substitutions can contain $(execpath :target) and $(rootpath :target) expansions, $(MAKEVAR) expansions and {{STAMP_VAR}} expansions when stamping is enabled for the target. | Dictionary: String -> String | optional | `{}` | | template | The template file to expand. | Label | required | | ## expand_template
load("@aspect_bazel_lib//lib:expand_template.bzl", "expand_template")

expand_template(name, template, **kwargs)
Wrapper macro for `expand_template_rule`. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | name of resulting rule | none | | template | the label of a template file, or a list of strings which are lines representing the content of the template. | none | | kwargs | other named parameters to `expand_template_rule`. | none | bazel-lib-2.22.5/docs/glob_match.md000066400000000000000000000035121513125663600170250ustar00rootroot00000000000000 Public API ## glob_match
load("@aspect_bazel_lib//lib:glob_match.bzl", "glob_match")

glob_match(expr, path, match_path_separator)
Test if the passed path matches the glob expression. `*` A single asterisk stands for zero or more arbitrary characters except for the the path separator `/` if `match_path_separator` is False `?` The question mark stands for exactly one character except for the the path separator `/` if `match_path_separator` is False `**` A double asterisk stands for an arbitrary sequence of 0 or more characters. It is only allowed when preceded by either the beginning of the string or a slash. Likewise it must be followed by a slash or the end of the pattern. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | expr | the glob expression | none | | path | the path against which to match the glob expression | none | | match_path_separator | whether or not to match the path separator '/' when matching `*` and `?` expressions | `False` | **RETURNS** True if the path matches the glob expression ## is_glob
load("@aspect_bazel_lib//lib:glob_match.bzl", "is_glob")

is_glob(expr)
Determine if the passed string is a global expression **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | expr | the potential glob expression | none | **RETURNS** True if the passed string is a global expression bazel-lib-2.22.5/docs/host_repo.md000066400000000000000000000025611513125663600167330ustar00rootroot00000000000000 Public API ## host_repo
load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo")

host_repo(name, repo_mapping)
Exposes information about the host platform **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this repository. | Name | required | | | repo_mapping | In `WORKSPACE` context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

For example, an entry `"@foo": "@bar"` declares that, for any time this repository depends on `@foo` (such as a dependency on `@foo//some:target`, it should actually resolve that dependency within globally-declared `@bar` (`@bar//some:target`).

This attribute is _not_ supported in `MODULE.bazel` context (when invoking a repository rule inside a module extension's implementation function). | Dictionary: String -> String | optional | | bazel-lib-2.22.5/docs/jq.md000066400000000000000000000001121513125663600153310ustar00rootroot00000000000000# jq rule This has been moved to https://github.com/bazel-contrib/jq.bzl bazel-lib-2.22.5/docs/lists.md000066400000000000000000000111661513125663600160700ustar00rootroot00000000000000 Functions for lists ## every
load("@aspect_bazel_lib//lib:lists.bzl", "every")

every(f, arr)
Check if every item of `arr` passes function `f`. Example: `every(lambda i: i.endswith(".js"), ["app.js", "lib.js"]) // True` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** True or False ## filter
load("@aspect_bazel_lib//lib:lists.bzl", "filter")

filter(f, arr)
Filter a list `arr` by applying a function `f` to each item. Example: `filter(lambda i: i.endswith(".js"), ["app.ts", "app.js", "lib.ts", "lib.js"]) // ["app.js", "lib.js"]` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** A new list containing items that passed the filter function. ## find
load("@aspect_bazel_lib//lib:lists.bzl", "find")

find(f, arr)
Find a particular item from list `arr` by a given function `f`. Unlike `pick`, the `find` method returns a tuple of the index and the value of first item passing by `f`. Furthermore `find` does not fail if no item passes `f`. In this case `(-1, None)` is returned. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** Tuple (index, item) ## map
load("@aspect_bazel_lib//lib:lists.bzl", "map")

map(f, arr)
Apply a function `f` with each item of `arr` and return a new list. Example: `map(lambda i: i*2, [1, 2, 3]) // [2, 4, 6]` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** A new list with all mapped items. ## once
load("@aspect_bazel_lib//lib:lists.bzl", "once")

once(f, arr)
Check if exactly one item in list `arr` passes the given function `f`. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** True or False ## pick
load("@aspect_bazel_lib//lib:lists.bzl", "pick")

pick(f, arr)
Pick a particular item in list `arr` by a given function `f`. Unlike `filter`, the `pick` method returns the first item _found_ by `f`. If no item has passed `f`, the function will _fail_. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** item ## some
load("@aspect_bazel_lib//lib:lists.bzl", "some")

some(f, arr)
Check if at least one item of `arr` passes function `f`. Example: `some(lambda i: i.endswith(".js"), ["app.js", "lib.ts"]) // True` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | f | Function to execute on every item | none | | arr | List to iterate over | none | **RETURNS** True or False ## unique
load("@aspect_bazel_lib//lib:lists.bzl", "unique")

unique(arr)
Return a new list with unique items in it. Example: `unique(["foo", "bar", "foo", "baz"]) // ["foo", "bar", "baz"]` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | arr | List to iterate over | none | **RETURNS** A new list with unique items bazel-lib-2.22.5/docs/output_files.md000066400000000000000000000051131513125663600174470ustar00rootroot00000000000000 A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo. See also [select_file](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/select_file_doc.md) from bazel-skylib. ## output_files
load("@aspect_bazel_lib//lib:output_files.bzl", "output_files")

output_files(name, output_group, paths, target)
A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | output_group | if set, we look in the specified output group for paths instead of DefaultInfo | String | optional | `""` | | paths | the paths of the file(s), relative to their roots, to provide via DefaultInfo from the given target's DefaultInfo or OutputGroupInfo | List of strings | required | | | target | the target to look in for requested paths in its' DefaultInfo or OutputGroupInfo | Label | required | | ## make_output_files
load("@aspect_bazel_lib//lib:output_files.bzl", "make_output_files")

make_output_files(name, target, paths, **kwargs)
Helper function to generate a output_files target and return its label. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | unique name for the generated `output_files` target | none | | target | `target` attribute passed to generated `output_files` target | none | | paths | `paths` attribute passed to generated `output_files` target | none | | kwargs | parameters to pass to generated `output_files` target | none | **RETURNS** The label `name` bazel-lib-2.22.5/docs/params_file.md000066400000000000000000000052521513125663600172130ustar00rootroot00000000000000 params_file public API ## params_file
load("@aspect_bazel_lib//lib:params_file.bzl", "params_file")

params_file(name, out, args, data, newline, **kwargs)
Generates a UTF-8 encoded params file from a list of arguments. Handles variable substitutions for args. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the rule. | none | | out | Path of the output file, relative to this package. | none | | args | Arguments to concatenate into a params file.

- Subject to 'Make variable' substitution. See https://docs.bazel.build/versions/main/be/make-variables.html.

- Subject to predefined source/output path variables substitutions.

The predefined variables `execpath`, `execpaths`, `rootpath`, `rootpaths`, `location`, and `locations` take label parameters (e.g. `$(execpath //foo:bar)`) and substitute the file paths denoted by that label.

See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_label_variables for more info.

NB: This $(location) substitution returns the manifest file path which differs from the `*_binary` & `*_test` args and genrule bazel substitutions. This will be fixed in a future major release. See docs string of `expand_location_into_runfiles` macro in `internal/common/expand_into_runfiles.bzl` for more info.

- Subject to predefined variables & custom variable substitutions.

Predefined "Make" variables such as `$(COMPILATION_MODE)` and `$(TARGET_CPU)` are expanded. See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_variables.

Custom variables are also expanded including variables set through the Bazel CLI with `--define=SOME_VAR=SOME_VALUE`. See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables.

Predefined genrule variables are not supported in this context. | `[]` | | data | Data for `$(location)` expansions in args. | `[]` | | newline | Line endings to use. One of [`"auto"`, `"unix"`, `"windows"`].

- `"auto"` for platform-determined - `"unix"` for LF - `"windows"` for CRLF | `"auto"` | | kwargs | undocumented named arguments | none | bazel-lib-2.22.5/docs/paths.md000066400000000000000000000101741513125663600160470ustar00rootroot00000000000000 Utilities for working with file paths. ## relative_file
load("@aspect_bazel_lib//lib:paths.bzl", "relative_file")

relative_file(to_file, frm_file)
Resolves a relative path between two files, "to_file" and "frm_file". If neither of the paths begin with ../ it is assumed that they share the same root. When finding the relative path, the incoming files are treated as actual files (not folders) so the resulting relative path may differ when compared to passing the same arguments to python's "os.path.relpath()" or NodeJs's "path.relative()". For example, 'relative_file("../foo/foo.txt", "bar/bar.txt")' will return '../../foo/foo.txt' **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | to_file | the path with file name to resolve to, from frm | none | | frm_file | the path with file name to resolve from | none | **RETURNS** The relative path from frm_file to to_file, including the file name ## to_output_relative_path
load("@aspect_bazel_lib//lib:paths.bzl", "to_output_relative_path")

to_output_relative_path(file)
The relative path from bazel-out/[arch]/bin to the given File object **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | file | a `File` object | none | **RETURNS** The output relative path for the `File` ## to_repository_relative_path
load("@aspect_bazel_lib//lib:paths.bzl", "to_repository_relative_path")

to_repository_relative_path(file)
The repository relative path for a `File` This is the full runfiles path of a `File` excluding its workspace name. This differs from root path (a.k.a. [short_path](https://bazel.build/rules/lib/File#short_path)) and rlocation path as it does not include the repository name if the `File` is from an external repository. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | file | a `File` object | none | **RETURNS** The repository relative path for the `File` ## to_rlocation_path
load("@aspect_bazel_lib//lib:paths.bzl", "to_rlocation_path")

to_rlocation_path(ctx, file)
The rlocation path for a `File` This produces the same value as the `rlocationpath` predefined source/output path variable. From https://bazel.build/reference/be/make-variables#predefined_genrule_variables: > `rlocationpath`: The path a built binary can pass to the `Rlocation` function of a runfiles > library to find a dependency at runtime, either in the runfiles directory (if available) > or using the runfiles manifest. > This is similar to root path (a.k.a. [short_path](https://bazel.build/rules/lib/File#short_path)) > in that it does not contain configuration prefixes, but differs in that it always starts with the > name of the repository. > The rlocation path of a `File` in an external repository repo will start with `repo/`, followed by the > repository-relative path. > Passing this path to a binary and resolving it to a file system path using the runfiles libraries > is the preferred approach to find dependencies at runtime. Compared to root path, it has the > advantage that it works on all platforms and even if the runfiles directory is not available. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | starlark rule execution context | none | | file | a `File` object | none | **RETURNS** The rlocationpath for the `File` bazel-lib-2.22.5/docs/platform_utils.md000066400000000000000000000013501513125663600177700ustar00rootroot00000000000000 Public API ## platform_utils.host_platform_is_darwin
load("@aspect_bazel_lib//lib:platform_utils.bzl", "platform_utils")

platform_utils.host_platform_is_darwin()
## platform_utils.host_platform_is_linux
load("@aspect_bazel_lib//lib:platform_utils.bzl", "platform_utils")

platform_utils.host_platform_is_linux()
## platform_utils.host_platform_is_windows
load("@aspect_bazel_lib//lib:platform_utils.bzl", "platform_utils")

platform_utils.host_platform_is_windows()
bazel-lib-2.22.5/docs/repo_utils.md000066400000000000000000000136771513125663600171300ustar00rootroot00000000000000 Public API ## patch
load("@aspect_bazel_lib//lib:repo_utils.bzl", "patch")

patch(ctx, patches, patch_cmds, patch_cmds_win, patch_tool, patch_args, auth, patch_directory)
Implementation of patching an already extracted repository. This rule is intended to be used in the implementation function of a repository rule. If the parameters `patches`, `patch_tool`, `patch_args`, `patch_cmds` and `patch_cmds_win` are not specified then they are taken from `ctx.attr`. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The repository context of the repository rule calling this utility function. | none | | patches | The patch files to apply. List of strings, Labels, or paths. | `None` | | patch_cmds | Bash commands to run for patching, passed one at a time to bash -c. List of strings | `None` | | patch_cmds_win | Powershell commands to run for patching, passed one at a time to powershell /c. List of strings. If the boolean value of this parameter is false, patch_cmds will be used and this parameter will be ignored. | `None` | | patch_tool | Path of the patch tool to execute for applying patches. String. | `None` | | patch_args | Arguments to pass to the patch tool. List of strings. | `None` | | auth | An optional dict specifying authentication information for some of the URLs. | `None` | | patch_directory | Directory to apply the patches in | `None` | ## repo_utils.get_env_var
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.get_env_var(rctx, name, default)
Find an environment variable in system. Doesn't %-escape the value! **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx | rctx | none | | name | environment variable name | none | | default | default value to return if env var is not set in system | none | **RETURNS** The environment variable value or the default if it is not set ## repo_utils.get_home_directory
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.get_home_directory(rctx)
**PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx |

-

| none | ## repo_utils.is_darwin
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.is_darwin(rctx)
Returns true if the host operating system is Darwin **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx |

-

| none | ## repo_utils.is_linux
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.is_linux(rctx)
Returns true if the host operating system is Linux **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx |

-

| none | ## repo_utils.is_windows
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.is_windows(rctx)
Returns true if the host operating system is Windows **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx |

-

| none | ## repo_utils.os
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.os(rctx)
Returns the name of the host operating system **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx | rctx | none | **RETURNS** The string "windows", "linux", "freebsd" or "darwin" that describes the host os ## repo_utils.platform
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")

repo_utils.platform(rctx)
Returns a normalized name of the host os and CPU architecture. Alias archictures names are normalized: x86_64 => amd64 aarch64 => arm64 The result can be used to generate repository names for host toolchain repositories for toolchains that use these normalized names. Common os & architecture pairs that are returned are, - darwin_amd64 - darwin_arm64 - linux_amd64 - linux_arm64 - linux_s390x - linux_ppc64le - windows_amd64 **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | rctx | rctx | none | **RETURNS** The normalized "_" string of the host os and CPU architecture. bazel-lib-2.22.5/docs/repositories.md000066400000000000000000000230621513125663600174570ustar00rootroot00000000000000 Macros for loading dependencies and registering toolchains ## aspect_bazel_lib_dependencies
load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies")

aspect_bazel_lib_dependencies()
Load dependencies required by aspect rules ## aspect_bazel_lib_register_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_register_toolchains")

aspect_bazel_lib_register_toolchains()
Register all bazel-lib toolchains at their default versions. To be more selective about which toolchains and versions to register, call the individual toolchain registration macros. ## register_bats_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_bats_toolchains")

register_bats_toolchains(name, core_version, support_version, assert_version, file_version,
                         libraries, register)
Registers bats toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"bats"` | | core_version | bats-core version to use | `"v1.10.0"` | | support_version | bats-support version to use | `"v0.3.0"` | | assert_version | bats-assert version to use | `"v2.1.0"` | | file_version | bats-file version to use | `"v0.4.0"` | | libraries | additional labels for libraries | `[]` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_copy_directory_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_copy_directory_toolchains")

register_copy_directory_toolchains(name, register)
Registers copy_directory toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"copy_directory"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_copy_to_directory_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_copy_to_directory_toolchains")

register_copy_to_directory_toolchains(name, register)
Registers copy_to_directory toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"copy_to_directory"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_coreutils_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_coreutils_toolchains")

register_coreutils_toolchains(name, version, register)
Registers coreutils toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"coreutils"` | | version | the version of coreutils to execute (see https://github.com/uutils/coreutils/releases) | `"0.1.0"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_expand_template_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_expand_template_toolchains")

register_expand_template_toolchains(name, register)
Registers expand_template toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"expand_template"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_jq_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_jq_toolchains")

register_jq_toolchains(name, version, register)
Registers jq toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"jq"` | | version | the version of jq to execute (see https://github.com/stedolan/jq/releases) | `"1.7"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_tar_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_tar_toolchains")

register_tar_toolchains(name, register)
Registers bsdtar toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"bsd_tar"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_yq_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_yq_toolchains")

register_yq_toolchains(name, version, register)
Registers yq toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"yq"` | | version | the version of yq to execute (see https://github.com/mikefarah/yq/releases) | `"4.45.2"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | ## register_zstd_toolchains
load("@aspect_bazel_lib//lib:repositories.bzl", "register_zstd_toolchains")

register_zstd_toolchains(name, register)
Registers zstd toolchain and repositories **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | override the prefix for the generated toolchain repositories | `"zstd"` | | register | whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension | `True` | bazel-lib-2.22.5/docs/resource_sets.md000066400000000000000000000015251513125663600176150ustar00rootroot00000000000000 Utilities for rules that expose resource_set on ctx.actions.run[_shell] Workaround for https://github.com/bazelbuild/bazel/issues/15187 Note, this workaround only provides some fixed values for either CPU or Memory. Rule authors who are ALSO the BUILD author might know better, and can write custom resource_set functions for use within their own repository. This seems to be the use case that Google engineers imagined. ## resource_set
load("@aspect_bazel_lib//lib:resource_sets.bzl", "resource_set")

resource_set(attr)
**PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attr |

-

| none | bazel-lib-2.22.5/docs/run_binary.md000066400000000000000000000130341513125663600170760ustar00rootroot00000000000000 Runs a binary as a build action. This rule does not require Bash (unlike native.genrule()). This fork of bazel-skylib's run_binary adds directory output support and better makevar expansions. ## run_binary
load("@aspect_bazel_lib//lib:run_binary.bzl", "run_binary")

run_binary(name, tool, srcs, args, env, outs, out_dirs, mnemonic, progress_message,
           execution_requirements, use_default_shell_env, stamp, **kwargs)
Runs a binary as a build action. This rule does not require Bash (unlike `native.genrule`). **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | The target name | none | | tool | The tool to run in the action.

Must be the label of a *_binary rule of a rule that generates an executable file, or of a file that can be executed as a subprocess (e.g. an .exe or .bat file on Windows or a binary with executable permission on Linux). This label is available for `$(location)` expansion in `args` and `env`. | none | | srcs | Additional inputs of the action.

These labels are available for `$(location)` expansion in `args` and `env`. | `[]` | | args | Command line arguments of the binary.

Subject to `$(location)` and make variable expansions via [expand_location](./expand_make_vars#expand_locations) and [expand_make_vars](./expand_make_vars). | `[]` | | env | Environment variables of the action.

Subject to `$(location)` and make variable expansions via [expand_location](./expand_make_vars#expand_locations) and [expand_make_vars](./expand_make_vars). | `{}` | | outs | Output files generated by the action.

These labels are available for `$(location)` expansion in `args` and `env`.

Output files cannot be nested within output directories in out_dirs. | `[]` | | out_dirs | Output directories generated by the action.

These labels are _not_ available for `$(location)` expansion in `args` and `env` since they are not pre-declared labels created via `attr.output_list()`. Output directories are declared instead by `ctx.actions.declare_directory`.

Output directories cannot be nested within other output directories in out_dirs. | `[]` | | mnemonic | A one-word description of the action, for example, CppCompile or GoLink. | `"RunBinary"` | | progress_message | Progress message to show to the user during the build, for example, "Compiling foo.cc to create foo.o". The message may contain %{label}, %{input}, or %{output} patterns, which are substituted with label string, first input, or output's path, respectively. Prefer to use patterns instead of static strings, because the former are more efficient. | `None` | | execution_requirements | Information for scheduling the action.

For example,

execution_requirements = {
    "no-cache": "1",
},


See https://docs.bazel.build/versions/main/be/common-definitions.html#common.tags for useful keys. | `None` | | use_default_shell_env | Passed to the underlying ctx.actions.run.

May introduce non-determinism when True; use with care! See e.g. https://github.com/bazelbuild/bazel/issues/4912

Refer to https://bazel.build/rules/lib/builtins/actions#run for more details. | `False` | | stamp | Whether to include build status files as inputs to the tool. Possible values:

- `stamp = 0` (default): Never include build status files as inputs to the tool. This gives good build result caching. Most tools don't use the status files, so including them in `--stamp` builds makes those builds have many needless cache misses. (Note: this default is different from most rules with an integer-typed `stamp` attribute.) - `stamp = 1`: Always include build status files as inputs to the tool, even in [--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. This setting should be avoided, since it is non-deterministic. It potentially causes remote cache misses for the target and any downstream actions that depend on the result. - `stamp = -1`: Inclusion of build status files as inputs is controlled by the [--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag. Stamped targets are not rebuilt unless their dependencies change.

When stamping is enabled, an additional two environment variables will be set for the action: - `BAZEL_STABLE_STATUS_FILE` - `BAZEL_VOLATILE_STATUS_FILE`

These files can be read and parsed by the action, for example to pass some values to a linker. | `0` | | kwargs | Additional arguments | none | bazel-lib-2.22.5/docs/stamping.md000066400000000000000000000105431513125663600165520ustar00rootroot00000000000000 # Version Stamping Bazel is generally only a build tool, and is unaware of your version control system. However, when publishing releases, you may want to embed version information in the resulting distribution. Bazel supports this with the concept of a "Workspace status" which is evaluated before each build. See [the Bazel workspace status docs](https://docs.bazel.build/versions/master/user-manual.html#workspace_status) To stamp a build, you pass the `--stamp` argument to Bazel. > Note: https://github.com/bazelbuild/bazel/issues/14341 proposes that Bazel enforce this by > only giving constant values to rule implementations when stamping isn't enabled. Stamping is typically performed on a later action in the graph, like on a linking or packaging rule (`pkg_*`). This means that a changed status variable only causes that action, not re-compilation and thus does not cause cascading re-builds. Bazel provides a couple of statuses by default, such as `BUILD_EMBED_LABEL` which is the value of the `--embed_label` argument, as well as `BUILD_HOST`, `BUILD_TIMESTAMP`, and `BUILD_USER`. You can supply more with the workspace status script, see below. Some rules accept an attribute that uses the status variables. They will usually say something like "subject to stamp variable replacements". ## Stamping with a Workspace status script To define additional statuses, pass the `--workspace_status_command` flag to `bazel`. This slows down every build, so you should avoid passing this flag unless you need to stamp this build. The value of this flag is a path to a script that prints space-separated key/value pairs, one per line, such as ```bash #!/usr/bin/env bash echo STABLE_GIT_COMMIT $(git rev-parse HEAD) ``` > For a more full-featured script, take a look at this [example in Angular] Make sure you set the executable bit, eg. `chmod +x tools/bazel_stamp_vars.sh`. > **NOTE** keys that start with `STABLE_` will cause a re-build when they change. > Other keys will NOT cause a re-build, so stale values can appear in your app. > Non-stable (volatile) keys should typically be things like timestamps that always vary between builds. You might like to encode your setup using an entry in `.bazelrc` such as: ```sh # This tells Bazel how to interact with the version control system # Enable this with --config=release build:release --stamp --workspace_status_command=./tools/bazel_stamp_vars.sh ``` [example in Angular]: https://github.com/angular/angular/blob/df274b478e6597cb1a2f31bb9f599281065aa250/dev-infra/release/env-stamp.ts ## Writing a custom rule which reads stamp variables First, load the helpers: ```starlark load("@aspect_bazel_lib//lib:stamping.bzl", "STAMP_ATTRS", "maybe_stamp") ``` In your rule implementation, call the `maybe_stamp` function. If it returns `None` then this build doesn't have stamping enabled. Otherwise you can use the returned struct to access two files. 1. The `stable_status` file contains the keys which were prefixed with `STABLE_`, see above. 2. The `volatile_status` file contains the rest of the keys. ```starlark def _rule_impl(ctx): args = ctx.actions.args() inputs = [] stamp = maybe_stamp(ctx) if stamp: args.add("--volatile_status_file", stamp.volatile_status_file.path) args.add("--stable_status_file", stamp.stable_status_file.path) inputs.extend([stamp.volatile_status_file, stamp.stable_status_file]) # ... call actions which parse the stamp files and do something with the values ... ``` Finally, in the declaration of the rule, include the `STAMP_ATTRS` to declare attributes which are read by that `maybe_stamp` function above. ```starlark my_stamp_aware_rule = rule( attrs = dict({ # ... my attributes ... }, **STAMP_ATTRS), ) ``` ## maybe_stamp
load("@aspect_bazel_lib//lib:stamping.bzl", "maybe_stamp")

maybe_stamp(ctx)
Provide the bazel-out/stable_status.txt and bazel-out/volatile_status.txt files. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context | none | **RETURNS** If stamping is not enabled for this rule under the current build, returns None. Otherwise, returns a struct containing (volatile_status_file, stable_status_file) keys bazel-lib-2.22.5/docs/strings.md000066400000000000000000000042221513125663600164160ustar00rootroot00000000000000 Utilities for strings ## chr
load("@aspect_bazel_lib//lib:strings.bzl", "chr")

chr(i)
returns a string encoding a codepoint chr returns a string that encodes the single Unicode code point whose value is specified by the integer `i` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | i | position of the character | none | **RETURNS** unicode string of the position ## hex
load("@aspect_bazel_lib//lib:strings.bzl", "hex")

hex(number)
Format integer to hexadecimal representation **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | number | number to format | none | **RETURNS** hexadecimal representation of the number argument ## ord
load("@aspect_bazel_lib//lib:strings.bzl", "ord")

ord(c)
returns the codepoint of a character ord(c) returns the integer value of the sole Unicode code point encoded by the string `c`. If `c` does not encode exactly one Unicode code point, `ord` fails. Each invalid code within the string is treated as if it encodes the Unicode replacement character, U+FFFD. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | c | character whose codepoint to be returned. | none | **RETURNS** codepoint of `c` argument. ## split_args
load("@aspect_bazel_lib//lib:strings.bzl", "split_args")

split_args(s)
Split a string into a list space separated arguments Unlike the naive `.split(" ")`, this function takes quoted strings and escapes into account. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | s | input string | none | **RETURNS** list of strings with each an argument found in the input string bazel-lib-2.22.5/docs/tar.md000066400000000000000000000001141513125663600155070ustar00rootroot00000000000000# tar rule This has been moved to https://github.com/bazel-contrib/tar.bzl bazel-lib-2.22.5/docs/testing.md000066400000000000000000000133341513125663600164060ustar00rootroot00000000000000 Helpers for making test assertions ## assert_archive_contains
load("@aspect_bazel_lib//lib:testing.bzl", "assert_archive_contains")

assert_archive_contains(name, archive, expected, type, **kwargs)
Assert that an archive file contains at least the given file entries. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | name of the resulting sh_test target | none | | archive | Label of the the .tar or .zip file | none | | expected | a (partial) file listing, either as a Label of a file containing it, or a list of strings | none | | type | "tar" or "zip". If None, a type will be inferred from the filename. | `None` | | kwargs | additional named arguments for the resulting sh_test | none | ## assert_contains
load("@aspect_bazel_lib//lib:testing.bzl", "assert_contains")

assert_contains(name, actual, expected, size, **kwargs)
Generates a test target which fails if the file doesn't contain the string. Depends on bash, as it creates an sh_test target. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | target to create | none | | actual | Label of a file | none | | expected | a string which should appear in the file | none | | size | standard attribute for tests | `"small"` | | kwargs | additional named arguments for the resulting sh_test | none | ## assert_directory_contains
load("@aspect_bazel_lib//lib:testing.bzl", "assert_directory_contains")

assert_directory_contains(name, directory, expected, **kwargs)
Assert that a directory contains at least the given file entries. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | name of the resulting sh_test target | none | | directory | Label of the directory artifact | none | | expected | a (partial) file listing, either as a Label of a file containing it, or a list of strings | none | | kwargs | additional named arguments for the resulting sh_test | none | ## assert_json_matches
load("@aspect_bazel_lib//lib:testing.bzl", "assert_json_matches")

assert_json_matches(name, file1, file2, filter1, filter2, **kwargs)
Assert that the given json files have the same semantic content. Uses jq to filter each file. The default value of `"."` as the filter means to compare the whole file. See the [jq rule](./jq.md#jq) for more about the filter expressions as well as setup notes for the `jq` toolchain. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | name of resulting diff_test target | none | | file1 | a json file | none | | file2 | another json file | none | | filter1 | a jq filter to apply to file1 | `"."` | | filter2 | a jq filter to apply to file2 | `"."` | | kwargs | additional named arguments for the resulting diff_test | none | ## assert_outputs
load("@aspect_bazel_lib//lib:testing.bzl", "assert_outputs")

assert_outputs(name, actual, expected, **kwargs)
Assert that the default outputs of a target are the expected ones. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | name of the resulting diff_test | none | | actual | string of the label to check the outputs | none | | expected | a list of rootpaths of expected outputs, as they would appear in a runfiles manifest | none | | kwargs | additional named arguments for the resulting diff_test | none | bazel-lib-2.22.5/docs/tools/000077500000000000000000000000001513125663600155435ustar00rootroot00000000000000bazel-lib-2.22.5/docs/tools/BUILD.bazel000066400000000000000000000004321513125663600174200ustar00rootroot00000000000000load("@rules_java//java:java_binary.bzl", "java_binary") package(default_visibility = ["//visibility:public"]) java_binary( name = "stardoc_renderer", main_class = "com/google/devtools/build/stardoc/renderer/RendererMain", runtime_deps = ["@stardoc-prebuilt//jar"], ) bazel-lib-2.22.5/docs/transitions.md000066400000000000000000000074751513125663600173170ustar00rootroot00000000000000 Rules for working with transitions. ## platform_transition_binary
load("@aspect_bazel_lib//lib:transitions.bzl", "platform_transition_binary")

platform_transition_binary(name, basename, binary, target_platform)
Transitions the binary to use the provided platform. Will forward RunEnvironmentInfo **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | basename | - | String | optional | `""` | | binary | - | Label | optional | `None` | | target_platform | The target platform to transition the binary. | Label | required | | ## platform_transition_filegroup
load("@aspect_bazel_lib//lib:transitions.bzl", "platform_transition_filegroup")

platform_transition_filegroup(name, srcs, target_platform)
Transitions the srcs to use the provided platform. The filegroup will contain artifacts for the target platform. **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | srcs | The input to be transitioned to the target platform. | List of labels | optional | `[]` | | target_platform | The target platform to transition the srcs. | Label | required | | ## platform_transition_test
load("@aspect_bazel_lib//lib:transitions.bzl", "platform_transition_test")

platform_transition_test(name, basename, binary, target_platform)
Transitions the test to use the provided platform. Will forward RunEnvironmentInfo **ATTRIBUTES** | Name | Description | Type | Mandatory | Default | | :------------- | :------------- | :------------- | :------------- | :------------- | | name | A unique name for this target. | Name | required | | | basename | - | String | optional | `""` | | binary | - | Label | optional | `None` | | target_platform | The target platform to transition the binary. | Label | required | | bazel-lib-2.22.5/docs/utils.md000066400000000000000000000605671513125663600161030ustar00rootroot00000000000000 General-purpose Starlark utility functions ## Usage example ```starlark load("@aspect_bazel_lib//lib:utils.bzl", "utils") out_label = utils.to_label(out_file) ``` ## consistent_label_str
load("@aspect_bazel_lib//lib:utils.bzl", "consistent_label_str")

consistent_label_str(ctx, label)
Generate a consistent label string for all Bazel versions. Starting in Bazel 6, the workspace name is empty for the local workspace and there's no other way to determine it. This behavior differs from Bazel 5 where the local workspace name was fully qualified in str(label). This utility function is meant for use in rules and requires the rule context to determine the user's workspace name (`ctx.workspace_name`). **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | label | A Label. | none | **RETURNS** String representation of the label including the repository name if the label is from an external repository. For labels in the user's repository the label will start with `@//`. ## default_timeout
load("@aspect_bazel_lib//lib:utils.bzl", "default_timeout")

default_timeout(size, timeout)
Provide a sane default for *_test timeout attribute. The [test-encyclopedia](https://bazel.build/reference/test-encyclopedia) says: > Tests may return arbitrarily fast regardless of timeout. > A test is not penalized for an overgenerous timeout, although a warning may be issued: > you should generally set your timeout as tight as you can without incurring any flakiness. However Bazel's default for timeout is medium, which is dumb given this guidance. It also says: > Tests which do not explicitly specify a timeout have one implied based on the test's size as follows Therefore if size is specified, we should allow timeout to take its implied default. If neither is set, then we can fix Bazel's wrong default here to avoid warnings under `--test_verbose_timeout_warnings`. This function can be used in a macro which wraps a testing rule. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | size | the size attribute of a test target | none | | timeout | the timeout attribute of a test target | none | **RETURNS** "short" if neither is set, otherwise timeout ## file_exists
load("@aspect_bazel_lib//lib:utils.bzl", "file_exists")

file_exists(path)
Check whether a file exists. Useful in macros to set defaults for a configuration file if it is present. This can only be called during the loading phase, not from a rule implementation. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | path | a label, or a string which is a path relative to this package | none | ## glob_directories
load("@aspect_bazel_lib//lib:utils.bzl", "glob_directories")

glob_directories(include, **kwargs)
**PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | include |

-

| none | | kwargs |

-

| none | ## is_bazel_6_or_greater
load("@aspect_bazel_lib//lib:utils.bzl", "is_bazel_6_or_greater")

is_bazel_6_or_greater()
Detects if the Bazel version being used is greater than or equal to 6 (including Bazel 6 pre-releases and RCs). Detecting Bazel 6 or greater is particularly useful in rules as slightly different code paths may be needed to support bzlmod which was added in Bazel 6. Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. **RETURNS** True if the Bazel version being used is greater than or equal to 6 (including pre-releases and RCs) ## is_bazel_7_or_greater
load("@aspect_bazel_lib//lib:utils.bzl", "is_bazel_7_or_greater")

is_bazel_7_or_greater()
Detects if the Bazel version being used is greater than or equal to 7 (including Bazel 7 pre-releases and RCs). Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. **RETURNS** True if the Bazel version being used is greater than or equal to 7 (including pre-releases and RCs) ## is_bzlmod_enabled
load("@aspect_bazel_lib//lib:utils.bzl", "is_bzlmod_enabled")

is_bzlmod_enabled()
Detect the value of the --enable_bzlmod flag ## is_external_label
load("@aspect_bazel_lib//lib:utils.bzl", "is_external_label")

is_external_label(param)
Returns True if the given Label (or stringy version of a label) represents a target outside of the workspace **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | param | a string or label | none | **RETURNS** a bool ## maybe_http_archive
load("@aspect_bazel_lib//lib:utils.bzl", "maybe_http_archive")

maybe_http_archive(**kwargs)
Adapts a maybe(http_archive, ...) to look like an http_archive. This makes WORKSPACE dependencies easier to read and update. Typical usage looks like, ``` load("//lib:utils.bzl", http_archive = "maybe_http_archive") http_archive( name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` instead of the classic maybe pattern of, ``` load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") maybe( http_archive, name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | kwargs | all arguments to pass-forward to http_archive | none | ## path_to_workspace_root
load("@aspect_bazel_lib//lib:utils.bzl", "path_to_workspace_root")

path_to_workspace_root()
Returns the path to the workspace root under bazel **RETURNS** Path to the workspace root ## propagate_common_binary_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "propagate_common_binary_rule_attributes")

propagate_common_binary_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all binary rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-binary **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common binary attributes ## propagate_common_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "propagate_common_rule_attributes")

propagate_common_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common attributes ## propagate_common_test_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "propagate_common_test_rule_attributes")

propagate_common_test_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all test rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-tests **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common test attributes ## propagate_well_known_tags
load("@aspect_bazel_lib//lib:utils.bzl", "propagate_well_known_tags")

propagate_well_known_tags(tags)
Returns a list of tags filtered from the input set that only contains the ones that are considered "well known" These are listed in Bazel's documentation: https://docs.bazel.build/versions/main/test-encyclopedia.html#tag-conventions https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | tags | List of tags to filter | `[]` | **RETURNS** List of tags that only contains the well known set ## to_label
load("@aspect_bazel_lib//lib:utils.bzl", "to_label")

to_label(param)
Converts a string to a Label. If Label is supplied, the same label is returned. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | param | a string representing a label or a Label | none | **RETURNS** a Label ## utils.consistent_label_str
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.consistent_label_str(ctx, label)
Generate a consistent label string for all Bazel versions. Starting in Bazel 6, the workspace name is empty for the local workspace and there's no other way to determine it. This behavior differs from Bazel 5 where the local workspace name was fully qualified in str(label). This utility function is meant for use in rules and requires the rule context to determine the user's workspace name (`ctx.workspace_name`). **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | ctx | The rule context. | none | | label | A Label. | none | **RETURNS** String representation of the label including the repository name if the label is from an external repository. For labels in the user's repository the label will start with `@//`. ## utils.default_timeout
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.default_timeout(size, timeout)
Provide a sane default for *_test timeout attribute. The [test-encyclopedia](https://bazel.build/reference/test-encyclopedia) says: > Tests may return arbitrarily fast regardless of timeout. > A test is not penalized for an overgenerous timeout, although a warning may be issued: > you should generally set your timeout as tight as you can without incurring any flakiness. However Bazel's default for timeout is medium, which is dumb given this guidance. It also says: > Tests which do not explicitly specify a timeout have one implied based on the test's size as follows Therefore if size is specified, we should allow timeout to take its implied default. If neither is set, then we can fix Bazel's wrong default here to avoid warnings under `--test_verbose_timeout_warnings`. This function can be used in a macro which wraps a testing rule. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | size | the size attribute of a test target | none | | timeout | the timeout attribute of a test target | none | **RETURNS** "short" if neither is set, otherwise timeout ## utils.file_exists
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.file_exists(path)
Check whether a file exists. Useful in macros to set defaults for a configuration file if it is present. This can only be called during the loading phase, not from a rule implementation. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | path | a label, or a string which is a path relative to this package | none | ## utils.glob_directories
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.glob_directories(include, **kwargs)
**PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | include |

-

| none | | kwargs |

-

| none | ## utils.is_bazel_6_or_greater
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.is_bazel_6_or_greater()
Detects if the Bazel version being used is greater than or equal to 6 (including Bazel 6 pre-releases and RCs). Detecting Bazel 6 or greater is particularly useful in rules as slightly different code paths may be needed to support bzlmod which was added in Bazel 6. Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. **RETURNS** True if the Bazel version being used is greater than or equal to 6 (including pre-releases and RCs) ## utils.is_bazel_7_or_greater
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.is_bazel_7_or_greater()
Detects if the Bazel version being used is greater than or equal to 7 (including Bazel 7 pre-releases and RCs). Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. **RETURNS** True if the Bazel version being used is greater than or equal to 7 (including pre-releases and RCs) ## utils.is_bzlmod_enabled
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.is_bzlmod_enabled()
Detect the value of the --enable_bzlmod flag ## utils.is_external_label
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.is_external_label(param)
Returns True if the given Label (or stringy version of a label) represents a target outside of the workspace **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | param | a string or label | none | **RETURNS** a bool ## utils.maybe_http_archive
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.maybe_http_archive(**kwargs)
Adapts a maybe(http_archive, ...) to look like an http_archive. This makes WORKSPACE dependencies easier to read and update. Typical usage looks like, ``` load("//lib:utils.bzl", http_archive = "maybe_http_archive") http_archive( name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` instead of the classic maybe pattern of, ``` load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") maybe( http_archive, name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | kwargs | all arguments to pass-forward to http_archive | none | ## utils.path_to_workspace_root
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.path_to_workspace_root()
Returns the path to the workspace root under bazel **RETURNS** Path to the workspace root ## utils.propagate_common_binary_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.propagate_common_binary_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all binary rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-binary **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common binary attributes ## utils.propagate_common_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.propagate_common_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common attributes ## utils.propagate_common_test_rule_attributes
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.propagate_common_test_rule_attributes(attrs)
Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all test rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-tests **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | attrs | Dict of parameters to filter | none | **RETURNS** The dict of parameters, containing only common test attributes ## utils.propagate_well_known_tags
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.propagate_well_known_tags(tags)
Returns a list of tags filtered from the input set that only contains the ones that are considered "well known" These are listed in Bazel's documentation: https://docs.bazel.build/versions/main/test-encyclopedia.html#tag-conventions https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | tags | List of tags to filter | `[]` | **RETURNS** List of tags that only contains the well known set ## utils.to_label
load("@aspect_bazel_lib//lib:utils.bzl", "utils")

utils.to_label(param)
Converts a string to a Label. If Label is supplied, the same label is returned. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | param | a string representing a label or a Label | none | **RETURNS** a Label bazel-lib-2.22.5/docs/write_source_files.md000066400000000000000000000301701513125663600206220ustar00rootroot00000000000000 write_source_files provides a workaround for the restriction that `bazel build` cannot write to the source tree. Read more about the philosophy of writing to the source tree: ## Usage ```starlark load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_foobar", files = { "foobar.json": "//some/generated:file", }, ) ``` To update the source file, run: ```bash bazel run //:write_foobar ``` The generated `diff_test` will fail if the file is out of date and print out instructions on how to update it. If the file does not exist, Bazel will fail at analysis time and print out instructions on how to create it. You can declare a tree of generated source file targets: ```starlark load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_all", additional_update_targets = [ # Other write_source_files targets to run when this target is run "//a/b/c:write_foo", "//a/b:write_bar", ] ) ``` And update them with a single run: ```bash bazel run //:write_all ``` When a file is out of date, you can leave a suggestion to run a target further up in the tree by specifying `suggested_update_target`. For example, ```starlark write_source_files( name = "write_foo", files = { "foo.json": ":generated-foo", }, suggested_update_target = "//:write_all" ) ``` A test failure from `foo.json` being out of date will yield the following message: ``` //a/b:c:foo.json is out of date. To update this and other generated files, run: bazel run //:write_all To update *only* this file, run: bazel run //a/b/c:write_foo ``` You can also add a more customized error message using the `diff_test_failure_message` argument: ```starlark write_source_file( name = "write_foo", out_file = "foo.json", in_file = ":generated-foo", diff_test_failure_message = "Failed to build Foo; please run {{TARGET}} to update." ) ``` A test failure from `foo.json` being out of date will then yield: ``` Failed to build Foo; please run //a/b/c:write_foo to update. ``` If you have many `write_source_files` targets that you want to update as a group, we recommend wrapping `write_source_files` in a macro that defaults `suggested_update_target` to the umbrella update target. NOTE: If you run formatters or linters on your codebase, it is advised that you exclude/ignore the outputs of this rule from those formatters/linters so as to avoid causing collisions and failing tests. ## WriteSourceFileInfo
load("@aspect_bazel_lib//lib:write_source_files.bzl", "WriteSourceFileInfo")

WriteSourceFileInfo(executable)
Provider for write_source_file targets **FIELDS** | Name | Description | | :------------- | :------------- | | executable | Executable that updates the source files | ## write_source_file
load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_file")

write_source_file(name, in_file, out_file, executable, additional_update_targets,
                  suggested_update_target, diff_test, diff_test_failure_message,
                  file_missing_failure_message, diff_args, check_that_out_file_exists, verbosity,
                  **kwargs)
Write a file or directory to the source tree. By default, a `diff_test` target ("{name}_test") is generated that ensure the source tree file or directory to be written to is up to date and the rule also checks that the source tree file or directory to be written to exists. To disable the exists check and up-to-date test set `diff_test` to `False`. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the runnable target that creates or updates the source tree file or directory. | none | | in_file | File or directory to use as the desired content to write to `out_file`.

This is typically a file or directory output of another target. If `in_file` is a directory then entire directory contents are copied. | `None` | | out_file | The file or directory to write to in the source tree.

The output file or directory must be within the same containing Bazel package as this target if `check_that_out_file_exists` is `True`. See `check_that_out_file_exists` docstring for more info. | `None` | | executable | Whether source tree file or files within the source tree directory written should be made executable. | `False` | | additional_update_targets | List of other `write_source_files` or `write_source_file` targets to call in the same run. | `[]` | | suggested_update_target | Label of the `write_source_files` or `write_source_file` target to suggest running when files are out of date. | `None` | | diff_test | Test that the source tree file or directory exist and is up to date. | `True` | | diff_test_failure_message | Text to print when the diff test fails, with templating options for relevant targets.

Substitutions are performed on the failure message, with the following substitutions being available:

`{{DEFAULT_MESSAGE}}`: Prints the default error message, listing the target(s) that may be run to update the file(s).

`{{TARGET}}`: The target to update the individual file that does not match in the diff test.

`{{SUGGESTED_UPDATE_TARGET}}`: The suggested_update_target if specified. | `"{{DEFAULT_MESSAGE}}"` | | file_missing_failure_message | Text to print when the output file is missing. Subject to the same substitutions as diff_test_failure_message. | `"{{DEFAULT_MESSAGE}}"` | | diff_args | Arguments to pass to the `diff` command. (Ignored on Windows) | `[]` | | check_that_out_file_exists | Test that the output file exists and print a helpful error message if it doesn't.

If `True`, the output file or directory must be in the same containing Bazel package as the target since the underlying mechanism for this check is limited to files in the same Bazel package. | `True` | | verbosity | Verbosity of message when the copy target is run. One of `full`, `short`, `quiet`. | `"full"` | | kwargs | Other common named parameters such as `tags` or `visibility` | none | **RETURNS** Name of the generated test target if requested, otherwise None. ## write_source_files
load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files")

write_source_files(name, files, executable, additional_update_targets, suggested_update_target,
                   diff_test, diff_test_failure_message, diff_args, file_missing_failure_message,
                   check_that_out_file_exists, **kwargs)
Write one or more files and/or directories to the source tree. By default, `diff_test` targets are generated that ensure the source tree files and/or directories to be written to are up to date and the rule also checks that all source tree files and/or directories to be written to exist. To disable the exists check and up-to-date tests set `diff_test` to `False`. **PARAMETERS** | Name | Description | Default Value | | :------------- | :------------- | :------------- | | name | Name of the runnable target that creates or updates the source tree files and/or directories. | none | | files | A dict where the keys are files or directories in the source tree to write to and the values are labels pointing to the desired content, typically file or directory outputs of other targets.

Destination files and directories must be within the same containing Bazel package as this target if `check_that_out_file_exists` is True. See `check_that_out_file_exists` docstring for more info. | `{}` | | executable | Whether source tree files written should be made executable.

This applies to all source tree files written by this target. This attribute is not propagated to `additional_update_targets`.

To set different executable permissions on different source tree files use multiple `write_source_files` targets. | `False` | | additional_update_targets | List of other `write_source_files` or `write_source_file` targets to call in the same run. | `[]` | | suggested_update_target | Label of the `write_source_files` or `write_source_file` target to suggest running when files are out of date. | `None` | | diff_test | Test that the source tree files and/or directories exist and are up to date. | `True` | | diff_test_failure_message | Text to print when the diff test fails, with templating options for relevant targets.

Substitutions are performed on the failure message, with the following substitutions being available:

`{{DEFAULT_MESSAGE}}`: Prints the default error message, listing the target(s) that may be run to update the file(s).

`{{TARGET}}`: The target to update the individual file that does not match in the diff test.

`{{SUGGESTED_UPDATE_TARGET}}`: The suggested_update_target if specified, or the target which will update all of the files which do not match. | `"{{DEFAULT_MESSAGE}}"` | | diff_args | Arguments to pass to the `diff` command. (Ignored on Windows) | `[]` | | file_missing_failure_message | Text to print when the output file is missing. Subject to the same substitutions as diff_test_failure_message. | `"{{DEFAULT_MESSAGE}}"` | | check_that_out_file_exists | Test that each output file exists and print a helpful error message if it doesn't.

If `True`, destination files and directories must be in the same containing Bazel package as the target since the underlying mechanism for this check is limited to files in the same Bazel package. | `True` | | kwargs | Other common named parameters such as `tags` or `visibility` | none | bazel-lib-2.22.5/docs/yq.md000066400000000000000000000001121513125663600153500ustar00rootroot00000000000000# yq rule This has been moved to https://github.com/bazel-contrib/yq.bzl bazel-lib-2.22.5/e2e/000077500000000000000000000000001513125663600141265ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/api_entries/000077500000000000000000000000001513125663600164305ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/api_entries/.bazeliskrc000077700000000000000000000000001513125663600233352../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/api_entries/.bazelrc000066400000000000000000000015521513125663600200560ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/api_entries/.bazelversion000077700000000000000000000000001513125663600242612../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/api_entries/BUILD.bazel000066400000000000000000000047301513125663600203120ustar00rootroot00000000000000load("@bazel_skylib//rules:build_test.bzl", "build_test") # Ensure all lib:* bzl_target libraries can be loaded from a MODULE # Targets from: `bazel query "kind('bzl_library', //lib:*)"` build_test( name = "api_bzl_entries", targets = [ "@aspect_bazel_lib//lib:base64", "@aspect_bazel_lib//lib:bats", "@aspect_bazel_lib//lib:bats_toolchain_type", "@aspect_bazel_lib//lib:bazelrc_presets", "@aspect_bazel_lib//lib:bzlmod", "@aspect_bazel_lib//lib:copy_directory", "@aspect_bazel_lib//lib:copy_directory_toolchain_type", "@aspect_bazel_lib//lib:copy_file", "@aspect_bazel_lib//lib:copy_to_bin", "@aspect_bazel_lib//lib:copy_to_directory", "@aspect_bazel_lib//lib:copy_to_directory_toolchain_type", "@aspect_bazel_lib//lib:coreutils_toolchain_type", "@aspect_bazel_lib//lib:diff_test", "@aspect_bazel_lib//lib:directory_path", "@aspect_bazel_lib//lib:docs", "@aspect_bazel_lib//lib:enable_runfiles", "@aspect_bazel_lib//lib:expand_make_vars", "@aspect_bazel_lib//lib:expand_template", "@aspect_bazel_lib//lib:expand_template_toolchain_type", "@aspect_bazel_lib//lib:extensions", "@aspect_bazel_lib//lib:flag_bzlmod", "@aspect_bazel_lib//lib:glob_match", "@aspect_bazel_lib//lib:host_repo", "@aspect_bazel_lib//lib:jq", "@aspect_bazel_lib//lib:jq_toolchain_type", "@aspect_bazel_lib//lib:lists", "@aspect_bazel_lib//lib:output_files", "@aspect_bazel_lib//lib:params_file", "@aspect_bazel_lib//lib:paths", "@aspect_bazel_lib//lib:platform_utils", "@aspect_bazel_lib//lib:repo_utils", "@aspect_bazel_lib//lib:repositories", "@aspect_bazel_lib//lib:resource_sets", "@aspect_bazel_lib//lib:run_binary", "@aspect_bazel_lib//lib:stamp", "@aspect_bazel_lib//lib:stamp_detect", "@aspect_bazel_lib//lib:stamping", "@aspect_bazel_lib//lib:strings", "@aspect_bazel_lib//lib:tar", "@aspect_bazel_lib//lib:tar_toolchain_type", "@aspect_bazel_lib//lib:testing", "@aspect_bazel_lib//lib:transitions", "@aspect_bazel_lib//lib:utils", "@aspect_bazel_lib//lib:windows_utils", "@aspect_bazel_lib//lib:write_source_files", "@aspect_bazel_lib//lib:yq", "@aspect_bazel_lib//lib:yq_toolchain_type", "@aspect_bazel_lib//lib:zstd_toolchain_type", ], ) bazel-lib-2.22.5/e2e/api_entries/MODULE.bazel000066400000000000000000000003541513125663600204360ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_dep(name = "bazel_skylib", version = "1.8.1", dev_dependency = True) bazel-lib-2.22.5/e2e/api_entries/WORKSPACE000066400000000000000000000016671513125663600177230ustar00rootroot00000000000000load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "bazel_skylib", sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", ], ) load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") bazel_skylib_workspace() local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "register_coreutils_toolchains") aspect_bazel_lib_dependencies() # Registering coreutils is required under WORKSPACE for the copy action to work # Under bzlmod, this is done automatically by just depending on the bazel-lib module. register_coreutils_toolchains() bazel-lib-2.22.5/e2e/api_entries/WORKSPACE.bzlmod000066400000000000000000000000001513125663600211650ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_action/000077500000000000000000000000001513125663600164355ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_action/.bazeliskrc000077700000000000000000000000001513125663600233422../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_action/.bazelrc000066400000000000000000000020731513125663600200620ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/copy_action/.bazelversion000077700000000000000000000000001513125663600242662../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_action/BUILD.bazel000066400000000000000000000003551513125663600203160ustar00rootroot00000000000000load("@bazel_skylib//rules:build_test.bzl", "build_test") load(":copy.bzl", "simple_copy_file") simple_copy_file( name = "copy", src = "foo.txt", out = "bar.txt", ) build_test( name = "test", targets = [":copy"], ) bazel-lib-2.22.5/e2e/copy_action/MODULE.bazel000066400000000000000000000003541513125663600204430ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_dep(name = "bazel_skylib", version = "1.8.1", dev_dependency = True) bazel-lib-2.22.5/e2e/copy_action/WORKSPACE000066400000000000000000000016671513125663600177300ustar00rootroot00000000000000load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "bazel_skylib", sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", ], ) load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") bazel_skylib_workspace() local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "register_coreutils_toolchains") aspect_bazel_lib_dependencies() # Registering coreutils is required under WORKSPACE for the copy action to work # Under bzlmod, this is done automatically by just depending on the bazel-lib module. register_coreutils_toolchains() bazel-lib-2.22.5/e2e/copy_action/WORKSPACE.bzlmod000066400000000000000000000000001513125663600211720ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_action/copy.bzl000066400000000000000000000016771513125663600201330ustar00rootroot00000000000000"""Rule that uses copy actions""" load("@aspect_bazel_lib//lib:copy_file.bzl", "COPY_FILE_TOOLCHAINS", "copy_file_action") load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "COPY_FILE_TO_BIN_TOOLCHAINS") def _simple_copy_file_impl(ctx): if len(ctx.files.src) != 1: fail("src must be a single file") if ctx.files.src[0].is_directory: fail("cannot use copy_file on a directory; try copy_directory instead") copy_file_action(ctx, ctx.files.src[0], ctx.outputs.out) files = depset(direct = [ctx.outputs.out]) runfiles = ctx.runfiles(files = [ctx.outputs.out]) return [DefaultInfo(files = files, runfiles = runfiles)] simple_copy_file = rule( implementation = _simple_copy_file_impl, provides = [DefaultInfo], attrs = { "src": attr.label(mandatory = True, allow_files = True), "out": attr.output(mandatory = True), }, toolchains = COPY_FILE_TOOLCHAINS + COPY_FILE_TO_BIN_TOOLCHAINS, ) bazel-lib-2.22.5/e2e/copy_action/foo.txt000066400000000000000000000000031513125663600177520ustar00rootroot00000000000000barbazel-lib-2.22.5/e2e/copy_to_directory/000077500000000000000000000000001513125663600176665ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/.bazeliskrc000077700000000000000000000000001513125663600245732../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/.bazelrc000066400000000000000000000020731513125663600213130ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/copy_to_directory/.bazelversion000077700000000000000000000000001513125663600255172../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/BUILD.bazel000066400000000000000000000030201513125663600215370ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory") load("@aspect_bazel_lib//lib:diff_test.bzl", "diff_test") # Test special cases of using "./**" and "./*/**" patterns in the root package copy_to_directory( name = "dir1", srcs = [ ":a", "//subpkg:b", ], include_srcs_packages = [ "./**", ], ) copy_to_directory( name = "dir1b", srcs = [ ":a", "//subpkg:b", ], ) diff_test( name = "test1", file1 = ":dir1", file2 = ":expected1", ) diff_test( name = "test1b", file1 = ":dir1b", file2 = ":expected1", ) copy_to_directory( name = "dir2", srcs = [ ":a", "//subpkg:b", ], include_srcs_packages = [ ".", ], ) copy_to_directory( name = "dir2b", srcs = [ ":a", "//subpkg:b", ], exclude_srcs_packages = [ "./*/**", ], ) diff_test( name = "test2", file1 = ":dir2", file2 = ":expected2", ) diff_test( name = "test2b", file1 = ":dir2b", file2 = ":expected2", ) copy_to_directory( name = "dir3", srcs = [ ":a", "//subpkg:b", ], include_srcs_packages = [ "./*/**", ], ) copy_to_directory( name = "dir3b", srcs = [ ":a", "//subpkg:b", ], exclude_srcs_packages = [ ".", ], ) diff_test( name = "test3", file1 = ":dir3", file2 = ":expected3", ) diff_test( name = "test3b", file1 = ":dir3b", file2 = ":expected3", ) bazel-lib-2.22.5/e2e/copy_to_directory/MODULE.bazel000066400000000000000000000003541513125663600216740ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_dep(name = "bazel_skylib", version = "1.8.1", dev_dependency = True) bazel-lib-2.22.5/e2e/copy_to_directory/WORKSPACE000066400000000000000000000022661513125663600211550ustar00rootroot00000000000000local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "register_copy_to_directory_toolchains") aspect_bazel_lib_dependencies() register_copy_to_directory_toolchains() ############################################ # rules_go is needed to consume tools from sources load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", sha256 = "90fe8fb402dee957a375f3eb8511455bd738c7ed562695f4dd117ac7d2d833b1", urls = ["https://github.com/bazelbuild/rules_go/releases/download/v0.52.0/rules_go-v0.52.0.zip"], ) http_archive( name = "gazelle", integrity = "sha256-dd8ojEsxyB61D1Hi4U9HY8t1SNquEmgXJHBkY3/Z6mI=", urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz"], ) load("@aspect_bazel_lib//:deps.bzl", "go_dependencies") go_dependencies() load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.18.3") load("@gazelle//:deps.bzl", "gazelle_dependencies") gazelle_dependencies() bazel-lib-2.22.5/e2e/copy_to_directory/WORKSPACE.bzlmod000066400000000000000000000000001513125663600224230ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/a000066400000000000000000000000011513125663600200200ustar00rootroot00000000000000abazel-lib-2.22.5/e2e/copy_to_directory/expected1/000077500000000000000000000000001513125663600215505ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/expected1/a000066400000000000000000000000011513125663600217020ustar00rootroot00000000000000abazel-lib-2.22.5/e2e/copy_to_directory/expected1/subpkg/000077500000000000000000000000001513125663600230435ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/expected1/subpkg/b000066400000000000000000000000011513125663600231760ustar00rootroot00000000000000bbazel-lib-2.22.5/e2e/copy_to_directory/expected2/000077500000000000000000000000001513125663600215515ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/expected2/a000066400000000000000000000000011513125663600217030ustar00rootroot00000000000000abazel-lib-2.22.5/e2e/copy_to_directory/expected3/000077500000000000000000000000001513125663600215525ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/expected3/subpkg/000077500000000000000000000000001513125663600230455ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/expected3/subpkg/b000066400000000000000000000000011513125663600232000ustar00rootroot00000000000000bbazel-lib-2.22.5/e2e/copy_to_directory/subpkg/000077500000000000000000000000001513125663600211615ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/copy_to_directory/subpkg/BUILD.bazel000066400000000000000000000000251513125663600230340ustar00rootroot00000000000000exports_files(["b"]) bazel-lib-2.22.5/e2e/copy_to_directory/subpkg/b000066400000000000000000000000011513125663600213140ustar00rootroot00000000000000bbazel-lib-2.22.5/e2e/coreutils/000077500000000000000000000000001513125663600161375ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/coreutils/.bazeliskrc000077700000000000000000000000001513125663600230442../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/coreutils/.bazelrc000066400000000000000000000020731513125663600175640ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/coreutils/.bazelversion000077700000000000000000000000001513125663600237702../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/coreutils/BUILD.bazel000066400000000000000000000014731513125663600200220ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") load("@aspect_bazel_lib//tools/release:hashes.bzl", "hashes") genrule( name = "ls", outs = ["ls.txt"], cmd = "$(COREUTILS_BIN) ls > $@", toolchains = ["@coreutils_toolchains//:resolved_toolchain"], ) hashes( name = "hash", src = "test.bin", ) filegroup( name = "md5", srcs = [":hash"], output_group = "md5", ) filegroup( name = "sha1", srcs = [":hash"], output_group = "sha1", ) # This tests that the "in" file to write_source_files can be a # label to an external repository target when bzlmod is enabled. write_source_files( name = "write_ls", files = { "ls.txt.expected": ":ls.txt", "sha256.txt": ":hash", "sha1.txt": ":sha1", "md5.txt": ":md5", }, ) bazel-lib-2.22.5/e2e/coreutils/MODULE.bazel000066400000000000000000000005131513125663600201420ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_lib_toolchains = use_extension("@aspect_bazel_lib//lib:extensions.bzl", "toolchains", dev_dependency = True) use_repo(bazel_lib_toolchains, "coreutils_toolchains") bazel-lib-2.22.5/e2e/coreutils/WORKSPACE000066400000000000000000000003741513125663600174240ustar00rootroot00000000000000local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "register_coreutils_toolchains") aspect_bazel_lib_dependencies() register_coreutils_toolchains() bazel-lib-2.22.5/e2e/coreutils/WORKSPACE.bzlmod000066400000000000000000000000001513125663600206740ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/coreutils/ls.txt.expected000066400000000000000000000000231513125663600211110ustar00rootroot00000000000000bazel-out external bazel-lib-2.22.5/e2e/coreutils/md5.txt000066400000000000000000000000521513125663600173620ustar00rootroot00000000000000160e389707f172f2d1333084fec4e650 test.bin bazel-lib-2.22.5/e2e/coreutils/sha1.txt000066400000000000000000000000621513125663600175320ustar00rootroot00000000000000b3dd96b0db6a12a3ae53899e8fbc04b749c980d6 test.bin bazel-lib-2.22.5/e2e/coreutils/sha256.txt000066400000000000000000000001121513125663600177020ustar00rootroot000000000000003285d399e870df47749162ab2ebfd0b727e9142925ab5f5ad221c3a42a852b08 test.bin bazel-lib-2.22.5/e2e/coreutils/test.bin000066400000000000000000000000351513125663600176060ustar00rootroot00000000000000act as if this is binary filebazel-lib-2.22.5/e2e/external_copy_to_directory/000077500000000000000000000000001513125663600215705ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/.bazelignore000066400000000000000000000000051513125663600240650ustar00rootroot00000000000000app/ bazel-lib-2.22.5/e2e/external_copy_to_directory/.bazeliskrc000077700000000000000000000000001513125663600264752../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/.bazelrc000066400000000000000000000020731513125663600232150ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/external_copy_to_directory/.bazelversion000077700000000000000000000000001513125663600274212../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/BUILD.bazel000066400000000000000000000003721513125663600234500ustar00rootroot00000000000000load("@bazel_skylib//rules:build_test.bzl", "build_test") load(":directory.bzl", "directory") directory( name = "dir", srcs = ["foo.txt"], visibility = ["//visibility:public"], ) build_test( name = "test", targets = [":dir"], ) bazel-lib-2.22.5/e2e/external_copy_to_directory/MODULE.bazel000066400000000000000000000003541513125663600235760ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_dep(name = "bazel_skylib", version = "1.8.1", dev_dependency = True) bazel-lib-2.22.5/e2e/external_copy_to_directory/WORKSPACE000066400000000000000000000021461513125663600230540ustar00rootroot00000000000000workspace(name = "external_copy_to_directory") local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies") aspect_bazel_lib_dependencies() # rules_go is needed to consume tools from sources load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", sha256 = "90fe8fb402dee957a375f3eb8511455bd738c7ed562695f4dd117ac7d2d833b1", urls = ["https://github.com/bazelbuild/rules_go/releases/download/v0.52.0/rules_go-v0.52.0.zip"], ) http_archive( name = "gazelle", integrity = "sha256-dd8ojEsxyB61D1Hi4U9HY8t1SNquEmgXJHBkY3/Z6mI=", urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz"], ) load("@aspect_bazel_lib//:deps.bzl", "go_dependencies") go_dependencies() load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.18.3") load("@gazelle//:deps.bzl", "gazelle_dependencies") gazelle_dependencies() bazel-lib-2.22.5/e2e/external_copy_to_directory/WORKSPACE.bzlmod000066400000000000000000000000001513125663600243250ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/app/000077500000000000000000000000001513125663600223505ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/app/.bazelrc000066400000000000000000000000001513125663600237610ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/app/.bazelversion000077700000000000000000000000001513125663600304142../../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/external_copy_to_directory/app/BUILD.bazel000066400000000000000000000003161513125663600242260ustar00rootroot00000000000000load("@rules_shell//shell:sh_test.bzl", "sh_test") sh_test( name = "test", srcs = ["test.sh"], data = ["@external_copy_to_directory//:dir"], deps = ["@bazel_tools//tools/bash/runfiles"], ) bazel-lib-2.22.5/e2e/external_copy_to_directory/app/WORKSPACE000066400000000000000000000022101513125663600236240ustar00rootroot00000000000000local_repository( name = "external_copy_to_directory", path = "..", ) local_repository( name = "aspect_bazel_lib", path = "../../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies") aspect_bazel_lib_dependencies() # rules_go is needed to consume tools from sources load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", sha256 = "90fe8fb402dee957a375f3eb8511455bd738c7ed562695f4dd117ac7d2d833b1", urls = ["https://github.com/bazelbuild/rules_go/releases/download/v0.52.0/rules_go-v0.52.0.zip"], ) http_archive( name = "gazelle", integrity = "sha256-dd8ojEsxyB61D1Hi4U9HY8t1SNquEmgXJHBkY3/Z6mI=", urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz"], ) load("@aspect_bazel_lib//:deps.bzl", "go_dependencies") go_dependencies() load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.18.3") load("@gazelle//:deps.bzl", "gazelle_dependencies") gazelle_dependencies() bazel-lib-2.22.5/e2e/external_copy_to_directory/app/test.sh000077500000000000000000000017021513125663600236660ustar00rootroot00000000000000# --- begin runfiles.bash initialization v2 --- # Copy-pasted from the Bazel Bash runfiles library v2. set -uo pipefail set +e f=bazel_tools/tools/bash/runfiles/runfiles.bash source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || source "$0.runfiles/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || { echo >&2 "ERROR: cannot find $f" exit 1 } f= set -e # --- end runfiles.bash initialization v2 --- # Read external directory and make sure it exists with a file. readonly DIR=$(rlocation external_copy_to_directory/dir/) readonly FILES=$(ls "${DIR}" | wc -l) if [[ ${FILES} != 1 ]]; then echo "Expected exactly 1 file under external directory, but found ${FILES}:" >&2 ls "${DIR}" >&2 exit 1 fi bazel-lib-2.22.5/e2e/external_copy_to_directory/directory.bzl000066400000000000000000000017001513125663600243030ustar00rootroot00000000000000"""Test rule executing `copy_to_directory_bin_action`.""" load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory_bin_action") def _directory_impl(ctx): dst = ctx.actions.declare_directory(ctx.attr.name) copy_to_directory_bin_action( ctx, name = ctx.attr.name, copy_to_directory_bin = ctx.executable._tool, dst = dst, files = ctx.files.srcs, verbose = True, ) return DefaultInfo(files = depset([dst])) directory = rule( implementation = _directory_impl, attrs = { "srcs": attr.label_list( mandatory = True, allow_files = True, ), "_tool": attr.label( executable = True, cfg = "exec", default = "@aspect_bazel_lib//tools/copy_to_directory", ), }, doc = """ Copies the given source files to a directory with `copy_to_directory_bin_action()`. """, ) bazel-lib-2.22.5/e2e/external_copy_to_directory/foo.txt000066400000000000000000000000041513125663600231060ustar00rootroot00000000000000foo bazel-lib-2.22.5/e2e/run_jq_symlinked_bin.sh000077500000000000000000000004331513125663600206720ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" case "$(uname -s)" in CYGWIN* | MINGW32* | MSYS* | MINGW*) bazel run $BZLMOD_FLAG @jq//:jq.exe -- --null-input .a=5 ;; *) bazel run $BZLMOD_FLAG @jq//:jq -- --null-input .a=5 ;; esac bazel-lib-2.22.5/e2e/run_yq_symlinked_bin.sh000077500000000000000000000004331513125663600207110ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" case "$(uname -s)" in CYGWIN* | MINGW32* | MSYS* | MINGW*) bazel run $BZLMOD_FLAG @yq//:yq.exe -- --null-input .a=5 ;; *) bazel run $BZLMOD_FLAG @yq//:yq -- --null-input .a=5 ;; esac bazel-lib-2.22.5/e2e/smoke/000077500000000000000000000000001513125663600152445ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/smoke/.bazelrc000066400000000000000000000022331513125663600166670ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # For testing expand_template common --workspace_status_command="echo BUILD_SCM_VERSION 1.2.3" # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/smoke/.bazelversion000077700000000000000000000000001513125663600230752../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/smoke/BUILD.bazel000066400000000000000000000066751513125663600171400ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:bats.bzl", "bats_test") load("@aspect_bazel_lib//lib:copy_directory.bzl", "copy_directory") load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory") load("@aspect_bazel_lib//lib:diff_test.bzl", "diff_test") load("@aspect_bazel_lib//lib:expand_template.bzl", "expand_template") load("@aspect_bazel_lib//lib:jq.bzl", "jq") load("@aspect_bazel_lib//lib:tar.bzl", "tar") load("@aspect_bazel_lib//lib:yq.bzl", "yq") load("@io_bazel_rules_go//go:def.bzl", "go_test") # Validate that JQ works and resolves its toolchain jq( name = "jq_case_no_sources", srcs = [], filter = ".", ) diff_test( name = "jq_test", file1 = "jq_case_no_sources", file2 = "expected_jq", ) # Validate that YQ works and resolves its toolchain yq( name = "yq_case_no_sources", srcs = [], expression = ".", ) diff_test( name = "yq_test", file1 = "yq_case_no_sources", file2 = "expected_yq", ) # Validate that copy_directory works and resolves its toolchain copy_directory( name = "copy_directory_case", src = "d", out = "d_out", verbose = True, ) diff_test( name = "copy_directory_test", file1 = "d", file2 = "copy_directory_case", ) # Validate that copy_to_directory works and resolves its toolchain copy_to_directory( name = "copy_to_directory_case", srcs = ["d"], out = "d2_out", replace_prefixes = {"d/": ""}, ) diff_test( name = "copy_to_directory_test", file1 = "d", file2 = "copy_to_directory_case", ) # Validate that expand_template works and resolves its toolchain expand_template( name = "a_tmpl_stamp", out = "a_stamp", data = ["a.tmpl"], stamp = 1, stamp_substitutions = { "{{VERSION}}": "v{{BUILD_SCM_VERSION}}", }, substitutions = { "{{VERSION}}": "v0.0.0", "{{WORKSPACE}}": "$(WORKSPACE)", }, template = "a.tmpl", ) diff_test( name = "a_stamp_test", file1 = ":a_stamp", file2 = select({ "@aspect_bazel_lib//lib:bzlmod": "a_stamp_expected_bzlmod", "//conditions:default": "a_stamp_expected", }), ) # Validate that tar works and resolves its toolchain tar( name = "tar_empty", srcs = [], mtree = [], ) bats_test( name = "bats", srcs = [ "basic.bats", ], ) copy_to_directory( name = "copy_to_directory_mtime_case", srcs = ["d"], out = "copy_to_directory_mtime_out", preserve_mtime = True, tags = ["no-remote"], ) copy_directory( name = "copy_directory_mtime_case", src = "d", out = "copy_directory_mtime_out", preserve_mtime = True, tags = ["no-remote"], ) go_test( name = "test_preserve_mtime", size = "small", srcs = ["test_preserve_mtime.go"], data = [ "d", ":copy_directory_mtime_case", ":copy_to_directory_mtime_case", ], # Note: This test is marked as manual as it is not reliable in the CI environment. The reason for is that changes # to only the modify time do not invalidate the Bazel cache. These failures can be reproduced by: # bazel clean --expunge # bazel test :test_preserve_mtime # This test should pass # touch d/1 # Update the mtime, in the CI environment this is done with the SCM integration. # bazel test :test_preserve_mtime # This test now fails tags = [ "external", "manual", "no-remote", ], deps = [ "@io_bazel_rules_go//go/tools/bazel:go_default_library", ], ) bazel-lib-2.22.5/e2e/smoke/MODULE.bazel000066400000000000000000000005251513125663600172520ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) bazel_dep(name = "bazel_skylib", version = "1.8.1", dev_dependency = True) bazel_dep(name = "rules_go", version = "0.55.0", dev_dependency = True, repo_name = "io_bazel_rules_go") bazel-lib-2.22.5/e2e/smoke/WORKSPACE000066400000000000000000000027771513125663600165420ustar00rootroot00000000000000local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "aspect_bazel_lib_register_toolchains") aspect_bazel_lib_dependencies() # Required rules_shell dependencies load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") rules_shell_dependencies() rules_shell_toolchains() aspect_bazel_lib_register_toolchains() load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@platforms//host:extension.bzl", "host_platform_repo") maybe( host_platform_repo, name = "host_platform", ) # rules_go is needed to consume tools from sources load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", sha256 = "90fe8fb402dee957a375f3eb8511455bd738c7ed562695f4dd117ac7d2d833b1", urls = ["https://github.com/bazelbuild/rules_go/releases/download/v0.52.0/rules_go-v0.52.0.zip"], ) http_archive( name = "gazelle", integrity = "sha256-dd8ojEsxyB61D1Hi4U9HY8t1SNquEmgXJHBkY3/Z6mI=", urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz"], ) load("@aspect_bazel_lib//:deps.bzl", "go_dependencies") go_dependencies() load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.18.3") load("@gazelle//:deps.bzl", "gazelle_dependencies") gazelle_dependencies() bazel-lib-2.22.5/e2e/smoke/WORKSPACE.bzlmod000066400000000000000000000000001513125663600200010ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/smoke/a.tmpl000066400000000000000000000001331513125663600163570ustar00rootroot00000000000000WORKSPACE: {{WORKSPACE}} VERSION: {{VERSION}} WORKSPACE: {{WORKSPACE}} VERSION: {{VERSION}}bazel-lib-2.22.5/e2e/smoke/a_stamp_expected000066400000000000000000000001071513125663600204720ustar00rootroot00000000000000WORKSPACE: __main__ VERSION: v1.2.3 WORKSPACE: __main__ VERSION: v1.2.3bazel-lib-2.22.5/e2e/smoke/a_stamp_expected_bzlmod000066400000000000000000000001011513125663600220330ustar00rootroot00000000000000WORKSPACE: _main VERSION: v1.2.3 WORKSPACE: _main VERSION: v1.2.3bazel-lib-2.22.5/e2e/smoke/basic.bats000066400000000000000000000001731513125663600172010ustar00rootroot00000000000000bats_load_library "bats-support" bats_load_library "bats-assert" @test 'basic' { run echo 'have' assert_output 'have' } bazel-lib-2.22.5/e2e/smoke/d/000077500000000000000000000000001513125663600154675ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/smoke/d/1000066400000000000000000000000011513125663600155410ustar00rootroot000000000000001bazel-lib-2.22.5/e2e/smoke/expected_jq000066400000000000000000000000051513125663600174550ustar00rootroot00000000000000null bazel-lib-2.22.5/e2e/smoke/expected_yq000066400000000000000000000000011513125663600174700ustar00rootroot00000000000000 bazel-lib-2.22.5/e2e/smoke/test_preserve_mtime.go000066400000000000000000000036031513125663600216620ustar00rootroot00000000000000package smoketest import ( "os" "path/filepath" "testing" "time" "github.com/bazelbuild/rules_go/go/tools/bazel" ) type runfilePath struct { // runfileDir is the directory that was provided as the bazel data dep. runfileDir string // subPaths to look for inside of the bazel tracked directory. subPaths []string } func mtime(path string) (time.Time, error) { info, err := os.Stat(path) if err != nil { return time.Time{}, err } return info.ModTime(), nil } func (r runfilePath) osPath() (string, error) { dirPath, err := bazel.Runfile(r.runfileDir) if err != nil { return "", err } parts := append([]string{dirPath}, r.subPaths...) return filepath.Join(parts...), nil } func TestPreserveMTime(t *testing.T) { cases := map[string]struct { original runfilePath copied runfilePath }{ "copy_directory": { original: runfilePath{ runfileDir: "d", subPaths: []string{"1"}, }, copied: runfilePath{ runfileDir: "copy_directory_mtime_out", subPaths: []string{"1"}, }, }, "copy_to_directory": { original: runfilePath{ runfileDir: "d", subPaths: []string{"1"}, }, copied: runfilePath{ runfileDir: "copy_to_directory_mtime_out", subPaths: []string{"d", "1"}, }, }, } for name, test := range cases { t.Run(name, func(t *testing.T) { originalPath, err := test.original.osPath() if err != nil { t.Fatal(err.Error()) } originalMTime, err := mtime(originalPath) if err != nil { t.Fatal(err.Error()) } copiedPath, err := test.copied.osPath() if err != nil { t.Fatal(err.Error()) } copiedMTime, err := mtime(copiedPath) if err != nil { t.Fatal(err.Error()) } if originalMTime != copiedMTime { t.Fatalf(`Modify times do not match for %s and %s: Original modify time: %s Copied modify time: %s`, originalPath, copiedPath, originalMTime, copiedMTime) } }) } } bazel-lib-2.22.5/e2e/write_source_files.sh000077500000000000000000000020271513125663600203620ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" function run_test { bazel run $BZLMOD_FLAG //lib/tests/write_source_files:write_dist local expected_out="lib/tests/write_source_files/dist.js" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi bazel run $BZLMOD_FLAG //lib/tests/write_source_files:write_dist_executable local expected_out="lib/tests/write_source_files/dist_executable.js" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ ! -x "$expected_out" ]; then echo "ERROR: expected $expected_out to be executable" exit 1 fi } # Run twice to make sure we can have permission to overwrite the outputs of a previous run rm -f lib/tests/write_source_files/dist.js rm -f lib/tests/write_source_files/dist_executable.js run_test run_test echo "All tests passed" bazel-lib-2.22.5/e2e/write_source_files/000077500000000000000000000000001513125663600200225ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/write_source_files/.bazeliskrc000077700000000000000000000000001513125663600247272../../.bazeliskrcustar00rootroot00000000000000bazel-lib-2.22.5/e2e/write_source_files/.bazelrc000066400000000000000000000020731513125663600214470ustar00rootroot00000000000000# Import Aspect bazelrc presets try-import %workspace%/../../.aspect/bazelrc/local/bazel7.bazelrc import %workspace%/../../.aspect/bazelrc/convenience.bazelrc import %workspace%/../../.aspect/bazelrc/correctness.bazelrc import %workspace%/../../.aspect/bazelrc/debug.bazelrc import %workspace%/../../.aspect/bazelrc/javascript.bazelrc import %workspace%/../../.aspect/bazelrc/performance.bazelrc ### YOUR PROJECT SPECIFIC OPTIONS GO HERE ### # Point tools such as coursier (used in rules_jvm_external) to Bazel's downloaded JDK # suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 common --repo_env=JAVA_HOME=../bazel_tools/jdk # Load any settings & overrides specific to the current user from `.aspect/bazelrc/user.bazelrc`. # This file should appear in `.gitignore` so that settings are not shared with team members. This # should be last statement in this config so the user configuration is able to overwrite flags from # this file. See https://bazel.build/configure/best-practices#bazelrc-file. try-import %workspace%/../../.aspect/bazelrc/user.bazelrc bazel-lib-2.22.5/e2e/write_source_files/.bazelversion000077700000000000000000000000001513125663600256532../../.bazelversionustar00rootroot00000000000000bazel-lib-2.22.5/e2e/write_source_files/BUILD.bazel000066400000000000000000000005011513125663600216740ustar00rootroot00000000000000load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") # This tests that the "in" file to write_source_files can be a # label to an external repository target when bzlmod is enabled. write_source_files( name = "write_external", files = { "foobar.txt": "@test//:foobar.txt", }, ) bazel-lib-2.22.5/e2e/write_source_files/MODULE.bazel000066400000000000000000000004211513125663600220230ustar00rootroot00000000000000bazel_dep(name = "aspect_bazel_lib", version = "0.0.0", dev_dependency = True) local_path_override( module_name = "aspect_bazel_lib", path = "../..", ) test_ext = use_extension("//:test_extension.bzl", "test_ext", dev_dependency = True) use_repo(test_ext, "test") bazel-lib-2.22.5/e2e/write_source_files/WORKSPACE000066400000000000000000000003761513125663600213110ustar00rootroot00000000000000local_repository( name = "aspect_bazel_lib", path = "../..", ) load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies") aspect_bazel_lib_dependencies() load(":test_extension.bzl", "test_repo") test_repo(name = "test") bazel-lib-2.22.5/e2e/write_source_files/WORKSPACE.bzlmod000066400000000000000000000000001513125663600225570ustar00rootroot00000000000000bazel-lib-2.22.5/e2e/write_source_files/foobar.txt000066400000000000000000000000071513125663600220300ustar00rootroot00000000000000foobar bazel-lib-2.22.5/e2e/write_source_files/test_extension.bzl000066400000000000000000000007121513125663600236060ustar00rootroot00000000000000"Test module extension to create a test repository" def _test_repo_impl(rctx): rctx.file("BUILD.bazel", """\ exports_files(["foobar.txt"], visibility = ["//visibility:public"]) """, executable = False) rctx.file("foobar.txt", "foobar\n") test_repo = repository_rule( local = True, implementation = _test_repo_impl, ) def _test_ext_impl(_): test_repo(name = "test") test_ext = module_extension( implementation = _test_ext_impl, ) bazel-lib-2.22.5/e2e/write_source_files_root.sh000077500000000000000000000015731513125663600214320ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" function run_test { bazel run $BZLMOD_FLAG //:write_source_file_root-test local expected_out="test-out/dist/write_source_file_root-test/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi expected_out="test-out/dist/write_source_file_root-test_b/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi } # Run twice to make sure we can have permission to overwrite the outputs of a previous run rm -Rf test-out run_test run_test echo "All tests passed" bazel-lib-2.22.5/e2e/write_source_files_subdir.sh000077500000000000000000000021131513125663600217260ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" function run_test { bazel run $BZLMOD_FLAG //lib/tests/write_source_files:write_subdir local expected_out="lib/tests/write_source_files/subdir_test/a/b/c/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi bazel run $BZLMOD_FLAG //lib/tests/write_source_files:write_subdir_executable local expected_out="lib/tests/write_source_files/subdir_executable_test/a/b/c/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ ! -x "$expected_out" ]; then echo "ERROR: expected $expected_out to be executable" exit 1 fi } # Run twice to make sure we can have permission to overwrite the outputs of a previous run rm -Rf lib/tests/write_source_files/subdir_test rm -Rf lib/tests/write_source_files/subdir_executable_test run_test run_test echo "All tests passed" bazel-lib-2.22.5/e2e/write_source_files_symlinks.sh000077500000000000000000000023301513125663600223100ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail BZLMOD_FLAG="${BZLMOD_FLAG:-}" function run_test { bazel run $BZLMOD_FLAG //lib/tests/write_source_files:write_symlinks local expected_out="lib/tests/write_source_files/symlink_test/a/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi if [ -L "$expected_out" ]; then echo "ERROR: expected $expected_out to not be a symlink" exit 1 fi local expected_out="lib/tests/write_source_files/symlink_test/b/test.txt" if [ ! -e "$expected_out" ]; then echo "ERROR: expected $expected_out to exist" exit 1 fi if [ -x "$expected_out" ]; then echo "ERROR: expected $expected_out to not be executable" exit 1 fi if [ -L "$expected_out" ]; then echo "ERROR: expected $expected_out to not be a symlink" exit 1 fi } # Run twice to make sure we can have permission to overwrite the outputs of a previous run rm -f lib/tests/write_source_files/symlink_test/a/test.txt rm -f lib/tests/write_source_files/symlink_test/b/test.txt run_test run_test echo "All tests passed" bazel-lib-2.22.5/go.mod000066400000000000000000000003421513125663600145600ustar00rootroot00000000000000module github.com/bazel-contrib/bazel-lib go 1.24.6 require ( github.com/bazelbuild/rules_go v0.55.0 github.com/bmatcuk/doublestar/v4 v4.7.1 golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 golang.org/x/sys v0.30.0 ) bazel-lib-2.22.5/go.sum000066400000000000000000000013241513125663600146060ustar00rootroot00000000000000github.com/bazelbuild/rules_go v0.55.0 h1:S8X/b/Oygw/Dtv7NuyW7ht0QwdynMEdXQqYigX5A1KY= github.com/bazelbuild/rules_go v0.55.0/go.mod h1:T90Gpyq4HDFlsrvtQa2CBdHNJ2P4rAu/uUTmQbanzf0= github.com/bmatcuk/doublestar/v4 v4.7.1 h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0CXv75Q= github.com/bmatcuk/doublestar/v4 v4.7.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA= golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= bazel-lib-2.22.5/lib/000077500000000000000000000000001513125663600142215ustar00rootroot00000000000000bazel-lib-2.22.5/lib/BUILD.bazel000066400000000000000000000153551513125663600161100ustar00rootroot00000000000000load("@aspect_bazel_lib//:bzl_library.bzl", "bzl_library") load("@bazel_skylib//rules:common_settings.bzl", "bool_flag") load("//lib:utils.bzl", "is_bzlmod_enabled") load("//lib/private:stamping.bzl", "stamp_build_setting") # Ensure that users building their own rules can dep on our bzl_library targets for their stardoc package(default_visibility = ["//visibility:public"]) exports_files( glob(["*.bzl"]), visibility = ["//visibility:public"], ) # Macro that creates targets enabling the use of `--stamp` in Starlark rules stamp_build_setting(name = "stamp") # Add a config indicating that bzlmod is enabled so that we can use select() # to skip bzlmod-incompatible targets. config_setting( name = "bzlmod", flag_values = { ":flag_bzlmod": "true", }, ) bool_flag( name = "flag_bzlmod", build_setting_default = True if is_bzlmod_enabled() else False, ) # TODO(3.0): change default to True. bool_flag( name = "tar_compute_unused_inputs", build_setting_default = False, ) config_setting( name = "enable_runfiles", values = {"enable_runfiles": "true"}, ) toolchain_type( name = "jq_toolchain_type", ) toolchain_type( name = "yq_toolchain_type", ) alias( name = "copy_directory_toolchain_type", actual = "@bazel_lib//lib:copy_directory_toolchain_type", ) alias( name = "copy_to_directory_toolchain_type", actual = "@bazel_lib//lib:copy_to_directory_toolchain_type", ) alias( name = "coreutils_toolchain_type", actual = "@bazel_lib//lib:coreutils_toolchain_type", ) alias( name = "expand_template_toolchain_type", actual = "@bazel_lib//lib:expand_template_toolchain_type", ) # TODO(3.0): remove alias( name = "tar_toolchain_type", actual = "@tar.bzl//tar/toolchain:type", ) toolchain_type( name = "zstd_toolchain_type", ) toolchain_type( name = "bats_toolchain_type", ) bzl_library( name = "expand_make_vars", srcs = ["expand_make_vars.bzl"], deps = [ "//lib/private:expand_locations", "//lib/private:expand_variables", ], ) bzl_library( name = "expand_template", srcs = ["expand_template.bzl"], deps = [ "//lib/private:expand_template", "@bazel_skylib//lib:types", "@bazel_skylib//rules:write_file", ], ) bzl_library( name = "params_file", srcs = ["params_file.bzl"], deps = ["//lib/private:params_file"], ) bzl_library( name = "paths", srcs = ["paths.bzl"], deps = ["//lib/private:paths"], ) bzl_library( name = "utils", srcs = ["utils.bzl"], deps = ["//lib/private:utils"], ) bzl_library( name = "tar", srcs = ["tar.bzl"], deps = [ "@tar.bzl//tar:mtree", "@tar.bzl//tar:tar", ], ) bzl_library( name = "jq", srcs = ["jq.bzl"], visibility = ["//visibility:public"], deps = [ "@jq.bzl//jq", ], ) bzl_library( name = "directory_path", srcs = ["directory_path.bzl"], deps = ["//lib/private:directory_path"], ) bzl_library( name = "output_files", srcs = ["output_files.bzl"], deps = ["//lib/private:output_files"], ) bzl_library( name = "copy_file", srcs = ["copy_file.bzl"], deps = ["@bazel_lib//lib:copy_file"], ) bzl_library( name = "copy_directory", srcs = ["copy_directory.bzl"], deps = ["//lib/private:copy_directory"], ) bzl_library( name = "copy_to_directory", srcs = ["copy_to_directory.bzl"], deps = ["//lib/private:copy_to_directory"], ) bzl_library( name = "copy_to_bin", srcs = ["copy_to_bin.bzl"], deps = [ ":copy_file", "@bazel_lib//lib:copy_to_bin", ], ) #keep bzl_library( name = "diff_test", srcs = ["diff_test.bzl"], deps = ["//lib/private:diff_test"], ) bzl_library( name = "write_source_files", srcs = ["write_source_files.bzl"], deps = [ ":diff_test", ":utils", # "//lib/private:fail_with_message_test", "//lib/private:write_source_file", ], ) bzl_library( name = "run_binary", srcs = ["run_binary.bzl"], deps = ["//lib/private:run_binary"], ) bzl_library( name = "repo_utils", srcs = ["repo_utils.bzl"], deps = [ "//lib/private:patch", "//lib/private:repo_utils", ], ) bzl_library( name = "yq", srcs = ["yq.bzl"], deps = ["@yq.bzl//yq"], ) bzl_library( name = "glob_match", srcs = ["glob_match.bzl"], deps = ["//lib/private:glob_match"], ) bzl_library( name = "host_repo", srcs = ["host_repo.bzl"], deps = [ "//lib/private:host_repo", "@bazel_skylib//lib:versions", ], ) bzl_library( name = "stamping", srcs = ["stamping.bzl"], deps = ["//lib/private:stamping"], ) bzl_library( name = "testing", srcs = ["testing.bzl"], deps = [ ":diff_test", ":jq", ":params_file", ":utils", "@bazel_skylib//lib:types", "@bazel_skylib//rules:write_file", "@rules_shell//shell:rules_bzl", ], ) bzl_library( name = "extensions", srcs = ["extensions.bzl"], deps = [ "//lib:repositories", "//lib/private:extension_utils", "//lib/private:host_repo", "@bazel_features//:features", ], ) bzl_library( name = "repositories", srcs = ["repositories.bzl"], deps = [ ":utils", "//lib/private:bats_toolchain", "//lib/private:copy_directory_toolchain", "//lib/private:copy_to_directory_toolchain", "//lib/private:coreutils_toolchain", "//lib/private:expand_template_toolchain", "//lib/private:jq_toolchain", "//lib/private:source_toolchains_repo", "//lib/private:tar_toolchain", "//lib/private:yq_toolchain", "//lib/private:zstd_toolchain", ], ) bzl_library( name = "transitions", srcs = ["transitions.bzl"], deps = [ "@bazel_skylib//lib:paths", ], ) bzl_library( name = "platform_utils", srcs = ["platform_utils.bzl"], deps = ["//lib/private:platform_utils"], ) bzl_library( name = "base64", srcs = ["base64.bzl"], deps = ["//lib/private:base64"], ) bzl_library( name = "bazelrc_presets", srcs = ["bazelrc_presets.bzl"], deps = [":write_source_files"], ) bzl_library( name = "strings", srcs = ["strings.bzl"], deps = ["//lib/private:strings"], ) bzl_library( name = "lists", srcs = ["lists.bzl"], deps = ["//lib/private:lists"], ) bzl_library( name = "docs", srcs = ["docs.bzl"], deps = ["//lib/private:docs"], ) bzl_library( name = "windows_utils", srcs = ["windows_utils.bzl"], deps = ["//lib/private:paths"], ) bzl_library( name = "bats", srcs = ["bats.bzl"], deps = ["//lib/private:bats"], ) bzl_library( name = "resource_sets", srcs = ["resource_sets.bzl"], ) bazel-lib-2.22.5/lib/base64.bzl000066400000000000000000000003751513125663600160230ustar00rootroot00000000000000"""Utility functions for encoding and decoding strings with base64. See https://en.wikipedia.org/wiki/Base64. """ load("//lib/private:base64.bzl", _decode = "decode", _encode = "encode") base64 = struct( decode = _decode, encode = _encode, ) bazel-lib-2.22.5/lib/bats.bzl000066400000000000000000000010121513125663600156550ustar00rootroot00000000000000"""A test rule that invokes the [Bash Automated Testing System](https://github.com/bats-core/bats-core). For example, a `bats_test` target containing a single .bat and basic configuration: ```starlark bats_test( name = "my_test", size = "small", srcs = [ "my_test.bats", ], data = [ "data.bin", ], env = { "DATA_PATH": "$(location :data.bin)", }, args = ["--timing"], ) ``` """ load("//lib/private:bats.bzl", _bats_test = "bats_test") bats_test = _bats_test bazel-lib-2.22.5/lib/bazelrc_presets.bzl000066400000000000000000000022551513125663600201250ustar00rootroot00000000000000"""'Presets' for bazelrc See https://docs.aspect.build/guides/bazelrc """ load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") ALL_PRESETS = [ "bazel6", "bazel7", "ci", "convenience", "correctness", "debug", "java", "javascript", "performance", ] def write_aspect_bazelrc_presets( name, presets = ALL_PRESETS, **kwargs): """Keeps your vendored copy of Aspect recommended `.bazelrc` presets up-to-date. This macro uses a [write_source_files](https://docs.aspect.build/rules/aspect_bazel_lib/docs/write_source_files) rule under the hood to keep your presets up-to-date. By default all presets are vendored but this list can be customized using the `presets` attribute. Args: name: a unique name for this target presets: a list of preset names to keep up-to-date **kwargs: Additional arguments to pass to `write_source_files` """ files = {} for p in presets: files["{}.bazelrc".format(p)] = "@aspect_bazel_lib//.aspect/bazelrc:{}.bazelrc".format(p) write_source_files( name = name, files = files, **kwargs ) bazel-lib-2.22.5/lib/copy_directory.bzl000066400000000000000000000021251513125663600177700ustar00rootroot00000000000000"""A rule that copies a directory to another place. The rule uses a precompiled binary to perform the copy, so no shell is required. ## Preserving modification times `copy_directory` and `copy_to_directory` have a `preserve_mtime` attribute, however there are two caveats to consider when using this feature: 1. Remote Execution / Caching: These layers will reset the modify time and are incompatible with this feature. To avoid these failures the [no-remote tag](https://bazel.build/reference/be/common-definitions) can be added. 2. Caching: Changes to only the modified time will not re-trigger cached actions. This can be worked around by using a clean build when these types of changes occur. For tests the [external tag](https://bazel.build/reference/be/common-definitions) can be used but this will result in tests never being cached. """ load( "//lib/private:copy_directory.bzl", _copy_directory = "copy_directory", _copy_directory_bin_action = "copy_directory_bin_action", ) copy_directory = _copy_directory copy_directory_bin_action = _copy_directory_bin_action bazel-lib-2.22.5/lib/copy_file.bzl000066400000000000000000000027701513125663600167110ustar00rootroot00000000000000# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # LOCAL MODIFICATIONS # this has a PR patched in on top of the original # https://github.com/bazelbuild/bazel-skylib/blob/7b859037a673db6f606661323e74c5d4751595e6/rules/private/copy_file_private.bzl # https://github.com/bazelbuild/bazel-skylib/pull/324 """A rule that copies a file to another place. `native.genrule()` is sometimes used to copy files (often wishing to rename them). The `copy_file` rule does this with a simpler interface than genrule. This rule uses a hermetic uutils/coreutils `cp` binary, no shell is required. This fork of bazel-skylib's copy_file adds `DirectoryPathInfo` support and allows multiple `copy_file` rules in the same package. """ load( "@bazel_lib//lib:copy_file.bzl", _copy_file = "copy_file", _copy_file_action = "copy_file_action", ) copy_file = _copy_file copy_file_action = _copy_file_action COPY_FILE_TOOLCHAINS = ["@aspect_bazel_lib//lib:coreutils_toolchain_type"] bazel-lib-2.22.5/lib/copy_to_bin.bzl000066400000000000000000000017501513125663600172410ustar00rootroot00000000000000"""A rule that copies source files to the output tree. This rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe command (fc.exe) on Windows (no Bash is required). Originally authored in rules_nodejs https://github.com/bazel-contrib/rules_nodejs/blob/8b5d27400db51e7027fe95ae413eeabea4856f8e/internal/common/copy_to_bin.bzl """ load( "@bazel_lib//lib:copy_to_bin.bzl", _copy_file_to_bin_action = "copy_file_to_bin_action", _copy_files_to_bin_actions = "copy_files_to_bin_actions", _copy_to_bin = "copy_to_bin", ) # bazel-lib 3.x COPY_FILE_TO_BIN_TOOLCHAINS references COPY_FILE_TOOLCHAINS. # bazel-lib 2.x COPY_FILE_[TO_BIN_]TOOLCHAINS must only expose the @aspect_bazel_lib toolchain # names, which may alias to bazel-lib 3.x load(":copy_file.bzl", "COPY_FILE_TOOLCHAINS") copy_file_to_bin_action = _copy_file_to_bin_action copy_files_to_bin_actions = _copy_files_to_bin_actions copy_to_bin = _copy_to_bin COPY_FILE_TO_BIN_TOOLCHAINS = COPY_FILE_TOOLCHAINS bazel-lib-2.22.5/lib/copy_to_directory.bzl000066400000000000000000000012401513125663600204670ustar00rootroot00000000000000"""Copy files and directories to an output directory. """ load( "//lib/private:copy_to_directory.bzl", _copy_to_directory_bin_action = "copy_to_directory_bin_action", _copy_to_directory_lib = "copy_to_directory_lib", ) # export the starlark library as a public API copy_to_directory_lib = _copy_to_directory_lib copy_to_directory_bin_action = _copy_to_directory_bin_action copy_to_directory = rule( doc = _copy_to_directory_lib.doc, implementation = _copy_to_directory_lib.impl, provides = _copy_to_directory_lib.provides, attrs = _copy_to_directory_lib.attrs, toolchains = ["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"], ) bazel-lib-2.22.5/lib/diff_test.bzl000066400000000000000000000021441513125663600167020ustar00rootroot00000000000000# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A test rule that compares two binary files or two directories. Similar to `bazel-skylib`'s [`diff_test`](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/diff_test.bzl) but also supports comparing directories. The rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe command (fc.exe) on Windows (no Bash is required). See also: [rules_diff](https://gitlab.arm.com/bazel/rules_diff) """ load( "//lib/private:diff_test.bzl", _diff_test = "diff_test", ) diff_test = _diff_test bazel-lib-2.22.5/lib/directory_path.bzl000066400000000000000000000010141513125663600177460ustar00rootroot00000000000000"""Rule and corresponding provider that joins a label pointing to a TreeArtifact with a path nested within that directory """ load( "//lib/private:directory_path.bzl", _DirectoryPathInfo = "DirectoryPathInfo", _directory_path = "directory_path", _make_directory_path = "make_directory_path", _make_directory_paths = "make_directory_paths", ) directory_path = _directory_path make_directory_path = _make_directory_path make_directory_paths = _make_directory_paths DirectoryPathInfo = _DirectoryPathInfo bazel-lib-2.22.5/lib/docs.bzl000066400000000000000000000003541513125663600156640ustar00rootroot00000000000000"Public API for docs helpers" load( "//lib/private:docs.bzl", _stardoc_with_diff_test = "stardoc_with_diff_test", _update_docs = "update_docs", ) stardoc_with_diff_test = _stardoc_with_diff_test update_docs = _update_docs bazel-lib-2.22.5/lib/expand_make_vars.bzl000066400000000000000000000005011513125663600202350ustar00rootroot00000000000000"Public API for expanding variables" # buildifier: disable=deprecated-function load("//lib/private:expand_locations.bzl", _expand_locations = "expand_locations") load("//lib/private:expand_variables.bzl", _expand_variables = "expand_variables") expand_locations = _expand_locations expand_variables = _expand_variables bazel-lib-2.22.5/lib/expand_template.bzl000066400000000000000000000017111513125663600201040ustar00rootroot00000000000000"Public API for expand template" load("@bazel_skylib//lib:types.bzl", "types") load("@bazel_skylib//rules:write_file.bzl", "write_file") load("//lib/private:expand_template.bzl", _expand_template = "expand_template") expand_template_rule = _expand_template def expand_template(name, template, **kwargs): """Wrapper macro for `expand_template_rule`. Args: name: name of resulting rule template: the label of a template file, or a list of strings which are lines representing the content of the template. **kwargs: other named parameters to `expand_template_rule`. """ if types.is_list(template): write_target = "{}_tmpl".format(name) write_file( name = write_target, out = "{}.txt".format(write_target), content = template, ) template = write_target _expand_template( name = name, template = template, **kwargs ) bazel-lib-2.22.5/lib/extensions.bzl000066400000000000000000000132601513125663600171330ustar00rootroot00000000000000"Module extensions for use with bzlmod" load( "@aspect_bazel_lib//lib:repositories.bzl", "DEFAULT_BATS_CORE_VERSION", "DEFAULT_BATS_REPOSITORY", "DEFAULT_COPY_DIRECTORY_REPOSITORY", "DEFAULT_COPY_TO_DIRECTORY_REPOSITORY", "DEFAULT_COREUTILS_REPOSITORY", "DEFAULT_COREUTILS_VERSION", "DEFAULT_EXPAND_TEMPLATE_REPOSITORY", "DEFAULT_JQ_REPOSITORY", "DEFAULT_JQ_VERSION", "DEFAULT_TAR_REPOSITORY", "DEFAULT_YQ_REPOSITORY", "DEFAULT_YQ_VERSION", "DEFAULT_ZSTD_REPOSITORY", "register_bats_toolchains", "register_copy_directory_toolchains", "register_copy_to_directory_toolchains", "register_coreutils_toolchains", "register_expand_template_toolchains", "register_jq_toolchains", "register_tar_toolchains", "register_yq_toolchains", "register_zstd_toolchains", ) load("@bazel_features//:features.bzl", "bazel_features") load("//lib/private:extension_utils.bzl", "extension_utils") load("//lib/private:host_repo.bzl", "host_repo") def _host_extension_impl(mctx): create_host_repo = False for module in mctx.modules: if len(module.tags.host) > 0: create_host_repo = True if create_host_repo: host_repo(name = "aspect_bazel_lib_host") host = module_extension( implementation = _host_extension_impl, tag_classes = { "host": tag_class(attrs = {}), }, ) def _toolchains_extension_impl(mctx): extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.copy_directory, toolchain_name = "copy_directory", toolchain_repos_fn = lambda name, version: register_copy_directory_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.copy_to_directory, toolchain_name = "copy_to_directory", toolchain_repos_fn = lambda name, version: register_copy_to_directory_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.jq, toolchain_name = "jq", toolchain_repos_fn = lambda name, version: register_jq_toolchains(name = name, version = version, register = False), ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.yq, toolchain_name = "yq", toolchain_repos_fn = lambda name, version: register_yq_toolchains(name = name, version = version, register = False), ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.coreutils, toolchain_name = "coreutils", toolchain_repos_fn = lambda name, version: register_coreutils_toolchains(name = name, version = version, register = False), ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.tar, toolchain_name = "tar", default_repository = DEFAULT_TAR_REPOSITORY, toolchain_repos_fn = lambda name, version: register_tar_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.zstd, toolchain_name = "zstd", default_repository = DEFAULT_ZSTD_REPOSITORY, toolchain_repos_fn = lambda name, version: register_zstd_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.expand_template, toolchain_name = "expand_template", toolchain_repos_fn = lambda name, version: register_expand_template_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) extension_utils.toolchain_repos_bfs( mctx = mctx, get_tag_fn = lambda tags: tags.bats, toolchain_name = "bats", default_repository = DEFAULT_BATS_REPOSITORY, toolchain_repos_fn = lambda name, version: register_bats_toolchains(name = name, core_version = version, register = False), get_version_fn = lambda attr: attr.core_version, ) if bazel_features.external_deps.extension_metadata_has_reproducible: return mctx.extension_metadata(reproducible = True) return mctx.extension_metadata() toolchains = module_extension( implementation = _toolchains_extension_impl, tag_classes = { "copy_directory": tag_class(attrs = {"name": attr.string(default = DEFAULT_COPY_DIRECTORY_REPOSITORY)}), "copy_to_directory": tag_class(attrs = {"name": attr.string(default = DEFAULT_COPY_TO_DIRECTORY_REPOSITORY)}), "jq": tag_class(attrs = {"name": attr.string(default = DEFAULT_JQ_REPOSITORY), "version": attr.string(default = DEFAULT_JQ_VERSION)}), "yq": tag_class(attrs = {"name": attr.string(default = DEFAULT_YQ_REPOSITORY), "version": attr.string(default = DEFAULT_YQ_VERSION)}), "coreutils": tag_class(attrs = {"name": attr.string(default = DEFAULT_COREUTILS_REPOSITORY), "version": attr.string(default = DEFAULT_COREUTILS_VERSION)}), "tar": tag_class(attrs = {"name": attr.string(default = DEFAULT_TAR_REPOSITORY)}), "zstd": tag_class(attrs = {"name": attr.string(default = DEFAULT_ZSTD_REPOSITORY)}), "expand_template": tag_class(attrs = {"name": attr.string(default = DEFAULT_EXPAND_TEMPLATE_REPOSITORY)}), "bats": tag_class(attrs = { "name": attr.string(default = DEFAULT_BATS_REPOSITORY), "core_version": attr.string(default = DEFAULT_BATS_CORE_VERSION), }), }, ) bazel-lib-2.22.5/lib/glob_match.bzl000066400000000000000000000002221513125663600170250ustar00rootroot00000000000000"Public API" load("//lib/private:glob_match.bzl", _glob_match = "glob_match", _is_glob = "is_glob") glob_match = _glob_match is_glob = _is_glob bazel-lib-2.22.5/lib/host_repo.bzl000066400000000000000000000001441513125663600167330ustar00rootroot00000000000000"Public API" load("//lib/private:host_repo.bzl", _host_repo = "host_repo") host_repo = _host_repo bazel-lib-2.22.5/lib/jq.bzl000066400000000000000000000002371513125663600153460ustar00rootroot00000000000000""" Re-export of https://registry.bazel.build/modules/jq.bzl to avoid breaking change. TODO(3.0): delete """ load("@jq.bzl//jq:jq.bzl", _jq = "jq") jq = _jq bazel-lib-2.22.5/lib/lists.bzl000066400000000000000000000004601513125663600160700ustar00rootroot00000000000000"Functions for lists" load("//lib/private:lists.bzl", _every = "every", _filter = "filter", _find = "find", _map = "map", _once = "once", _pick = "pick", _some = "some", _unique = "unique") every = _every filter = _filter find = _find map = _map once = _once pick = _pick some = _some unique = _unique bazel-lib-2.22.5/lib/output_files.bzl000066400000000000000000000006621513125663600174600ustar00rootroot00000000000000"""A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo. See also [select_file](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/select_file_doc.md) from bazel-skylib. """ load( "//lib/private:output_files.bzl", _make_output_files = "make_output_files", _output_files = "output_files", ) output_files = _output_files make_output_files = _make_output_files bazel-lib-2.22.5/lib/params_file.bzl000066400000000000000000000047111513125663600172170ustar00rootroot00000000000000"params_file public API" load("//lib/private:params_file.bzl", _params_file = "params_file") def params_file( name, out, args = [], data = [], newline = "auto", **kwargs): """Generates a UTF-8 encoded params file from a list of arguments. Handles variable substitutions for args. Args: name: Name of the rule. out: Path of the output file, relative to this package. args: Arguments to concatenate into a params file. - Subject to 'Make variable' substitution. See https://docs.bazel.build/versions/main/be/make-variables.html. - Subject to predefined source/output path variables substitutions. The predefined variables `execpath`, `execpaths`, `rootpath`, `rootpaths`, `location`, and `locations` take label parameters (e.g. `$(execpath //foo:bar)`) and substitute the file paths denoted by that label. See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_label_variables for more info. NB: This $(location) substitution returns the manifest file path which differs from the `*_binary` & `*_test` args and genrule bazel substitutions. This will be fixed in a future major release. See docs string of `expand_location_into_runfiles` macro in `internal/common/expand_into_runfiles.bzl` for more info. - Subject to predefined variables & custom variable substitutions. Predefined "Make" variables such as `$(COMPILATION_MODE)` and `$(TARGET_CPU)` are expanded. See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_variables. Custom variables are also expanded including variables set through the Bazel CLI with `--define=SOME_VAR=SOME_VALUE`. See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables. Predefined genrule variables are not supported in this context. data: Data for `$(location)` expansions in args. newline: Line endings to use. One of [`"auto"`, `"unix"`, `"windows"`]. - `"auto"` for platform-determined - `"unix"` for LF - `"windows"` for CRLF **kwargs: undocumented named arguments """ _params_file( name = name, out = out, args = args, data = data, newline = newline or "auto", **kwargs ) bazel-lib-2.22.5/lib/paths.bzl000066400000000000000000000026061513125663600160550ustar00rootroot00000000000000"Utilities for working with file paths." load("//lib/private:paths.bzl", "paths") relative_file = paths.relative_file to_output_relative_path = paths.to_output_relative_path to_repository_relative_path = paths.to_repository_relative_path to_rlocation_path = paths.to_rlocation_path # Bash helper function for looking up runfiles. # See windows_utils.bzl for the cmd.exe equivalent. # Vendored from # https://github.com/bazelbuild/bazel/blob/master/tools/bash/runfiles/runfiles.bash BASH_RLOCATION_FUNCTION = r""" # --- begin runfiles.bash initialization v3 --- # Copy-pasted from the Bazel Bash runfiles library v3. # https://github.com/bazelbuild/bazel/blob/master/tools/bash/runfiles/runfiles.bash set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \ source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \ source "$0.runfiles/$f" 2>/dev/null || \ source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ { echo>&2 "ERROR: runfiles.bash initializer cannot find $f. An executable rule may have forgotten to expose it in the runfiles, or the binary may require RUNFILES_DIR to be set."; exit 1; }; f=; set -e # --- end runfiles.bash initialization v3 --- """ bazel-lib-2.22.5/lib/platform_utils.bzl000066400000000000000000000001751513125663600200010ustar00rootroot00000000000000"Public API" load("//lib/private:platform_utils.bzl", _platform_utils = "platform_utils") platform_utils = _platform_utils bazel-lib-2.22.5/lib/private/000077500000000000000000000000001513125663600156735ustar00rootroot00000000000000bazel-lib-2.22.5/lib/private/BUILD.bazel000066400000000000000000000155051513125663600175570ustar00rootroot00000000000000load("@aspect_bazel_lib//:bzl_library.bzl", "bzl_library") load("//lib:utils.bzl", "is_bazel_7_or_greater") load(":utf8_environment.bzl", "utf8_environment") exports_files( [ "diff_test_tmpl.sh", "diff_test_tmpl.bat", ], visibility = ["//visibility:public"], ) exports_files( glob(["*.bzl"]), visibility = ["//lib/private/docs:__pkg__"], ) utf8_environment( name = "utf8_environment", visibility = ["//visibility:public"], ) bzl_library( name = "base64", srcs = ["base64.bzl"], visibility = ["//lib:__subpackages__"], deps = [":strings"], ) bzl_library( name = "copy_directory", srcs = ["copy_directory.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":platform_utils", "@bazel_lib//lib:copy_directory", ], ) bzl_library( name = "copy_directory_toolchain", srcs = ["copy_directory_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "//tools:integrity", "//tools:version", ], ) bzl_library( name = "copy_to_directory", srcs = ["copy_to_directory.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":directory_path", "@bazel_lib//lib:copy_to_directory", "@bazel_skylib//lib:paths", ], ) bzl_library( name = "copy_to_directory_toolchain", srcs = ["copy_to_directory_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "//tools:integrity", "//tools:version", ], ) bzl_library( name = "directory_path", srcs = ["directory_path.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "//lib:utils", "@bazel_lib//lib:directory_path", ], ) #keep bzl_library( name = "diff_test", srcs = ["diff_test.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":directory_path", "//lib:utils", "@bazel_skylib//lib:shell", "@bazel_skylib//lib:types", "@bazel_skylib//rules:write_file", ], ) bzl_library( name = "docs", srcs = ["docs.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "//lib:write_source_files", "@stardoc//stardoc:stardoc_lib", #keep ], ) bzl_library( name = "expand_template", srcs = ["expand_template.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":expand_variables", "//lib:stamping", "@bazel_skylib//lib:dicts", ], ) bzl_library( name = "expand_template_toolchain", srcs = ["expand_template_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "//tools:integrity", "//tools:version", ], ) bzl_library( name = "expand_variables", srcs = ["expand_variables.bzl"], visibility = ["//lib:__subpackages__"], deps = ["@bazel_skylib//lib:paths"], ) bzl_library( name = "host_repo", srcs = ["host_repo.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":repo_utils", "@bazel_skylib//lib:versions", ], ) bzl_library( name = "jq_toolchain", srcs = ["jq_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [":repo_utils"], ) bzl_library( name = "output_files", srcs = ["output_files.bzl"], visibility = ["//lib:__subpackages__"], deps = ["//lib:utils"], ) bzl_library( name = "params_file", srcs = ["params_file.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":expand_variables", ":strings", ], ) bzl_library( name = "patch", srcs = ["patch.bzl"], visibility = ["//lib:__subpackages__"], deps = [":repo_utils"], ) bzl_library( name = "paths", srcs = ["paths.bzl"], visibility = ["//lib:__subpackages__"], deps = ["@bazel_skylib//lib:paths"], ) bzl_library( name = "run_binary", srcs = ["run_binary.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":expand_variables", ":strings", "//lib:resource_sets", "//lib:stamping", "@bazel_skylib//lib:dicts", ], ) bzl_library( name = "utils", srcs = ["utils.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "@bazel_tools//tools/build_defs/repo:http.bzl", "@bazel_tools//tools/build_defs/repo:utils.bzl", ] + (["@bazel_tools//tools/build_defs/repo:cache.bzl"] if is_bazel_7_or_greater() else []), ) # keep bzl_library( name = "fail_with_message_test", srcs = ["fail_with_message_test.bzl"], ) bzl_library( name = "write_source_file", srcs = ["write_source_file.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":diff_test", ":directory_path", ":fail_with_message_test", ":utils", ], ) bzl_library( name = "yq_toolchain", srcs = ["yq_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [":repo_utils"], ) bzl_library( name = "platform_utils", srcs = [ "platform_utils.bzl", "@host_platform//:constraints.bzl", # keep "@platforms//host:constraints.bzl", # keep ], visibility = ["//lib:__subpackages__"], deps = [], # keep ) bzl_library( name = "tar_toolchain", srcs = ["tar_toolchain.bzl"], visibility = ["//lib:__subpackages__"], deps = [ "utf8_environment.bzl", ":repo_utils", ], ) bzl_library( name = "bats", srcs = ["bats.bzl"], visibility = ["//lib:__subpackages__"], deps = [ ":expand_variables", "@aspect_bazel_lib//lib:paths", "@aspect_bazel_lib//lib:windows_utils", ], ) bzl_library( name = "bats_toolchain", srcs = ["bats_toolchain.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "coreutils_toolchain", srcs = ["coreutils_toolchain.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "expand_locations", srcs = ["expand_locations.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "extension_utils", srcs = ["extension_utils.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "glob_match", srcs = ["glob_match.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "lists", srcs = ["lists.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "repo_utils", srcs = ["repo_utils.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "source_toolchains_repo", srcs = ["source_toolchains_repo.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "stamping", srcs = ["stamping.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "strings", srcs = ["strings.bzl"], visibility = ["//lib:__subpackages__"], ) bzl_library( name = "zstd_toolchain", srcs = ["zstd_toolchain.bzl"], visibility = ["//lib:__subpackages__"], ) bazel-lib-2.22.5/lib/private/base64.bzl000066400000000000000000000142161513125663600174740ustar00rootroot00000000000000"""Base64 encoder/decoder utility for Starlark Handles string only and not binary data Implementation based on https://gist.github.com/trondhumbor/ce57c0c2816bb45a8fbb but adapted to use the subset of python available in Starlark. """ load(":strings.bzl", "chr", "ord") def decode(data): """Decode a base64 encoded string. Args: data: base64-encoded string Returns: A string containing the decoded data """ padding = data.count("=") data = data.replace("=", "A") binstring = "" for i in range(len(data)): index = BASE64_CHARS.find(data[i]) if index == -1: fail("expected a base64 encoded string") binstring += _int_to_binary(index, 6) eight_chunks = _chunk(binstring, 8) outstring = "" for chunk in eight_chunks: outstring += chr(int(chunk, 2)) return outstring if padding == 0 else outstring[:-padding] def encode(data): """Base64 encode a string. Args: data: string to encode Returns: The base64-encoded string """ padding = 0 if len(data) % 3 != 0: padding = (len(data) + 3 - len(data) % 3) - len(data) data += "\0" * padding three_chunks = _chunk(data, 3) binstring = "" for chunk in three_chunks: for i in range(len(chunk)): binstring += _int_to_binary(ord(chunk[i])) six_chunks = _chunk(binstring, 6) outstring = "" for element in six_chunks: outstring += BASE64_CHARS[int(element, 2)] return outstring if padding == 0 else outstring[:-padding] + "=" * padding def _chunk(data, length): return [data[i:i + length] for i in range(0, len(data), length)] BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" # Starlark support octal values that we can leverage for this conversion. # Generated by lib/private/string.py utility script. INT_TO_BINARY = [ "00000000", "00000001", "00000010", "00000011", "00000100", "00000101", "00000110", "00000111", "00001000", "00001001", "00001010", "00001011", "00001100", "00001101", "00001110", "00001111", "00010000", "00010001", "00010010", "00010011", "00010100", "00010101", "00010110", "00010111", "00011000", "00011001", "00011010", "00011011", "00011100", "00011101", "00011110", "00011111", "00100000", "00100001", "00100010", "00100011", "00100100", "00100101", "00100110", "00100111", "00101000", "00101001", "00101010", "00101011", "00101100", "00101101", "00101110", "00101111", "00110000", "00110001", "00110010", "00110011", "00110100", "00110101", "00110110", "00110111", "00111000", "00111001", "00111010", "00111011", "00111100", "00111101", "00111110", "00111111", "01000000", "01000001", "01000010", "01000011", "01000100", "01000101", "01000110", "01000111", "01001000", "01001001", "01001010", "01001011", "01001100", "01001101", "01001110", "01001111", "01010000", "01010001", "01010010", "01010011", "01010100", "01010101", "01010110", "01010111", "01011000", "01011001", "01011010", "01011011", "01011100", "01011101", "01011110", "01011111", "01100000", "01100001", "01100010", "01100011", "01100100", "01100101", "01100110", "01100111", "01101000", "01101001", "01101010", "01101011", "01101100", "01101101", "01101110", "01101111", "01110000", "01110001", "01110010", "01110011", "01110100", "01110101", "01110110", "01110111", "01111000", "01111001", "01111010", "01111011", "01111100", "01111101", "01111110", "01111111", "10000000", "10000001", "10000010", "10000011", "10000100", "10000101", "10000110", "10000111", "10001000", "10001001", "10001010", "10001011", "10001100", "10001101", "10001110", "10001111", "10010000", "10010001", "10010010", "10010011", "10010100", "10010101", "10010110", "10010111", "10011000", "10011001", "10011010", "10011011", "10011100", "10011101", "10011110", "10011111", "10100000", "10100001", "10100010", "10100011", "10100100", "10100101", "10100110", "10100111", "10101000", "10101001", "10101010", "10101011", "10101100", "10101101", "10101110", "10101111", "10110000", "10110001", "10110010", "10110011", "10110100", "10110101", "10110110", "10110111", "10111000", "10111001", "10111010", "10111011", "10111100", "10111101", "10111110", "10111111", "11000000", "11000001", "11000010", "11000011", "11000100", "11000101", "11000110", "11000111", "11001000", "11001001", "11001010", "11001011", "11001100", "11001101", "11001110", "11001111", "11010000", "11010001", "11010010", "11010011", "11010100", "11010101", "11010110", "11010111", "11011000", "11011001", "11011010", "11011011", "11011100", "11011101", "11011110", "11011111", "11100000", "11100001", "11100010", "11100011", "11100100", "11100101", "11100110", "11100111", "11101000", "11101001", "11101010", "11101011", "11101100", "11101101", "11101110", "11101111", "11110000", "11110001", "11110010", "11110011", "11110100", "11110101", "11110110", "11110111", "11111000", "11111001", "11111010", "11111011", "11111100", "11111101", "11111110", "11111111", ] def _int_to_binary(i, digits = 8): if i < 0 or i > 255: fail("expected a int between 0 and 255 (inclusive)") if digits < 1 or digits > 8: fail("expected digits to be between 1 and 8 (inclusive)") return INT_TO_BINARY[i][8 - digits:] bazel-lib-2.22.5/lib/private/bats.bzl000066400000000000000000000074361513125663600173470ustar00rootroot00000000000000"bats_test" load("//lib:paths.bzl", "BASH_RLOCATION_FUNCTION", "to_rlocation_path") load("//lib:windows_utils.bzl", "create_windows_native_launcher_script") load(":expand_variables.bzl", "expand_variables") _LAUNCHER_TMPL = """#!/usr/bin/env bash set -o errexit -o nounset -o pipefail {BASH_RLOCATION_FUNCTION} readonly core_path="$(rlocation {core})" readonly bats="$core_path/bin/bats" readonly libs=( {libraries} ) {envs} NEW_LIBS=() for lib in "${{libs[@]}}"; do NEW_LIBS+=( $(cd "$(rlocation $lib)/.." && pwd) ) done export BATS_LIB_PATH=$( IFS=: echo "${{NEW_LIBS[*]}}" ) export BATS_TEST_TIMEOUT="$TEST_TIMEOUT" export BATS_TMPDIR="$TEST_TMPDIR" # Undocumented: bats can write the JUnit report to any file we specify: # https://github.com/bats-core/bats-core/blob/b640ec3cf2c7c9cfc9e6351479261186f76eeec8/libexec/bats-core/bats#L400 BATS_REPORT_FILENAME="$(basename $XML_OUTPUT_FILE)" exec $bats {tests} --report-formatter junit --output "$(dirname $XML_OUTPUT_FILE)" "$@" """ _ENV_SET = """export {key}=\"{value}\"""" def _bats_test_impl(ctx): toolchain = ctx.toolchains["@aspect_bazel_lib//lib:bats_toolchain_type"] batsinfo = toolchain.batsinfo is_windows = ctx.target_platform_has_constraint(ctx.attr._windows_constraint[platform_common.ConstraintValueInfo]) envs = [] for (key, value) in ctx.attr.env.items(): envs.append(_ENV_SET.format( key = key, value = expand_variables(ctx, ctx.expand_location(value, targets = ctx.attr.data), attribute_name = "env"), )) # See https://www.msys2.org/wiki/Porting/: # > Setting MSYS2_ARG_CONV_EXCL=* prevents any path transformation. if is_windows: envs.append(_ENV_SET.format( key = "MSYS2_ARG_CONV_EXCL", value = "*", )) envs.append(_ENV_SET.format( key = "MSYS_NO_PATHCONV", value = "1", )) bash_launcher = ctx.actions.declare_file("%s_bats.sh" % ctx.label.name) ctx.actions.write( output = bash_launcher, content = _LAUNCHER_TMPL.format( core = to_rlocation_path(ctx, batsinfo.core), libraries = " ".join([to_rlocation_path(ctx, lib) for lib in batsinfo.libraries]), tests = " ".join(["$(rlocation %s)" % to_rlocation_path(ctx, test) for test in ctx.files.srcs]), envs = "\n".join(envs), BASH_RLOCATION_FUNCTION = BASH_RLOCATION_FUNCTION, ), is_executable = True, ) launcher = create_windows_native_launcher_script(ctx, bash_launcher) if is_windows else bash_launcher runfiles = ctx.runfiles(ctx.files.srcs + ctx.files.data + [bash_launcher]) runfiles = runfiles.merge(toolchain.default.default_runfiles) runfiles = runfiles.merge(ctx.attr._runfiles.default_runfiles) return DefaultInfo( executable = launcher, runfiles = runfiles, ) bats_test = rule( implementation = _bats_test_impl, attrs = { "srcs": attr.label_list( allow_files = [".bats"], doc = "Test files", ), "data": attr.label_list( allow_files = True, doc = "Runtime dependencies of the test.", ), "env": attr.string_dict( doc = """Environment variables of the action. Subject to [$(location)](https://bazel.build/reference/be/make-variables#predefined_label_variables) and ["Make variable"](https://bazel.build/reference/be/make-variables) substitution. """, ), "_runfiles": attr.label(default = "@bazel_tools//tools/bash/runfiles"), "_windows_constraint": attr.label(default = "@platforms//os:windows"), }, toolchains = [ "@aspect_bazel_lib//lib:bats_toolchain_type", "@bazel_tools//tools/sh:toolchain_type", ], test = True, ) bazel-lib-2.22.5/lib/private/bats_toolchain.bzl000066400000000000000000000047411513125663600214030ustar00rootroot00000000000000"Provide access to a bats executable" BATS_CORE_VERSIONS = { "v1.10.0": "a1a9f7875aa4b6a9480ca384d5865f1ccf1b0b1faead6b47aa47d79709a5c5fd", } BATS_SUPPORT_VERSIONS = { "v0.3.0": "7815237aafeb42ddcc1b8c698fc5808026d33317d8701d5ec2396e9634e2918f", } BATS_ASSERT_VERSIONS = { "v2.1.0": "98ca3b685f8b8993e48ec057565e6e2abcc541034ed5b0e81f191505682037fd", } BATS_FILE_VERSIONS = { "v0.4.0": "9b69043241f3af1c2d251f89b4fcafa5df3f05e97b89db18d7c9bdf5731bb27a", } BATS_CORE_TEMPLATE = """\ load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS") load("@aspect_bazel_lib//lib/private:bats_toolchain.bzl", "bats_toolchain") load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory") copy_to_directory( name = "core", hardlink = "on", srcs = glob([ "lib/**", "libexec/**" ]) + ["bin/bats"], out = "bats-core", ) bats_toolchain( name = "toolchain", core = ":core", libraries = {libraries} ) toolchain( name = "bats_toolchain", exec_compatible_with = HOST_CONSTRAINTS, toolchain = ":toolchain", toolchain_type = "@aspect_bazel_lib//lib:bats_toolchain_type", ) """ BATS_LIBRARY_TEMPLATE = """\ load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory") copy_to_directory( name = "{name}", hardlink = "on", srcs = glob([ "src/**", "load.bash", ]), out = "bats-{name}", visibility = ["//visibility:public"] ) """ BatsInfo = provider( doc = "Provide info for executing bats", fields = { "core": "bats executable", "libraries": "bats helper libraries", }, ) def _bats_toolchain_impl(ctx): core = ctx.file.core default_info = DefaultInfo( files = depset(ctx.files.core + ctx.files.libraries), runfiles = ctx.runfiles(ctx.files.core + ctx.files.libraries), ) batsinfo = BatsInfo( core = core, libraries = ctx.files.libraries, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( batsinfo = batsinfo, default = default_info, ) return [toolchain_info, default_info] bats_toolchain = rule( implementation = _bats_toolchain_impl, attrs = { "core": attr.label( doc = "Label to the bats executable", allow_single_file = True, mandatory = True, ), "libraries": attr.label_list(), }, ) bazel-lib-2.22.5/lib/private/copy_directory.bzl000066400000000000000000000124061513125663600214450ustar00rootroot00000000000000"""Implementation of copy_directory macro and underlying rules. This rule copies a directory to another location using a precompiled binary. """ load("@bazel_lib//lib:copy_directory.bzl", _copy_directory_bin_action = "copy_directory_bin_action") def copy_directory_bin_action( ctx, src, dst, copy_directory_bin, copy_directory_toolchain = "@aspect_bazel_lib//lib:copy_directory_toolchain_type", hardlink = "auto", verbose = False, preserve_mtime = False): """Factory function that creates an action to copy a directory from src to dst using a tool binary. The tool binary will typically be the `@aspect_bazel_lib//tools/copy_directory` `go_binary` either built from source or provided by a toolchain. This helper is used by the copy_directory rule. It is exposed as a public API so it can be used within other rule implementations. Args: ctx: The rule context. src: The source directory to copy. dst: The directory to copy to. Must be a TreeArtifact. copy_directory_bin: Copy to directory tool binary. copy_directory_toolchain: The toolchain type for Auto Exec Groups. The default is probably what you want. hardlink: Controls when to use hardlinks to files instead of making copies. See copy_directory rule documentation for more details. verbose: print verbose logs to stdout preserve_mtime: preserve the modified time from the source. See the caveats above about interactions with remote execution and caching. """ _copy_directory_bin_action( ctx, src = src, dst = dst, copy_directory_bin = copy_directory_bin, copy_directory_toolchain = copy_directory_toolchain, hardlink = hardlink, verbose = verbose, preserve_mtime = preserve_mtime, ) def _copy_directory_impl(ctx): copy_directory_bin = ctx.toolchains["@aspect_bazel_lib//lib:copy_directory_toolchain_type"].copy_directory_info.bin dst = ctx.actions.declare_directory(ctx.attr.out) copy_directory_bin_action( ctx, src = ctx.file.src, dst = dst, # copy_directory_bin = ctx.executable._tool, # use for development copy_directory_bin = copy_directory_bin, hardlink = ctx.attr.hardlink, verbose = ctx.attr.verbose, preserve_mtime = ctx.attr.preserve_mtime, ) return [ DefaultInfo( files = depset([dst]), runfiles = ctx.runfiles([dst]), ), ] _copy_directory = rule( implementation = _copy_directory_impl, provides = [DefaultInfo], attrs = { "src": attr.label(mandatory = True, allow_single_file = True), # Cannot declare out as an output here, because there's no API for declaring # TreeArtifact outputs. "out": attr.string(mandatory = True), "hardlink": attr.string( values = ["auto", "off", "on"], default = "auto", ), "verbose": attr.bool(), "preserve_mtime": attr.bool( doc = """If True, the last modified time of copied files is preserved. Note the caveats on copy_directory.""", default = False, ), # use '_tool' attribute for development only; do not commit with this attribute active since it # propagates a dependency on rules_go which would be breaking for users # "_tool": attr.label( # executable = True, # cfg = "exec", # default = "//tools/copy_directory", # ), }, toolchains = ["@aspect_bazel_lib//lib:copy_directory_toolchain_type"], ) def copy_directory( name, src, out, hardlink = "auto", **kwargs): """Copies a directory to another location. This rule uses a precompiled binary to perform the copy, so no shell is required. If using this rule with source directories, it is recommended that you use the `--host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1` startup option so that changes to files within source directories are detected. See https://github.com/bazelbuild/bazel/commit/c64421bc35214f0414e4f4226cc953e8c55fa0d2 for more context. Args: name: Name of the rule. src: The directory to make a copy of. Can be a source directory or TreeArtifact. out: Path of the output directory, relative to this package. hardlink: Controls when to use hardlinks to files instead of making copies. Creating hardlinks is much faster than making copies of files with the caveat that hardlinks share file permissions with their source. Since Bazel removes write permissions on files in the output tree after an action completes, hardlinks to source files within source directories is not recommended since write permissions will be inadvertently removed from sources files. - "auto": hardlinks are used if src is a tree artifact already in the output tree - "off": files are always copied - "on": hardlinks are always used (not recommended) **kwargs: further keyword arguments, e.g. `visibility` """ _copy_directory( name = name, src = src, out = out, hardlink = hardlink, **kwargs ) bazel-lib-2.22.5/lib/private/copy_directory_toolchain.bzl000066400000000000000000000146151513125663600235110ustar00rootroot00000000000000"Setup copy_directory toolchain repositories and rules" # https://github.com/bazel-contrib/bazel-lib/releases load("//tools:integrity.bzl", "RELEASED_BINARY_INTEGRITY") load("//tools:version.bzl", "VERSION") # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl COPY_DIRECTORY_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "freebsd_amd64": struct( compatible_with = [ "@platforms//os:freebsd", "@platforms//cpu:x86_64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "linux_s390x": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:s390x", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:arm64", ], ), } CopyToDirectoryInfo = provider( doc = "Provide info for executing copy_directory", fields = { "bin": "Executable copy_directory binary", }, ) def _copy_directory_toolchain_impl(ctx): binary = ctx.file.bin default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) copy_directory_info = CopyToDirectoryInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( copy_directory_info = copy_directory_info, default = default_info, ) return [default_info, toolchain_info] copy_directory_toolchain = rule( implementation = _copy_directory_toolchain_impl, attrs = { "bin": attr.label( mandatory = True, allow_single_file = True, executable = True, cfg = "exec", ), }, ) def _copy_directory_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:copy_directory_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:copy_directory_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.copy_directory_info, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:copy_directory_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_directory_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the copy_directory_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in COPY_DIRECTORY_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:copy_directory_toolchain", toolchain_type = "@aspect_bazel_lib//lib:copy_directory_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) copy_directory_toolchains_repo = repository_rule( _copy_directory_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _copy_directory_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") meta = COPY_DIRECTORY_PLATFORMS[rctx.attr.platform] release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform release_file = "copy_directory-{}{}".format(release_platform, ".exe" if is_windows else "") # https://github.com/bazel-contrib/bazel-lib/releases/download/v1.19.0/copy_directory-linux_amd64 url = "https://github.com/bazel-contrib/bazel-lib/releases/download/v{}/{}".format( VERSION, release_file, ) rctx.download( url = url, output = "copy_directory.exe" if is_windows else "copy_directory", executable = True, sha256 = RELEASED_BINARY_INTEGRITY[release_file], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_directory_toolchain.bzl load("@aspect_bazel_lib//lib/private:copy_directory_toolchain.bzl", "copy_directory_toolchain") exports_files(["{0}"]) copy_directory_toolchain(name = "copy_directory_toolchain", bin = "{0}", visibility = ["//visibility:public"]) """.format("copy_directory.exe" if is_windows else "copy_directory") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) copy_directory_platform_repo = repository_rule( implementation = _copy_directory_platform_repo_impl, doc = "Fetch external tools needed for copy_directory toolchain", attrs = { "platform": attr.string(mandatory = True, values = COPY_DIRECTORY_PLATFORMS.keys()), }, ) bazel-lib-2.22.5/lib/private/copy_to_directory.bzl000066400000000000000000000413231513125663600221470ustar00rootroot00000000000000"copy_to_directory implementation" load("@bazel_lib//lib:copy_to_directory.bzl", _copy_to_directory_bin_action = "copy_to_directory_bin_action") load(":directory_path.bzl", "DirectoryPathInfo") _filter_transforms_order_docstring = """Filters and transformations are applied in the following order: 1. `include_external_repositories` 2. `include_srcs_packages` 3. `exclude_srcs_packages` 4. `root_paths` 5. `include_srcs_patterns` 6. `exclude_srcs_patterns` 7. `replace_prefixes` For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. """ _glob_support_docstring = """Glob patterns are supported. Standard wildcards (globbing patterns) plus the `**` doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns. """ _copy_to_directory_doc = """Copies files and directories to an output directory. Files and directories can be arranged as needed in the output directory using the `root_paths`, `include_srcs_patterns`, `exclude_srcs_patterns` and `replace_prefixes` attributes. {filters_transform_order_docstring} {glob_support_docstring} """.format( filters_transform_order_docstring = _filter_transforms_order_docstring, glob_support_docstring = _glob_support_docstring, ) _copy_to_directory_attr_doc = { # srcs "srcs": """Files and/or directories or targets that provide `DirectoryPathInfo` to copy into the output directory.""", # out "out": """Path of the output directory, relative to this package. If not set, the name of the target is used. """, "add_directory_to_runfiles": """Whether to add the outputted directory to the target's runfiles.""", # root_paths "root_paths": """List of paths (with glob support) that are roots in the output directory. If any parent directory of a file being copied matches one of the root paths patterns specified, the output directory path will be the path relative to the root path instead of the path relative to the file's workspace. If there are multiple root paths that match, the longest match wins. Matching is done on the parent directory of the output file path so a trailing '**' glob patterm will match only up to the last path segment of the dirname and will not include the basename. Only complete path segments are matched. Partial matches on the last segment of the root path are ignored. Forward slashes (`/`) should be used as path separators. A `"."` value expands to the target's package path (`ctx.label.package`). Defaults to `["."]` which results in the output directory path of files in the target's package and and sub-packages are relative to the target's package and files outside of that retain their full workspace relative paths. Globs are supported (see rule docstring above). """, # include_external_repositories "include_external_repositories": """List of external repository names (with glob support) to include in the output directory. Files from external repositories are only copied into the output directory if the external repository they come from matches one of the external repository patterns specified or if they are in the same external repository as this target. When copied from an external repository, the file path in the output directory defaults to the file's path within the external repository. The external repository name is _not_ included in that path. For example, the following copies `@external_repo//path/to:file` to `path/to/file` within the output directory. ``` copy_to_directory( name = "dir", include_external_repositories = ["external_*"], srcs = ["@external_repo//path/to:file"], ) ``` Files that come from matching external are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. The external repository name of the file from an external repository is not included in the output directory path and is considered in subsequent filters and transformations. Globs are supported (see rule docstring above). """, # include_srcs_packages "include_srcs_packages": """List of Bazel packages (with glob support) to include in output directory. Files in srcs are only copied to the output directory if the Bazel package of the file matches one of the patterns specified. Forward slashes (`/`) should be used as path separators. A first character of `"."` will be replaced by the target's package path. Defaults to `["**"]` which includes sources from all packages. Files that have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. Globs are supported (see rule docstring above). """, # exclude_srcs_packages "exclude_srcs_packages": """List of Bazel packages (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if the Bazel package of the file matches one of the patterns specified. Forward slashes (`/`) should be used as path separators. A first character of `"."` will be replaced by the target's package path. Files that have do not have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. Globs are supported (see rule docstring above). """, # include_srcs_patterns "include_srcs_patterns": """List of paths (with glob support) to include in output directory. Files in srcs are only copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified. Forward slashes (`/`) should be used as path separators. Defaults to `["**"]` which includes all sources. Files that have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. Globs are supported (see rule docstring above). """, # exclude_srcs_patterns "exclude_srcs_patterns": """List of paths (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified. Forward slashes (`/`) should be used as path separators. Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. Globs are supported (see rule docstring above). """, # replace_prefixes "replace_prefixes": """Map of paths prefixes (with glob support) to replace in the output directory path when copying files. If the output directory path for a file starts with or fully matches a a key in the dict then the matching portion of the output directory path is replaced with the dict value for that key. The final path segment matched can be a partial match of that segment and only the matching portion will be replaced. If there are multiple keys that match, the longest match wins. Forward slashes (`/`) should be used as path separators. Replace prefix transformation are the final step in the list of filters and transformations. The final output path of a file being copied into the output directory is determined at this step. Globs are supported (see rule docstring above). """, # allow_overwrites "allow_overwrites": """If True, allow files to be overwritten if the same output file is copied to twice. The order of srcs matters as the last copy of a particular file will win when overwriting. Performance of copy_to_directory will be slightly degraded when allow_overwrites is True since copies cannot be parallelized out as they are calculated. Instead all copy paths must be calculated before any copies can be started. """, # hardlink "hardlink": """Controls when to use hardlinks to files instead of making copies. Creating hardlinks is much faster than making copies of files with the caveat that hardlinks share file permissions with their source. Since Bazel removes write permissions on files in the output tree after an action completes, hardlinks to source files are not recommended since write permissions will be inadvertently removed from sources files. - `auto`: hardlinks are used for generated files already in the output tree - `off`: all files are copied - `on`: hardlinks are used for all files (not recommended) """, "preserve_mtime": """If True, the last modified time of copied files is preserved. See the [caveats on copy_directory](/docs/copy_directory.md#preserving-modification-times) about interactions with remote execution and caching.""", # verbose "verbose": """If true, prints out verbose logs to stdout""", } _copy_to_directory_attr = { "srcs": attr.label_list( allow_files = True, doc = _copy_to_directory_attr_doc["srcs"], ), # Cannot declare out as an output here, because there's no API for declaring # TreeArtifact outputs. "out": attr.string( doc = _copy_to_directory_attr_doc["out"], ), # TODO(3.0): Remove this attribute and do not add directory to runfiles by default. # https://github.com/bazel-contrib/bazel-lib/issues/748 "add_directory_to_runfiles": attr.bool( default = True, doc = _copy_to_directory_attr_doc["add_directory_to_runfiles"], ), "root_paths": attr.string_list( default = ["."], doc = _copy_to_directory_attr_doc["root_paths"], ), "include_external_repositories": attr.string_list( doc = _copy_to_directory_attr_doc["include_external_repositories"], ), "include_srcs_packages": attr.string_list( default = ["**"], doc = _copy_to_directory_attr_doc["include_srcs_packages"], ), "exclude_srcs_packages": attr.string_list( doc = _copy_to_directory_attr_doc["exclude_srcs_packages"], ), "include_srcs_patterns": attr.string_list( default = ["**"], doc = _copy_to_directory_attr_doc["include_srcs_patterns"], ), "exclude_srcs_patterns": attr.string_list( doc = _copy_to_directory_attr_doc["exclude_srcs_patterns"], ), "replace_prefixes": attr.string_dict( doc = _copy_to_directory_attr_doc["replace_prefixes"], ), "allow_overwrites": attr.bool( doc = _copy_to_directory_attr_doc["allow_overwrites"], ), "hardlink": attr.string( values = ["auto", "off", "on"], default = "auto", doc = _copy_to_directory_attr_doc["hardlink"], ), "preserve_mtime": attr.bool( default = False, doc = _copy_to_directory_attr_doc["preserve_mtime"], ), "verbose": attr.bool( doc = _copy_to_directory_attr_doc["verbose"], ), # use '_tool' attribute for development only; do not commit with this attribute active since it # propagates a dependency on rules_go which would be breaking for users # "_tool": attr.label( # executable = True, # cfg = "exec", # default = "//tools/copy_to_directory", # ), } def _copy_to_directory_impl(ctx): copy_to_directory_bin = ctx.toolchains["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"].copy_to_directory_info.bin dst = ctx.actions.declare_directory(ctx.attr.out if ctx.attr.out else ctx.attr.name) copy_to_directory_bin_action( ctx, name = ctx.attr.name, dst = dst, # copy_to_directory_bin = ctx.executable._tool, # use for development copy_to_directory_bin = copy_to_directory_bin, files = ctx.files.srcs, targets = [t for t in ctx.attr.srcs if DirectoryPathInfo in t], root_paths = ctx.attr.root_paths, include_external_repositories = ctx.attr.include_external_repositories, include_srcs_packages = ctx.attr.include_srcs_packages, exclude_srcs_packages = ctx.attr.exclude_srcs_packages, include_srcs_patterns = ctx.attr.include_srcs_patterns, exclude_srcs_patterns = ctx.attr.exclude_srcs_patterns, replace_prefixes = ctx.attr.replace_prefixes, allow_overwrites = ctx.attr.allow_overwrites, hardlink = ctx.attr.hardlink, preserve_mtime = ctx.attr.preserve_mtime, verbose = ctx.attr.verbose, ) runfiles = ctx.runfiles([dst]) if ctx.attr.add_directory_to_runfiles else None return [ DefaultInfo( files = depset([dst]), runfiles = runfiles, ), ] def copy_to_directory_bin_action( ctx, name, dst, copy_to_directory_bin, copy_to_directory_toolchain = "@aspect_bazel_lib//lib:copy_to_directory_toolchain_type", files = [], targets = [], root_paths = ["."], include_external_repositories = [], include_srcs_packages = ["**"], exclude_srcs_packages = [], include_srcs_patterns = ["**"], exclude_srcs_patterns = [], replace_prefixes = {}, allow_overwrites = False, hardlink = "auto", preserve_mtime = False, verbose = False): """Factory function to copy files to a directory using a tool binary. The tool binary will typically be the `@aspect_bazel_lib//tools/copy_to_directory` `go_binary` either built from source or provided by a toolchain. This helper is used by copy_to_directory. It is exposed as a public API so it can be used within other rule implementations where additional_files can also be passed in. Args: ctx: The rule context. name: Name of target creating this action used for config file generation. dst: The directory to copy to. Must be a TreeArtifact. copy_to_directory_bin: Copy to directory tool binary. copy_to_directory_toolchain: The toolchain type for Auto Exec Groups. The default is probably what you want. files: List of files to copy into the output directory. targets: List of targets that provide `DirectoryPathInfo` to copy into the output directory. root_paths: List of paths that are roots in the output directory. See copy_to_directory rule documentation for more details. include_external_repositories: List of external repository names to include in the output directory. See copy_to_directory rule documentation for more details. include_srcs_packages: List of Bazel packages to include in output directory. See copy_to_directory rule documentation for more details. exclude_srcs_packages: List of Bazel packages (with glob support) to exclude from output directory. See copy_to_directory rule documentation for more details. include_srcs_patterns: List of paths (with glob support) to include in output directory. See copy_to_directory rule documentation for more details. exclude_srcs_patterns: List of paths (with glob support) to exclude from output directory. See copy_to_directory rule documentation for more details. replace_prefixes: Map of paths prefixes to replace in the output directory path when copying files. See copy_to_directory rule documentation for more details. allow_overwrites: If True, allow files to be overwritten if the same output file is copied to twice. See copy_to_directory rule documentation for more details. hardlink: Controls when to use hardlinks to files instead of making copies. See copy_to_directory rule documentation for more details. preserve_mtime: If true, preserve the modified time from the source. verbose: If true, prints out verbose logs to stdout """ return _copy_to_directory_bin_action( ctx, name = name, dst = dst, copy_to_directory_bin = copy_to_directory_bin, copy_to_directory_toolchain = copy_to_directory_toolchain, files = files, targets = targets, root_paths = root_paths, include_external_repositories = include_external_repositories, include_srcs_packages = include_srcs_packages, exclude_srcs_packages = exclude_srcs_packages, include_srcs_patterns = include_srcs_patterns, exclude_srcs_patterns = exclude_srcs_patterns, replace_prefixes = replace_prefixes, allow_overwrites = allow_overwrites, hardlink = hardlink, preserve_mtime = preserve_mtime, verbose = verbose, ) copy_to_directory_lib = struct( doc = _copy_to_directory_doc, attr_doc = _copy_to_directory_attr_doc, attrs = _copy_to_directory_attr, impl = _copy_to_directory_impl, provides = [DefaultInfo], ) bazel-lib-2.22.5/lib/private/copy_to_directory_toolchain.bzl000066400000000000000000000150021513125663600242020ustar00rootroot00000000000000"Setup copy_to_directory toolchain repositories and rules" # https://github.com/bazel-contrib/bazel-lib/releases load("//tools:integrity.bzl", "RELEASED_BINARY_INTEGRITY") load("//tools:version.bzl", "VERSION") # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl COPY_TO_DIRECTORY_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "freebsd_amd64": struct( compatible_with = [ "@platforms//os:freebsd", "@platforms//cpu:x86_64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "linux_s390x": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:s390x", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:arm64", ], ), } CopyToDirectoryInfo = provider( doc = "Provide info for executing copy_to_directory", fields = { "bin": "Executable copy_to_directory binary", }, ) def _copy_to_directory_toolchain_impl(ctx): binary = ctx.file.bin default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) copy_to_directory_info = CopyToDirectoryInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( copy_to_directory_info = copy_to_directory_info, default = default_info, ) return [default_info, toolchain_info] copy_to_directory_toolchain = rule( implementation = _copy_to_directory_toolchain_impl, attrs = { "bin": attr.label( mandatory = True, allow_single_file = True, executable = True, cfg = "exec", ), }, ) def _copy_to_directory_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.copy_to_directory_info, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the copy_to_directory_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in COPY_TO_DIRECTORY_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:copy_to_directory_toolchain", toolchain_type = "@aspect_bazel_lib//lib:copy_to_directory_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) copy_to_directory_toolchains_repo = repository_rule( _copy_to_directory_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _copy_to_directory_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") meta = COPY_TO_DIRECTORY_PLATFORMS[rctx.attr.platform] release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform release_file = "copy_to_directory-{}{}".format(release_platform, ".exe" if is_windows else "") # https://github.com/bazel-contrib/bazel-lib/releases/download/v1.19.0/copy_to_directory-linux_amd64 url = "https://github.com/bazel-contrib/bazel-lib/releases/download/v{}/{}".format( VERSION, release_file, ) rctx.download( url = url, output = "copy_to_directory.exe" if is_windows else "copy_to_directory", executable = True, sha256 = RELEASED_BINARY_INTEGRITY[release_file], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl load("@aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl", "copy_to_directory_toolchain") exports_files(["{0}"]) copy_to_directory_toolchain(name = "copy_to_directory_toolchain", bin = "{0}", visibility = ["//visibility:public"]) """.format("copy_to_directory.exe" if is_windows else "copy_to_directory") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) copy_to_directory_platform_repo = repository_rule( implementation = _copy_to_directory_platform_repo_impl, doc = "Fetch external tools needed for copy_to_directory toolchain", attrs = { "platform": attr.string(mandatory = True, values = COPY_TO_DIRECTORY_PLATFORMS.keys()), }, ) bazel-lib-2.22.5/lib/private/coreutils_toolchain.bzl000066400000000000000000000227531513125663600224660ustar00rootroot00000000000000"Setup coreutils toolchain repositories and rules" # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl COREUTILS_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:aarch64", ], ), } # https://github.com/uutils/coreutils/releases # # The integrity hashes can be automatically fetched for the coreutils releases by running # `tools/coreutils_mirror_release.sh`. COREUTILS_VERSIONS = { "0.1.0": { "darwin_arm64": { "filename": "coreutils-0.1.0-aarch64-apple-darwin.tar.gz", "sha256": "sha256-fYBo89ESeNlveOtCtn0kC7j7I4ZyTqWXSB6X7HUmXZw=", }, "windows_arm64": { "filename": "coreutils-0.1.0-aarch64-pc-windows-msvc.zip", "sha256": "sha256-n6oOwPPfR8r6Cgn86tRtoo4mQLX+ExatnLfhHxkFC9Q=", }, "linux_arm64": { "filename": "coreutils-0.1.0-aarch64-unknown-linux-musl.tar.gz", "sha256": "sha256-ZXIpLudLtqfvqI8F0NCnpcaWuuCuNBpDi5g653dcnUc=", }, "darwin_amd64": { "filename": "coreutils-0.1.0-x86_64-apple-darwin.tar.gz", "sha256": "sha256-CifwnwOBEom53c/4xrfBv26XG16sPdU2IIpA4sHqnNk=", }, "windows_amd64": { "filename": "coreutils-0.1.0-x86_64-pc-windows-msvc.zip", "sha256": "sha256-T/PH5RSa3iCjQkh9HAnMbMY1ma9t+yjSVYuSV4CnLYI=", }, "linux_amd64": { "filename": "coreutils-0.1.0-x86_64-unknown-linux-musl.tar.gz", "sha256": "sha256-RjZINHsfwzdBSoZL2pYMnL0b1KVA80TAEP9bs1GZ5tc=", }, }, "0.0.27": { "darwin_arm64": { "filename": "coreutils-0.0.27-aarch64-apple-darwin.tar.gz", "sha256": "sha256-BjAeGgJ8+sLCIwmokCOkfelCCLtnNRH49QcFnrDq8a4=", }, "linux_arm64": { "filename": "coreutils-0.0.27-aarch64-unknown-linux-musl.tar.gz", "sha256": "sha256-doU+ZfTyA5I8RSwDAcsOkEI3BZXFuFwBfEbg+diS06g=", }, "darwin_amd64": { "filename": "coreutils-0.0.27-x86_64-apple-darwin.tar.gz", "sha256": "sha256-1ivz4ue8/ROUYhPh22Bg2ASPgC6MKMulR52nLgZvTBo=", }, "windows_amd64": { "filename": "coreutils-0.0.27-x86_64-pc-windows-msvc.zip", "sha256": "sha256-DC4H+hQX51aHoFudV39n7u217NDcNL9AiG4o4edboV0=", }, "linux_amd64": { "filename": "coreutils-0.0.27-x86_64-unknown-linux-musl.tar.gz", "sha256": "sha256-tM+hJd16cCjflJyMwsCaevPYZMiBkIKZJm7/XC+760w=", }, }, "0.0.26": { "darwin_arm64": { "filename": "coreutils-0.0.26-aarch64-apple-darwin.tar.gz", "sha256": "sha256-/A6CNYWmvOwPW443pH+wO+VtzDFgussN1hRGuANnFOU=", }, "linux_arm64": { "filename": "coreutils-0.0.26-aarch64-unknown-linux-musl.tar.gz", "sha256": "sha256-9zGLFOMDjUDbraDY/hrE5zFJ0O+QYrvx2wHk3Gw3q/A=", }, "darwin_amd64": { # TODO: remove this version_override hack once 0.0.27 is releases and contains a darwin arm binary "version_override": "0.0.23", "filename": "coreutils-0.0.23-x86_64-apple-darwin.tar.gz", "sha256": "sha256-SswetVAuK/hMK1r9uBvNnKj5JpSgD0bzkbsHTxOabCo=", }, "windows_amd64": { "filename": "coreutils-0.0.26-x86_64-pc-windows-msvc.zip", "sha256": "sha256-6qPkqxQZM4XBBBJ80t1uvzfZiz0gBeT/zoCdfqOO3uk=", }, "linux_amd64": { "filename": "coreutils-0.0.26-x86_64-unknown-linux-musl.tar.gz", "sha256": "sha256-QpGVp3wmHqpt5Brd/bdj7pyMQNftcihOtaRI8z2uhp0=", }, }, } DEFAULT_COREUTILS_VERSION = COREUTILS_VERSIONS.keys()[0] CoreUtilsInfo = provider( doc = "Provide info for executing coreutils", fields = { "bin": "Executable coreutils binary", }, ) def _coreutils_toolchain_impl(ctx): binary = ctx.file.binary # Make the $(COREUTILS_BIN) variable available in places like genrules. # See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables template_variables = platform_common.TemplateVariableInfo({ "COREUTILS_BIN": binary.path, }) default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) coreutils_info = CoreUtilsInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( coreutils_info = coreutils_info, template_variables = template_variables, default = default_info, ) return [default_info, toolchain_info, template_variables] coreutils_toolchain = rule( implementation = _coreutils_toolchain_impl, attrs = { "binary": attr.label( mandatory = True, allow_single_file = True, ), }, ) def _coreutils_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:coreutils_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:coreutils_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.coreutils_info, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:coreutils_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:coreutils_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the coreutils_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in COREUTILS_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:coreutils_toolchain", toolchain_type = "@aspect_bazel_lib//lib:coreutils_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) coreutils_toolchains_repo = repository_rule( _coreutils_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _coreutils_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") platform = rctx.attr.platform filename = COREUTILS_VERSIONS[rctx.attr.version][platform]["filename"] version = rctx.attr.version if "version_override" in COREUTILS_VERSIONS[rctx.attr.version][platform]: version = COREUTILS_VERSIONS[rctx.attr.version][platform]["version_override"] url = "https://github.com/uutils/coreutils/releases/download/{}/{}".format( version, filename, ) rctx.download_and_extract( url = url, stripPrefix = filename.replace(".zip", "").replace(".tar.gz", ""), integrity = COREUTILS_VERSIONS[rctx.attr.version][platform]["sha256"], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:coreutils_toolchain.bzl load("@aspect_bazel_lib//lib/private:coreutils_toolchain.bzl", "coreutils_toolchain") exports_files(["{0}"]) coreutils_toolchain(name = "coreutils_toolchain", binary = "{0}", visibility = ["//visibility:public"]) """.format("coreutils.exe" if is_windows else "coreutils") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) coreutils_platform_repo = repository_rule( implementation = _coreutils_platform_repo_impl, doc = "Fetch external tools needed for coreutils toolchain", attrs = { "version": attr.string(mandatory = True, values = COREUTILS_VERSIONS.keys()), "platform": attr.string(mandatory = True, values = COREUTILS_PLATFORMS.keys()), }, ) bazel-lib-2.22.5/lib/private/diff_test.bzl000066400000000000000000000121331513125663600203530ustar00rootroot00000000000000# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A test rule that compares two binary files or two directories. Similar to `bazel-skylib`'s [`diff_test`](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/diff_test.bzl) but also supports comparing directories. The rule uses a Bash command (diff) on Linux/macOS/non-Windows, and a cmd.exe command (fc.exe) on Windows (no Bash is required). """ load("@bazel_skylib//lib:shell.bzl", "shell") load("@bazel_skylib//lib:types.bzl", "types") load("@bazel_skylib//rules:write_file.bzl", "write_file") load(":directory_path.bzl", "DirectoryPathInfo") def _runfiles_path(f): if f.root.path: return f.path[len(f.root.path) + 1:] # generated file else: return f.path # source file def _diff_test_impl(ctx): is_windows = ctx.target_platform_has_constraint(ctx.attr._windows_constraint[platform_common.ConstraintValueInfo]) if DirectoryPathInfo in ctx.attr.file1: file1 = ctx.attr.file1[DirectoryPathInfo].directory file1_path = "/".join([_runfiles_path(file1), ctx.attr.file1[DirectoryPathInfo].path]) else: if len(ctx.files.file1) != 1: fail("file1 must be a single file or a target that provides a DirectoryPathInfo") file1 = ctx.files.file1[0] file1_path = _runfiles_path(file1) if DirectoryPathInfo in ctx.attr.file2: file2 = ctx.attr.file2[DirectoryPathInfo].directory file2_path = "/".join([_runfiles_path(file2), ctx.attr.file2[DirectoryPathInfo].path]) else: if len(ctx.files.file2) != 1: fail("file2 must be a single file or a target that provides a DirectoryPathInfo") file2 = ctx.files.file2[0] file2_path = _runfiles_path(file2) if file1 == file2: msg = "diff_test comparing the same file %s" % file1 fail(msg) if is_windows: test_suffix = "-test.bat" template = ctx.file._diff_test_tmpl_bat else: test_suffix = "-test.sh" template = ctx.file._diff_test_tmpl_sh test_bin = ctx.actions.declare_file(ctx.label.name + test_suffix) ctx.actions.expand_template( template = template, output = test_bin, substitutions = { "{name}": ctx.attr.name, "{fail_msg}": ctx.attr.failure_message, "{file1}": file1_path, "{file2}": file2_path, "{build_file_path}": ctx.build_file_path, "{diff_args}": " ".join([ shell.quote(arg) for arg in ctx.attr.diff_args ]), }, is_executable = True, ) return DefaultInfo( executable = test_bin, files = depset(direct = [test_bin]), runfiles = ctx.runfiles(files = [test_bin, file1, file2]), ) _diff_test = rule( attrs = { "failure_message": attr.string(), "file1": attr.label( allow_files = True, mandatory = True, ), "file2": attr.label( allow_files = True, mandatory = True, ), "diff_args": attr.string_list(), "_windows_constraint": attr.label(default = "@platforms//os:windows"), "_diff_test_tmpl_sh": attr.label( default = ":diff_test_tmpl.sh", allow_single_file = True, ), "_diff_test_tmpl_bat": attr.label( default = ":diff_test_tmpl.bat", allow_single_file = True, ), }, test = True, implementation = _diff_test_impl, ) def diff_test(name, file1, file2, diff_args = [], size = "small", **kwargs): """A test that compares two files. The test succeeds if the files' contents match. Args: name: The name of the test rule. file1: Label of the file to compare to file2. file2: Label of the file to compare to file1, or a list of strings which are the lines to expect file1 to contain. diff_args: Arguments to pass to the `diff` command. (Ignored on Windows) size: standard attribute for tests **kwargs: The common attributes for tests. """ if types.is_list(file2): write_file2_target = name + ".file2" write_file( name = write_file2_target, out = write_file2_target + ".txt", content = file2, ) file2 = write_file2_target _diff_test( name = name, file1 = file1, file2 = file2, size = size, diff_args = diff_args, **kwargs ) bazel-lib-2.22.5/lib/private/diff_test_tmpl.bat000066400000000000000000000055501513125663600213730ustar00rootroot00000000000000@rem @generated by @aspect_bazel_lib//lib/private:diff_test.bzl @echo off :: TODO: Add support for XML_OUTPUT_FILE like in diff_test_tmpl.sh SETLOCAL ENABLEEXTENSIONS SETLOCAL ENABLEDELAYEDEXPANSION set MF=%RUNFILES_MANIFEST_FILE:/=\\% set PATH=%SYSTEMROOT%\\system32 set F1={file1} set F2={file2} if "!F1:~0,9!" equ "external/" (set F1=!F1:~9!) else (set F1=!TEST_WORKSPACE!/!F1!) if "!F2:~0,9!" equ "external/" (set F2=!F2:~9!) else (set F2=!TEST_WORKSPACE!/!F2!) for /F "tokens=2* usebackq" %%i in (`findstr.exe /l /c:"!F1! " "%MF%"`) do ( set RF1=%%i set RF1=!RF1:/=\\! ) if "!RF1!" equ "" ( if "%RUNFILES_MANIFEST_ONLY%" neq "1" if exist "%RUNFILES_DIR%\\%F1%" ( set RF1="%RUNFILES_DIR%\\%F1%" ) else ( if exist "{file1}" ( set RF1="{file1}" ) ) if "!RF1!" neq "" ( set RF1=!RF1:/=\\! ) else ( echo>&2 ERROR: !F1! not found exit /b 1 ) ) for /F "tokens=2* usebackq" %%i in (`findstr.exe /l /c:"!F2! " "%MF%"`) do ( set RF2=%%i set RF2=!RF2:/=\\! ) if "!RF2!" equ "" ( if "%RUNFILES_MANIFEST_ONLY%" neq "1" if exist "%RUNFILES_DIR%\\%F2%" ( set RF2="%RUNFILES_DIR%\\%F2%" ) else ( if exist "{file2}" ( set RF2="{file2}" ) ) if "!RF2!" neq "" ( set RF2=!RF2:/=\\! ) else ( echo>&2 ERROR: !F2! not found exit /b 1 ) ) set DF1=0 set DF2=0 if exist "!RF1!\\*" ( set DF1=1 ) if exist "!RF2!\\*" ( set DF2=1 ) if %DF1% equ 1 ( if %DF2% equ 0 ( echo>&2 ERROR: Cannot compare directory "{file1}" and a file "{file2}" exit /b 1 ) ) if %DF1% equ 0 ( if %DF2% equ 1 ( echo>&2 ERROR: Cannot compare file "{file1}" and a directory "{file2}" exit /b 1 ) ) set DFX=0 if %DF1% equ 1 ( if %DF2% equ 1 ( set DFX=1 ) ) if %DFX% equ 1 ( for /f "delims=" %%F in ( 'echo "."^&forfiles /s /p "!RF1!" /m "*" /c "cmd /c echo @relpath"' ) do ( if not exist "!RF2!\\%%~F" ( echo>&2 FAIL: file "%%~F" exists in "{file1}" and not in "{file2}". {fail_msg} GOTO fail ) if not exist "!RF1!\\%%~F\\*" ( fc.exe /B "!RF1!\\%%~F" "!RF2!\\%%~F" 2>NUL 1>NUL if !ERRORLEVEL! neq 0 ( if !ERRORLEVEL! equ 1 ( echo>&2 FAIL: files "{file1}\\%%~F" and "{file2}\\%%~F" differ. {fail_msg} GOTO fail ) else ( fc.exe /B "!RF1!\\%%~F" "!RF2!\\%%~F" GOTO fail ) ) ) ) for /f "delims=" %%F in ( 'echo "."^&forfiles /s /p "!RF2!" /m "*" /c "cmd /c echo @relpath"' ) do ( if not exist "!RF1!\\%%~F" ( echo>&2 FAIL: file "%%~F" exists in "{file2}" and not in "{file1}". {fail_msg} GOTO fail ) ) ) else ( fc.exe /B "!RF1!" "!RF2!" 2>NUL 1>NUL if %ERRORLEVEL% neq 0 ( if %ERRORLEVEL% equ 1 ( echo>&2 FAIL: files "{file1}" and "{file2}" differ. {fail_msg} exit /b 1 ) else ( fc.exe /B "!RF1!" "!RF2!" exit /b %errorlevel% ) ) ) exit /b 0 :fail exit /b 1 bazel-lib-2.22.5/lib/private/diff_test_tmpl.sh000066400000000000000000000046141513125663600212370ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail escape() { echo "$1" | sed 's/&/\&/g; s//\>/g; s/"/\"/g; s/'"'"'/\'/g' | awk 1 ORS=' ' # preserve newlines } fail() { cat <"${XML_OUTPUT_FILE:-/dev/null}" EOF echo >&2 "FAIL: $1" exit 1 } resolve_exec_root() { local RUNFILES_PARENT RUNFILES_PARENT=$(dirname "$RUNFILES_DIR") local BIN_DIR BIN_DIR="${RUNFILES_PARENT%$BUILD_FILE_DIR}" local EXEC_ROOT EXEC_ROOT=$(dirname $(dirname $(dirname "${BIN_DIR}"))) echo -n "$EXEC_ROOT" } find_file() { local F_RAW="$1" local F="$2" local RF= if [[ -f "$TEST_SRCDIR/$F1" || -d "$TEST_SRCDIR/$F" ]]; then RF="$TEST_SRCDIR/$F" elif [[ -d "${RUNFILES_DIR:-/dev/null}" && "${RUNFILES_MANIFEST_ONLY:-}" != 1 ]]; then EXEC_ROOT=$(resolve_exec_root) if [[ -e "$EXEC_ROOT/$F_RAW" ]]; then RF="$EXEC_ROOT/$F_RAW" else RF="$RUNFILES_DIR/$F1" fi elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then RF="$(grep -F -m1 "$F " "$RUNFILES_MANIFEST_FILE" | sed 's/^[^ ]* //')" else echo >&2 "ERROR: could not find \"${F_RAW}\"" exit 1 fi echo -n "$RF" } BUILD_FILE_DIR="$(dirname "{build_file_path}")" F1="{file1}" F2="{file2}" [[ "$F1" =~ ^external/ ]] && F1="${F1#external/}" || F1="$TEST_WORKSPACE/$F1" [[ "$F2" =~ ^external/ ]] && F2="${F2#external/}" || F2="$TEST_WORKSPACE/$F2" RF1="$(find_file {file1} "$F1")" RF2="$(find_file {file2} "$F2")" DF1= DF2= [[ ! -d "$RF1" ]] || DF1=1 [[ ! -d "$RF2" ]] || DF2=1 if [[ "$DF1" ]] && [[ ! "$DF2" ]]; then echo >&2 "ERROR: cannot compare a directory \"{file1}\" against a file \"{file2}\"" exit 1 fi if [[ ! "$DF1" ]] && [[ "$DF2" ]]; then echo >&2 "ERROR: cannot compare a file \"{file1}\" against a directory \"{file2}\"" exit 1 fi if [[ "$DF1" ]] || [[ "$DF2" ]]; then if ! diff {diff_args} -r "$RF1" "$RF2"; then fail "directories \"{file1}\" and \"{file2}\" differ. {fail_msg}" fi else if ! diff {diff_args} "$RF1" "$RF2"; then fail "files \"{file1}\" and \"{file2}\" differ. {fail_msg}" fi fi bazel-lib-2.22.5/lib/private/directory_path.bzl000066400000000000000000000074011513125663600214260ustar00rootroot00000000000000"""Rule and corresponding provider that joins a label pointing to a TreeArtifact with a path nested within that directory """ load("@bazel_lib//lib:directory_path.bzl", _DirectoryPathInfo = "DirectoryPathInfo") load("//lib:utils.bzl", _to_label = "to_label") # Alias the modern bazel_lib v3 providers to ease migration of rulesets to v3. DirectoryPathInfo = _DirectoryPathInfo def _directory_path(ctx): if not ctx.file.directory.is_directory: msg = "Expected directory to be a TreeArtifact (ctx.actions.declare_directory) but {} is either a source file or does not exist.".format(ctx.file.directory) fail(msg) return [DirectoryPathInfo(path = ctx.attr.path, directory = ctx.file.directory)] directory_path = rule( doc = """Provide DirectoryPathInfo to reference some path within a directory. Otherwise there is no way to give a Bazel label for it.""", implementation = _directory_path, attrs = { "directory": attr.label( doc = "a TreeArtifact (ctx.actions.declare_directory)", mandatory = True, allow_single_file = True, ), "path": attr.string( doc = "path relative to the directory", mandatory = True, ), }, provides = [DirectoryPathInfo], ) def make_directory_path(name, directory, path, **kwargs): """Helper function to generate a directory_path target and return its label. Args: name: unique name for the generated `directory_path` target directory: `directory` attribute passed to generated `directory_path` target path: `path` attribute passed to generated `directory_path` target **kwargs: parameters to pass to generated `output_files` target Returns: The label `name` """ directory_path( name = name, directory = directory, path = path, **kwargs ) return _to_label(name) def make_directory_paths(name, dict, **kwargs): """Helper function to convert a dict of directory to path mappings to directory_path targets and labels. For example, ``` make_directory_paths("my_name", { "//directory/artifact:target_1": "file/path", "//directory/artifact:target_2": ["file/path1", "file/path2"], }) ``` generates the targets, ``` directory_path( name = "my_name_0", directory = "//directory/artifact:target_1", path = "file/path" ) directory_path( name = "my_name_1", directory = "//directory/artifact:target_2", path = "file/path1" ) directory_path( name = "my_name_2", directory = "//directory/artifact:target_2", path = "file/path2" ) ``` and the list of targets is returned, ``` [ "my_name_0", "my_name_1", "my_name_2", ] ``` Args: name: The target name to use for the generated targets & labels. The names are generated as zero-indexed `name + "_" + i` dict: The dictionary of directory keys to path or path list values. **kwargs: additional parameters to pass to each generated target Returns: The label of the generated `directory_path` targets named `name + "_" + i` """ labels = [] pairs = [] for directory, val in dict.items(): if type(val) == "list": for path in val: pairs.append((directory, path)) elif type(val) == "string": pairs.append((directory, val)) else: fail("Value must be a list or string") for i, pair in enumerate(pairs): directory, path = pair labels.append(make_directory_path( "%s_%d" % (name, i), directory, path, **kwargs )) return labels bazel-lib-2.22.5/lib/private/docs.bzl000066400000000000000000000054061513125663600173410ustar00rootroot00000000000000"Helpers for generating stardoc documentation" load("@stardoc//stardoc:stardoc.bzl", _stardoc = "stardoc") load("//lib:write_source_files.bzl", "write_source_files") def stardoc_with_diff_test( name, bzl_library_target, **kwargs): """Creates a stardoc target that can be auto-detected by update_docs to write the generated doc to the source tree and test that it's up to date. This is helpful for minimizing boilerplate in repos with lots of stardoc targets. Args: name: the name of the stardoc file to be written to the current source directory (.md will be appended to the name). Call bazel run on this target to update the file. bzl_library_target: the label of the `bzl_library` target to generate documentation for **kwargs: additional attributes passed to the stardoc() rule, such as for overriding the templates """ target_compatible_with = kwargs.pop("target_compatible_with", select({ # stardoc produces different line endings on Windows # which makes the diff_test fail Label("@platforms//os:windows"): [Label("@platforms//:incompatible")], "//conditions:default": [], })) # Generate MD from .bzl _stardoc( name = name, out = name + "-docgen.md", input = bzl_library_target + ".bzl", deps = [bzl_library_target], tags = kwargs.pop("tags", []) + ["package:" + native.package_name()], # Tag the package name which will help us reconstruct the write_source_files label in update_docs target_compatible_with = target_compatible_with, **kwargs ) def update_docs(name = "update", **kwargs): """Stamps an executable run for writing all stardocs declared with stardoc_with_diff_test to the source tree. This is to be used in tandem with `stardoc_with_diff_test()` to produce a convenient workflow for generating, testing, and updating all doc files as follows: ``` bash # on CI cd docs; bazel test :all # if it's out-of-date, then cd docs; bazel run update ``` Args: name: the name of executable target **kwargs: Other common named parameters such as `tags` or `visibility` """ update_files = {} for r in native.existing_rules().values(): if r["generator_function"] == "stardoc_with_diff_test" and r["generator_name"] == r["name"]: for tag in r["tags"]: if tag.startswith("package:"): stardoc_name = r["name"] source_file_name = stardoc_name + ".md" generated_file_name = stardoc_name + "-docgen.md" update_files[source_file_name] = generated_file_name write_source_files( name = name, files = update_files, **kwargs ) bazel-lib-2.22.5/lib/private/expand_locations.bzl000066400000000000000000000027761513125663600217520ustar00rootroot00000000000000"Helpers to expand location" def expand_locations(ctx, input, targets = []): """Expand location templates. Expands all `$(execpath ...)`, `$(rootpath ...)` and deprecated `$(location ...)` templates in the given string by replacing with the expanded path. Expansion only works for labels that point to direct dependencies of this rule or that are explicitly listed in the optional argument targets. See https://docs.bazel.build/versions/main/be/make-variables.html#predefined_label_variables. Use `$(rootpath)` and `$(rootpaths)` to expand labels to the runfiles path that a built binary can use to find its dependencies. This path is of the format: - `./file` - `path/to/file` - `../external_repo/path/to/file` Use `$(execpath)` and `$(execpaths)` to expand labels to the execroot (where Bazel runs build actions). This is of the format: - `./file` - `path/to/file` - `external/external_repo/path/to/file` - `/path/to/file` - `/external/external_repo/path/to/file` The deprecated `$(location)` and `$(locations)` expansions returns either the execpath or rootpath depending on the context. Args: ctx: context input: String to be expanded targets: List of targets for additional lookup information. Returns: The expanded path or the original path Deprecated: Use vanilla `ctx.expand_location(input, targets = targets)` instead """ return ctx.expand_location(input, targets = targets) bazel-lib-2.22.5/lib/private/expand_template.bzl000066400000000000000000000126761513125663600215720ustar00rootroot00000000000000"expand_template rule" load("@bazel_skylib//lib:dicts.bzl", "dicts") load("//lib:stamping.bzl", "STAMP_ATTRS", "maybe_stamp") load(":expand_variables.bzl", "expand_variables") def _expand_substitutions(ctx, output, substitutions): result = {} for k, v in substitutions.items(): result[k] = expand_variables(ctx, ctx.expand_location(v, targets = ctx.attr.data), outs = [output], attribute_name = "substitutions") return result def _expand_template_impl(ctx): output = ctx.outputs.out if not output: if ctx.file.template and ctx.file.template.is_source: output = ctx.actions.declare_file(ctx.file.template.basename, sibling = ctx.file.template) else: output = ctx.actions.declare_file(ctx.attr.name + ".txt") substitutions = _expand_substitutions(ctx, output, ctx.attr.substitutions) expand_template_info = ctx.toolchains["@aspect_bazel_lib//lib:expand_template_toolchain_type"].expand_template_info stamp = maybe_stamp(ctx) if stamp: substitutions = dicts.add(substitutions, _expand_substitutions(ctx, output, ctx.attr.stamp_substitutions)) substitutions_out = ctx.actions.declare_file("{}_substitutions.json".format(ctx.label.name)) ctx.actions.write( output = substitutions_out, content = json.encode(substitutions), ) inputs = [ ctx.file.template, stamp.volatile_status_file, stamp.stable_status_file, substitutions_out, ] args = ctx.actions.args() args.add(ctx.file.template) args.add(output) args.add(substitutions_out) args.add(stamp.volatile_status_file) args.add(stamp.stable_status_file) args.add(ctx.attr.is_executable) ctx.actions.run( arguments = [args], outputs = [output], inputs = inputs, executable = expand_template_info.bin, toolchain = "@aspect_bazel_lib//lib:expand_template_toolchain_type", ) else: ctx.actions.expand_template( template = ctx.file.template, output = output, substitutions = substitutions, is_executable = ctx.attr.is_executable, ) all_outs = [output] runfiles = ctx.runfiles( files = all_outs, transitive_files = depset(transitive = [ target[DefaultInfo].files for target in ctx.attr.data ]), ) return [DefaultInfo( files = depset(all_outs), runfiles = runfiles.merge_all([ target[DefaultInfo].default_runfiles for target in ctx.attr.data ]), )] expand_template_lib = struct( doc = """Template expansion This performs a simple search over the template file for the keys in substitutions, and replaces them with the corresponding values. Values may also use location templates as documented in [expand_locations](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/expand_make_vars.md#expand_locations) as well as [configuration variables](https://docs.bazel.build/versions/main/skylark/lib/ctx.html#var) such as `$(BINDIR)`, `$(TARGET_CPU)`, and `$(COMPILATION_MODE)` as documented in [expand_variables](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/expand_make_vars.md#expand_variables). """, implementation = _expand_template_impl, toolchains = ["@aspect_bazel_lib//lib:expand_template_toolchain_type"], attrs = dicts.add({ "data": attr.label_list( doc = "List of targets for additional lookup information.", allow_files = True, ), "is_executable": attr.bool( doc = "Whether to mark the output file as executable.", ), "out": attr.output( doc = """Where to write the expanded file. If the `template` is a source file, then `out` defaults to be named the same as the template file and outputted to the same workspace-relative path. In this case there will be no pre-declared label for the output file. It can be referenced by the target label instead. This pattern is similar to `copy_to_bin` but with substitutions on the copy. Otherwise, `out` defaults to `[name].txt`. """, ), "stamp_substitutions": attr.string_dict( doc = """Mapping of strings to substitutions. There are overlaid on top of substitutions when stamping is enabled for the target. Substitutions can contain $(execpath :target) and $(rootpath :target) expansions, $(MAKEVAR) expansions and {{STAMP_VAR}} expansions when stamping is enabled for the target. """, ), "substitutions": attr.string_dict( doc = """Mapping of strings to substitutions. Substitutions can contain $(execpath :target) and $(rootpath :target) expansions, $(MAKEVAR) expansions and {{STAMP_VAR}} expansions when stamping is enabled for the target. """, ), "template": attr.label( doc = "The template file to expand.", mandatory = True, allow_single_file = True, ), }, **STAMP_ATTRS), ) expand_template = rule( doc = expand_template_lib.doc, implementation = expand_template_lib.implementation, toolchains = expand_template_lib.toolchains, attrs = expand_template_lib.attrs, ) bazel-lib-2.22.5/lib/private/expand_template_toolchain.bzl000066400000000000000000000146701513125663600236260ustar00rootroot00000000000000"Setup expand_template toolchain repositories and rules" # https://github.com/bazel-contrib/bazel-lib/releases load("//tools:integrity.bzl", "RELEASED_BINARY_INTEGRITY") load("//tools:version.bzl", "VERSION") # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl EXPAND_TEMPLATE_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "freebsd_amd64": struct( compatible_with = [ "@platforms//os:freebsd", "@platforms//cpu:x86_64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "linux_s390x": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:s390x", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:arm64", ], ), } ExpandTemplateInfo = provider( doc = "Provide info for executing expand_template", fields = { "bin": "Executable expand_template binary", }, ) def _expand_template_toolchain_impl(ctx): binary = ctx.executable.bin default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) expand_template_info = ExpandTemplateInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( expand_template_info = expand_template_info, default = default_info, ) return [default_info, toolchain_info] expand_template_toolchain = rule( implementation = _expand_template_toolchain_impl, attrs = { "bin": attr.label( mandatory = True, allow_single_file = True, executable = True, cfg = "exec", ), }, ) def _expand_template_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:expand_template_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:expand_template_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.expand_template_info, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:expand_template_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:expand_template_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the expand_template_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in EXPAND_TEMPLATE_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:expand_template_toolchain", toolchain_type = "@aspect_bazel_lib//lib:expand_template_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) expand_template_toolchains_repo = repository_rule( _expand_template_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _expand_template_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") meta = EXPAND_TEMPLATE_PLATFORMS[rctx.attr.platform] release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform release_file = "expand_template-{}{}".format(release_platform, ".exe" if is_windows else "") # https://github.com/bazel-contrib/bazel-lib/releases/download/v1.19.0/expand_template-linux_amd64 url = "https://github.com/bazel-contrib/bazel-lib/releases/download/v{}/{}".format( VERSION, release_file, ) rctx.download( url = url, output = "expand_template.exe" if is_windows else "expand_template", executable = True, sha256 = RELEASED_BINARY_INTEGRITY[release_file], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:expand_template_toolchain.bzl load("@aspect_bazel_lib//lib/private:expand_template_toolchain.bzl", "expand_template_toolchain") exports_files(["{0}"]) expand_template_toolchain(name = "expand_template_toolchain", bin = "{0}", visibility = ["//visibility:public"]) """.format("expand_template.exe" if is_windows else "expand_template") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) expand_template_platform_repo = repository_rule( implementation = _expand_template_platform_repo_impl, doc = "Fetch external tools needed for expand_template toolchain", attrs = { "platform": attr.string(mandatory = True, values = EXPAND_TEMPLATE_PLATFORMS.keys()), }, ) bazel-lib-2.22.5/lib/private/expand_variables.bzl000066400000000000000000000072601513125663600217200ustar00rootroot00000000000000"Helpers to expand make variables" load("@bazel_skylib//lib:paths.bzl", _spaths = "paths") def expand_variables(ctx, s, outs = [], inputs = [], attribute_name = "args"): """Expand make variables and substitute like genrule does. Bazel [pre-defined variables](https://bazel.build/reference/be/make-variables#predefined_variables) are expanded however only `$@`, `$(@D)` and `$(RULEDIR)` of [pre-defined genrule variables](https://bazel.build/reference/be/make-variables#predefined_genrule_variables) are supported. This function is the same as ctx.expand_make_variables with the additional genrule-like substitutions of: - `$<`: The input file if it is a single file. Else triggers a build error. - `$@`: The output file if it is a single file. Else triggers a build error. - `$(@D)`: The output directory. If there is only one file name in outs, this expands to the directory containing that file. If there is only one directory in outs, this expands to the single output directory. If there are multiple files, this instead expands to the package's root directory in the bin tree, even if all generated files belong to the same subdirectory! - `$(RULEDIR)`: The output directory of the rule, that is, the directory corresponding to the name of the package containing the rule under the bin tree. - `$(BUILD_FILE_PATH)`: ctx.build_file_path - `$(VERSION_FILE)`: ctx.version_file.path - `$(INFO_FILE)`: ctx.info_file.path - `$(TARGET)`: ctx.label - `$(WORKSPACE)`: ctx.workspace_name See https://docs.bazel.build/versions/main/be/general.html#genrule.cmd and https://docs.bazel.build/versions/main/be/make-variables.html#predefined_genrule_variables for more information of how these special variables are expanded. Args: ctx: starlark rule context s: expression to expand outs: declared outputs of the rule, for expanding references to outputs inputs: declared inputs of the rule, for expanding references to inputs attribute_name: name of the attribute containing the expression. Used for error reporting. Returns: `s` with the variables expanded """ rule_dir = _spaths.join( ctx.bin_dir.path, ctx.label.workspace_root, ctx.label.package, ) additional_substitutions = {} if s.find("$@") != -1 or s.find("$(@)") != -1: if len(outs) > 1: fail("$@ substitution may only be used with a single out.") if len(outs) == 1: additional_substitutions["@"] = outs[0].path if outs[0].is_directory: output_dir = outs[0].path else: output_dir = outs[0].dirname else: output_dir = rule_dir if s.find("$<") != -1 or s.find("$(<)") != -1: if len(inputs) != 1: fail("$< substitution may only be used with a single input.") additional_substitutions["<"] = inputs[0].path additional_substitutions["@D"] = output_dir additional_substitutions["RULEDIR"] = rule_dir # Add some additional make variable substitutions for common useful values in the context additional_substitutions["BUILD_FILE_PATH"] = ctx.build_file_path additional_substitutions["VERSION_FILE"] = ctx.version_file.path additional_substitutions["INFO_FILE"] = ctx.info_file.path additional_substitutions["TARGET"] = "{}//{}:{}".format( "@" + ctx.label.workspace_name if ctx.label.workspace_name else "", ctx.label.package, ctx.label.name, ) additional_substitutions["WORKSPACE"] = ctx.workspace_name return ctx.expand_make_variables(attribute_name, s, additional_substitutions) bazel-lib-2.22.5/lib/private/extension_utils.bzl000066400000000000000000000110251513125663600216370ustar00rootroot00000000000000"""Utility functions for bzlmod extensions""" def _toolchain_repos_bfs(mctx, get_tag_fn, toolchain_name, toolchain_repos_fn, default_repository = None, get_name_fn = None, get_version_fn = None): """Create toolchain repositories from bzlmod extensions using a breadth-first resolution strategy. Toolchains are assumed to have a "default" or canonical repository name so that across all invocations of the module extension with that name only a single toolchain repository is created. As such, it is recommended to default the toolchain name in the extension's tag class attributes so that diverging from the canonical name is a special case. The resolved toolchain version will be the one invoked closest to the root module, following Bazel's breadth-first ordering of modules in the dependency graph. For example, given the module extension usage in a MODULE file: ```starlark ext = use_extension("@my_lib//lib:extensions.bzl", "ext") ext.foo_toolchain(version = "1.2.3") # Default `name = "foo"` use_repo(ext, "foo") register_toolchains( "@foo//:all", ) ``` This macro would be used in the module extension implementation as follows: ```starlark extension_utils.toolchain_repos( mctx = mctx, get_tag_fn = lambda tags: tags.foo_toolchain, toolchain_name = "foo", toolchain_repos_fn = lambda name, version: register_foo_toolchains(name = name, register = False), get_version_fn = lambda attr: None, ) ``` Where `register_foo_toolchains` is a typical WORKSPACE macro used to register the foo toolchain for a particular version, minus the actual registration step which is done separately in the MODULE file. This macro enforces that only root MODULEs may use a different name for the toolchain in case several versions of the toolchain repository is desired. Args: mctx: The module context get_tag_fn: A function that takes in `module.tags` and returns the tag used for the toolchain. For example, `tag: lambda tags: tags.foo_toolchain`. This is required because `foo_toolchain` cannot be accessed as a simple string key from `module.tags`. toolchain_name: Name of the toolchain to use in error messages toolchain_repos_fn: A function that takes (name, version) and creates a toolchain repository. This lambda should call a typical reposotiory rule to create toolchains. default_repository: Default name of the toolchain repository to pass to the repos_fn. By default, it equals `toolchain_name`. get_name_fn: A function that extracts the module name from the toolchain tag's attributes. Defaults to grabbing the `name` attribute. get_version_fn: A function that extracts the module version from the a tag's attributes. Defaults to grabbing the `version` attribute. Override this to a lambda that returns `None` if version isn't used as an attribute. """ if default_repository == None: default_repository = toolchain_name if get_name_fn == None: get_name_fn = lambda attr: attr.name if get_version_fn == None: get_version_fn = lambda attr: attr.version registrations = {} for mod in mctx.modules: for attr in get_tag_fn(mod.tags): name = get_name_fn(attr) version = get_version_fn(attr) if name != default_repository and not mod.is_root: fail("Only the root module may provide a name for the {} toolchain.".format(toolchain_name)) if name in registrations.keys(): if name == default_repository: # Prioritize the root-most registration of the default toolchain version and # ignore any further registrations (modules are processed breadth-first) continue if version == registrations[name]: # No problem to register a matching toolchain twice continue fail("Multiple conflicting {} toolchains declared for name {} ({} and {})".format( toolchain_name, name, version, registrations[name], )) else: registrations[name] = version for name, version in registrations.items(): toolchain_repos_fn( name = name, version = version, ) extension_utils = struct( toolchain_repos_bfs = _toolchain_repos_bfs, ) bazel-lib-2.22.5/lib/private/fail_with_message_test.bzl000066400000000000000000000004431513125663600231160ustar00rootroot00000000000000"Test rule that always fails and prints a message" def _fail_with_message_test_impl(ctx): fail(ctx.attr.message) fail_with_message_test = rule( attrs = { "message": attr.string(mandatory = True), }, implementation = _fail_with_message_test_impl, test = True, ) bazel-lib-2.22.5/lib/private/glob_match.bzl000066400000000000000000000155251513125663600205130ustar00rootroot00000000000000""" Basic glob match implementation for starlark based on the golang [doublestar](https://github.com/bmatcuk/doublestar/blob/465a339d8daa03b8620e49b8ae541f71651426ad/match.go#L74) library. This was originally developed by @jbedard for use in rules_js (https://github.com/aspect-build/rules_js/blob/6ca32d5199ddc0bf19bd704f591030dc1468ca5f/npm/private/pkg_glob.bzl) to support the pnpm public-hoist-expr option (https://pnpm.io/npmrc#public-hoist-expr). The pnpm implementation and tests were used as a reference implementation: https://github.com/pnpm/pnpm/blob/v7.4.0-2/packages/matcher/src/index.ts https://github.com/pnpm/pnpm/blob/v7.4.0-2/packages/matcher/test/index.ts """ # "forever" (2^30) for ~ while(true) loops _FOREVER = range(1073741824) def _validate_glob(expr): expr_len = len(expr) for i in range(expr_len): if expr[i] == "*" and i < expr_len - 1 and expr[i + 1] == "*": if i > 0 and expr[i - 1] != "/": msg = "glob_match: `**` globstar in expression `{}` must be at the start of the expression or preceded by `/`".format(expr) fail(msg) if i < expr_len - 2 and expr[i + 2] != "/": msg = "glob_match: `**` globstar in expression `{}` must be at the end of the expression or followed by `/`".format(expr) fail(msg) def is_glob(expr): """Determine if the passed string is a global expression Args: expr: the potential glob expression Returns: True if the passed string is a global expression """ return expr.find("*") != -1 or expr.find("?") != -1 def glob_match(expr, path, match_path_separator = False): """Test if the passed path matches the glob expression. `*` A single asterisk stands for zero or more arbitrary characters except for the the path separator `/` if `match_path_separator` is False `?` The question mark stands for exactly one character except for the the path separator `/` if `match_path_separator` is False `**` A double asterisk stands for an arbitrary sequence of 0 or more characters. It is only allowed when preceded by either the beginning of the string or a slash. Likewise it must be followed by a slash or the end of the pattern. Args: expr: the glob expression path: the path against which to match the glob expression match_path_separator: whether or not to match the path separator '/' when matching `*` and `?` expressions Returns: True if the path matches the glob expression """ # See https://github.com/bmatcuk/doublestar/blob/465a339d8daa03b8620e49b8ae541f71651426ad/match.go#L74 # for reference implementation. if expr == "": fail("glob_match: invalid empty glob expression") if expr == "**": # matches everything return True if not is_glob(expr): # the expression is not a glob (does bot have any glob symbols) so the only match is an exact match return expr == path _validate_glob(expr) # Cursor of the latest '**' expression within the path doublestar_expr_backtrack = -1 doublestar_path_backtrack = -1 # Cursor of the latest '*' expression within the path star_expr_backtrack = -1 star_path_backtrack = -1 # Current indexes into path and expression expr_i = 0 expr_len = len(expr) path_i = 0 path_len = len(path) start_of_segment = True for _ in _FOREVER: if path_i >= path_len: break # Potentially advance the expression if expr_i < expr_len: # star if expr[expr_i] == "*": # Advance past the * expr_i = expr_i + 1 # doublestar if expr_i < expr_len and expr[expr_i] == "*": # Assert unsupported ** expressions were prevented by _validate_glob() if not start_of_segment or (expr_i + 1 < expr_len and expr[expr_i + 1] != "/"): fail("glob_match: invalid '**' should be prevented by _validate_glob()") # Advance past the ** expr_i = expr_i + 1 # Trailing /** matches everything if expr_i >= expr_len: return True # Advance past the **/ expr_i = expr_i + 1 # Start the doublestar cursor doublestar_expr_backtrack = expr_i doublestar_path_backtrack = path_i star_expr_backtrack = -1 star_path_backtrack = -1 continue else: # Start the star expression cursor start_of_segment = False star_expr_backtrack = expr_i star_path_backtrack = path_i continue elif expr[expr_i] == "?": start_of_segment = False if match_path_separator or path[path_i] != "/": expr_i = expr_i + 1 path_i = path_i + 1 continue else: break elif path_i < path_len and expr[expr_i] == path[path_i]: start_of_segment = path[path_i] == "/" expr_i = expr_i + 1 path_i = path_i + 1 continue # Did not advance the expression or path. # Advance any star expression if possible. if star_expr_backtrack >= 0 and (match_path_separator or path[star_path_backtrack] != "/"): star_path_backtrack = star_path_backtrack + 1 expr_i = star_expr_backtrack path_i = star_path_backtrack start_of_segment = False continue # Advance any double star expression if possible. if doublestar_expr_backtrack >= 0: super_continue = False # ** backtrack, advance path_i past next separator path_i = doublestar_path_backtrack for _ in _FOREVER: if path_i >= path_len: break path_current = path[path_i] path_i = path_i + 1 if path_current == "/": doublestar_path_backtrack = path_i expr_i = doublestar_expr_backtrack start_of_segment = True super_continue = True break # Successfully consumed a path segment if super_continue: continue # Failed to advance the path or expression return False # Exited the loop without reaching the end if path_i < path_len: return False # Reached the end of the path, check if the expression ended or is on a final wildcard trailing = expr[expr_i:] return trailing == "" or trailing == "*" or trailing == "**" bazel-lib-2.22.5/lib/private/host_repo.bzl000066400000000000000000000025741513125663600204160ustar00rootroot00000000000000"A repository that exposes information about the host platform" load("@bazel_skylib//lib:versions.bzl", "versions") load(":repo_utils.bzl", "repo_utils") def _host_repo_impl(rctx): # Base BUILD file for this repository rctx.file("BUILD.bazel", """# @generated by @aspect_bazel_lib//lib/private:host_repo.bzl load("@aspect_bazel_lib//:bzl_library.bzl", "bzl_library") bzl_library( name = "defs", srcs = ["defs.bzl"], visibility = ["//visibility:public"], ) """) # defs.bzl file for this repository rctx.file("defs.bzl", content = """# @generated by @aspect_bazel_lib//lib/private:host_repo.bzl # Information about the host platform host = struct( bazel_version = "{bazel_version}", is_darwin = {is_darwin}, is_linux = {is_linux}, is_windows = {is_windows}, os = "{os}", platform = "{platform}", ) """.format( bazel_version = versions.get(), is_darwin = repo_utils.is_darwin(rctx), is_linux = repo_utils.is_linux(rctx), is_windows = repo_utils.is_windows(rctx), os = repo_utils.os(rctx), platform = repo_utils.platform(rctx), )) host_repo = repository_rule( implementation = _host_repo_impl, # always invalidate this repository since so that the bazel_version is # always updated on every invocation of bazel local = True, doc = "Exposes information about the host platform", ) bazel-lib-2.22.5/lib/private/jq_toolchain.bzl000066400000000000000000000164061513125663600210650ustar00rootroot00000000000000"Setup jq toolchain repositories and rules" load(":repo_utils.bzl", "repo_utils") # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl JQ_PLATFORMS = { "darwin_amd64": struct( release_platform = "macos-amd64", compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( release_platform = "macos-arm64", compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "linux_amd64": struct( release_platform = "linux-amd64", compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( release_platform = "linux-arm64", compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "windows_amd64": struct( release_platform = "win64", compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), } DEFAULT_JQ_VERSION = "1.7" # https://github.com/stedolan/jq/releases # # The integrity hashes can be computed with # shasum -b -a 384 [downloaded file] | awk '{ print $1 }' | xxd -r -p | base64 JQ_VERSIONS = { "1.7": { "linux-amd64": "sha384-4wJ15NoxFf7r1Zf5YVGUeMPx/pfWlSfMJWLFcu4fUcBFe5L4BOpF/njEK8AH58od", "linux-arm64": "sha384-y9BwX+RyXf2a16xwtvcjHFfIBp3K3Ukyg4GjtmxBtynD/BKNf+0tuLtZx64TTI+/", "macos-amd64": "sha384-N0WdpiD8zl1k9888yGxWW/dHzztOTU+RTlZrzOYJMXXUUMqjnqXq8GwnHDsC9Lk3", "macos-arm64": "sha384-0nnKlrEAU7NCzTM63XYkhAGGapA/IT2O2jkU+H+ZbQFu3E+XEbgw5E/+o0oHjLGf", "win64": "sha384-2QfBgUpi1I5KPVrKtZnPcur+Wn/iE+tZVPFKXiIPoBKTpqZKhzc/CdqjcBn+IPiy", }, } JqInfo = provider( doc = "Provide info for executing jq", fields = { "bin": "Executable jq binary", }, ) def _jq_toolchain_impl(ctx): binary = ctx.file.bin # Make the $(JQ_BIN) variable available in places like genrules. # See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables template_variables = platform_common.TemplateVariableInfo({ "JQ_BIN": binary.path, }) default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) jq_info = JqInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( jqinfo = jq_info, template_variables = template_variables, default = default_info, ) return [default_info, toolchain_info, template_variables] jq_toolchain = rule( implementation = _jq_toolchain_impl, attrs = { "bin": attr.label( mandatory = True, allow_single_file = True, ), }, ) def _jq_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:jq_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:jq_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.jqinfo, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:jq_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:jq_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the jq_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in JQ_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:jq_toolchain", toolchain_type = "@aspect_bazel_lib//lib:jq_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) jq_toolchains_repo = repository_rule( _jq_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _jq_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") meta = JQ_PLATFORMS[rctx.attr.platform] release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform url = "https://github.com/stedolan/jq/releases/download/jq-{0}/jq-{1}{2}".format( rctx.attr.version, release_platform, ".exe" if is_windows else "", ) rctx.download( url = url, output = "jq.exe" if is_windows else "jq", executable = True, integrity = JQ_VERSIONS[rctx.attr.version][release_platform], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:jq_toolchain.bzl load("@aspect_bazel_lib//lib/private:jq_toolchain.bzl", "jq_toolchain") exports_files(["{0}"]) jq_toolchain(name = "jq_toolchain", bin = "{0}", visibility = ["//visibility:public"]) """.format("jq.exe" if is_windows else "jq") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) jq_platform_repo = repository_rule( implementation = _jq_platform_repo_impl, doc = "Fetch external tools needed for jq toolchain", attrs = { "version": attr.string(mandatory = True, values = JQ_VERSIONS.keys()), "platform": attr.string(mandatory = True, values = JQ_PLATFORMS.keys()), }, ) def _jq_host_alias_repo(rctx): ext = ".exe" if repo_utils.is_windows(rctx) else "" # Base BUILD file for this repository rctx.file("BUILD.bazel", """# @generated by @aspect_bazel_lib//lib/private:jq_toolchain.bzl package(default_visibility = ["//visibility:public"]) exports_files(["jq{ext}"]) """.format( ext = ext, )) rctx.symlink("../{name}_{platform}/jq{ext}".format( name = rctx.attr.name, platform = repo_utils.platform(rctx), ext = ext, ), "jq{ext}".format(ext = ext)) jq_host_alias_repo = repository_rule( _jq_host_alias_repo, doc = """Creates a repository with a shorter name meant for the host platform, which contains a BUILD.bazel file that exports symlinks to the host platform's binaries """, ) bazel-lib-2.22.5/lib/private/lists.bzl000066400000000000000000000061271513125663600175500ustar00rootroot00000000000000"Function definitions for working with lists" def every(f, arr): """Check if every item of `arr` passes function `f`. Example: `every(lambda i: i.endswith(".js"), ["app.js", "lib.js"]) // True` Args: f: Function to execute on every item arr: List to iterate over Returns: True or False """ return len(filter(f, arr)) == len(arr) def filter(f, arr): """Filter a list `arr` by applying a function `f` to each item. Example: `filter(lambda i: i.endswith(".js"), ["app.ts", "app.js", "lib.ts", "lib.js"]) // ["app.js", "lib.js"]` Args: f: Function to execute on every item arr: List to iterate over Returns: A new list containing items that passed the filter function. """ res = [] for a in arr: if f(a): res.append(a) return res def find(f, arr): """Find a particular item from list `arr` by a given function `f`. Unlike `pick`, the `find` method returns a tuple of the index and the value of first item passing by `f`. Furthermore `find` does not fail if no item passes `f`. In this case `(-1, None)` is returned. Args: f: Function to execute on every item arr: List to iterate over Returns: Tuple (index, item) """ i = 0 for a in arr: if f(a): return (i, a) i += 1 return (-1, None) def map(f, arr): """Apply a function `f` with each item of `arr` and return a new list. Example: `map(lambda i: i*2, [1, 2, 3]) // [2, 4, 6]` Args: f: Function to execute on every item arr: List to iterate over Returns: A new list with all mapped items. """ return [f(a) for a in arr] def once(f, arr): """Check if exactly one item in list `arr` passes the given function `f`. Args: f: Function to execute on every item arr: List to iterate over Returns: True or False """ return len(filter(f, arr)) == 1 def pick(f, arr): """Pick a particular item in list `arr` by a given function `f`. Unlike `filter`, the `pick` method returns the first item _found_ by `f`. If no item has passed `f`, the function will _fail_. Args: f: Function to execute on every item arr: List to iterate over Returns: item """ for a in arr: if f(a): return a fail("Could not find any item") def some(f, arr): """Check if at least one item of `arr` passes function `f`. Example: `some(lambda i: i.endswith(".js"), ["app.js", "lib.ts"]) // True` Args: f: Function to execute on every item arr: List to iterate over Returns: True or False """ for a in arr: if f(a): return True return False def unique(arr): """Return a new list with unique items in it. Example: `unique(["foo", "bar", "foo", "baz"]) // ["foo", "bar", "baz"]` Args: arr: List to iterate over Returns: A new list with unique items """ res = [] for a in arr: if a not in res: res.append(a) return res bazel-lib-2.22.5/lib/private/output_files.bzl000066400000000000000000000062241513125663600211320ustar00rootroot00000000000000"""output_files implementation """ load("//lib:utils.bzl", _to_label = "to_label") def _output_files(ctx): files = [] files_depset = depset() if ctx.attr.output_group: if OutputGroupInfo not in ctx.attr.target: msg = "%s output_group is specified but %s does not provide an OutputGroupInfo" % (ctx.attr.output_group, ctx.attr.target) fail(msg) if ctx.attr.output_group not in ctx.attr.target[OutputGroupInfo]: msg = "%s output_group is specified but %s does not provide this output group" % (ctx.attr.output_group, ctx.attr.target) fail(msg) files_depset = ctx.attr.target[OutputGroupInfo][ctx.attr.output_group] else: files_depset = ctx.attr.target[DefaultInfo].files files_list = files_depset.to_list() for path in ctx.attr.paths: file = _find_short_path_in_files_list(files_list, path) if not file: if ctx.attr.output_group: msg = "%s file not found within the %s output group of %s" % (path, ctx.attr.output_group, ctx.attr.target) else: msg = "%s file not found within the DefaultInfo of %s" % (path, ctx.attr.target) fail(msg) files.append(file) return [DefaultInfo( files = depset(direct = files), runfiles = ctx.runfiles(files = files), )] output_files = rule( doc = "A rule that provides file(s) specific via DefaultInfo from a given target's DefaultInfo or OutputGroupInfo", implementation = _output_files, attrs = { "target": attr.label( doc = "the target to look in for requested paths in its' DefaultInfo or OutputGroupInfo", mandatory = True, ), "paths": attr.string_list( doc = "the paths of the file(s), relative to their roots, to provide via DefaultInfo from the given target's DefaultInfo or OutputGroupInfo", mandatory = True, allow_empty = False, ), "output_group": attr.string( doc = "if set, we look in the specified output group for paths instead of DefaultInfo", ), }, provides = [DefaultInfo], ) def make_output_files(name, target, paths, **kwargs): """Helper function to generate a output_files target and return its label. Args: name: unique name for the generated `output_files` target target: `target` attribute passed to generated `output_files` target paths: `paths` attribute passed to generated `output_files` target **kwargs: parameters to pass to generated `output_files` target Returns: The label `name` """ output_files( name = name, target = target, paths = paths, **kwargs ) return _to_label(name) def _find_short_path_in_files_list(files_list, short_path): """Helper function find a file in a DefaultInfo by short path Args: files_list: a list of files short_path: the short path (path relative to root) to search for Returns: The File if found else None """ for file in files_list: if file.short_path == short_path: return file return None bazel-lib-2.22.5/lib/private/params_file.bzl000066400000000000000000000027631513125663600206760ustar00rootroot00000000000000"params_file rule" load(":expand_variables.bzl", "expand_variables") load(":strings.bzl", "split_args") _ATTRS = { "args": attr.string_list(), "data": attr.label_list(allow_files = True), "newline": attr.string( values = ["unix", "windows", "auto"], default = "auto", ), "out": attr.output(mandatory = True), "_windows_constraint": attr.label(default = "@platforms//os:windows"), } def _params_file_impl(ctx): is_windows = ctx.target_platform_has_constraint(ctx.attr._windows_constraint[platform_common.ConstraintValueInfo]) if ctx.attr.newline == "auto": newline = "\r\n" if is_windows else "\n" elif ctx.attr.newline == "windows": newline = "\r\n" else: newline = "\n" expanded_args = [] # Expand predefined source/output path && predefined variables & custom variables for a in ctx.attr.args: expanded_args += split_args(expand_variables(ctx, ctx.expand_location(a, targets = ctx.attr.data), outs = [ctx.outputs.out])) # ctx.actions.write creates a FileWriteAction which uses UTF-8 encoding. ctx.actions.write( output = ctx.outputs.out, content = newline.join(expanded_args), is_executable = False, ) files = depset(direct = [ctx.outputs.out]) runfiles = ctx.runfiles(files = [ctx.outputs.out]) return [DefaultInfo(files = files, runfiles = runfiles)] params_file = rule( implementation = _params_file_impl, provides = [DefaultInfo], attrs = _ATTRS, ) bazel-lib-2.22.5/lib/private/patch.bzl000066400000000000000000000140471513125663600175110ustar00rootroot00000000000000# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fork of @bazel_tools//tools/build_defs/repo:utils.bzl patch function with working_directory argument added. Upstream code is at https://github.com/bazelbuild/bazel/blob/f4214746fcd15f0ef8c4e747ef8e3edca9f112a5/tools/build_defs/repo/utils.bzl#L87 """ load(":repo_utils.bzl", "repo_utils") # Temporary directory for downloading remote patch files. _REMOTE_PATCH_DIR = ".tmp_remote_patches" def _use_native_patch(patch_args): """If patch_args only contains -p options, we can use the native patch implementation.""" for arg in patch_args: if not arg.startswith("-p"): return False return True def _download_patch(ctx, patch_url, integrity, auth): name = patch_url.split("/")[-1] patch_path = ctx.path(_REMOTE_PATCH_DIR).get_child(name) ctx.download( patch_url, patch_path, canonical_id = ctx.attr.canonical_id, auth = auth, integrity = integrity, ) return patch_path def patch(ctx, patches = None, patch_cmds = None, patch_cmds_win = None, patch_tool = None, patch_args = None, auth = None, patch_directory = None): """Implementation of patching an already extracted repository. This rule is intended to be used in the implementation function of a repository rule. If the parameters `patches`, `patch_tool`, `patch_args`, `patch_cmds` and `patch_cmds_win` are not specified then they are taken from `ctx.attr`. Args: ctx: The repository context of the repository rule calling this utility function. patches: The patch files to apply. List of strings, Labels, or paths. patch_cmds: Bash commands to run for patching, passed one at a time to bash -c. List of strings patch_cmds_win: Powershell commands to run for patching, passed one at a time to powershell /c. List of strings. If the boolean value of this parameter is false, patch_cmds will be used and this parameter will be ignored. patch_tool: Path of the patch tool to execute for applying patches. String. patch_args: Arguments to pass to the patch tool. List of strings. auth: An optional dict specifying authentication information for some of the URLs. patch_directory: Directory to apply the patches in """ bash_exe = ctx.os.environ["BAZEL_SH"] if "BAZEL_SH" in ctx.os.environ else "bash" powershell_exe = ctx.os.environ["BAZEL_POWERSHELL"] if "BAZEL_POWERSHELL" in ctx.os.environ else "powershell.exe" if patches == None and hasattr(ctx.attr, "patches"): patches = ctx.attr.patches if patches == None: patches = [] remote_patches = {} remote_patch_strip = 0 if hasattr(ctx.attr, "remote_patches") and ctx.attr.remote_patches: if hasattr(ctx.attr, "remote_patch_strip"): remote_patch_strip = ctx.attr.remote_patch_strip remote_patches = ctx.attr.remote_patches if patch_cmds == None and hasattr(ctx.attr, "patch_cmds"): patch_cmds = ctx.attr.patch_cmds if patch_cmds == None: patch_cmds = [] if patch_cmds_win == None and hasattr(ctx.attr, "patch_cmds_win"): patch_cmds_win = ctx.attr.patch_cmds_win if patch_cmds_win == None: patch_cmds_win = [] if patch_tool == None and hasattr(ctx.attr, "patch_tool"): patch_tool = ctx.attr.patch_tool if not patch_tool: patch_tool = "patch" native_patch = True else: native_patch = False if patch_args == None and hasattr(ctx.attr, "patch_args"): patch_args = ctx.attr.patch_args if patch_args == None: patch_args = [] if len(remote_patches) > 0 or len(patches) > 0 or len(patch_cmds) > 0: ctx.report_progress("Patching repository") # Apply remote patches for patch_url in remote_patches: integrity = remote_patches[patch_url] patchfile = _download_patch(ctx, patch_url, integrity, auth) ctx.patch(patchfile, remote_patch_strip) ctx.delete(patchfile) ctx.delete(ctx.path(_REMOTE_PATCH_DIR)) # Apply local patches if native_patch and _use_native_patch(patch_args) and not patch_directory: if patch_args: strip = int(patch_args[-1][2:]) else: strip = 0 for patchfile in patches: ctx.patch(patchfile, strip) else: for patchfile in patches: command = "{patchtool} {patch_args} < {patchfile}".format( patchtool = patch_tool, patchfile = ctx.path(patchfile), patch_args = " ".join([ "'%s'" % arg for arg in patch_args ]), ) st = ctx.execute([bash_exe, "-c", command], working_directory = patch_directory) if st.return_code: msg = "Error applying patch {}:\n{}{}".format(str(patchfile), st.stderr, st.stdout) fail(msg) if repo_utils.is_windows(ctx) and patch_cmds_win: for cmd in patch_cmds_win: st = ctx.execute([powershell_exe, "/c", cmd], working_directory = patch_directory) if st.return_code: msg = "Error applying patch command {}:\n{}{}".format(cmd, st.stdout, st.stderr) fail(msg) else: for cmd in patch_cmds: st = ctx.execute([bash_exe, "-c", cmd], working_directory = patch_directory) if st.return_code: msg = "Error applying patch command {}:\n{}{}".format(cmd, st.stdout, st.stderr) fail(msg) bazel-lib-2.22.5/lib/private/paths.bzl000066400000000000000000000121351513125663600175250ustar00rootroot00000000000000"""Path utils built on top of Skylib's path utils""" load("@bazel_skylib//lib:paths.bzl", _spaths = "paths") def _relative_file(to_file, frm_file): """Resolves a relative path between two files, "to_file" and "frm_file". If neither of the paths begin with ../ it is assumed that they share the same root. When finding the relative path, the incoming files are treated as actual files (not folders) so the resulting relative path may differ when compared to passing the same arguments to python's "os.path.relpath()" or NodeJs's "path.relative()". For example, 'relative_file("../foo/foo.txt", "bar/bar.txt")' will return '../../foo/foo.txt' Args: to_file: the path with file name to resolve to, from frm frm_file: the path with file name to resolve from Returns: The relative path from frm_file to to_file, including the file name """ to_parent_count = to_file.count("../") frm_parent_count = frm_file.count("../") parent_count = to_parent_count if to_parent_count > 0 and frm_parent_count > 0: if frm_parent_count > to_parent_count: fail("traversing more parent directories (with '../') for 'frm_file' than 'to_file' requires file layout knowledge") parent_count = to_parent_count - frm_parent_count to_segments = _spaths.normalize(to_file if to_file.startswith("/") else "/" + to_file).split("/")[:-1] frm_segments = _spaths.normalize(frm_file if frm_file.startswith("/") else "/" + frm_file).split("/")[:-1] to_segments_len = len(to_segments) frm_segments_len = len(frm_segments) if to_segments_len == 0 and frm_segments_len == 0: return to_file # since we prefix a "/" and normalize, the first segment is always "". So split point will be at least 1 split_point = 1 # if either of the paths starts with ../ then assume that any shared paths are a coincidence if to_segments[0] != ".." and frm_segments[0] != "..": i = 0 for _ in to_segments if to_segments_len <= frm_segments_len else frm_segments: if to_segments[i] != frm_segments[i]: break i += 1 split_point = i segments = [".."] * (frm_segments_len - split_point + parent_count) segments.extend(to_segments[split_point:]) segments.append(to_file[to_file.rfind("/") + 1:]) return "/".join(segments) def _to_output_relative_path(file): """ The relative path from bazel-out/[arch]/bin to the given File object Args: file: a `File` object Returns: The output relative path for the `File` """ if file.is_source: execroot = "../../../" else: execroot = "" if file.short_path.startswith("../"): path = "external/" + file.short_path[3:] else: path = file.short_path return execroot + path def _to_rlocation_path(ctx, file): """The rlocation path for a `File` This produces the same value as the `rlocationpath` predefined source/output path variable. From https://bazel.build/reference/be/make-variables#predefined_genrule_variables: > `rlocationpath`: The path a built binary can pass to the `Rlocation` function of a runfiles > library to find a dependency at runtime, either in the runfiles directory (if available) > or using the runfiles manifest. > This is similar to root path (a.k.a. [short_path](https://bazel.build/rules/lib/File#short_path)) > in that it does not contain configuration prefixes, but differs in that it always starts with the > name of the repository. > The rlocation path of a `File` in an external repository repo will start with `repo/`, followed by the > repository-relative path. > Passing this path to a binary and resolving it to a file system path using the runfiles libraries > is the preferred approach to find dependencies at runtime. Compared to root path, it has the > advantage that it works on all platforms and even if the runfiles directory is not available. Args: ctx: starlark rule execution context file: a `File` object Returns: The rlocationpath for the `File` """ if file.short_path.startswith("../"): return file.short_path[3:] else: return ctx.workspace_name + "/" + file.short_path def _to_repository_relative_path(file): """The repository relative path for a `File` This is the full runfiles path of a `File` excluding its workspace name. This differs from root path (a.k.a. [short_path](https://bazel.build/rules/lib/File#short_path)) and rlocation path as it does not include the repository name if the `File` is from an external repository. Args: file: a `File` object Returns: The repository relative path for the `File` """ if file.short_path.startswith("../"): return file.short_path[file.short_path.find("/", 3) + 1:] else: return file.short_path paths = struct( relative_file = _relative_file, to_output_relative_path = _to_output_relative_path, to_repository_relative_path = _to_repository_relative_path, to_rlocation_path = _to_rlocation_path, ) bazel-lib-2.22.5/lib/private/platform_utils.bzl000066400000000000000000000010551513125663600214510ustar00rootroot00000000000000"""Utility functions for platforms""" load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS") def _host_platform_is_darwin(): return "@platforms//os:osx" in HOST_CONSTRAINTS def _host_platform_is_linux(): return "@platforms//os:linux" in HOST_CONSTRAINTS def _host_platform_is_windows(): return "@platforms//os:windows" in HOST_CONSTRAINTS platform_utils = struct( host_platform_is_darwin = _host_platform_is_darwin, host_platform_is_linux = _host_platform_is_linux, host_platform_is_windows = _host_platform_is_windows, ) bazel-lib-2.22.5/lib/private/repo_utils.bzl000066400000000000000000000065601513125663600206000ustar00rootroot00000000000000"""Utility functions for repository rules""" def _is_darwin(rctx): """Returns true if the host operating system is Darwin""" return rctx.os.name.lower().startswith("mac os") def _is_linux(rctx): """Returns true if the host operating system is Linux""" return rctx.os.name.lower().startswith("linux") def _is_freebsd(rctx): """Returns true if the host operating system is FreeBSD""" return rctx.os.name.lower().startswith("freebsd") def _is_windows(rctx): """Returns true if the host operating system is Windows""" return rctx.os.name.lower().find("windows") != -1 def _os(rctx): """Returns the name of the host operating system Args: rctx: rctx Returns: The string "windows", "linux", "freebsd" or "darwin" that describes the host os """ if _is_darwin(rctx): return "darwin" if _is_linux(rctx): return "linux" if _is_freebsd(rctx): return "freebsd" if _is_windows(rctx): return "windows" fail("unrecognized os") def _get_env_var(rctx, name, default): """Find an environment variable in system. Doesn't %-escape the value! Args: rctx: rctx name: environment variable name default: default value to return if env var is not set in system Returns: The environment variable value or the default if it is not set """ # On Windows, the HOME environment variable is named differently. # See https://en.wikipedia.org/wiki/Home_directory#Default_home_directory_per_operating_system if name == "HOME" and _is_windows(rctx): name = "USERPROFILE" if name in rctx.os.environ: return rctx.os.environ[name] return default def _get_home_directory(rctx): return _get_env_var(rctx, "HOME", None) def _platform(rctx): """Returns a normalized name of the host os and CPU architecture. Alias archictures names are normalized: x86_64 => amd64 aarch64 => arm64 The result can be used to generate repository names for host toolchain repositories for toolchains that use these normalized names. Common os & architecture pairs that are returned are, - darwin_amd64 - darwin_arm64 - linux_amd64 - linux_arm64 - linux_s390x - linux_ppc64le - windows_amd64 Args: rctx: rctx Returns: The normalized "_" string of the host os and CPU architecture. """ os = _os(rctx) # NB: in bazel 5.1.1 rctx.os.arch was added which https://github.com/bazelbuild/bazel/commit/32d1606dac2fea730abe174c41870b7ee70ae041. # Once we drop support for anything older than Bazel 5.1.1 than we can simplify # this function. if os == "windows": proc_arch = (_get_env_var(rctx, "PROCESSOR_ARCHITECTURE", "") or _get_env_var(rctx, "PROCESSOR_ARCHITEW6432", "")) if proc_arch == "ARM64": arch = "arm64" else: arch = "amd64" else: arch = rctx.execute(["uname", "-m"]).stdout.strip() arch_map = { "x86_64": "amd64", "aarch64": "arm64", } if arch in arch_map.keys(): arch = arch_map[arch] return "%s_%s" % (os, arch) repo_utils = struct( is_darwin = _is_darwin, is_linux = _is_linux, is_windows = _is_windows, get_env_var = _get_env_var, get_home_directory = _get_home_directory, os = _os, platform = _platform, ) bazel-lib-2.22.5/lib/private/run_binary.bzl000066400000000000000000000225371513125663600205650ustar00rootroot00000000000000# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """run_binary implementation""" load("@bazel_skylib//lib:dicts.bzl", "dicts") load("//lib:resource_sets.bzl", "resource_set", "resource_set_attr") load("//lib:stamping.bzl", "STAMP_ATTRS", "maybe_stamp") load(":expand_variables.bzl", "expand_variables") load(":strings.bzl", "split_args") def _run_binary_impl(ctx): args = ctx.actions.args() outputs = [] outputs.extend(ctx.outputs.outs) for _out_dir in ctx.attr.out_dirs: out_dir = ctx.actions.declare_directory(_out_dir) for output in outputs: if output.path.startswith(out_dir.path + "/"): fail("output {} is nested within output directory {}; outputs cannot be nested within each other!".format(output.path, out_dir.path)) if output.is_directory and out_dir.path.startswith(output.path + "/"): fail("output directory {} is nested within output directory {}; outputs cannot be nested within each other!".format(out_dir.path, output.path)) outputs.append(out_dir) if len(outputs) < 1: fail("""\ ERROR: target {target} is not configured to produce any outputs. Bazel only executes actions when their outputs are required, so it's never correct to create an action with no outputs. Possible fixes: - Predict what outputs are created, and list them in the outs and out_dirs attributes. - If {rule_kind} is a binary, and you meant to run it for its side-effects, then call it directly with `bazel run` and don't wrap it in a run_binary rule. """.format( target = str(ctx.label), rule_kind = str(ctx.attr.tool.label), )) for a in ctx.attr.args: args.add_all(split_args(expand_variables(ctx, ctx.expand_location(a, targets = ctx.attr.srcs), inputs = ctx.files.srcs, outs = outputs))) envs = {} for k, v in ctx.attr.env.items(): envs[k] = expand_variables(ctx, ctx.expand_location(v, targets = ctx.attr.srcs), inputs = ctx.files.srcs, outs = outputs, attribute_name = "env") stamp = maybe_stamp(ctx) if stamp: inputs = ctx.files.srcs + [stamp.volatile_status_file, stamp.stable_status_file] envs["BAZEL_STABLE_STATUS_FILE"] = stamp.stable_status_file.path envs["BAZEL_VOLATILE_STATUS_FILE"] = stamp.volatile_status_file.path else: inputs = ctx.files.srcs ctx.actions.run( outputs = outputs, inputs = inputs, executable = ctx.executable.tool, arguments = [args], resource_set = resource_set(ctx.attr), mnemonic = ctx.attr.mnemonic if ctx.attr.mnemonic else None, progress_message = ctx.attr.progress_message if ctx.attr.progress_message else None, execution_requirements = ctx.attr.execution_requirements if ctx.attr.execution_requirements else None, use_default_shell_env = ctx.attr.use_default_shell_env, env = dicts.add(ctx.configuration.default_shell_env, envs), ) return DefaultInfo( files = depset(outputs), runfiles = ctx.runfiles(files = outputs), ) _run_binary = rule( implementation = _run_binary_impl, attrs = dicts.add({ "tool": attr.label( executable = True, allow_files = True, mandatory = True, cfg = "exec", ), "env": attr.string_dict(), "srcs": attr.label_list( allow_files = True, ), "out_dirs": attr.string_list(), "outs": attr.output_list(), "args": attr.string_list(), "mnemonic": attr.string(), "progress_message": attr.string(), "execution_requirements": attr.string_dict(), "use_default_shell_env": attr.bool(), }, resource_set_attr, STAMP_ATTRS), ) def run_binary( name, tool, srcs = [], args = [], env = {}, outs = [], out_dirs = [], mnemonic = "RunBinary", progress_message = None, execution_requirements = None, use_default_shell_env = False, stamp = 0, **kwargs): """Runs a binary as a build action. This rule does not require Bash (unlike `native.genrule`). Args: name: The target name tool: The tool to run in the action. Must be the label of a *_binary rule of a rule that generates an executable file, or of a file that can be executed as a subprocess (e.g. an .exe or .bat file on Windows or a binary with executable permission on Linux). This label is available for `$(location)` expansion in `args` and `env`. srcs: Additional inputs of the action. These labels are available for `$(location)` expansion in `args` and `env`. args: Command line arguments of the binary. Subject to `$(location)` and make variable expansions via [expand_location](./expand_make_vars#expand_locations) and [expand_make_vars](./expand_make_vars). env: Environment variables of the action. Subject to `$(location)` and make variable expansions via [expand_location](./expand_make_vars#expand_locations) and [expand_make_vars](./expand_make_vars). outs: Output files generated by the action. These labels are available for `$(location)` expansion in `args` and `env`. Output files cannot be nested within output directories in out_dirs. out_dirs: Output directories generated by the action. These labels are _not_ available for `$(location)` expansion in `args` and `env` since they are not pre-declared labels created via `attr.output_list()`. Output directories are declared instead by `ctx.actions.declare_directory`. Output directories cannot be nested within other output directories in out_dirs. mnemonic: A one-word description of the action, for example, CppCompile or GoLink. progress_message: Progress message to show to the user during the build, for example, "Compiling foo.cc to create foo.o". The message may contain %{label}, %{input}, or %{output} patterns, which are substituted with label string, first input, or output's path, respectively. Prefer to use patterns instead of static strings, because the former are more efficient. execution_requirements: Information for scheduling the action. For example, ``` execution_requirements = { "no-cache": "1", }, ``` See https://docs.bazel.build/versions/main/be/common-definitions.html#common.tags for useful keys. use_default_shell_env: Passed to the underlying ctx.actions.run. May introduce non-determinism when True; use with care! See e.g. https://github.com/bazelbuild/bazel/issues/4912 Refer to https://bazel.build/rules/lib/builtins/actions#run for more details. stamp: Whether to include build status files as inputs to the tool. Possible values: - `stamp = 0` (default): Never include build status files as inputs to the tool. This gives good build result caching. Most tools don't use the status files, so including them in `--stamp` builds makes those builds have many needless cache misses. (Note: this default is different from most rules with an integer-typed `stamp` attribute.) - `stamp = 1`: Always include build status files as inputs to the tool, even in [--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. This setting should be avoided, since it is non-deterministic. It potentially causes remote cache misses for the target and any downstream actions that depend on the result. - `stamp = -1`: Inclusion of build status files as inputs is controlled by the [--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag. Stamped targets are not rebuilt unless their dependencies change. When stamping is enabled, an additional two environment variables will be set for the action: - `BAZEL_STABLE_STATUS_FILE` - `BAZEL_VOLATILE_STATUS_FILE` These files can be read and parsed by the action, for example to pass some values to a linker. **kwargs: Additional arguments """ _run_binary( name = name, tool = tool, srcs = srcs, args = args, env = env, outs = outs, out_dirs = out_dirs, mnemonic = mnemonic, progress_message = progress_message, execution_requirements = execution_requirements, use_default_shell_env = use_default_shell_env, stamp = stamp, **kwargs ) bazel-lib-2.22.5/lib/private/source_toolchains_repo.bzl000066400000000000000000000066771513125663600231740ustar00rootroot00000000000000"""Create a repository to hold the toolchains This follows guidance here: https://docs.bazel.build/versions/main/skylark/deploying.html#registering-toolchains " Note that in order to resolve toolchains in the analysis phase Bazel needs to analyze all toolchain targets that are registered. Bazel will not need to analyze all targets referenced by toolchain.toolchain attribute. If in order to register toolchains you need to perform complex computation in the repository, consider splitting the repository with toolchain targets from the repository with _toolchain targets. Former will be always fetched, and the latter will only be fetched when user actually needs to build code. " The "complex computation" in our case is simply downloading large artifacts. This guidance tells us how to avoid that: we put the toolchain targets in the alias repository with only the toolchain attribute pointing into the platform-specific repositories. """ # Add more platforms as needed to mirror all the binaries # published by the upstream project. DEFS_TMPL = """\ # Generated by source_toolchains_repo.bzl for {toolchain_type} load("@bazel_skylib//lib:structs.bzl", "structs") # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["{toolchain_type}"] return [toolchain_info] + structs.to_dict(toolchain_info).values() # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["{toolchain_type}"], ) """ BUILD_TMPL = """\ # Generated by source_toolchains_repo.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all of these toolchains are registered by the oci_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") load("{toolchain_rule_load_from}", toolchain_rule = "{toolchain_rule}") resolved_toolchain(name = "current_toolchain", visibility = ["//visibility:public"]) toolchain_rule( name = "source", bin = "{binary}", visibility = ["//visibility:public"], ) toolchain( name = "toolchain", toolchain = ":source", toolchain_type = "{toolchain_type}", ) """ def _source_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 rctx.file("defs.bzl", DEFS_TMPL.format( toolchain_type = rctx.attr.toolchain_type, )) rctx.file("BUILD.bazel", BUILD_TMPL.format( toolchain_type = rctx.attr.toolchain_type, toolchain_rule_load_from = rctx.attr.toolchain_rule_load_from, toolchain_rule = rctx.attr.toolchain_rule, binary = rctx.attr.binary, )) source_toolchains_repo = repository_rule( _source_toolchains_repo_impl, doc = "Creates a repository with toolchain definitions for source binaries.", attrs = { "toolchain_type": attr.string(doc = "Label to the toolchain_type", mandatory = True), "toolchain_rule_load_from": attr.string(doc = "Label to the concrete toolchain rule to load from", mandatory = True), "toolchain_rule": attr.string(doc = "Name of the concrete toolchain rule", mandatory = True), "binary": attr.string(doc = "Label to the binary", mandatory = True), }, ) bazel-lib-2.22.5/lib/private/stamping.bzl000066400000000000000000000034001513125663600202230ustar00rootroot00000000000000"""A small utility module dedicated to detecting whether or not the `--stamp` flag is enabled This module can be removed likely after the following PRs ar addressed: - https://github.com/bazelbuild/bazel/issues/11164 """ StampSettingInfo = provider( doc = "Information about the `--stamp` command line flag", fields = { "value": "bool: Whether or not the `--stamp` flag was enabled", }, ) def _stamp_build_setting_impl(ctx): return StampSettingInfo(value = ctx.attr.value) _stamp_build_setting = rule( doc = "Adapter from our config_setting to a Provider for downstream rules", implementation = _stamp_build_setting_impl, attrs = { "value": attr.bool( doc = "The default value of the stamp build flag", mandatory = True, ), }, ) def stamp_build_setting(name, visibility = ["//visibility:public"]): native.config_setting( name = "stamp_detect", values = {"stamp": "1"}, visibility = visibility, ) _stamp_build_setting( name = name, value = select({ ":stamp_detect": True, "//conditions:default": False, }), visibility = visibility, ) def is_stamping_enabled(attr): """Determine whether or not build stamping is enabled. Args: attr (struct): A rule's struct of attributes (`ctx.attr`) Returns: bool: The stamp value """ stamp_num = getattr(attr, "stamp", -1) if stamp_num > 0: return True elif stamp_num == 0: return False elif stamp_num < 0: stamp_flag = getattr(attr, "_stamp_flag", None) return stamp_flag[StampSettingInfo].value if stamp_flag else False else: fail("Unexpected `stamp` value: {}".format(stamp_num)) bazel-lib-2.22.5/lib/private/strings.bzl000066400000000000000000000253141513125663600201020ustar00rootroot00000000000000"String utilities" CHAR_TO_INT = { "\0": 0, "\1": 1, "\2": 2, "\3": 3, "\4": 4, "\5": 5, "\6": 6, "\7": 7, "\10": 8, "\11": 9, "\12": 10, "\13": 11, "\14": 12, "\15": 13, "\16": 14, "\17": 15, "\20": 16, "\21": 17, "\22": 18, "\23": 19, "\24": 20, "\25": 21, "\26": 22, "\27": 23, "\30": 24, "\31": 25, "\32": 26, "\33": 27, "\34": 28, "\35": 29, "\36": 30, "\37": 31, "\40": 32, "\41": 33, "\42": 34, "\43": 35, "\44": 36, "\45": 37, "\46": 38, "\47": 39, "\50": 40, "\51": 41, "\52": 42, "\53": 43, "\54": 44, "\55": 45, "\56": 46, "\57": 47, "\60": 48, "\61": 49, "\62": 50, "\63": 51, "\64": 52, "\65": 53, "\66": 54, "\67": 55, "\70": 56, "\71": 57, "\72": 58, "\73": 59, "\74": 60, "\75": 61, "\76": 62, "\77": 63, "\100": 64, "\101": 65, "\102": 66, "\103": 67, "\104": 68, "\105": 69, "\106": 70, "\107": 71, "\110": 72, "\111": 73, "\112": 74, "\113": 75, "\114": 76, "\115": 77, "\116": 78, "\117": 79, "\120": 80, "\121": 81, "\122": 82, "\123": 83, "\124": 84, "\125": 85, "\126": 86, "\127": 87, "\130": 88, "\131": 89, "\132": 90, "\133": 91, "\134": 92, "\135": 93, "\136": 94, "\137": 95, "\140": 96, "\141": 97, "\142": 98, "\143": 99, "\144": 100, "\145": 101, "\146": 102, "\147": 103, "\150": 104, "\151": 105, "\152": 106, "\153": 107, "\154": 108, "\155": 109, "\156": 110, "\157": 111, "\160": 112, "\161": 113, "\162": 114, "\163": 115, "\164": 116, "\165": 117, "\166": 118, "\167": 119, "\170": 120, "\171": 121, "\172": 122, "\173": 123, "\174": 124, "\175": 125, "\176": 126, "\177": 127, "\200": 128, "\201": 129, "\202": 130, "\203": 131, "\204": 132, "\205": 133, "\206": 134, "\207": 135, "\210": 136, "\211": 137, "\212": 138, "\213": 139, "\214": 140, "\215": 141, "\216": 142, "\217": 143, "\220": 144, "\221": 145, "\222": 146, "\223": 147, "\224": 148, "\225": 149, "\226": 150, "\227": 151, "\230": 152, "\231": 153, "\232": 154, "\233": 155, "\234": 156, "\235": 157, "\236": 158, "\237": 159, "\240": 160, "\241": 161, "\242": 162, "\243": 163, "\244": 164, "\245": 165, "\246": 166, "\247": 167, "\250": 168, "\251": 169, "\252": 170, "\253": 171, "\254": 172, "\255": 173, "\256": 174, "\257": 175, "\260": 176, "\261": 177, "\262": 178, "\263": 179, "\264": 180, "\265": 181, "\266": 182, "\267": 183, "\270": 184, "\271": 185, "\272": 186, "\273": 187, "\274": 188, "\275": 189, "\276": 190, "\277": 191, "\300": 192, "\301": 193, "\302": 194, "\303": 195, "\304": 196, "\305": 197, "\306": 198, "\307": 199, "\310": 200, "\311": 201, "\312": 202, "\313": 203, "\314": 204, "\315": 205, "\316": 206, "\317": 207, "\320": 208, "\321": 209, "\322": 210, "\323": 211, "\324": 212, "\325": 213, "\326": 214, "\327": 215, "\330": 216, "\331": 217, "\332": 218, "\333": 219, "\334": 220, "\335": 221, "\336": 222, "\337": 223, "\340": 224, "\341": 225, "\342": 226, "\343": 227, "\344": 228, "\345": 229, "\346": 230, "\347": 231, "\350": 232, "\351": 233, "\352": 234, "\353": 235, "\354": 236, "\355": 237, "\356": 238, "\357": 239, "\360": 240, "\361": 241, "\362": 242, "\363": 243, "\364": 244, "\365": 245, "\366": 246, "\367": 247, "\370": 248, "\371": 249, "\372": 250, "\373": 251, "\374": 252, "\375": 253, "\376": 254, "\377": 255, } INT_TO_CHAR = [ "\0", "\1", "\2", "\3", "\4", "\5", "\6", "\7", "\10", "\11", "\12", "\13", "\14", "\15", "\16", "\17", "\20", "\21", "\22", "\23", "\24", "\25", "\26", "\27", "\30", "\31", "\32", "\33", "\34", "\35", "\36", "\37", "\40", "\41", "\42", "\43", "\44", "\45", "\46", "\47", "\50", "\51", "\52", "\53", "\54", "\55", "\56", "\57", "\60", "\61", "\62", "\63", "\64", "\65", "\66", "\67", "\70", "\71", "\72", "\73", "\74", "\75", "\76", "\77", "\100", "\101", "\102", "\103", "\104", "\105", "\106", "\107", "\110", "\111", "\112", "\113", "\114", "\115", "\116", "\117", "\120", "\121", "\122", "\123", "\124", "\125", "\126", "\127", "\130", "\131", "\132", "\133", "\134", "\135", "\136", "\137", "\140", "\141", "\142", "\143", "\144", "\145", "\146", "\147", "\150", "\151", "\152", "\153", "\154", "\155", "\156", "\157", "\160", "\161", "\162", "\163", "\164", "\165", "\166", "\167", "\170", "\171", "\172", "\173", "\174", "\175", "\176", "\177", "\200", "\201", "\202", "\203", "\204", "\205", "\206", "\207", "\210", "\211", "\212", "\213", "\214", "\215", "\216", "\217", "\220", "\221", "\222", "\223", "\224", "\225", "\226", "\227", "\230", "\231", "\232", "\233", "\234", "\235", "\236", "\237", "\240", "\241", "\242", "\243", "\244", "\245", "\246", "\247", "\250", "\251", "\252", "\253", "\254", "\255", "\256", "\257", "\260", "\261", "\262", "\263", "\264", "\265", "\266", "\267", "\270", "\271", "\272", "\273", "\274", "\275", "\276", "\277", "\300", "\301", "\302", "\303", "\304", "\305", "\306", "\307", "\310", "\311", "\312", "\313", "\314", "\315", "\316", "\317", "\320", "\321", "\322", "\323", "\324", "\325", "\326", "\327", "\330", "\331", "\332", "\333", "\334", "\335", "\336", "\337", "\340", "\341", "\342", "\343", "\344", "\345", "\346", "\347", "\350", "\351", "\352", "\353", "\354", "\355", "\356", "\357", "\360", "\361", "\362", "\363", "\364", "\365", "\366", "\367", "\370", "\371", "\372", "\373", "\374", "\375", "\376", "\377", ] def ord(c): """returns the codepoint of a character ord(c) returns the integer value of the sole Unicode code point encoded by the string `c`. If `c` does not encode exactly one Unicode code point, `ord` fails. Each invalid code within the string is treated as if it encodes the Unicode replacement character, U+FFFD. Args: c: character whose codepoint to be returned. Returns: codepoint of `c` argument. """ if len(c) != 1: fail("expected a string with a single character") return CHAR_TO_INT.get(c) def chr(i): """returns a string encoding a codepoint chr returns a string that encodes the single Unicode code point whose value is specified by the integer `i` Args: i: position of the character Returns: unicode string of the position """ if i < 0 or i > 255: fail("expected a int between 0 and 255 (inclusive)") return INT_TO_CHAR[i] def _to_char(n): alpha = "0123456789abcdef" return alpha[n] def hex(number): """Format integer to hexadecimal representation Args: number: number to format Returns: hexadecimal representation of the number argument """ hex_string = "" is_signed = number < 0 r = number * -1 if is_signed else number for _ in range(1000000): if r > 0: rem = r % 16 hex_string = _to_char(rem) + hex_string r //= 16 else: break if not hex_string: hex_string = "0" return "{}0x{}".format("-" if is_signed else "", hex_string) def split_args(s): """Split a string into a list space separated arguments Unlike the naive `.split(" ")`, this function takes quoted strings and escapes into account. Args: s: input string Returns: list of strings with each an argument found in the input string """ args = [] arg = "" single_quote = False double_quote = False escape = False for c in s.elems(): if c == "\\": escape = True continue if escape: # this is an escaped character if c == " ": # a dangling escape is not an escape, put the backslack back arg = arg + "\\" else: escape = False else: # not an escaped character, look for quotes & spaces if c == "'": # single quote char if double_quote: # we're in a double quote so single quotes are just chars pass elif single_quote: # end of single quote single_quote = False continue else: # start of single quote single_quote = True continue elif c == "\"": # double quote char if single_quote: # we're in a single quote so double quotes are just chars pass elif double_quote: # end of double quote double_quote = False continue else: # start of double quote double_quote = True continue if c == " ": if not single_quote and not double_quote: # splitting space if arg != "": args.append(arg) arg = "" continue arg = arg + c # final arg? if arg != "": args.append(arg) return args bazel-lib-2.22.5/lib/private/strings.py000066400000000000000000000007531513125663600177430ustar00rootroot00000000000000# python utility to seed the starlark constants in strings.bzl print("") print("CHAR_TO_INT = {") for i in range(256): print(" \"\{o}\": {i},".format( o = oct(i)[2:], i = i, )) print("}") print("") print("INT_TO_CHAR = [") for i in range(256): print(" \"\{o}\",".format( o = oct(i)[2:], )) print("]") print("") print("INT_TO_BINARY = [") for i in range(256): print(" \"{b}\",".format( b = "{:0>8}".format(bin(i)[2:]) )) print("]") bazel-lib-2.22.5/lib/private/tar_toolchain.bzl000066400000000000000000000153661513125663600212450ustar00rootroot00000000000000"Provide access to a BSD tar" load(":utf8_environment.bzl", "Utf8EnvironmentInfo") BSDTAR_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:osx", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:osx", "@platforms//cpu:aarch64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:aarch64", ], ), } BSDTAR_PREBUILT = { "darwin_amd64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1/tar_darwin_amd64", "921118f1d043aff08a8d7d7b477217781efb9dacad111646add724bc51575c6a", ), "darwin_arm64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1/tar_darwin_arm64", "9e78a0b3e21bc05c67e54004e5b29c2b19c3a9f16ccec4de2a227b1e01aea5fd", ), "linux_amd64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1/tar_linux_amd64", "a703af6fc8df1a89f1ca864c651a9003b75069dd6b80bd32dcd94a7d255df07d", ), "linux_arm64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1/tar_linux_arm64", "663f498baab2a9b7758e46d0c377b311c5b058758a37958372a0503c5dda4028", ), "windows_arm64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1-fix.1/tar_windows_arm64.exe", "130d69268b0a387bca387d00663821779dd1915557caf7fcbfd5ded3f41074f3", ), "windows_amd64": ( "https://github.com/aspect-build/bsdtar-prebuilt/releases/download/v3.8.1-fix.1/tar_windows_x86_64.exe", "f48c81e1812956adb4906c6f057ca856dd280a455e7867d77800e6d5ef9fc81d", ), } def _bsdtar_binary_repo(rctx): (url, sha256) = BSDTAR_PREBUILT[rctx.attr.platform] binary = "tar.exe" if rctx.attr.platform.startswith("windows") else "tar" rctx.download( url = url, output = binary, executable = True, sha256 = sha256, ) rctx.file("BUILD.bazel", """\ # @generated by @aspect_bazel_lib//lib/private:tar_toolchain.bzl load("@aspect_bazel_lib//lib/private:tar_toolchain.bzl", "tar_toolchain") package(default_visibility = ["//visibility:public"]) tar_toolchain(name = "bsdtar_toolchain", binary = "{}") """.format(binary)) bsdtar_binary_repo = repository_rule( implementation = _bsdtar_binary_repo, attrs = { "platform": attr.string(mandatory = True, values = BSDTAR_PLATFORMS.keys()), }, ) TarInfo = provider( doc = "Provide info for executing BSD tar", fields = { # environment appears on the toolchain since it's platform-specific, and we want to pair it with the tool. # Currently known to be required only for the extract mode; see # https://github.com/bazelbuild/bazel-central-registry/issues/2256 "default_env": "environment variables which should be set when spawning tar, to ensure reproducible results", "binary": "tar executable", }, ) def _tar_toolchain_impl(ctx): binary = ctx.executable.binary # Make the $(BSDTAR_BIN) variable available in places like genrules. # See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables template_variables = platform_common.TemplateVariableInfo({ "BSDTAR_BIN": binary.path, }) default_info = DefaultInfo( files = depset(ctx.files.binary + ctx.files.files), ) tarinfo = TarInfo( default_env = ctx.attr._utf8_environment[Utf8EnvironmentInfo].environment, binary = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( tarinfo = tarinfo, template_variables = template_variables, default = default_info, ) return [toolchain_info, template_variables, default_info] tar_toolchain = rule( implementation = _tar_toolchain_impl, attrs = { "binary": attr.label( doc = "a command to find on the system path", allow_files = True, executable = True, cfg = "exec", ), "_utf8_environment": attr.label( default = ":utf8_environment", cfg = "exec", ), "files": attr.label_list(allow_files = True), }, ) def _tar_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """\ # @generated by @aspect_bazel_lib//lib/private:tar_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:tar_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.tarinfo, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:tar_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:tar_toolchain.bzl load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"])""" for [platform, meta] in BSDTAR_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:bsdtar_toolchain", toolchain_type = "@aspect_bazel_lib//lib:tar_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) rctx.file("BUILD.bazel", build_content) tar_toolchains_repo = repository_rule( _tar_toolchains_repo_impl, doc = """Creates a repository that exposes a tar_toolchain_type target.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) bazel-lib-2.22.5/lib/private/utf8_environment.bzl000066400000000000000000000052271513125663600217240ustar00rootroot00000000000000# Vendored from # https://github.com/bazelbuild/rules_java/blob/c22454fadb4773cbd202bfa3e28f1d6a88c4c94a/toolchains/utf8_environment.bzl # # Copyright 2024 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Determines the environment required for actions to support UTF-8. """ Utf8EnvironmentInfo = provider( doc = "The environment required for actions to support UTF-8.", fields = { "environment": "The environment to use for actions to support UTF-8.", }, ) # NB: https://github.com/bazelbuild/rules_java/blob/c22454fadb4773cbd202bfa3e28f1d6a88c4c94a/toolchains/utf8_environment.bzl # uses LC_CTYPE which is technically more correct: # > The LC_CTYPE category determines character handling rules governing the interpretation of # > sequences of bytes of text data characters (that is, single-byte versus multibyte characters), # > the classification of characters (for example, alpha, digit, and so on), # > and the behavior of character classes. # # However libarchive only looks for LC_ALL, otherwise it spams warnings like "tar: Failed to set default locale" # https://github.com/libarchive/libarchive/blob/65196fdd1a385f22114f245a9002ee8dc899f2c4/tar/bsdtar.c#L192 # Docs for LC_ALL: # > Overrides the value of the LANG environment variable and the values of any other LC_* environment variables. _LOCALE_VAR = "LC_ALL" # The default UTF-8 locale on all recent Linux distributions. It is also available in Cygwin and # MSYS2, but doesn't matter for determining the bsdtar encoding on Windows, which always # uses the active code page. _DEFAULT = "C.UTF-8" # macOS doesn't have the C.UTF-8 locale, but en_US.UTF-8 is available and works the same way. _MACOS = "en_US.UTF-8" def _utf8_environment_impl(ctx): is_macos = ctx.target_platform_has_constraint(ctx.attr._macos_constraint[platform_common.ConstraintValueInfo]) return Utf8EnvironmentInfo(environment = {_LOCALE_VAR: _MACOS if is_macos else _DEFAULT}) utf8_environment = rule( _utf8_environment_impl, attrs = { "_macos_constraint": attr.label(default = "@platforms//os:macos"), }, doc = "Returns a suitable environment for actions to support UTF-8.", ) bazel-lib-2.22.5/lib/private/utils.bzl000066400000000000000000000314531513125663600175520ustar00rootroot00000000000000"""General utility functions""" load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_archive = "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def _propagate_well_known_tags(tags = []): """Returns a list of tags filtered from the input set that only contains the ones that are considered "well known" These are listed in Bazel's documentation: https://docs.bazel.build/versions/main/test-encyclopedia.html#tag-conventions https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes Args: tags: List of tags to filter Returns: List of tags that only contains the well known set """ WELL_KNOWN_TAGS = [ "no-sandbox", "no-cache", "no-remote-cache", "no-remote-exec", "no-remote", "local", "requires-network", "block-network", "requires-fakeroot", "exclusive", "manual", "external", ] # cpu:n tags allow setting the requested number of CPUs for a test target. # More info at https://docs.bazel.build/versions/main/test-encyclopedia.html#other-resources CPU_PREFIX = "cpu:" return [ tag for tag in tags if tag in WELL_KNOWN_TAGS or tag.startswith(CPU_PREFIX) ] def _to_label(param): """Converts a string to a Label. If Label is supplied, the same label is returned. Args: param: a string representing a label or a Label Returns: a Label """ root_repo = "@@" if _is_bazel_6_or_greater() else "@" param_type = type(param) if param_type == "string": if param.startswith("@"): return Label(param) if param.startswith("//"): return Label("{}{}".format(root_repo, param)) if param.startswith(":"): param = param[1:] return Label("{}//{}:{}".format(root_repo, native.package_name(), param)) elif param_type == "Label": return param else: msg = "Expected 'string' or 'Label' but got '{}'".format(param_type) fail(msg) def _consistent_label_str(ctx, label): """Generate a consistent label string for all Bazel versions. Starting in Bazel 6, the workspace name is empty for the local workspace and there's no other way to determine it. This behavior differs from Bazel 5 where the local workspace name was fully qualified in str(label). This utility function is meant for use in rules and requires the rule context to determine the user's workspace name (`ctx.workspace_name`). Args: ctx: The rule context. label: A Label. Returns: String representation of the label including the repository name if the label is from an external repository. For labels in the user's repository the label will start with `@//`. """ return "@{}//{}:{}".format( "" if label.workspace_name == ctx.workspace_name else label.workspace_name, label.package, label.name, ) def _is_external_label(param): """Returns True if the given Label (or stringy version of a label) represents a target outside of the workspace Args: param: a string or label Returns: a bool """ if not _is_bazel_6_or_greater() and str(param).startswith("@@//"): # Work-around for https://github.com/bazelbuild/bazel/issues/16528 return False return len(_to_label(param).workspace_root) > 0 # Path to the root of the workspace def _path_to_workspace_root(): """ Returns the path to the workspace root under bazel Returns: Path to the workspace root """ return "/".join([".."] * len(native.package_name().split("/"))) # Like glob() but returns directories only def _glob_directories(include, **kwargs): all = native.glob(include, exclude_directories = 0, **kwargs) files = native.glob(include, **kwargs) directories = [p for p in all if p not in files] return directories def _file_exists(path): """Check whether a file exists. Useful in macros to set defaults for a configuration file if it is present. This can only be called during the loading phase, not from a rule implementation. Args: path: a label, or a string which is a path relative to this package """ label = _to_label(path) file_abs = "%s/%s" % (label.package, label.name) file_rel = file_abs[len(native.package_name()) + 1:] file_glob = native.glob([file_rel], exclude_directories = 1, allow_empty = True) return len(file_glob) > 0 def _default_timeout(size, timeout): """Provide a sane default for *_test timeout attribute. The [test-encyclopedia](https://bazel.build/reference/test-encyclopedia) says: > Tests may return arbitrarily fast regardless of timeout. > A test is not penalized for an overgenerous timeout, although a warning may be issued: > you should generally set your timeout as tight as you can without incurring any flakiness. However Bazel's default for timeout is medium, which is dumb given this guidance. It also says: > Tests which do not explicitly specify a timeout have one implied based on the test's size as follows Therefore if size is specified, we should allow timeout to take its implied default. If neither is set, then we can fix Bazel's wrong default here to avoid warnings under `--test_verbose_timeout_warnings`. This function can be used in a macro which wraps a testing rule. Args: size: the size attribute of a test target timeout: the timeout attribute of a test target Returns: "short" if neither is set, otherwise timeout """ if size == None and timeout == None: return "short" return timeout def _is_bazel_6_or_greater(): """Detects if the Bazel version being used is greater than or equal to 6 (including Bazel 6 pre-releases and RCs). Detecting Bazel 6 or greater is particularly useful in rules as slightly different code paths may be needed to support bzlmod which was added in Bazel 6. Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. Returns: True if the Bazel version being used is greater than or equal to 6 (including pre-releases and RCs) """ # Hacky way to check if the we're using at least Bazel 6. Would be nice if there was a ctx.bazel_version instead. # native.bazel_version only works in repository rules. return "apple_binary" not in dir(native) def _is_bazel_7_or_greater(): """Detects if the Bazel version being used is greater than or equal to 7 (including Bazel 7 pre-releases and RCs). Unlike the undocumented `native.bazel_version`, which only works in WORKSPACE and repository rules, this function can be used in rules and BUILD files. An alternate approach to make the Bazel version available in BUILD files and rules would be to use the [host_repo](https://github.com/bazel-contrib/bazel-lib/blob/main/docs/host_repo.md) repository rule which contains the bazel_version in the exported `host` struct: WORKSPACE: ``` load("@aspect_bazel_lib//lib:host_repo.bzl", "host_repo") host_repo(name = "aspect_bazel_lib_host") ``` BUILD.bazel: ``` load("@aspect_bazel_lib_host//:defs.bzl", "host") print(host.bazel_version) ``` That approach, however, incurs a cost in the user's WORKSPACE. Returns: True if the Bazel version being used is greater than or equal to 7 (including pre-releases and RCs) """ # Hacky way to check if the we're using at least Bazel 7. Would be nice if there was a ctx.bazel_version instead. # native.bazel_version only works in repository rules. return "apple_binary" not in dir(native) and "cc_host_toolchain_alias" not in dir(native) def is_bzlmod_enabled(): """Detect the value of the --enable_bzlmod flag""" return str(Label("//:BUILD.bazel")).startswith("@@") def _maybe_http_archive(**kwargs): """Adapts a maybe(http_archive, ...) to look like an http_archive. This makes WORKSPACE dependencies easier to read and update. Typical usage looks like, ``` load("//lib:utils.bzl", http_archive = "maybe_http_archive") http_archive( name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` instead of the classic maybe pattern of, ``` load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") maybe( http_archive, name = "aspect_rules_js", sha256 = "5bb643d9e119832a383e67f946dc752b6d719d66d1df9b46d840509ceb53e1f1", strip_prefix = "rules_js-1.6.2", url = "https://github.com/aspect-build/rules_js/archive/refs/tags/v1.6.2.tar.gz", ) ``` Args: **kwargs: all arguments to pass-forward to http_archive """ maybe(_http_archive, **kwargs) _COMMON_RULE_ATTRIBUTES = [ "compatible_with", "deprecation", "distribs", "exec_compatible_with", "exec_properties", "features", "restricted_to", "tags", "target_compatible_with", "testonly", "toolchains", "visibility", ] _COMMON_TEST_RULE_ATTRIBUTES = _COMMON_RULE_ATTRIBUTES + [ "args", "env", "env_inherit", "size", "timeout", "flaky", "shard_count", "local", ] _COMMON_BINARY_RULE_ATTRIBUTES = _COMMON_RULE_ATTRIBUTES + [ "args", "env", "output_licenses", ] def _propagate_common_rule_attributes(attrs): """Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes Args: attrs: Dict of parameters to filter Returns: The dict of parameters, containing only common attributes """ return { k: attrs[k] for k in attrs if k in _COMMON_RULE_ATTRIBUTES } def _propagate_common_test_rule_attributes(attrs): """Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all test rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-tests Args: attrs: Dict of parameters to filter Returns: The dict of parameters, containing only common test attributes """ return { k: attrs[k] for k in attrs if k in _COMMON_TEST_RULE_ATTRIBUTES } def _propagate_common_binary_rule_attributes(attrs): """Returns a dict of rule parameters filtered from the input dict that only contains the ones that are common to all binary rules These are listed in Bazel's documentation: https://bazel.build/reference/be/common-definitions#common-attributes https://bazel.build/reference/be/common-definitions#common-attributes-binary Args: attrs: Dict of parameters to filter Returns: The dict of parameters, containing only common binary attributes """ return { k: attrs[k] for k in attrs if k in _COMMON_RULE_ATTRIBUTES or k in _COMMON_BINARY_RULE_ATTRIBUTES } utils = struct( default_timeout = _default_timeout, file_exists = _file_exists, glob_directories = _glob_directories, is_bazel_6_or_greater = _is_bazel_6_or_greater, is_bazel_7_or_greater = _is_bazel_7_or_greater, is_bzlmod_enabled = is_bzlmod_enabled, is_external_label = _is_external_label, maybe_http_archive = _maybe_http_archive, path_to_workspace_root = _path_to_workspace_root, propagate_well_known_tags = _propagate_well_known_tags, propagate_common_rule_attributes = _propagate_common_rule_attributes, propagate_common_test_rule_attributes = _propagate_common_test_rule_attributes, propagate_common_binary_rule_attributes = _propagate_common_binary_rule_attributes, to_label = _to_label, consistent_label_str = _consistent_label_str, ) bazel-lib-2.22.5/lib/private/write_source_file.bzl000066400000000000000000000427311513125663600221240ustar00rootroot00000000000000"write_source_file implementation" load(":diff_test.bzl", _diff_test = "diff_test") load(":directory_path.bzl", "DirectoryPathInfo") load(":fail_with_message_test.bzl", "fail_with_message_test") load(":utils.bzl", "utils") WriteSourceFileInfo = provider( "Provider for write_source_file targets", fields = { "executable": "Executable that updates the source files", }, ) def write_source_file( name, in_file = None, out_file = None, executable = False, additional_update_targets = [], suggested_update_target = None, diff_test = True, diff_test_failure_message = "{{DEFAULT_MESSAGE}}", file_missing_failure_message = "{{DEFAULT_MESSAGE}}", diff_args = [], check_that_out_file_exists = True, verbosity = "full", **kwargs): """Write a file or directory to the source tree. By default, a `diff_test` target ("{name}_test") is generated that ensure the source tree file or directory to be written to is up to date and the rule also checks that the source tree file or directory to be written to exists. To disable the exists check and up-to-date test set `diff_test` to `False`. Args: name: Name of the runnable target that creates or updates the source tree file or directory. in_file: File or directory to use as the desired content to write to `out_file`. This is typically a file or directory output of another target. If `in_file` is a directory then entire directory contents are copied. out_file: The file or directory to write to in the source tree. The output file or directory must be within the same containing Bazel package as this target if `check_that_out_file_exists` is `True`. See `check_that_out_file_exists` docstring for more info. executable: Whether source tree file or files within the source tree directory written should be made executable. additional_update_targets: List of other `write_source_files` or `write_source_file` targets to call in the same run. suggested_update_target: Label of the `write_source_files` or `write_source_file` target to suggest running when files are out of date. diff_test: Test that the source tree file or directory exist and is up to date. diff_test_failure_message: Text to print when the diff test fails, with templating options for relevant targets. Substitutions are performed on the failure message, with the following substitutions being available: `{{DEFAULT_MESSAGE}}`: Prints the default error message, listing the target(s) that may be run to update the file(s). `{{TARGET}}`: The target to update the individual file that does not match in the diff test. `{{SUGGESTED_UPDATE_TARGET}}`: The suggested_update_target if specified. file_missing_failure_message: Text to print when the output file is missing. Subject to the same substitutions as diff_test_failure_message. diff_args: Arguments to pass to the `diff` command. (Ignored on Windows) check_that_out_file_exists: Test that the output file exists and print a helpful error message if it doesn't. If `True`, the output file or directory must be in the same containing Bazel package as the target since the underlying mechanism for this check is limited to files in the same Bazel package. verbosity: Verbosity of message when the copy target is run. One of `full`, `short`, `quiet`. **kwargs: Other common named parameters such as `tags` or `visibility` Returns: Name of the generated test target if requested, otherwise None. """ if out_file: if not in_file: fail("in_file must be specified if out_file is set") if in_file: if not out_file: fail("out_file must be specified if in_file is set") if out_file: out_file = utils.to_label(out_file) if utils.is_external_label(out_file): msg = "out file {} must be in the user workspace".format(out_file) fail(msg) if check_that_out_file_exists and out_file.package != native.package_name(): msg = "out file {} (in package '{}') must be a source file within the target's package: '{}'; set check_that_out_file_exists to False to work-around this requirement".format(out_file, out_file.package, native.package_name()) fail(msg) _write_source_file( name = name, in_file = in_file, out_file = str(out_file) if out_file else None, executable = executable, additional_update_targets = additional_update_targets, verbosity = verbosity, **kwargs ) if not in_file or not out_file or not diff_test: return None out_file_missing = check_that_out_file_exists and _is_file_missing(out_file) test_target_name = "%s_test" % name update_target_string = "//%s:%s" % (native.package_name(), name) suggested_update_target_string = str(utils.to_label(suggested_update_target)) if suggested_update_target else None if out_file_missing: if suggested_update_target == None: default_message = """ %s does not exist. To create & update this file, run: bazel run %s """ % (out_file, update_target_string) else: default_message = """ %s does not exist. To create & update this and other generated files, run: bazel run %s To create an update *only* this file, run: bazel run %s """ % (out_file, suggested_update_target_string, update_target_string) message = _do_diff_test_message_replacements(file_missing_failure_message, default_message, update_target_string, suggested_update_target_string) # Stamp out a test that fails with a helpful message when the source file doesn't exist. # Note that we cannot simply call fail() here since it will fail during the analysis # phase and prevent the user from calling bazel run //update/the:file. fail_with_message_test( name = test_target_name, message = message, visibility = kwargs.get("visibility"), tags = kwargs.get("tags"), size = "small", ) else: if suggested_update_target == None: default_message = """ %s is out of date. To update this file, run: bazel run %s """ % (out_file, update_target_string) else: default_message = """ %s is out of date. To update this and other generated files, run: bazel run %s To update *only* this file, run: bazel run %s """ % (out_file, suggested_update_target_string, update_target_string) message = _do_diff_test_message_replacements(diff_test_failure_message, default_message, update_target_string, suggested_update_target_string) # Stamp out a diff test the check that the source file is up to date _diff_test( name = test_target_name, file1 = in_file, file2 = out_file, failure_message = message, diff_args = diff_args, **kwargs ) return test_target_name _write_source_file_attrs = { "in_file": attr.label(allow_files = True, mandatory = False), # out_file is intentionally an attr.string() and not a attr.label(). This is so that # bazel query 'kind("source file", deps(//path/to:target))' does not return # out_file in the list of source file deps. ibazel uses this query to determine # which source files to watch so if the out_file is returned then ibazel watches # and it goes into an infinite update, notify loop when running this target. # See https://github.com/bazel-contrib/bazel-lib/pull/52 for more context. "out_file": attr.string(mandatory = False), "executable": attr.bool(), # buildifier: disable=attr-cfg "additional_update_targets": attr.label_list( # Intentionally use the target platform since the target is always meant to be `bazel run` # on the host machine but we don't want to transition it to the host platform and have the # generated file rebuilt in a separate output tree. Target platform should always be equal # to the host platform when using `write_source_files`. cfg = "target", mandatory = False, providers = [WriteSourceFileInfo], ), "verbosity": attr.string( values = ["full", "short", "quiet"], ), "_windows_constraint": attr.label(default = "@platforms//os:windows"), "_macos_constraint": attr.label(default = "@platforms//os:macos"), } def _write_source_file_sh(ctx, paths): is_macos = ctx.target_platform_has_constraint(ctx.attr._macos_constraint[platform_common.ConstraintValueInfo]) updater = ctx.actions.declare_file( ctx.label.name + "_update.sh", ) additional_update_scripts = [] for target in ctx.attr.additional_update_targets: additional_update_scripts.append(target[WriteSourceFileInfo].executable) contents = ["""#!/usr/bin/env bash set -o errexit -o nounset -o pipefail runfiles_dir=$PWD # BUILD_WORKSPACE_DIRECTORY not set when running as a test, uses the sandbox instead if [[ ! -z "${BUILD_WORKSPACE_DIRECTORY:-}" ]]; then cd "$BUILD_WORKSPACE_DIRECTORY" fi"""] if ctx.attr.executable: executable_file = "chmod +x \"$out\"" executable_dir = "chmod -R +x \"$out\"" else: executable_file = "chmod -x \"$out\"" if is_macos: # -x+X doesn't work on macos so we have to find files and remove the execute bits only from those executable_dir = "find \"$out\" -type f | xargs chmod -x" else: # Remove execute/search bit recursively from files bit not directories: https://superuser.com/a/434418 executable_dir = "chmod -R -x+X \"$out\"" progress_message_dir = "" progress_message_file = "" if ctx.attr.verbosity == "full": progress_message_dir = "echo \"Copying directory $in to $out in $PWD\"" progress_message_file = "echo \"Copying file $in to $out in $PWD\"" elif ctx.attr.verbosity == "short": progress_message_dir = "echo \"Updating directory $out\"" progress_message_file = "echo \"Updating file $out\"" for in_path, out_path in paths: contents.append(""" in=$runfiles_dir/{in_path} out={out_path} mkdir -p "$(dirname "$out")" if [[ -f "$in" ]]; then {progress_message_file} # in case `cp` from previous command was terminated midway which can result in read-only files/dirs chmod -R +w "$out" > /dev/null 2>&1 || true rm -Rf "$out" cp -f "$in" "$out" # cp should make the file writable but call chmod anyway as a defense in depth chmod +w "$out" # cp should make the file not-executable but set the desired execute bit in both cases as a defense in depth {executable_file} else {progress_message_dir} # in case `cp` from previous command was terminated midway which can result in read-only files/dirs chmod -R +w "$out" > /dev/null 2>&1 || true rm -Rf "$out"/{{*,.[!.]*}} mkdir -p "$out" cp -fRL "$in"/. "$out" chmod -R +w "$out" {executable_dir} fi """.format( in_path = in_path, out_path = out_path, executable_file = executable_file, executable_dir = executable_dir, progress_message_dir = progress_message_dir, progress_message_file = progress_message_file, )) contents.extend([ "cd \"$runfiles_dir\"", "# Run the update scripts for all write_source_file deps", ]) for update_script in additional_update_scripts: contents.append("./\"{update_script}\"".format(update_script = update_script.short_path)) ctx.actions.write( output = updater, is_executable = True, content = "\n".join(contents), ) return updater def _write_source_file_bat(ctx, paths): updater = ctx.actions.declare_file( ctx.label.name + "_update.bat", ) additional_update_scripts = [] for target in ctx.attr.additional_update_targets: if target[DefaultInfo].files_to_run and target[DefaultInfo].files_to_run.executable: additional_update_scripts.append(target[DefaultInfo].files_to_run.executable) else: fail("additional_update_targets target %s does not provide an executable") contents = ["""@rem @generated by @aspect_bazel_lib//:lib/private:write_source_file.bzl @echo off set runfiles_dir=%cd% if defined BUILD_WORKSPACE_DIRECTORY ( cd /d %BUILD_WORKSPACE_DIRECTORY% )"""] progress_message = "" if ctx.attr.verbosity == "full": progress_message = "echo Copying %in% to %out% in %cd%" elif ctx.attr.verbosity == "short": progress_message = "echo Updating %out%" for in_path, out_path in paths: contents.append(""" set in=%runfiles_dir%\\{in_path} set out={out_path} if not defined BUILD_WORKSPACE_DIRECTORY ( @rem Because there's no sandboxing in windows, if we copy over the target @rem file's symlink it will get copied back into the source directory @rem during tests. Work around this in tests by deleting the target file @rem symlink before copying over it. del %out% ) {progress_message} if exist "%in%\\*" ( mkdir "%out%" >NUL 2>NUL robocopy "%in%" "%out%" /E >NUL ) else ( copy %in% %out% >NUL ) """.format( in_path = in_path.replace("/", "\\"), out_path = out_path.replace("/", "\\"), progress_message = progress_message, )) contents.extend([ "cd /d %runfiles_dir%", "@rem Run the update scripts for all write_source_file deps", ]) for update_script in additional_update_scripts: contents.append("call {update_script}".format(update_script = update_script.short_path)) ctx.actions.write( output = updater, is_executable = True, content = "\n".join(contents).replace("\n", "\r\n"), ) return updater def _write_source_file_impl(ctx): is_windows = ctx.target_platform_has_constraint(ctx.attr._windows_constraint[platform_common.ConstraintValueInfo]) out_file = Label(ctx.attr.out_file) if ctx.attr.out_file else None if out_file and not ctx.attr.in_file: fail("in_file must be specified if out_file is set") if ctx.attr.in_file and not out_file: fail("out_file must be specified if in_file is set") paths = [] runfiles = [] if ctx.attr.in_file and out_file: if DirectoryPathInfo in ctx.attr.in_file: in_path = "/".join([ ctx.attr.in_file[DirectoryPathInfo].directory.short_path, ctx.attr.in_file[DirectoryPathInfo].path, ]) runfiles.append(ctx.attr.in_file[DirectoryPathInfo].directory) elif len(ctx.files.in_file) == 0: msg = "in file {} must provide files".format(ctx.attr.in_file.label) fail(msg) elif len(ctx.files.in_file) == 1: in_path = ctx.files.in_file[0].short_path else: msg = "in file {} must be a single file or a target that provides a DirectoryPathInfo".format(ctx.attr.in_file.label) fail(msg) out_path = "/".join([out_file.package, out_file.name]) if out_file.package else out_file.name paths.append((in_path, out_path)) if is_windows: updater = _write_source_file_bat(ctx, paths) else: updater = _write_source_file_sh(ctx, paths) runfiles = ctx.runfiles( files = runfiles, transitive_files = ctx.attr.in_file.files if ctx.attr.in_file else None, ) runfiles = runfiles.merge_all( [dep[DefaultInfo].default_runfiles for dep in ctx.attr.additional_update_targets], ) return [ DefaultInfo( executable = updater, runfiles = runfiles, ), WriteSourceFileInfo( executable = updater, ), ] _write_source_file = rule( attrs = _write_source_file_attrs, implementation = _write_source_file_impl, executable = True, ) def _is_file_missing(label): """Check if a file is missing by passing its relative path through a glob() Args label: the file's label """ file_abs = "%s/%s" % (label.package, label.name) file_rel = file_abs[len(native.package_name()) + 1:] file_glob = native.glob([file_rel], exclude_directories = 0, allow_empty = True) # Check for subpackages in case the expected output contains BUILD files, # the above files glob will return empty. subpackage_glob = [] if hasattr(native, "subpackages"): subpackage_glob = native.subpackages(include = [file_rel], allow_empty = True) return len(file_glob) == 0 and len(subpackage_glob) == 0 def _do_diff_test_message_replacements(message, default_message, target, suggested_update_target): """Constructs the diff test failures message from the provided template. Replaces the {{DEFAULT_MESSAGE}}, {{TARGET}}, and {{SUGGESTED_UPDATE_TARGET}} strings in message with the corresponding arguments. Args: message: The user-provided message to do template replacement on. default_message: The message to fill in for the {{DEFAULT_MESSAGE}} parameter. target: The string to fill in for the {{TARGET}} parameter. suggested_update_target: The string to fill in for the {{SUGGESTED_UPDATE_TARGET}} parameter.""" return message.replace("{{DEFAULT_MESSAGE}}", default_message).replace("{{TARGET}}", target).replace("{{SUGGESTED_UPDATE_TARGET}}", suggested_update_target if suggested_update_target else "") bazel-lib-2.22.5/lib/private/yq_toolchain.bzl000066400000000000000000000702011513125663600210750ustar00rootroot00000000000000"Setup yq toolchain repositories and rules" load(":repo_utils.bzl", "repo_utils") # Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl YQ_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:macos", "@platforms//cpu:aarch64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "linux_s390x": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:s390x", ], ), "linux_riscv64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:riscv64", ], ), "linux_ppc64le": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:ppc", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), "windows_arm64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:aarch64", ], ), } # Note: this is not the latest release, because it has significant breaking changes. # See https://github.com/bazel-contrib/bazel-lib/pull/421 DEFAULT_YQ_VERSION = "4.45.2" # https://github.com/mikefarah/yq/releases # # The integrity hashes can be automatically fetched for the latest yq release by running # `tools/yq_mirror_release.sh`. To calculate for a specific release run # `tools/yq_mirror_release.sh ` # # Alternatively, you can compute them manually by running # `shasum -b -a 384 [downloaded file] | awk '{ print $1 }' | xxd -r -p | base64` YQ_VERSIONS = { "4.45.2": { "darwin_amd64": "sha384-TBsrUTy6n6qA2hiSlpnEN6iEDDz4Tiy++AxLOpeXU1aUaI6uIuEBx8hgPYWWuD8V", "darwin_arm64": "sha384-bnZ5TqsG5pcWB6gC87QKrBrjcKYmdOcSD7TpFVeCU6Nj7z5egeZzm4BH1FHbqo0e", "linux_amd64": "sha384-jEOdMXHPvRiaFXWRnSA5Mw41VCKkNPv42i35i9BiVxrAnfyl/3/Li/iyQyj16QIr", "linux_arm64": "sha384-4bEWn6fDQhIomb6Smzm8yw26RvqsjHh3PH/SogwWoLC9uJRoyQagY2PJZaYWxUDY", "linux_s390x": "sha384-9uU3CXqjUG/SuPiHPKIUqbOVyqx7JiVOtRzeFta9IBFkJyUB0pBBOYkoDppvrmzz", "linux_riscv64": "sha384-FWM1djpKjWctmhaInat/z/CcwQuiqLTeQcb0MMU5+sNiwMTuWyjvNlbwA4rRG3ZQ", "linux_ppc64le": "sha384-bB03rZ0ptRt2EuFnA9SvscPMe3gVJecBvxhzPbYe7wsfoHvzzYqWffCchZVxRg+9", "windows_amd64": "sha384-vG8R2+s/sD8DbeCM9H0xCy5JgtAOII7SLRx2g+ALtQZWW/q3XjXlzN2CKW/zU+EH", "windows_arm64": "sha384-XHgi894S4cQ2qgJx47cPu5vtb2MOXA2YZ7QgExODwNoIPhji5wXK2MrgMB+RI7gZ", }, "4.45.1": { "darwin_amd64": "sha384-ZoEgzfCLmDk7eoKdJSoq/nny1iX3Cq9mMJ3gnPZ2ejhKMxSgHUQIa7MREToxYl6Z", "darwin_arm64": "sha384-nHYFqoarTzGba/XtpN8N3U0X9hMTg64Vn7XZ8yiF2cbJFdY3VWFVw80vsg/JXaOg", "linux_amd64": "sha384-hkMtSRoq1GZKoH9C6OesKhgFLtkcm91wUD2W7L/xlAOS7jZbii23uEMHApo5r7Qs", "linux_arm64": "sha384-4N6BWZ7ExxmnfqXGGTo7Szi73kJfbgMaUXW0FT10kcy2fNW0VbjBBAfClC14lES2", "linux_s390x": "sha384-DRzz5Sb3JvwDVjQWGVto3Eh7a7tNQmwXZtMTQy+SidCYGQ2sLA3SQqqsQicNaD8A", "linux_riscv64": "sha384-/4wDvlLP7f3lvEU/hrCa6wcGLzj8z1PYkWlULxIWHGn65Ai5xnI+Dp21VnM7iyi3", "linux_ppc64le": "sha384-pnzDz7jn4b+1wOeasaEU6q5ASQhZw0Uz6sEehzpztqQglU6ynTkS8n4Nw/oqG5y9", "windows_amd64": "sha384-P5c1L9KPhkLdByJ3G8IL3ouwNojoHSDDz6N851RRXxK1Y+ssYKPO/cbQzjQnpKvc", }, "4.33.3": { "darwin_amd64": "sha384-IJhMHD71yq+OR8AHFPfZr3XVpFlG2ZAfcexDKojtSLcCMV1pw0X2jza4qFUZiKEt", "darwin_arm64": "sha384-euQkz1Bu/dFuJoRgG4xIh9BhP2RvOceTDPSY8EzSIM5xykbMkwDNhr1PtCcUF5ye", "linux_amd64": "sha384-FxFu8W26rRzme76WNhyIfxdqoPOw19Ghjq7m1RwmwODdz1a88kCg32p+imQdjyWj", "linux_arm64": "sha384-F7U1tgKNNYFEpvinw/xR8ssPKO1ek6BlYOrcSWydSz8oJvVld6cRpvslvhsoMVxm", "linux_s390x": "sha384-CFXPW+fJZ/1Xo40JRNPUq50JeffybujfphqVgjIeAqHXkkQ6lClhEXw+vryUDAcT", "linux_ppc64le": "sha384-2gZP9kabZgq7W0h8Y765He90iWlW9fXGI9yNTWxcG9HsP+BPWCEaKSRRNogG7CyB", "windows_amd64": "sha384-39INMTRP1pJJSVaewmo6m0uW1Hr1+gl+YwhLjvWmnf398px/c2yEMxMqMroUGa+T", }, "4.33.2": { "darwin_amd64": "sha384-XtZjB1INvy8sjKvqzNwMcrKrhg7C6NO4L3orOg1c6Md3jnphPI4KMZha0Lo24783", "darwin_arm64": "sha384-BKad2vcROUyJTHOVWXXIoalCJor4RaPz17BbzFz5o3S8m9fa1mmwOVIJGL8obKnP", "linux_amd64": "sha384-HPudnhx0IPFTDwjOJptaucSMWXolD3UkXzyBYbPBTPNgcNlRb0HKmM3zHvcqXXhe", "linux_arm64": "sha384-lP9wYHbqw84BWtbzB6vlFQUwtswjomUNyewSuq1vRP6KvK+cTtBM0dOuX2sB8sQk", "linux_s390x": "sha384-cFYDpNs4lZq5MIEawBv/wDAVSfq/k1NpB+K8ARSwGSGVQ6+gi/X8OqMw87vqNAxb", "linux_ppc64le": "sha384-MN72jQflMlMZ/5AZRDcpgejIaP4vo4gQlO7Z/eG9vsLVIVbSRXyyR9hisd3nQXvz", "windows_amd64": "sha384-WZg1jUKAF16o3WtWz3ks9kOIKb5KKW7SbO5dZo7O2xT4yuBRUIzsQ8uL00K4KKfE", }, "4.33.1": { "darwin_amd64": "sha384-xzOpa6L3LvJOSTN9+VRf6sQKFPo13ZMNbDNhb05Dncoz9r6+2V/ytNh32OdulJMV", "darwin_arm64": "sha384-rFUnzTgVkMoU+Tvts1LKbMnaiaq1y69bKcPm2973jSxEm/AauNirbaJE4rcBm1C6", "linux_amd64": "sha384-KVzh5wvwStXkdQa2XjBLDs98Kmna/pAarh9ewdSUKVRMPo4LGa6JmqcoVC0JWaTa", "linux_arm64": "sha384-5ytwsHbS+POc7qehjvs5BUGerTHUNQiPYChQdDCxBD0lrWfonkEnEBkpV4TkGybQ", "linux_s390x": "sha384-hiiIiqBHlxrDL6Fy0vRDbNGgv3kriH7GPSlhGe6v6ccO+9Zqg2hH/nFnDORrh9vr", "linux_ppc64le": "sha384-fxnAtNDoLHemF4t7v/hMHVcR2fRetpIJ69Xn8J83I0E7Me7a6RabRhbMPT3ChfDq", "windows_amd64": "sha384-7V7vbTqFicN4qrXgvFw/hXgNx5PSgA5cj95l9200p56AkB4hhZypIexUmKe72Sct", }, "4.32.2": { "darwin_amd64": "sha384-oujkjEXlsgQqadsFDoISMlh1CgITdU9yoZo1WChZhjWEmoSGAjtxxq1UbUn5xKXy", "darwin_arm64": "sha384-Z9vogzsLZFrZcNFqNJM1N4SGGQvIIfsEOTsuPBsSjQJUKtna8Tix3HGqT7IIP+y+", "linux_amd64": "sha384-Nh0XBd1SFo6bentP1bVZlPWkrPZA1AXNtOMjBtwr5zCLlnPgdy13JUcyXDX5ZErG", "linux_arm64": "sha384-8B06ZuVybfe4Ct16V7LPjwexIYZH6uENs57MO1ej7yKDspZZLNZFlnS1BK1W1Iq4", "linux_s390x": "sha384-hoIH6IBZ++9yYSWRV0w2eX2J9RJ1ezPJ4bAKMGkN0TNwWxLFr2zndVz00TxBLr/p", "linux_ppc64le": "sha384-mXvIwqUzP5YLU5dS1CCzkMsiM5jcq5JCbOwwFD2whCie+K07sEnKDuF6Kq3NH1Pv", "windows_amd64": "sha384-W8NchvmJR2/mH2e0WNQfRU+dy0BWk6lMRUWseb0Q+CwB8ML1YD66qrgKlSLI0UQL", }, "4.32.1": { "darwin_amd64": "sha384-dC52sgUGWBCM6g+NHqGM6lGuWH8D43wDCycIRiP5fA0z0KfekgOKMexhoiIofw8u", "darwin_arm64": "sha384-GMClI5c7R8I3GcA/gCDH7klGOjytDYMkGmDxkk3+nM5sxmGyX73kyw1pzIPqlstN", "linux_amd64": "sha384-fGfnoAhqirivPO8Zu6Yik4iA/Y6Qg9R1GPjTQjMdJ70OTz2eIWKa66j36uuZiSXV", "linux_arm64": "sha384-tEJdFobIyINNCDHDlWApK4AY5aF1T+8zCZjka9HJzQfIl/JdJHy6cdx5GCbOVy8l", "linux_s390x": "sha384-KETACRoNt5F/2afheRNfbXP02JkzDtBuxkXJ65VOEx842z+wpBFGNMBhTNsXJJWY", "linux_ppc64le": "sha384-y0lz6WzI+w1M+TBpLKqLzkykz44kcK2z1wHkZCBWiriAUOrRW7jGUIp8/lkShB6m", "windows_amd64": "sha384-ez5I08/Lp0uXpBox8KtlighDChdOWzmIkQ+jXSu5Q0Vo67+v5NhVfpQziwEhj7is", }, "4.31.2": { "darwin_amd64": "sha384-pLTjWopl7zvRZDWNmoVqYFFH5t8v9WMlQeH8DLdv0WIv8X9+zg4/FxSii144x3Tl", "darwin_arm64": "sha384-Yac/bbE1Vtg+o4B17UKZAWMBc4rRK4izItFdBL/fPT+Pcy0lH8m5lL6ozT74mdE0", "linux_amd64": "sha384-pqr5rrKsELcBvn+FPEYyH9gBRuhGD+n59d2IckdkStAjkK5QTDdXKDxY4r7Gstrl", "linux_arm64": "sha384-sdLKk5iGvJRYOkpjhOjneIn+Q0RDcqTKzaq3mmilcAy9MrBCNgKEBusLaNnV9/vP", "linux_s390x": "sha384-6bTlnAXkocRjBq3FAJy9xN6+H2TJsJu9NAaQxPPpbNQba+y/KqUTfIFAJuKm9LjO", "linux_ppc64le": "sha384-3Nn0eohG4XCB9JHM6mXirwe9z0AH7Ic/tsvcYxG4OAWs/U3vZuZlIp6f2Ts3kOGv", "windows_amd64": "sha384-Qy+JKO2iHuZxuOnq0ygxUa4mXdVflTr6URIP3dldGIgX+g4azdJC6I3Bvc3+qQNb", }, "4.31.1": { "darwin_amd64": "sha384-k9Ftk7RfXjbFq8jMRXXH3nRAsGYPFV+aPpbDKtq33Kj59t25IkGxypR5bUKimIe2", "darwin_arm64": "sha384-6fLNJ+IuuCODGyIbObRgApWo/WakANSIEymoKeR4kt6mqIq0CVEbSJoBiGjIMMw6", "linux_amd64": "sha384-kX4ued7s19fNm6yYyZBiOG+UFb7yh65L8L64BkzvPNwAMAwQ+VgPh9lOySacgT7/", "linux_arm64": "sha384-EZrQjrlQODWsm6B8q36sbe7gvcNHNWQEgfRP8AsAvXS5PsD82sC17AeRvMbArAT4", "linux_s390x": "sha384-FvS4xs7A1e8Rom85xGCz8ldKTibqTMgN9WEAWIZ5ZjoJIXdTVqAUvPVNC56TEm18", "linux_ppc64le": "sha384-3mBcDXHCaG9+oDfmrrCG74UAulD5rsh0wl6FjFgN26/pSxUZ7nNtzqi0Ck4prx2f", "windows_amd64": "sha384-hEuszAhbPMkGL5ih2EwHfDedrhtmpT8WyQMZYLXzc0Fs5Nl90EqWXJ12wiYrTCz8", }, "4.30.8": { "darwin_amd64": "sha384-cr734pTKzXdnhDJaBGgsG9stpihJKh+QyJHfnHYWhALyg/cPfVdEETkLhtj0qyiG", "darwin_arm64": "sha384-SBAt6LTJ//Qut9daSZ/4rg4BqspZR68AW15uBO1z8SYMnrVZERPjwIxnOgvaYpzF", "linux_amd64": "sha384-ym4aPXQZw8WaRV4utRzcPwEyqbKv0hUv0JhQqC0qs4HgaRm7r/CtwzUF8AOJ4/ys", "linux_arm64": "sha384-dDIUBKY9O6mYZZ+VXClt0jXzxSCC0XAtDp4qh9UXUGmySrQ6NbQlWBkeGYEAnQba", "linux_s390x": "sha384-jYgpByc5Li9GSfwKtQJwty7/INBT9k9TrHzaiBZ2dH0ptroZJLy4eqBy8n1LB1eA", "linux_ppc64le": "sha384-i/+d6ws6MjzNr+uFWa9Ca/GDKlH24hRuDaeYNWyn4qvvoGJQCMk8yYyDlvlJzUOV", "windows_amd64": "sha384-zcS0scnyOmYME8VL1OP5fIFhUzUgSWYR+0QWdh6QykpGEMWUjHkkAYWD03R8lXgK", }, "4.30.7": { "darwin_amd64": "sha384-tUt6MQaK08R8BtAiHZa0mWlNPRnOm2LeyBAWN3v2JRolOJ8+gVA4fvhVgvawxx06", "darwin_arm64": "sha384-WWTrnfPjGhJhmoeOhPpcsIGVvmPPfhXqDE7wYhnV577qo7Iy0YDqprqg064JwfVQ", "linux_amd64": "sha384-6peNflw6HogPErPTmD2Fxd0IrPYwtBGRd8fag7Jgi6JmWSv4G9AyYVrRquWXw55J", "linux_arm64": "sha384-Bhlp2CZ363kAarj1GZ/Fj+nV8ISKHPqCInUNu9qBvBdlGSsZ16NYTN9HEn/BWQnk", "linux_s390x": "sha384-kPYUc9sn4gRfkr7uAiFcOElmBggUiF2sl8sgG0oiudysGWw87DxNBUWXkWRQqkDj", "linux_ppc64le": "sha384-kzC2vlWrmINddlsd/BYzhuUUfiZnmIDJi+WftwcPB+IWPEFpeYkCuK1bNO3nLI8s", "windows_amd64": "sha384-NON5Qd2wE+2ilmJ+j7J5Vc4EYKX+kTHGwLQJvpqa8Xf+BfwPJA389mSYk5mWtX2U", }, "4.30.6": { "darwin_amd64": "sha384-I8oY8+z38GJMzaZDzxQ9FA2mOE9AkgZGs6JnP5wnjcGX85zbjjRdrMReaP6ZFTli", "darwin_arm64": "sha384-dYF6a2CQ6rl5zXBJaAtjg35cDRgYL164FTz/R1321REZHnJu/XqdVso5D10yLsb9", "linux_amd64": "sha384-yJAe6Vpsy0cz6G2D7nXYlqVlXcJjn53/0nlQWe67JgCfBpb0XnQOA6FuGsW6FttH", "linux_arm64": "sha384-QeC9CZNqy0iPu5LKSWcGuNW7Kk9UBjw+/VxnO4mlbJ9EHJRllT0QvTVoLHwhuCev", "linux_s390x": "sha384-ZPfwmcPczB/SAtcPtW3Qp1HvpeA45V6sjtiPAh9O0x33VnC/m0kHm4g4zJvILTza", "linux_ppc64le": "sha384-iKDFd83tC3LPxqcyge4b5TuETeAVdgYXDcuGDXNC2Rt6vhZ6syT0CJFtwm8bvl19", "windows_amd64": "sha384-zCwrdoR8bRBzvhQuUHCWHlgemOPNZOWxH2Gci+JIk55CUN48T4ES4kX6D/jNIzOg", }, "4.30.5": { "darwin_amd64": "sha384-s63cFkXgchNM3CMZWGtlQ87mMd7x5ZkzbClQAOYV7lXCi1XSTnCxSccNJByvZBWW", "darwin_arm64": "sha384-hc6DFV3lgjUS13KzkfXP2DvdUPruT50//7skgXZUCuWoAro84r+VNOg4gt4AlFw+", "linux_amd64": "sha384-jHiMhF4qj1cVVWK8pGYhza8AcHKvtXlQG3kQZS+iziZmPf0GLQ08bAzWvYeKe8M/", "linux_arm64": "sha384-nk5G36aNWtlg/pSqF9GnfMVLkz2VYM3QgIJlTrLIVkFnO3ygp3BS0r+Wj8DVxXZ1", "linux_s390x": "sha384-UATZYKNkBNXWUVs7/rv9cU+yPlMPAr+p4fiwDDGwrTmj7QnxKuQ9XDvw0rryied3", "linux_ppc64le": "sha384-KlfxemM25f9ZJlXaUm/VBMLJ+x6D7E0i+ea8B8zf3VqVjAreOwCR2+0NvKJixvrY", "windows_amd64": "sha384-OrYnZnmhxfPbyVVsNfR06D0nlIP6wDeFPrgML0L9Epg73a32HA8c5LPYJn18g/II", }, "4.30.4": { "darwin_amd64": "sha384-eYHqU7tN4p1fgHnCmsHmgWAzEjCh6zyTA5pCGfE1tH7XJQ2Dr5NwUFAyMTRmnqGp", "darwin_arm64": "sha384-iPAb+GPe4+S5j906JRfJgiB50tQJd+AlJiF6HuCOMEsqTsyNjAid+ag7Lt49HW2E", "linux_amd64": "sha384-KPG44IxvaQw0lg93R6tZbxNFDzw8vgCSuJc4vveDe6/cIVnQMZB4OPRGiCU1n+z2", "linux_arm64": "sha384-3EeHJQXwhXnwnmI48nH9BT5PRxvMQUw2yeI2Q8jRONSE3nVoZy3PDPhkDi4U9k/1", "linux_s390x": "sha384-tMgt6wKBVtjQKwNMC6hhHUz3VlgYomazAwqsGmiV/acqO5Nq+gHDqbm7WZeSx1Lu", "linux_ppc64le": "sha384-EiVxl0MmOD5ExaZx9rJA4qiBUf+M8DLkrHpEBniNjMn/XaUAbEp8lDfclkQ9o1oi", "windows_amd64": "sha384-F93l6mZThCLAudlFJXlzRBXg+YWO/1N8Va27QEoOCfcuJ7wJsVIPoAFcuP3VOtia", }, "4.30.3": { "darwin_amd64": "sha384-aF1mKEe13/8ycOr6o3H7wpDB2mvLNdQvvW6Sv19AxRl8KWvl88+ELpo/nUpSZy3s", "darwin_arm64": "sha384-TO5/c3FC4xxxWEu3IU/s+g7vcOL0YPJwMLLQC85sF1OM4wOxzAinI0hxsxfynQdU", "linux_amd64": "sha384-PM/GG/kKT2iC5MD1hYh6R//F1lVhwBNFV3vnuB66K5x1NYqu6Tbei0wxxpkOAn1L", "linux_arm64": "sha384-2Ynn7Pw2dY6iIVBilF5OuNMscyQzeExbDhm6oVpCmXu4uhMW/3qS7KFOLE1rx/2s", "linux_s390x": "sha384-P4F2B8oWjlasazLRyKnG6HMJ+WAHwJG17bLBCmbGLtmL+J47IYve3Go8SDytNhbq", "linux_ppc64le": "sha384-oAlKG4DpmybovYjBAzxSx8dUuAjicKvC+DPdVHRhKxmyU6YsZtpA2qhksO0Dmka1", "windows_amd64": "sha384-+zAMM9aobwSio58t77oIQs1YuCQ5AM8UTUnyl+XHMIm9LHkKLTSPEgWur1HJuutx", }, "4.30.2": { "darwin_amd64": "sha384-rXpT6g1AU269cdK9OM/E+AWd1ebDCP2/2B4YWr3ReacBhhagvHCTBDS1ooc6adi4", "darwin_arm64": "sha384-rn68m4/REEBNX37NjX4EAZw3aBtqZTk8oOlyTTd3Hjpa2zy/zdXtQq4Q52CRvh7r", "linux_amd64": "sha384-AH3aFTqsVST0hCcHj7FwFJ7wmY/n3q0fzi/ZqerAwxRmX80W6n/v9PZN4U5EyYXu", "linux_arm64": "sha384-tXAeZo6umhL1BRm4xArb97DW8UT34b1JP3OxUYQ3ugSb+Td7SKDTih3dCWXDozxH", "linux_s390x": "sha384-WMnziv/oMWXNNVdr5fCP7mSPg1UlFR8chnazOEnycwLsB2M7LxkENuQeYfqbstff", "linux_ppc64le": "sha384-S4FYx4L7BgrVJdU35uKoxm4/4kmweDP55GF3qmw7wcJzlNu552blknJDNJMMB2Gb", "windows_amd64": "sha384-VDJA/2vyvPmiQFstAIqp1WShmfnBtUysPQHupWptLZ6rmplSYBLYL6UtqOtHdMaI", }, "4.30.1": { "darwin_amd64": "sha384-D2naPOWkB7iBbWOfNiM5RCXeHJvOLH/ib8wjE5f0SEvKhRSJ7eQ8fnVHzw1Zzi/w", "darwin_arm64": "sha384-JDQWrvpu3EoRVJT8qqmEyIvD2ovm48BrxOQgjJcTeY7/U8izuwPH7zrshnYxao0R", "linux_amd64": "sha384-k/N+JzgqLRjkDDuq6XPCJyS32B2zuM/k1feOI6/VqwFGZS0oXKGNnIdhDi1OmjVt", "linux_arm64": "sha384-CfiZSUynXXVlsbjVJbPPbQP2/BtxNSNem8KudyTiFaR5qHlldLo4Az9NaelRrmZv", "linux_s390x": "sha384-mMKIb35SdLlqJMjUflId7zBE+n24+5EQSk5qwDaSJ23sybvr36FIu8WvakopP52U", "linux_ppc64le": "sha384-FqwY/8VundrO775EF3VoMF2YeMEVjBACg4wE9YnjChj9nt2B95c2sjVQCbESEqtu", "windows_amd64": "sha384-OCdYU2tB5aPlqjqL0NyGBWe87v5rn0kjXvbJdz5V1DC+pK2y6aZwOxLVUqgt8byp", }, "4.29.2": { "darwin_amd64": "sha384-N9MXB/2SOWuL07IG9ShVRWIUnr38y+Ly7hQIq42MsxPbNEGlt8JG5BzMmfxlFWVu", "darwin_arm64": "sha384-wwiVQYzZ6yaZ3MpwEffha1JyDEPo8BL7chaSE1DnupldLQES3k8rXSldynQteysD", "linux_amd64": "sha384-zViR/M36ICnNzFUN0vWKCHOna86inL0aFYrETjd6PSx8Eqbl13jNcZ7hHv6AeKSk", "linux_arm64": "sha384-pChFNLv6hf1Y3r4QMu8D9NqFcUuQZdGo9WpLW3mUUU4/0nGu6mKRb+cGx1K9QLYg", "linux_s390x": "sha384-Qm/7ICuxR3kB3Uovt3P1aZMlHNUVSvLpIwfudaz0Vdkx/wxvJuHqCqcjWZ0DRCev", "linux_ppc64le": "sha384-oI/Of8ncfLFQKgA+P/bfDD8O+KrOTy4qatrd4KoO1172XyJz14DHIeWoFTXOBl2m", "windows_amd64": "sha384-Zg0Ltumeuy+8czlhBXpdHeKNd8rflWJGMBCrO1AwAY6KsFUSuSGeXDi3wMotT+Qv", }, "4.29.1": { "darwin_amd64": "sha384-W3nmcSOs6i42/1JljCDefTje22Q6t8zMryNVK9JbhtIghZ9VlbeE9E8az5su0BNQ", "darwin_arm64": "sha384-1xPziJ5N275Y46ZlYDfz7IocliIR+MCpPG9KrXfo7IA/KW5qV9aM7EhDjjf/aiXs", "linux_amd64": "sha384-waB6IJiMLTRG7At3RmL4MdpRZaaWNTDy6GOy1TpQK24NbQsnTD8QHGtF4mX2un71", "linux_arm64": "sha384-nfXpDxuyuoKjNtEr4Gw0ShuAqWsM08q4pceDwhWFg4vKJe9Z7A26iqeGxPI9daF+", "linux_s390x": "sha384-X4lOVFgaJs2ESaLCASM6vqHgQyasmMlFFEKqQtD5qBs3txEkLz/xUyJ96BDdFF4B", "linux_ppc64le": "sha384-zXDgMcUpMVdVgefD+tqNHpwcr5CaxsQ9iKuPcWXeeNWQ5WHM+s/imWv+jCSWLVbq", "windows_amd64": "sha384-x6d2r2cAPtsCeJ3b9gJeas4hOWef3iF7pYmpr3jMuCmNgTH0NYQR9ghdu7Bxr1bB", }, "4.28.2": { "darwin_amd64": "sha384-4AXeU2VHBbcMuj41t/uQ1GDZgOCWpautbnoOoBkxKlpF70BPsJQcfJADHbfkKpWL", "darwin_arm64": "sha384-GjK93wtKupFpR1JBmVsoxpoM6KsNZ4DprT6kZ2j1xTYWjYbpUXfF65pUMiAbhLU1", "linux_amd64": "sha384-kp3GzKtmoz1XgkCjztSu5NsqsWK6BiumFQuPVP0iVcKnSoRR78q+51COpFmKnOze", "linux_arm64": "sha384-a6EOkjRqT7AYAT7Kx8x9VERiFNax+4mH3FGrsLf+tNKxN1Uglfcp5qHsD1wLRTAQ", "linux_s390x": "sha384-RnJdSQo6+JK73PIWNFVbSey05xxfVQ2T5iahFE/zzd4wwwaWCVq560UskTnj1hX3", "linux_ppc64le": "sha384-Qnhh8beQEBVBGmq3g19UqGRklFA/w9fApAlp65qn7fjClZaU9feg8wtXbFuE34AJ", "windows_amd64": "sha384-e+LWtKw1AC69Ma2pWD84CGjvX38y8zWVKlOzm+Pf2HHYjtMae9JYxN6EsvHDdlBE", }, "4.28.1": { "darwin_amd64": "sha384-8lV1gSf41Ud4XpuaQ+0TE5OEmBOfgJVLcoa3SjxsTE56RL0MgVoqa8A6CrOdzYTC", "darwin_arm64": "sha384-t0noxlOYiv2xyjfBskOMTcsCz+AwfXaPRhgD//yeGgRAIiylTgp7LFy3HKrSqjtN", "linux_amd64": "sha384-n3Y2PYn9/Ydwti+pqqlDOxpM19E/InXo95kDiywb2NEjqHfzzEN57MRdm0kdd8bK", "linux_arm64": "sha384-W+fkBuf5vrofHYXI0qBUefP63TUYnhwGAAi09YxgIBFk09BUG8Fk1coPzCOaEJ7d", "linux_s390x": "sha384-1+D4UGDjssGnCGK8S1X69kMla5J7/1cu+Y0lD2yAIEGneLz2NtvxiN3mtalwTWaN", "linux_ppc64le": "sha384-jXtlobgI4JAXQUSvQER3oWuzSWil4rm13eyxVOorzzKtvaG1eAXl+skOH+8BNEqL", "windows_amd64": "sha384-DooYFtPjxiuZ1EV/CStC4bklQgLBgxdW7r5jJ/+GgBkXltjkaZgI11XkHFhUAnxj", }, "4.27.5": { "darwin_amd64": "sha384-vy5Lym+7yVMR6BQEBMvN0lM/b4h8t5B2RtbMO8suBuQov2Rshw5AtWKVm3FhWqbc", "darwin_arm64": "sha384-PQjvVAdRlJNdI7UmZzsZsan9E+pBAgrf6xKg5NmNUE4jXwT6VoM9ena82xL9Kc/H", "linux_amd64": "sha384-3FsXfJdVH9gK1FEBFZukRrqDZRUvz7YZxv4B33j9j7hnnI/tw9kF7rOFHIpKsDWd", "linux_arm64": "sha384-14bPrTE0pKfQD8q1TZ8uCy7Bt2fFJSMuaecJRyhjd0LCLBPw+UbuC7ZSsZknqgLG", "linux_s390x": "sha384-WQJOeiy+YRGBQLNEFfMy/xFI5OXHuKQOLJnAAyuRCvg4v427EvQbxMUAW+hr+uCL", "linux_ppc64le": "sha384-YhgIsXOPq2FpSiJGS6Q/yY9T5uki1vM+AEzJ2SnZuVGd9uX5iWAZN3ZHb5fv4rv0", "windows_amd64": "sha384-2oLJz7lym2uIm1QSgMBy3u0TsqZdQ6PFlSMUiLbn+e8jjaEAMHtnfqm338JDk92m", }, "4.27.3": { "darwin_amd64": "sha384-fWL3t5KJZ4vJK9vjYI2Rk9QT+tW7zon4T+VE1XvmdwLn0oQH3R7BMc04jv90Qu8H", "darwin_arm64": "sha384-K/BhuDtIkBtfzdzMt0XvqQSwqkp8ynDnFJsMnmq+EXIWLHCXK1KD/yTowQOXGDeR", "linux_amd64": "sha384-1PwDnUZWikPr5eYn1vdQVJX523+Ftz5T5/YmaJhfWg1u+YkapFGzrFsVDh5JYXUv", "linux_arm64": "sha384-goxKzNBAuAt7F0Egqrg5JkdZPLMCOp7yaU7hGzrHWla5E4w4j/+2HVM3tsJaZK1R", "linux_s390x": "sha384-1MUbqdM9JkSzBWSVxhWPJwrYE6k0jtgWh8PnLYyugiVbE2bOa2cuXdoGxfpgDIGH", "linux_ppc64le": "sha384-uHdGKiWTTpxnewNuR72XyZTeh0H8TSKU1q9EDAeuPEhCZzRYyP8W7XPS1oPaQ8l2", "windows_amd64": "sha384-fj/h6eZ/hWNl+ERH3FTPk3wVVxIf/9zecx42wtxuoSGpQfKWL7CGNbDRvWNAVyYv", }, "4.27.2": { "darwin_amd64": "sha384-dDG2xx6W+LWP922Ihe2dhacnzhjXJBklZSyJCG5anFGYZn7N2xqWpTookLfegVC2", "darwin_arm64": "sha384-bfHab2ci86GRlE3jAbKLPvAj1ulnr0N+GNC/1frcYaGFOKjrFN7lia/KPPU/ZFVJ", "linux_amd64": "sha384-sl0i3SVGdOQCc/vf09VwDPhiPM9W/wG2yMhjM51oyVVDHrLs63kHMnTqaCvr/e6n", "linux_arm64": "sha384-bJqQ2BcX20CVmaH9c25rdIr9WNqtdTHWXzACQTDvPHnSnHrTpEJrWP57sVGGwyZ+", "linux_s390x": "sha384-mLaO2DJGgqBn79sASogwX1qCvBALNWjvGfV2fDuuLuKzFqQmTZKXghLiv8rbZ2G+", "linux_ppc64le": "sha384-DwlV76JUvOV6J8MD9g48rQfzFCPC9hi5eRhz1iVrNRfKoGqfGkHxufpmAWYpRWVH", "windows_amd64": "sha384-T0Vc4hlJnh8eoa04I3Q4/BIbGOch31OxTUsHDkzlku/s5r2Ms9Y+YopYksmK9FcH", }, "4.26.1": { "darwin_amd64": "sha384-CXHTzHhkXvpAc2hCn7VizSzbfJDM0DO6LI4Gy9iOx3kODMi6v21AdEhSPiAsG36z", "darwin_arm64": "sha384-BwsMtgoteA8n2xP/64E9gDF9jz7mTpAz4z90NqbnoJSau+ri/Mh8Bw7Ymb9A31GN", "linux_amd64": "sha384-/cy001wSx8tbEmhibNe9ef3cFY1oAjm5Ae3+OBEezI45unE/BYnyzaodk2tS+s5i", "linux_arm64": "sha384-kHYvn9xiQlwvfPy7CBuc7bbXK6Z+cliKIYmk9rQs0hQIXps9HpjTCH1XNXUCm9WX", "linux_s390x": "sha384-WuiL9i5iMHZ8gQYmTjoiX2LK6WC2bLFYhhh7to1/qjn0U6ZvI3ylhORkjZ84WnN2", "linux_ppc64le": "sha384-LyU+MR2uLLEYpRZJriKCcGSR3iXZ+C2erLmuydM4YsXrucPmUkigfG8iM3uzF0I/", "windows_amd64": "sha384-shjvmGSa79aYKqeWLlOuzrHUvnrK75Y0ku4obQ/k+s1vofZIkevdW8UnW1SNrOMe", }, "4.25.3": { "darwin_amd64": "sha384-8Ok6gt8rA/4iPTx3yGs4ZrJWWmKwWKQuYbuVpYHuzQJE5eHGz5ePh1dPvmnm81Y5", "darwin_arm64": "sha384-gIEE8Jymptr9vftXY8hvFwUsWJ3drmAWGxMjsv0YeIGF7C4LksvYUufKDRgvPKis", "linux_amd64": "sha384-ziQP4MAN3jJkT8XTL05ZI4SxadBN9VyQqVcR1+53uDANaCto7t0p3uWL7IcqZ3to", "linux_arm64": "sha384-FLKcZBzUnzRWOVOTFv1mm59aD7K0d9hRthO5Eatonz/oHXSJw8BjTzvHasRkqjlZ", "linux_s390x": "sha384-K39zTD8zJnI8kR4NfSvnrLd3oEoNuBCIgCmC+2nwzEpn+SqVvNFESIdh+ui/7RcX", "linux_ppc64le": "sha384-iTzvYkCHIWc9keN0tM9pOPhGyzxdwdROWQYmtragW0F1aPWTFR4+YxX9rhbwO2W/", "windows_amd64": "sha384-KwQmB+VjNuPJZkMJn7OnFa/WwXdLxjrno6eeMSA1sxZeBjrXSPzIadwY271n/fNn", }, "4.25.2": { "darwin_amd64": "sha384-JOSKdcN5JoSfryJBDFzTSk21uFVNw+bWdLHTErwIyaUOAZZV9LISzlmsYiQoPfo3", "darwin_arm64": "sha384-COVD0Ko3vQUmSS/SS17VrpA4gTaxuyszgPfE9P8vNKLlB+65I7HznstHg/iElxrk", "linux_amd64": "sha384-uK7+qPUYBO1bnKUNYKqKuGpfTKsRktfptGATlV14AFb5hiVp6vcWvDyTRSfiZn5f", "linux_arm64": "sha384-2SwY2OtotYhupSEeUSHRKTMbUoIhUyIt7QgujH3UyaQ/9AoXWNZ3h05OAdWL5WbL", "linux_s390x": "sha384-AXZe1USYMi0mg5ylHnU8OGqQQZcMDETD/bLWG0BKytSBhZ0Xkkhn9r90fJYM4xVS", "linux_ppc64le": "sha384-N6UXrIzrpPy6zojzI8J7AFP5z3UAe9KU8WLuUKe8WrttuD1Fl3YTwvo/OM2+5NTt", "windows_amd64": "sha384-wD0GpKHTLQIWWNJv43ts+l2rIdAiyYYtb3upncdIOLLydFcWxB39+thcQ8aSdaW+", }, "4.24.5": { "darwin_amd64": "sha384-Y6Utm9NAX7q69apRHLAU6oNYk5Kn5b6LUccBolbTm2CXXYye8pabeFPsaREFIHbw", "darwin_arm64": "sha384-d6+hFiZrsUeqnXJufnvadTi0BL/sfbd6K7LnJyLVDy31C0isjyHipVqlibKYbFSu", "linux_amd64": "sha384-FEWzb66XTTiMfz5wA/hCs/n0N+PVj4lXzKX8ZIUXnM3JTlFlBvA9X59elqqEJUPq", "linux_arm64": "sha384-u8H3RxTssXKr1lEylydi1tzXKKsoax7aDXi4R/JF8irZ7RTwCqU/ogMj30B0Xo01", "linux_s390x": "sha384-ccipOj8IBVDb6ZxBYDyRDVvfOTHRSD4nGuMbikrDrigGdYyI/iVb+R8lb6kdLarb", "linux_ppc64le": "sha384-HWzKwuNx+uZI/8KXSNFVg+drCZiZU/17hIl8gG+b+UyLMAFZ/sOB/nu7yzEOdzvH", "windows_amd64": "sha384-6T42wIkqXZ8OCetIeMjTlTIVQDwlRpTXj8pi+SrGzU4r5waq3SwIYSrDqUxMD43j", }, "4.24.4": { "darwin_amd64": "sha384-H5JnUD7c0jpbOvvN1pGz12XFi3XrX+ism4iGnH9wv37i+qdkD2AdTbTe4MIFtMR+", "darwin_arm64": "sha384-9B85+dFTGRmMWWP2M+PVOkl8CtAb/HV4+XNGC0OBfdBvdJU85FyiTb12XGEgNjFp", "linux_amd64": "sha384-y8vr5fWIqSvJhMoHwldoVPOJpAfLi4iHcnhfTcm/nuJAxGAJmI2MiBbk3t7lQNHC", "linux_arm64": "sha384-nxvFzxOVNtbt1lQZshkUnM6SHQnXKkzWKEw4TzU9HOms6mUJnYbYXc0x0LwPkpQK", "linux_s390x": "sha384-525bIc8L80mIMVH+PmNDi4vBP4AfvBw/736ISW0F7+7zowSYOUK+EN/REo31kNdN", "linux_ppc64le": "sha384-Sm3PniOqhRIlYaVBZOwncKRpPDLhiuHNCvVWUW9ihnAQM3woXvhb5iNfbws0Rz+G", "windows_amd64": "sha384-f8jkaz3oRaDcn8jiXupeDO665t6d2tTnFuU0bKwLWszXSz8r29My/USG+UoO9hOr", }, } YqInfo = provider( doc = "Provide info for executing yq", fields = { "bin": "Executable yq binary", }, ) def _yq_toolchain_impl(ctx): binary = ctx.file.bin # Make the $(YQ_BIN) variable available in places like genrules. # See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables template_variables = platform_common.TemplateVariableInfo({ "YQ_BIN": binary.path, }) default_info = DefaultInfo( files = depset([binary]), runfiles = ctx.runfiles(files = [binary]), ) yq_info = YqInfo( bin = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( yqinfo = yq_info, template_variables = template_variables, default = default_info, ) return [default_info, toolchain_info, template_variables] yq_toolchain = rule( implementation = _yq_toolchain_impl, attrs = { "bin": attr.label( mandatory = True, allow_single_file = True, ), }, ) def _yq_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or target platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """# @generated by @aspect_bazel_lib//lib/private:yq_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:yq_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.yqinfo, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:yq_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:yq_toolchain.bzl # # These can be registered in the workspace file or passed to --extra_toolchains flag. # By default all these toolchains are registered by the yq_register_toolchains macro # so you don't normally need to interact with these targets. load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) """ for [platform, meta] in YQ_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:yq_toolchain", toolchain_type = "@aspect_bazel_lib//lib:yq_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) yq_toolchains_repo = repository_rule( _yq_toolchains_repo_impl, doc = """Creates a repository with toolchain definitions for all known platforms which can be registered or selected.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) def _yq_platform_repo_impl(rctx): is_windows = rctx.attr.platform.startswith("windows_") meta = YQ_PLATFORMS[rctx.attr.platform] release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform #https://github.com/mikefarah/yq/releases/download/v4.24.4/yq_linux_386 url = "https://github.com/mikefarah/yq/releases/download/v{0}/yq_{1}{2}".format( rctx.attr.version, release_platform, ".exe" if is_windows else "", ) rctx.download( url = url, output = "yq.exe" if is_windows else "yq", executable = True, integrity = YQ_VERSIONS[rctx.attr.version][release_platform], ) build_content = """# @generated by @aspect_bazel_lib//lib/private:yq_toolchain.bzl load("@aspect_bazel_lib//lib/private:yq_toolchain.bzl", "yq_toolchain") exports_files(["{0}"]) yq_toolchain(name = "yq_toolchain", bin = "{0}", visibility = ["//visibility:public"]) """.format("yq.exe" if is_windows else "yq") # Base BUILD file for this repository rctx.file("BUILD.bazel", build_content) yq_platform_repo = repository_rule( implementation = _yq_platform_repo_impl, doc = "Fetch external tools needed for yq toolchain", attrs = { "version": attr.string(mandatory = True, values = YQ_VERSIONS.keys()), "platform": attr.string(mandatory = True, values = YQ_PLATFORMS.keys()), }, ) def _yq_host_alias_repo(rctx): ext = ".exe" if repo_utils.is_windows(rctx) else "" # Base BUILD file for this repository rctx.file("BUILD.bazel", """# @generated by @aspect_bazel_lib//lib/private:yq_toolchain.bzl package(default_visibility = ["//visibility:public"]) exports_files(["yq{ext}"]) """.format( ext = ext, )) rctx.symlink("../{name}_{platform}/yq{ext}".format( name = rctx.attr.name, platform = repo_utils.platform(rctx), ext = ext, ), "yq{ext}".format(ext = ext)) yq_host_alias_repo = repository_rule( _yq_host_alias_repo, doc = """Creates a repository with a shorter name meant for the host platform, which contains a BUILD.bazel file that exports symlinks to the host platform's binaries """, ) bazel-lib-2.22.5/lib/private/zstd_toolchain.bzl000066400000000000000000000136531513125663600214400ustar00rootroot00000000000000"Provide access to ZSTD" ZSTD_PLATFORMS = { "darwin_amd64": struct( compatible_with = [ "@platforms//os:osx", "@platforms//cpu:x86_64", ], ), "darwin_arm64": struct( compatible_with = [ "@platforms//os:osx", "@platforms//cpu:aarch64", ], ), "linux_amd64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ), "linux_arm64": struct( compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ), "windows_amd64": struct( compatible_with = [ "@platforms//os:windows", "@platforms//cpu:x86_64", ], ), } ZSTD_PREBUILT = { "darwin_amd64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_darwin_amd64", "E4D517212005CF26F8B8D657455D1380318B071CB52A3FFD9DFBDF4C2BA71A13", ), "darwin_arm64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_darwin_arm64", "6E210EEAE08FB6BA38C3AC2D1857075C28113AEF68296F7E396F1180F7E894B9", ), "linux_amd64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_linux_amd64", "0F0BD1193509A598629D7FA745C4B0B6D5FA6719E0C94C01EF0F20E466D801A7", ), "linux_arm64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_linux_arm64", "82AACF8F1C67FF3C94E04AFB0721A848BBBA70FBF8249EE4BC4C9085AFB84548", ), "windows_amd64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_windows_x86_64.exe", "A944FDE13D01892C7CF0970FE4271F9561373F5E0A46ECEA756B6AE9A31E056C", ), "windows_arm64": ( "https://github.com/aspect-build/zstd-prebuilt/releases/download/v1.5.6-bcr1/zstd_windows_arm64.exe", "8CA462473BCCD13C9D9A952F09E5F628153785323949D539E8858B2ABB85E246", ), } def _zstd_binary_repo(rctx): (url, sha256) = ZSTD_PREBUILT[rctx.attr.platform] rctx.download( url = url, output = "zstd", executable = True, sha256 = sha256, ) binary = "zstd" rctx.file("BUILD.bazel", """\ # @generated by @aspect_bazel_lib//lib/private:zstd_toolchain.bzl load("@aspect_bazel_lib//lib/private:zstd_toolchain.bzl", "zstd_toolchain") package(default_visibility = ["//visibility:public"]) zstd_toolchain(name = "zstd_toolchain", binary = "{}") """.format(binary)) zstd_binary_repo = repository_rule( implementation = _zstd_binary_repo, attrs = { "platform": attr.string(mandatory = True, values = ZSTD_PLATFORMS.keys()), }, ) ZstdInfo = provider( doc = "Provide info for executing zstd", fields = { "binary": "zstd executable", }, ) def _zstd_toolchain_impl(ctx): binary = ctx.executable.binary # Make the $(ZSTD_BIN) variable available in places like genrules. # See https://docs.bazel.build/versions/main/be/make-variables.html#custom_variables template_variables = platform_common.TemplateVariableInfo({ "ZSTD_BIN": binary.path, }) default_info = DefaultInfo( files = depset(ctx.files.binary + ctx.files.files), ) zstdinfo = ZstdInfo( binary = binary, ) # Export all the providers inside our ToolchainInfo # so the resolved_toolchain rule can grab and re-export them. toolchain_info = platform_common.ToolchainInfo( zstdinfo = zstdinfo, template_variables = template_variables, default = default_info, ) return [toolchain_info, template_variables, default_info] zstd_toolchain = rule( implementation = _zstd_toolchain_impl, attrs = { "binary": attr.label( doc = "a command to find on the system path", allow_files = True, executable = True, cfg = "exec", ), "files": attr.label_list(allow_files = True), }, ) def _zstd_toolchains_repo_impl(rctx): # Expose a concrete toolchain which is the result of Bazel resolving the toolchain # for the execution or zstdget platform. # Workaround for https://github.com/bazelbuild/bazel/issues/14009 starlark_content = """\ # @generated by @aspect_bazel_lib//lib/private:zstd_toolchain.bzl # Forward all the providers def _resolved_toolchain_impl(ctx): toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:zstd_toolchain_type"] return [ toolchain_info, toolchain_info.default, toolchain_info.zstdinfo, toolchain_info.template_variables, ] # Copied from java_toolchain_alias # https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl resolved_toolchain = rule( implementation = _resolved_toolchain_impl, toolchains = ["@aspect_bazel_lib//lib:zstd_toolchain_type"], ) """ rctx.file("defs.bzl", starlark_content) build_content = """# @generated by @aspect_bazel_lib//lib/private:zstd_toolchain.bzl load(":defs.bzl", "resolved_toolchain") resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"])""" for [platform, meta] in ZSTD_PLATFORMS.items(): build_content += """ toolchain( name = "{platform}_toolchain", exec_compatible_with = {compatible_with}, toolchain = "@{user_repository_name}_{platform}//:zstd_toolchain", toolchain_type = "@aspect_bazel_lib//lib:zstd_toolchain_type", ) """.format( platform = platform, user_repository_name = rctx.attr.user_repository_name, compatible_with = meta.compatible_with, ) rctx.file("BUILD.bazel", build_content) zstd_toolchains_repo = repository_rule( _zstd_toolchains_repo_impl, doc = """Creates a repository that exposes a zstd_toolchain_type zstdget.""", attrs = { "user_repository_name": attr.string(doc = "Base name for toolchains repository"), }, ) bazel-lib-2.22.5/lib/repo_utils.bzl000066400000000000000000000002521513125663600171160ustar00rootroot00000000000000"Public API" load("//lib/private:patch.bzl", _patch = "patch") load("//lib/private:repo_utils.bzl", _repo_utils = "repo_utils") repo_utils = _repo_utils patch = _patch bazel-lib-2.22.5/lib/repositories.bzl000066400000000000000000000401031513125663600174570ustar00rootroot00000000000000"Macros for loading dependencies and registering toolchains" load("//lib:utils.bzl", http_archive = "maybe_http_archive") load("//lib/private:bats_toolchain.bzl", "BATS_ASSERT_VERSIONS", "BATS_CORE_TEMPLATE", "BATS_CORE_VERSIONS", "BATS_FILE_VERSIONS", "BATS_LIBRARY_TEMPLATE", "BATS_SUPPORT_VERSIONS") load("//lib/private:copy_directory_toolchain.bzl", "COPY_DIRECTORY_PLATFORMS", "copy_directory_platform_repo", "copy_directory_toolchains_repo") load("//lib/private:copy_to_directory_toolchain.bzl", "COPY_TO_DIRECTORY_PLATFORMS", "copy_to_directory_platform_repo", "copy_to_directory_toolchains_repo") load("//lib/private:coreutils_toolchain.bzl", "COREUTILS_PLATFORMS", "coreutils_platform_repo", "coreutils_toolchains_repo", _DEFAULT_COREUTILS_VERSION = "DEFAULT_COREUTILS_VERSION") load("//lib/private:expand_template_toolchain.bzl", "EXPAND_TEMPLATE_PLATFORMS", "expand_template_platform_repo", "expand_template_toolchains_repo") load("//lib/private:jq_toolchain.bzl", "JQ_PLATFORMS", "jq_host_alias_repo", "jq_platform_repo", "jq_toolchains_repo", _DEFAULT_JQ_VERSION = "DEFAULT_JQ_VERSION") load("//lib/private:source_toolchains_repo.bzl", "source_toolchains_repo") load("//lib/private:tar_toolchain.bzl", "BSDTAR_PLATFORMS", "bsdtar_binary_repo", "tar_toolchains_repo") load("//lib/private:yq_toolchain.bzl", "YQ_PLATFORMS", "yq_host_alias_repo", "yq_platform_repo", "yq_toolchains_repo", _DEFAULT_YQ_VERSION = "DEFAULT_YQ_VERSION") load("//lib/private:zstd_toolchain.bzl", "ZSTD_PLATFORMS", "zstd_binary_repo", "zstd_toolchains_repo") load("//tools:version.bzl", "IS_PRERELEASE") # buildifier: disable=unnamed-macro def aspect_bazel_lib_dependencies(): "Load dependencies required by aspect rules" http_archive( name = "bazel_skylib", sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", urls = [ "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", ], ) http_archive( name = "platforms", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/1.0.0/platforms-1.0.0.tar.gz", "https://github.com/bazelbuild/platforms/releases/download/1.0.0/platforms-1.0.0.tar.gz", ], sha256 = "3384eb1c30762704fbe38e440204e114154086c8fc8a8c2e3e28441028c019a8", ) http_archive( name = "bazel_lib", sha256 = "6fd3b1e1a38ca744f9664be4627ced80895c7d2ee353891c172f1ab61309c933", strip_prefix = "bazel-lib-3.0.0", url = "https://github.com/bazel-contrib/bazel-lib/releases/download/v3.0.0/bazel-lib-v3.0.0.tar.gz", ) http_archive( name = "tar.bzl", sha256 = "b47e3c83a0c1440ce335aa1ae18753da6eb7cd551d4946fa303de2abde07e20b", strip_prefix = "tar.bzl-0.5.1", url = "https://github.com/bazel-contrib/tar.bzl/releases/download/v0.5.1/tar.bzl-v0.5.1.tar.gz", ) http_archive( name = "jq.bzl", sha256 = "7b63435aa19cc6a0cfd1a82fbdf2c7a2f0a94db1a79ff7a4469ffa94286261ab", strip_prefix = "jq.bzl-0.1.0", url = "https://github.com/bazel-contrib/jq.bzl/releases/download/v0.1.0/jq.bzl-v0.1.0.tar.gz", ) http_archive( name = "yq.bzl", sha256 = "b51d82b561a78ab21d265107b0edbf98d68a390b4103992d0b03258bb3819601", strip_prefix = "yq.bzl-0.1.1", url = "https://github.com/bazel-contrib/yq.bzl/releases/download/v0.1.1/yq.bzl-v0.1.1.tar.gz", ) http_archive( name = "rules_shell", sha256 = "bc61ef94facc78e20a645726f64756e5e285a045037c7a61f65af2941f4c25e1", strip_prefix = "rules_shell-0.4.1", url = "https://github.com/bazelbuild/rules_shell/releases/download/v0.4.1/rules_shell-v0.4.1.tar.gz", ) DEFAULT_JQ_REPOSITORY = "jq" DEFAULT_JQ_VERSION = _DEFAULT_JQ_VERSION def register_jq_toolchains(name = DEFAULT_JQ_REPOSITORY, version = DEFAULT_JQ_VERSION, register = True): """Registers jq toolchain and repositories Args: name: override the prefix for the generated toolchain repositories version: the version of jq to execute (see https://github.com/stedolan/jq/releases) register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ for [platform, _] in JQ_PLATFORMS.items(): jq_platform_repo( name = "%s_%s" % (name, platform), platform = platform, version = version, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) jq_host_alias_repo(name = name) jq_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_YQ_REPOSITORY = "yq" DEFAULT_YQ_VERSION = _DEFAULT_YQ_VERSION def register_yq_toolchains(name = DEFAULT_YQ_REPOSITORY, version = DEFAULT_YQ_VERSION, register = True): """Registers yq toolchain and repositories Args: name: override the prefix for the generated toolchain repositories version: the version of yq to execute (see https://github.com/mikefarah/yq/releases) register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ for [platform, _] in YQ_PLATFORMS.items(): yq_platform_repo( name = "%s_%s" % (name, platform), platform = platform, version = version, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) yq_host_alias_repo(name = name) yq_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_TAR_REPOSITORY = "bsd_tar" def register_tar_toolchains(name = DEFAULT_TAR_REPOSITORY, register = True): """Registers bsdtar toolchain and repositories Args: name: override the prefix for the generated toolchain repositories register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ for [platform, _] in BSDTAR_PLATFORMS.items(): bsdtar_binary_repo( name = "%s_%s" % (name, platform), platform = platform, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) tar_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_ZSTD_REPOSITORY = "zstd" def register_zstd_toolchains(name = DEFAULT_ZSTD_REPOSITORY, register = True): """Registers zstd toolchain and repositories Args: name: override the prefix for the generated toolchain repositories register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ for [platform, _] in ZSTD_PLATFORMS.items(): zstd_binary_repo( name = "%s_%s" % (name, platform), platform = platform, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) zstd_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_BATS_REPOSITORY = "bats" DEFAULT_BATS_CORE_VERSION = "v1.10.0" DEFAULT_BATS_SUPPORT_VERSION = "v0.3.0" DEFAULT_BATS_ASSERT_VERSION = "v2.1.0" DEFAULT_BATS_FILE_VERSION = "v0.4.0" def register_bats_toolchains( name = DEFAULT_BATS_REPOSITORY, core_version = DEFAULT_BATS_CORE_VERSION, support_version = DEFAULT_BATS_SUPPORT_VERSION, assert_version = DEFAULT_BATS_ASSERT_VERSION, file_version = DEFAULT_BATS_FILE_VERSION, libraries = [], register = True): """Registers bats toolchain and repositories Args: name: override the prefix for the generated toolchain repositories core_version: bats-core version to use support_version: bats-support version to use assert_version: bats-assert version to use file_version: bats-file version to use libraries: additional labels for libraries register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ http_archive( name = "%s_support" % name, sha256 = BATS_SUPPORT_VERSIONS[support_version], urls = [ "https://github.com/bats-core/bats-support/archive/{}.tar.gz".format(support_version), ], strip_prefix = "bats-support-{}".format(support_version.removeprefix("v")), build_file_content = BATS_LIBRARY_TEMPLATE.format(name = "support"), ) http_archive( name = "%s_assert" % name, sha256 = BATS_ASSERT_VERSIONS[assert_version], urls = [ "https://github.com/bats-core/bats-assert/archive/{}.tar.gz".format(assert_version), ], strip_prefix = "bats-assert-{}".format(assert_version.removeprefix("v")), build_file_content = BATS_LIBRARY_TEMPLATE.format(name = "assert"), ) http_archive( name = "%s_file" % name, sha256 = BATS_FILE_VERSIONS[file_version], urls = [ "https://github.com/bats-core/bats-file/archive/{}.tar.gz".format(file_version), ], strip_prefix = "bats-file-{}".format(file_version.removeprefix("v")), build_file_content = BATS_LIBRARY_TEMPLATE.format(name = "file"), ) http_archive( name = "%s_toolchains" % name, sha256 = BATS_CORE_VERSIONS[core_version], urls = [ "https://github.com/bats-core/bats-core/archive/{}.tar.gz".format(core_version), ], strip_prefix = "bats-core-{}".format(core_version.removeprefix("v")), build_file_content = BATS_CORE_TEMPLATE.format(libraries = [ "@%s_support//:support" % name, "@%s_assert//:assert" % name, "@%s_file//:file" % name, ] + libraries), ) if register: native.register_toolchains("@%s_toolchains//:bats_toolchain" % name) DEFAULT_COREUTILS_REPOSITORY = "coreutils" DEFAULT_COREUTILS_VERSION = _DEFAULT_COREUTILS_VERSION def register_coreutils_toolchains(name = DEFAULT_COREUTILS_REPOSITORY, version = DEFAULT_COREUTILS_VERSION, register = True): """Registers coreutils toolchain and repositories Args: name: override the prefix for the generated toolchain repositories version: the version of coreutils to execute (see https://github.com/uutils/coreutils/releases) register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ for [platform, _] in COREUTILS_PLATFORMS.items(): coreutils_platform_repo( name = "%s_%s" % (name, platform), platform = platform, version = version, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) coreutils_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_COPY_DIRECTORY_REPOSITORY = "copy_directory" def register_copy_directory_toolchains(name = DEFAULT_COPY_DIRECTORY_REPOSITORY, register = True): """Registers copy_directory toolchain and repositories Args: name: override the prefix for the generated toolchain repositories register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ if IS_PRERELEASE: source_toolchains_repo( name = "%s_toolchains" % name, toolchain_type = "@aspect_bazel_lib//lib:copy_directory_toolchain_type", toolchain_rule_load_from = "@aspect_bazel_lib//lib/private:copy_directory_toolchain.bzl", toolchain_rule = "copy_directory_toolchain", binary = "@aspect_bazel_lib//tools/copy_directory", ) if register: native.register_toolchains("@%s_toolchains//:toolchain" % name) return for [platform, _] in COPY_DIRECTORY_PLATFORMS.items(): copy_directory_platform_repo( name = "%s_%s" % (name, platform), platform = platform, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) copy_directory_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_COPY_TO_DIRECTORY_REPOSITORY = "copy_to_directory" def register_copy_to_directory_toolchains(name = DEFAULT_COPY_TO_DIRECTORY_REPOSITORY, register = True): """Registers copy_to_directory toolchain and repositories Args: name: override the prefix for the generated toolchain repositories register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ if IS_PRERELEASE: source_toolchains_repo( name = "%s_toolchains" % name, toolchain_type = "@aspect_bazel_lib//lib:copy_to_directory_toolchain_type", toolchain_rule_load_from = "@aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl", toolchain_rule = "copy_to_directory_toolchain", binary = "@aspect_bazel_lib//tools/copy_to_directory", ) if register: native.register_toolchains("@%s_toolchains//:toolchain" % name) return for [platform, _] in COPY_TO_DIRECTORY_PLATFORMS.items(): copy_to_directory_platform_repo( name = "%s_%s" % (name, platform), platform = platform, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) copy_to_directory_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) DEFAULT_EXPAND_TEMPLATE_REPOSITORY = "expand_template" def register_expand_template_toolchains(name = DEFAULT_EXPAND_TEMPLATE_REPOSITORY, register = True): """Registers expand_template toolchain and repositories Args: name: override the prefix for the generated toolchain repositories register: whether to call through to native.register_toolchains. Should be True for WORKSPACE users, but false when used under bzlmod extension """ if IS_PRERELEASE: source_toolchains_repo( name = "%s_toolchains" % name, toolchain_type = "@aspect_bazel_lib//lib:expand_template_toolchain_type", toolchain_rule_load_from = "@aspect_bazel_lib//lib/private:expand_template_toolchain.bzl", toolchain_rule = "expand_template_toolchain", binary = "@aspect_bazel_lib//tools/expand_template", ) if register: native.register_toolchains("@%s_toolchains//:toolchain" % name) return for [platform, _] in EXPAND_TEMPLATE_PLATFORMS.items(): expand_template_platform_repo( name = "%s_%s" % (name, platform), platform = platform, ) if register: native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) expand_template_toolchains_repo( name = "%s_toolchains" % name, user_repository_name = name, ) # buildifier: disable=unnamed-macro def aspect_bazel_lib_register_toolchains(): """Register all bazel-lib toolchains at their default versions. To be more selective about which toolchains and versions to register, call the individual toolchain registration macros. """ register_copy_directory_toolchains() register_copy_to_directory_toolchains() register_expand_template_toolchains() register_coreutils_toolchains() register_jq_toolchains() register_yq_toolchains() register_tar_toolchains() register_zstd_toolchains() register_bats_toolchains() bazel-lib-2.22.5/lib/resource_sets.bzl000066400000000000000000000050301513125663600176150ustar00rootroot00000000000000"""Utilities for rules that expose resource_set on ctx.actions.run[_shell] Workaround for https://github.com/bazelbuild/bazel/issues/15187 Note, this workaround only provides some fixed values for either CPU or Memory. Rule authors who are ALSO the BUILD author might know better, and can write custom resource_set functions for use within their own repository. This seems to be the use case that Google engineers imagined. """ resource_set_values = [ "cpu_2", "cpu_4", "default", "mem_512m", "mem_1g", "mem_2g", "mem_4g", "mem_8g", "mem_16g", "mem_32g", ] def _resource_set_cpu_2(_, __): return {"cpu": 2} def _resource_set_cpu_4(_, __): return {"cpu": 4} def _resource_set_mem_512m(_, __): return {"memory": 512} def _resource_set_mem_1g(_, __): return {"memory": 1024} def _resource_set_mem_2g(_, __): return {"memory": 2048} def _resource_set_mem_4g(_, __): return {"memory": 4096} def _resource_set_mem_8g(_, __): return {"memory": 8192} def _resource_set_mem_16g(_, __): return {"memory": 16384} def _resource_set_mem_32g(_, __): return {"memory": 32768} # buildifier: disable=function-docstring def resource_set(attr): if attr.resource_set == "cpu_2": return _resource_set_cpu_2 if attr.resource_set == "cpu_4": return _resource_set_cpu_4 if attr.resource_set == "default": return None if attr.resource_set == "mem_512m": return _resource_set_mem_512m if attr.resource_set == "mem_1g": return _resource_set_mem_1g if attr.resource_set == "mem_2g": return _resource_set_mem_2g if attr.resource_set == "mem_4g": return _resource_set_mem_4g if attr.resource_set == "mem_8g": return _resource_set_mem_8g if attr.resource_set == "mem_16g": return _resource_set_mem_16g if attr.resource_set == "mem_32g": return _resource_set_mem_32g fail("unknown resource set", attr.resource_set) resource_set_attr = { "resource_set": attr.string( doc = """A predefined function used as the resource_set for actions. Used with --experimental_action_resource_set to reserve more RAM/CPU, preventing Bazel overscheduling resource-intensive actions. By default, Bazel allocates 1 CPU and 250M of RAM. https://github.com/bazelbuild/bazel/blob/058f943037e21710837eda9ca2f85b5f8538c8c5/src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java#L77 """, default = "default", values = resource_set_values, ), } bazel-lib-2.22.5/lib/run_binary.bzl000066400000000000000000000004571513125663600171100ustar00rootroot00000000000000"""Runs a binary as a build action. This rule does not require Bash (unlike native.genrule()). This fork of bazel-skylib's run_binary adds directory output support and better makevar expansions. """ load( "//lib/private:run_binary.bzl", _run_binary = "run_binary", ) run_binary = _run_binary bazel-lib-2.22.5/lib/stamping.bzl000066400000000000000000000126371513125663600165650ustar00rootroot00000000000000"""# Version Stamping Bazel is generally only a build tool, and is unaware of your version control system. However, when publishing releases, you may want to embed version information in the resulting distribution. Bazel supports this with the concept of a "Workspace status" which is evaluated before each build. See [the Bazel workspace status docs](https://docs.bazel.build/versions/master/user-manual.html#workspace_status) To stamp a build, you pass the `--stamp` argument to Bazel. > Note: https://github.com/bazelbuild/bazel/issues/14341 proposes that Bazel enforce this by > only giving constant values to rule implementations when stamping isn't enabled. Stamping is typically performed on a later action in the graph, like on a linking or packaging rule (`pkg_*`). This means that a changed status variable only causes that action, not re-compilation and thus does not cause cascading re-builds. Bazel provides a couple of statuses by default, such as `BUILD_EMBED_LABEL` which is the value of the `--embed_label` argument, as well as `BUILD_HOST`, `BUILD_TIMESTAMP`, and `BUILD_USER`. You can supply more with the workspace status script, see below. Some rules accept an attribute that uses the status variables. They will usually say something like "subject to stamp variable replacements". ## Stamping with a Workspace status script To define additional statuses, pass the `--workspace_status_command` flag to `bazel`. This slows down every build, so you should avoid passing this flag unless you need to stamp this build. The value of this flag is a path to a script that prints space-separated key/value pairs, one per line, such as ```bash #!/usr/bin/env bash echo STABLE_GIT_COMMIT $(git rev-parse HEAD) ``` > For a more full-featured script, take a look at this [example in Angular] Make sure you set the executable bit, eg. `chmod +x tools/bazel_stamp_vars.sh`. > **NOTE** keys that start with `STABLE_` will cause a re-build when they change. > Other keys will NOT cause a re-build, so stale values can appear in your app. > Non-stable (volatile) keys should typically be things like timestamps that always vary between builds. You might like to encode your setup using an entry in `.bazelrc` such as: ```sh # This tells Bazel how to interact with the version control system # Enable this with --config=release build:release --stamp --workspace_status_command=./tools/bazel_stamp_vars.sh ``` [example in Angular]: https://github.com/angular/angular/blob/df274b478e6597cb1a2f31bb9f599281065aa250/dev-infra/release/env-stamp.ts ## Writing a custom rule which reads stamp variables First, load the helpers: ```starlark load("@aspect_bazel_lib//lib:stamping.bzl", "STAMP_ATTRS", "maybe_stamp") ``` In your rule implementation, call the `maybe_stamp` function. If it returns `None` then this build doesn't have stamping enabled. Otherwise you can use the returned struct to access two files. 1. The `stable_status` file contains the keys which were prefixed with `STABLE_`, see above. 2. The `volatile_status` file contains the rest of the keys. ```starlark def _rule_impl(ctx): args = ctx.actions.args() inputs = [] stamp = maybe_stamp(ctx) if stamp: args.add("--volatile_status_file", stamp.volatile_status_file.path) args.add("--stable_status_file", stamp.stable_status_file.path) inputs.extend([stamp.volatile_status_file, stamp.stable_status_file]) # ... call actions which parse the stamp files and do something with the values ... ``` Finally, in the declaration of the rule, include the `STAMP_ATTRS` to declare attributes which are read by that `maybe_stamp` function above. ```starlark my_stamp_aware_rule = rule( attrs = dict({ # ... my attributes ... }, **STAMP_ATTRS), ) ``` """ load("//lib/private:stamping.bzl", "is_stamping_enabled") def maybe_stamp(ctx): """Provide the bazel-out/stable_status.txt and bazel-out/volatile_status.txt files. Args: ctx: The rule context Returns: If stamping is not enabled for this rule under the current build, returns None. Otherwise, returns a struct containing (volatile_status_file, stable_status_file) keys """ if is_stamping_enabled(ctx.attr): return struct( volatile_status_file = ctx.version_file, stable_status_file = ctx.info_file, ) return None STAMP_ATTRS = { "stamp": attr.int( doc = """\ Whether to encode build information into the output. Possible values: - `stamp = 1`: Always stamp the build information into the output, even in [--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. This setting should be avoided, since it is non-deterministic. It potentially causes remote cache misses for the target and any downstream actions that depend on the result. - `stamp = 0`: Never stamp, instead replace build information by constant values. This gives good build result caching. - `stamp = -1`: Embedding of build information is controlled by the [--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag. Stamped targets are not rebuilt unless their dependencies change. """, default = -1, values = [1, 0, -1], ), "_stamp_flag": attr.label( doc = "Internal use only. A setting used to determine whether or not the `--stamp` flag is enabled.", default = Label("//lib:stamp"), ), } bazel-lib-2.22.5/lib/strings.bzl000066400000000000000000000002741513125663600164260ustar00rootroot00000000000000"Utilities for strings" load("//lib/private:strings.bzl", _chr = "chr", _hex = "hex", _ord = "ord", _split_args = "split_args") chr = _chr ord = _ord hex = _hex split_args = _split_args bazel-lib-2.22.5/lib/tar.bzl000066400000000000000000000013601513125663600155200ustar00rootroot00000000000000"""Re-export of https://registry.bazel.build/modules/tar.bzl to avoid breaking change. https://github.com/bazel-contrib/bazel-lib/pull/1083 moved these symbols to tar.bzl TODO(3.0): delete """ load("@tar.bzl//tar:mtree.bzl", _mtree_mutate = "mtree_mutate", _mtree_spec = "mtree_spec") load("@tar.bzl//tar:tar.bzl", _tar = "tar", _tar_lib = "tar_lib", _tar_rule = "tar_rule") tar_lib = struct( attrs = _tar_lib.attrs, implementation = _tar_lib.implementation, mtree_attrs = _tar_lib.mtree_attrs, mtree_implementation = _tar_lib.mtree_implementation, toolchain_type = "@aspect_bazel_lib//lib:tar_toolchain_type", common = _tar_lib.common, ) mtree_mutate = _mtree_mutate mtree_spec = _mtree_spec tar = _tar tar_rule = _tar_rule bazel-lib-2.22.5/lib/testing.bzl000066400000000000000000000171611513125663600164150ustar00rootroot00000000000000"Helpers for making test assertions" load("@bazel_skylib//lib:types.bzl", "types") load("@bazel_skylib//rules:write_file.bzl", "write_file") load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//lib:diff_test.bzl", "diff_test") load("//lib:jq.bzl", "jq") load("//lib:params_file.bzl", "params_file") def assert_contains(name, actual, expected, size = "small", **kwargs): """Generates a test target which fails if the file doesn't contain the string. Depends on bash, as it creates an sh_test target. Args: name: target to create actual: Label of a file expected: a string which should appear in the file size: standard attribute for tests **kwargs: additional named arguments for the resulting sh_test """ test_sh = "{}_test.sh".format(name) expected_file = "{}_expected.txt".format(name) write_file( name = "{}_expected".format(name), out = expected_file, content = [expected], ) write_file( name = "{}_gen".format(name), out = test_sh, content = [ "#!/usr/bin/env bash", "set -o errexit", "grep --fixed-strings -f $1 $2", ], ) sh_test( name = name, srcs = [test_sh], args = ["$(rootpath %s)" % expected_file, "$(rootpath %s)" % actual], size = size, data = [actual, expected_file], **kwargs ) def assert_outputs(name, actual, expected, **kwargs): """Assert that the default outputs of a target are the expected ones. Args: name: name of the resulting diff_test actual: string of the label to check the outputs expected: a list of rootpaths of expected outputs, as they would appear in a runfiles manifest **kwargs: additional named arguments for the resulting diff_test """ if not types.is_list(expected): fail("expected should be a list of strings, not " + type(expected)) params_file( name = name + "_actual", data = [actual], args = ["$(rootpaths {})".format(actual)], out = "{}_outputs.txt".format(name), ) write_file( name = name + "_expected", content = expected, out = "{}_expected.txt".format(name), ) diff_test( name = name, file1 = name + "_expected", file2 = name + "_actual", **kwargs ) def assert_json_matches(name, file1, file2, filter1 = ".", filter2 = ".", **kwargs): """Assert that the given json files have the same semantic content. Uses jq to filter each file. The default value of `"."` as the filter means to compare the whole file. See the [jq rule](./jq.md#jq) for more about the filter expressions as well as setup notes for the `jq` toolchain. Args: name: name of resulting diff_test target file1: a json file file2: another json file filter1: a jq filter to apply to file1 filter2: a jq filter to apply to file2 **kwargs: additional named arguments for the resulting diff_test """ name1 = "{}_jq1".format(name) name2 = "{}_jq2".format(name) jq( name = name1, srcs = [file1], filter = filter1, ) jq( name = name2, srcs = [file2], filter = filter2, ) diff_test( name = name, file1 = name1, file2 = name2, failure_message = "'{}' from {} doesn't match '{}' from {}".format( filter1, file1, filter2, file2, ), **kwargs ) def assert_archive_contains(name, archive, expected, type = None, **kwargs): """Assert that an archive file contains at least the given file entries. Args: name: name of the resulting sh_test target archive: Label of the the .tar or .zip file expected: a (partial) file listing, either as a Label of a file containing it, or a list of strings type: "tar" or "zip". If None, a type will be inferred from the filename. **kwargs: additional named arguments for the resulting sh_test """ if not type: if archive.endswith(".whl") or archive.endswith(".zip"): type = "zip" elif archive.endswith(".tar"): type = "tar" else: fail("could not infer type from {}, please set the type attribute explicitly".format(archive)) if not type in ["tar", "zip"]: fail("type must be 'tar' or 'zip', not " + type) # Command to list the files in the archive command = "unzip -Z1" if type == "zip" else "tar -tf" # -f $actual: use this file to contain one pattern per line # -F: treat each pattern as a plain string, not a regex # -x: match whole lines only # -v: only print lines which don't match grep = "grep -F -x -v -f $actual" script_name = name + "_gen_assert" expected_name = name + "_expected" if types.is_list(expected): write_file( name = expected_name, out = expected_name + ".mf", content = expected, ) else: expected_name = expected write_file( name = script_name, out = "assert_{}.sh".format(name), content = [ "#!/usr/bin/env bash", "actual=$(mktemp)", "{} $1 > $actual".format(command), "# Grep exits 1 if no matches, which is success for this test.", "if {} $2; then".format(grep), " echo", " echo 'ERROR: above line(s) appeared in {} but are not present in the archive' $1".format(expected_name), " exit 1", "fi", ], ) sh_test( name = name, srcs = [script_name], args = ["$(rootpath %s)" % archive, "$(rootpath %s)" % expected_name], data = [archive, expected_name], timeout = "short", **kwargs ) def assert_directory_contains(name, directory, expected, **kwargs): """Assert that a directory contains at least the given file entries. Args: name: name of the resulting sh_test target directory: Label of the directory artifact expected: a (partial) file listing, either as a Label of a file containing it, or a list of strings **kwargs: additional named arguments for the resulting sh_test """ # -f $actual: use this file to contain one pattern per line # -F: treat each pattern as a plain string, not a regex # -x: match whole lines only # -v: only print lines which don't match grep = "grep -F -x -v -f $actual" script_name = name + "_gen_assert" expected_name = name + "_expected" if types.is_list(expected): write_file( name = expected_name, out = expected_name + ".mf", content = expected, ) else: expected_name = expected write_file( name = script_name, out = "assert_{}.sh".format(name), content = [ "#!/usr/bin/env bash", "actual=$(mktemp)", "pushd $1 > /dev/null", "find . -type l,f | cut -b 3- > $actual", "popd > /dev/null", "# Grep exits 1 if no matches, which is success for this test.", "if {} $2; then".format(grep), " echo", " echo 'ERROR: above line(s) appeared in {} but are not present in the directory' $1".format(expected_name), " exit 1", "fi", ], ) sh_test( name = name, srcs = [script_name], args = ["$(rootpath %s)" % directory, "$(rootpath %s)" % expected_name], data = [directory, expected_name], timeout = "short", **kwargs ) bazel-lib-2.22.5/lib/transitions.bzl000066400000000000000000000113531513125663600173120ustar00rootroot00000000000000"Rules for working with transitions." load("@bazel_skylib//lib:paths.bzl", "paths") def _transition_platform_impl(_, attr): return {"//command_line_option:platforms": str(attr.target_platform)} # Transition from any input configuration to one that includes the # --platforms command-line flag. _transition_platform = transition( implementation = _transition_platform_impl, inputs = [], outputs = ["//command_line_option:platforms"], ) def _platform_transition_filegroup_impl(ctx): files = [] runfiles = ctx.runfiles() for src in ctx.attr.srcs: files.append(src[DefaultInfo].files) runfiles = runfiles.merge_all([src[DefaultInfo].default_runfiles for src in ctx.attr.srcs]) return [DefaultInfo( files = depset(transitive = files), runfiles = runfiles, )] platform_transition_filegroup = rule( _platform_transition_filegroup_impl, attrs = { # Required to Opt-in to the transitions feature. "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", ), "target_platform": attr.label( doc = "The target platform to transition the srcs.", mandatory = True, ), "srcs": attr.label_list( allow_empty = False, cfg = _transition_platform, doc = "The input to be transitioned to the target platform.", ), }, doc = "Transitions the srcs to use the provided platform. The filegroup will contain artifacts for the target platform.", ) def _platform_transition_binary_impl(ctx): # We need to forward the DefaultInfo provider from the underlying rule. # Unfortunately, we can't do this directly, because Bazel requires that the executable to run # is actually generated by this rule, so we need to symlink to it, and generate a synthetic # forwarding DefaultInfo. result = [] # ctx.attr.binary is a singleton list if this rule uses an outgoing transition. if type(ctx.attr.binary) == type([]): binary = ctx.attr.binary[0] else: binary = ctx.attr.binary default_info = binary[DefaultInfo] files = default_info.files new_executable = None original_executable = default_info.files_to_run.executable runfiles = default_info.default_runfiles if not original_executable: fail("Cannot transition a 'binary' that is not executable") new_executable_name = ctx.attr.basename if ctx.attr.basename else original_executable.basename # In order for the symlink to have the same basename as the original # executable (important in the case of proto plugins), put it in a # subdirectory named after the label to prevent collisions. new_executable = ctx.actions.declare_file(paths.join(ctx.label.name, new_executable_name)) ctx.actions.symlink( output = new_executable, target_file = original_executable, is_executable = True, ) files = depset(direct = [new_executable], transitive = [files]) runfiles = runfiles.merge(ctx.runfiles([new_executable])) result.append( DefaultInfo( files = files, runfiles = runfiles, executable = new_executable, ), ) if RunEnvironmentInfo in binary: result.append(binary[RunEnvironmentInfo]) return result def _get_platform_transition_attrs(binary_cfg): return { "basename": attr.string(), "binary": attr.label(allow_files = True, cfg = binary_cfg), "target_platform": attr.label( doc = "The target platform to transition the binary.", mandatory = True, ), "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", ), } platform_transition_binary = rule( implementation = _platform_transition_binary_impl, # Use an outgoing transition since the target platform of the # platform_transition_binary doesn't matter and it results in a more # intuitive output path (matching an untransitioned binary). attrs = _get_platform_transition_attrs(binary_cfg = _transition_platform), executable = True, doc = "Transitions the binary to use the provided platform. Will forward RunEnvironmentInfo", ) platform_transition_test = rule( implementation = _platform_transition_binary_impl, attrs = _get_platform_transition_attrs(binary_cfg = "target"), # Use an incoming transition since the target platform of the # platform_transition_test does matter for the exec platform resolution of # the test action. cfg = _transition_platform, test = True, doc = "Transitions the test to use the provided platform. Will forward RunEnvironmentInfo", ) bazel-lib-2.22.5/lib/utils.bzl000066400000000000000000000022771513125663600161020ustar00rootroot00000000000000"""General-purpose Starlark utility functions ## Usage example ```starlark load("@aspect_bazel_lib//lib:utils.bzl", "utils") out_label = utils.to_label(out_file) ``` """ load("//lib/private:utils.bzl", _utils = "utils") utils = _utils # TODO(3.0): remove these fine grained re-exports default_timeout = _utils.default_timeout file_exists = _utils.file_exists glob_directories = _utils.glob_directories is_bazel_6_or_greater = _utils.is_bazel_6_or_greater is_bazel_7_or_greater = _utils.is_bazel_7_or_greater is_bzlmod_enabled = _utils.is_bzlmod_enabled is_external_label = _utils.is_external_label maybe_http_archive = _utils.maybe_http_archive path_to_workspace_root = _utils.path_to_workspace_root propagate_well_known_tags = _utils.propagate_well_known_tags propagate_common_rule_attributes = _utils.propagate_common_rule_attributes propagate_common_test_rule_attributes = _utils.propagate_common_test_rule_attributes propagate_common_binary_rule_attributes = _utils.propagate_common_binary_rule_attributes to_label = _utils.to_label consistent_label_str = _utils.consistent_label_str # DON'T ADD ANY MORE fine-grained re-exports here; new util functions # should just go through the 'utils' export above bazel-lib-2.22.5/lib/windows_utils.bzl000066400000000000000000000067451513125663600176600ustar00rootroot00000000000000# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Helpers for rules running on windows" load("//lib/private:paths.bzl", "paths") # cmd.exe function for looking up runfiles. # Equivalent of the BASH_RLOCATION_FUNCTION in paths.bzl. # Use this to write actions that don't require bash. # Originally by @meteorcloudy in # https://github.com/bazel-contrib/rules_nodejs/commit/f06553a BATCH_RLOCATION_FUNCTION = r""" rem Usage of rlocation function: rem call :rlocation rem The rlocation function maps the given to its absolute rem path and stores the result in a variable named . rem This function fails if the doesn't exist in mainifest rem file. :: Start of rlocation goto :rlocation_end :rlocation if "%~2" equ "" ( echo>&2 ERROR: Expected two arguments for rlocation function. exit 1 ) if "%RUNFILES_MANIFEST_ONLY%" neq "1" ( set %~2=%~1 exit /b 0 ) if exist "%RUNFILES_DIR%" ( set RUNFILES_MANIFEST_FILE=%RUNFILES_DIR%_manifest ) if "%RUNFILES_MANIFEST_FILE%" equ "" ( set RUNFILES_MANIFEST_FILE=%~f0.runfiles\MANIFEST ) if not exist "%RUNFILES_MANIFEST_FILE%" ( set RUNFILES_MANIFEST_FILE=%~f0.runfiles_manifest ) set MF=%RUNFILES_MANIFEST_FILE:/=\% if not exist "%MF%" ( echo>&2 ERROR: Manifest file %MF% does not exist. exit 1 ) set runfile_path=%~1 for /F "tokens=2* usebackq" %%i in (`%SYSTEMROOT%\system32\findstr.exe /l /c:"!runfile_path! " "%MF%"`) do ( set abs_path=%%i ) if "!abs_path!" equ "" ( echo>&2 ERROR: !runfile_path! not found in runfiles manifest exit 1 ) set %~2=!abs_path! exit /b 0 :rlocation_end :: End of rlocation """ def create_windows_native_launcher_script(ctx, shell_script): """Create a Windows Batch file to launch the given shell script. The rule should specify @bazel_tools//tools/sh:toolchain_type as a required toolchain. Args: ctx: Rule context shell_script: The bash launcher script Returns: A windows launcher script """ name = shell_script.basename if name.endswith(".sh"): name = name[:-3] win_launcher = ctx.actions.declare_file(name + ".bat", sibling = shell_script) ctx.actions.write( output = win_launcher, content = r"""@echo off SETLOCAL ENABLEEXTENSIONS SETLOCAL ENABLEDELAYEDEXPANSION set RUNFILES_MANIFEST_ONLY=1 {rlocation_function} call :rlocation "{sh_script}" run_script for %%a in ("{bash_bin}") do set "bash_bin_dir=%%~dpa" set PATH=%bash_bin_dir%;%PATH% set args=%* rem Escape \ and * in args before passing it with double quote if defined args ( set args=!args:\=\\\\! set args=!args:"=\"! ) "{bash_bin}" -c "!run_script! !args!" """.format( bash_bin = ctx.toolchains["@bazel_tools//tools/sh:toolchain_type"].path, sh_script = paths.to_rlocation_path(ctx, shell_script), rlocation_function = BATCH_RLOCATION_FUNCTION, ), is_executable = True, ) return win_launcher bazel-lib-2.22.5/lib/write_source_files.bzl000066400000000000000000000177051513125663600206400ustar00rootroot00000000000000"""write_source_files provides a workaround for the restriction that `bazel build` cannot write to the source tree. Read more about the philosophy of writing to the source tree: ## Usage ```starlark load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_foobar", files = { "foobar.json": "//some/generated:file", }, ) ``` To update the source file, run: ```bash bazel run //:write_foobar ``` The generated `diff_test` will fail if the file is out of date and print out instructions on how to update it. If the file does not exist, Bazel will fail at analysis time and print out instructions on how to create it. You can declare a tree of generated source file targets: ```starlark load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files") write_source_files( name = "write_all", additional_update_targets = [ # Other write_source_files targets to run when this target is run "//a/b/c:write_foo", "//a/b:write_bar", ] ) ``` And update them with a single run: ```bash bazel run //:write_all ``` When a file is out of date, you can leave a suggestion to run a target further up in the tree by specifying `suggested_update_target`. For example, ```starlark write_source_files( name = "write_foo", files = { "foo.json": ":generated-foo", }, suggested_update_target = "//:write_all" ) ``` A test failure from `foo.json` being out of date will yield the following message: ``` //a/b:c:foo.json is out of date. To update this and other generated files, run: bazel run //:write_all To update *only* this file, run: bazel run //a/b/c:write_foo ``` You can also add a more customized error message using the `diff_test_failure_message` argument: ```starlark write_source_file( name = "write_foo", out_file = "foo.json", in_file = ":generated-foo", diff_test_failure_message = "Failed to build Foo; please run {{TARGET}} to update." ) ``` A test failure from `foo.json` being out of date will then yield: ``` Failed to build Foo; please run //a/b/c:write_foo to update. ``` If you have many `write_source_files` targets that you want to update as a group, we recommend wrapping `write_source_files` in a macro that defaults `suggested_update_target` to the umbrella update target. NOTE: If you run formatters or linters on your codebase, it is advised that you exclude/ignore the outputs of this rule from those formatters/linters so as to avoid causing collisions and failing tests. """ load( "//lib/private:write_source_file.bzl", _WriteSourceFileInfo = "WriteSourceFileInfo", _write_source_file = "write_source_file", ) WriteSourceFileInfo = _WriteSourceFileInfo def write_source_files( name, files = {}, executable = False, additional_update_targets = [], suggested_update_target = None, diff_test = True, diff_test_failure_message = "{{DEFAULT_MESSAGE}}", diff_args = [], file_missing_failure_message = "{{DEFAULT_MESSAGE}}", check_that_out_file_exists = True, **kwargs): """Write one or more files and/or directories to the source tree. By default, `diff_test` targets are generated that ensure the source tree files and/or directories to be written to are up to date and the rule also checks that all source tree files and/or directories to be written to exist. To disable the exists check and up-to-date tests set `diff_test` to `False`. Args: name: Name of the runnable target that creates or updates the source tree files and/or directories. files: A dict where the keys are files or directories in the source tree to write to and the values are labels pointing to the desired content, typically file or directory outputs of other targets. Destination files and directories must be within the same containing Bazel package as this target if `check_that_out_file_exists` is True. See `check_that_out_file_exists` docstring for more info. executable: Whether source tree files written should be made executable. This applies to all source tree files written by this target. This attribute is not propagated to `additional_update_targets`. To set different executable permissions on different source tree files use multiple `write_source_files` targets. additional_update_targets: List of other `write_source_files` or `write_source_file` targets to call in the same run. suggested_update_target: Label of the `write_source_files` or `write_source_file` target to suggest running when files are out of date. diff_test: Test that the source tree files and/or directories exist and are up to date. diff_test_failure_message: Text to print when the diff test fails, with templating options for relevant targets. Substitutions are performed on the failure message, with the following substitutions being available: `{{DEFAULT_MESSAGE}}`: Prints the default error message, listing the target(s) that may be run to update the file(s). `{{TARGET}}`: The target to update the individual file that does not match in the diff test. `{{SUGGESTED_UPDATE_TARGET}}`: The suggested_update_target if specified, or the target which will update all of the files which do not match. diff_args: Arguments to pass to the `diff` command. (Ignored on Windows) file_missing_failure_message: Text to print when the output file is missing. Subject to the same substitutions as diff_test_failure_message. check_that_out_file_exists: Test that each output file exists and print a helpful error message if it doesn't. If `True`, destination files and directories must be in the same containing Bazel package as the target since the underlying mechanism for this check is limited to files in the same Bazel package. **kwargs: Other common named parameters such as `tags` or `visibility` """ single_update_target = len(files.keys()) == 1 update_targets = [] test_targets = [] for i, pair in enumerate(files.items()): out_file, in_file = pair this_suggested_update_target = suggested_update_target if single_update_target: update_target_name = name else: update_target_name = "%s_%d" % (name, i) update_targets.append(update_target_name) if not this_suggested_update_target: this_suggested_update_target = name # Runnable target that writes to the out file to the source tree test_target = _write_source_file( name = update_target_name, in_file = in_file, out_file = out_file, executable = executable, additional_update_targets = additional_update_targets if single_update_target else [], suggested_update_target = this_suggested_update_target, diff_test = diff_test, diff_test_failure_message = diff_test_failure_message, diff_args = diff_args, file_missing_failure_message = file_missing_failure_message, check_that_out_file_exists = check_that_out_file_exists, **kwargs ) if test_target: test_targets.append(test_target) if len(test_targets) > 0: native.test_suite( name = "%s_tests" % name, tests = test_targets, visibility = kwargs.get("visibility"), tags = kwargs.get("tags"), ) if not single_update_target: _write_source_file( name = name, additional_update_targets = update_targets + additional_update_targets, suggested_update_target = suggested_update_target, **kwargs ) write_source_file = _write_source_file bazel-lib-2.22.5/lib/yq.bzl000066400000000000000000000002371513125663600153650ustar00rootroot00000000000000""" Re-export of https://registry.bazel.build/modules/yq.bzl to avoid breaking change. TODO(3.0): delete """ load("@yq.bzl//yq:yq.bzl", _yq = "yq") yq = _yq bazel-lib-2.22.5/platforms/000077500000000000000000000000001513125663600154625ustar00rootroot00000000000000bazel-lib-2.22.5/platforms/BUILD.bazel000066400000000000000000000016301513125663600173400ustar00rootroot00000000000000load("//platforms/config:defs.bzl", "platforms") [platform( name = "{}_{}".format( p.os, p.cpu, ), constraint_values = [ "@platforms//os:{}".format(p.os), "@platforms//cpu:{}".format(p.cpu), ], visibility = ["//visibility:public"], ) for p in platforms] alias( name = "linux_amd64", actual = ":linux_x86_64", visibility = ["//visibility:public"], ) alias( name = "linux_arm64", actual = ":linux_aarch64", visibility = ["//visibility:public"], ) platform( name = "x86_64_linux_remote", constraint_values = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], exec_properties = { "OSFamily": "Linux", "container-image": "docker://public.ecr.aws/docker/library/python@sha256:247105bbbe7f7afc7c12ac893be65b5a32951c1d0276392dc2bf09861ba288a6", }, visibility = ["//visibility:public"], ) bazel-lib-2.22.5/platforms/config/000077500000000000000000000000001513125663600167275ustar00rootroot00000000000000bazel-lib-2.22.5/platforms/config/BUILD.bazel000066400000000000000000000011231513125663600206020ustar00rootroot00000000000000load(":defs.bzl", "platforms") config_setting( name = "aarch64", constraint_values = [ "@platforms//cpu:aarch64", ], visibility = ["//visibility:public"], ) config_setting( name = "x86_64", constraint_values = [ "@platforms//cpu:x86_64", ], visibility = ["//visibility:public"], ) [config_setting( name = "{}_{}".format( p.os, p.cpu, ), constraint_values = [ "@platforms//os:{}".format(p.os), "@platforms//cpu:{}".format(p.cpu), ], visibility = ["//visibility:public"], ) for p in platforms] bazel-lib-2.22.5/platforms/config/defs.bzl000066400000000000000000000002731513125663600203630ustar00rootroot00000000000000"""This module generated the platforms list for the build matrix.""" platforms = [ struct(os = os, cpu = cpu) for os in ["linux", "macos"] for cpu in ["aarch64", "x86_64"] ] bazel-lib-2.22.5/renovate.json000066400000000000000000000011521513125663600161700ustar00rootroot00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ ":dependencyDashboard", ":enablePreCommit", ":semanticPrefixFixDepsChoreOthers", "group:monorepos", "group:recommended", "replacements:all", "workarounds:all" ], "schedule": ["before 4am on monday"], "packageRules": [ { "matchFiles": ["MODULE.bazel"], "matchPackageNames": ["pre-commit/mirrors-prettier"], "enabled": false }, { "matchManagers": ["gomod"], "groupName": "all Go dependencies", "groupSlug": "all-go-deps" } ], "labels": ["deps"] } bazel-lib-2.22.5/shlib/000077500000000000000000000000001513125663600145545ustar00rootroot00000000000000bazel-lib-2.22.5/shlib/lib/000077500000000000000000000000001513125663600153225ustar00rootroot00000000000000bazel-lib-2.22.5/shlib/lib/BUILD.bazel000066400000000000000000000003131513125663600171750ustar00rootroot00000000000000load("@rules_shell//shell:sh_library.bzl", "sh_library") package(default_visibility = ["//visibility:public"]) sh_library( name = "assertions", testonly = True, srcs = ["assertions.sh"], ) bazel-lib-2.22.5/shlib/lib/assertions.sh000066400000000000000000000042231513125663600200510ustar00rootroot00000000000000#!/usr/bin/env bash # Fail a test with the specified message. # # Args: # err_msg: The message to print to stderr. # # Outputs: # stdout: None. # stderr: The error message. fail() { local err_msg="${1:-}" if [[ -z "${err_msg:-}" ]]; then err_msg="Unspecified error occurred." fi echo >&2 "${err_msg}" exit 1 } make_err_msg() { local err_msg="${1}" local prefix="${2:-}" if [[ -n "${prefix:-}" ]]; then err_msg="${prefix} ${err_msg}" fi echo "${err_msg}" } # Asserts that the actual value equals the expected value. # # Args: # expected: The expected value. # actual: The actual value. # err_msg: Optional. The error message to print if the assertion fails. # # Outputs: # stdout: None. # stderr: None. assert_equal() { local expected="${1}" local actual="${2}" local err_msg err_msg="$( make_err_msg \ "Expected to be equal. expected: ${expected}, actual: ${actual}" "${3:-}" )" if [[ "${expected}" != "${actual}" ]]; then fail "${err_msg}" fi } # Asserts that the actual value contains the specified regex pattern. # # Args: # pattern: The expected pattern. # actual: The actual value. # err_msg: Optional. The error message to print if the assertion fails. # # Outputs: # stdout: None. # stderr: None. assert_match() { local pattern=${1} local actual="${2}" local err_msg err_msg="$( make_err_msg \ "Expected to match. pattern: ${pattern}, actual: ${actual}" "${3:-}" )" if [[ ! "${actual}" =~ ${pattern} ]]; then fail "${err_msg}" fi } # Asserts that the actual value does not contain the specified regex pattern. # # Args: # pattern: The expected pattern. # actual: The actual value. # err_msg: Optional. The error message to print if the assertion fails. # # Outputs: # stdout: None. # stderr: None. assert_no_match() { local pattern=${1} local actual="${2}" local err_msg err_msg="$( make_err_msg \ "Expected not to match. pattern: ${pattern}, actual: ${actual}" "${3:-}" )" if [[ "${actual}" =~ ${pattern} ]]; then fail "${err_msg}" fi # Because this is a negative test, we need to end on a positive note if all is well. echo "" } bazel-lib-2.22.5/shlib/tests/000077500000000000000000000000001513125663600157165ustar00rootroot00000000000000bazel-lib-2.22.5/shlib/tests/lib_tests/000077500000000000000000000000001513125663600177065ustar00rootroot00000000000000bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/000077500000000000000000000000001513125663600233225ustar00rootroot00000000000000bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/BUILD.bazel000066400000000000000000000015571513125663600252100ustar00rootroot00000000000000load("@rules_shell//shell:sh_library.bzl", "sh_library") load("@rules_shell//shell:sh_test.bzl", "sh_test") sh_library( name = "assert_fail", testonly = True, srcs = ["assert_fail.sh"], ) sh_test( name = "assert_equal_test", size = "small", srcs = ["assert_equal_test.sh"], deps = [ ":assert_fail", "//shlib/lib:assertions", "@bazel_tools//tools/bash/runfiles", ], ) sh_test( name = "assert_match_test", size = "small", srcs = ["assert_match_test.sh"], deps = [ ":assert_fail", "//shlib/lib:assertions", "@bazel_tools//tools/bash/runfiles", ], ) sh_test( name = "assert_no_match_test", size = "small", srcs = ["assert_no_match_test.sh"], deps = [ ":assert_fail", "//shlib/lib:assertions", "@bazel_tools//tools/bash/runfiles", ], ) bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/assert_equal_test.sh000077500000000000000000000031601513125663600274100ustar00rootroot00000000000000#!/usr/bin/env bash # --- begin runfiles.bash initialization v2 --- # Copy-pasted from the Bazel Bash runfiles library v2. set -o nounset -o pipefail f=bazel_tools/tools/bash/runfiles/runfiles.bash # shellcheck disable=SC1090 source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || source "$0.runfiles/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || { echo >&2 "ERROR: cannot find $f" exit 1 } f= set -e # --- end runfiles.bash initialization v2 --- assertions_sh_location=aspect_bazel_lib/shlib/lib/assertions.sh assertions_sh="$(rlocation "${assertions_sh_location}")" || (echo >&2 "Failed to locate ${assertions_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/../../../lib/assertions.sh source "${assertions_sh}" assert_fail_sh_location=aspect_bazel_lib/shlib/tests/lib_tests/assertions_tests/assert_fail.sh assert_fail_sh="$(rlocation "${assert_fail_sh_location}")" || (echo >&2 "Failed to locate ${assert_fail_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/assert_fail.sh source "${assert_fail_sh}" # MARK - Test assert_equal reset_fail_err_msgs assert_equal "hello" "goodbye" assert_fail "Expected to be equal." reset_fail_err_msgs reset_fail_err_msgs assert_equal "hello" "goodbye" "Custom prefix." assert_fail "Custom prefix. Expected to be equal." reset_fail_err_msgs reset_fail_err_msgs assert_equal "hello" "hello" assert_no_fail reset_fail_err_msgs bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/assert_fail.sh000066400000000000000000000016151513125663600261550ustar00rootroot00000000000000#!/usr/bin/env bash FAIL_ERR_MSGS=() fail() { local err_msg="${1:-"Unspecified error occurred."}" FAIL_ERR_MSGS+=("${err_msg}") } reset_fail_err_msgs() { FAIL_ERR_MSGS=() } new_fail() { local err_msg="${1:-}" [[ -n "${err_msg}" ]] || err_msg="Unspecified error occurred." echo >&2 "${err_msg}" exit 1 } assert_fail() { local pattern=${1} [[ ${#FAIL_ERR_MSGS[@]} == 0 ]] && new_fail "Expected a failure. None found. pattern: ${pattern}" [[ ${#FAIL_ERR_MSGS[@]} -gt 1 ]] && new_fail "Expected a single failure. Found ${#FAIL_ERR_MSGS[@]}. pattern: ${pattern}" [[ "${FAIL_ERR_MSGS[0]}" =~ ${pattern} ]] || new_fail "Unexpected failure. Found '${FAIL_ERR_MSGS[0]}'. pattern: ${pattern}" } assert_no_fail() { [[ ${#FAIL_ERR_MSGS[@]} == 0 ]] || ( err_msg=$("${FAIL_ERR_MSGS[@]}") && new_fail "Expected no failures. Found ${#FAIL_ERR_MSGS[@]}. '${err_msg}'" ) } bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/assert_match_test.sh000077500000000000000000000027671513125663600274110ustar00rootroot00000000000000#!/usr/bin/env bash # --- begin runfiles.bash initialization v2 --- # Copy-pasted from the Bazel Bash runfiles library v2. set -o nounset -o pipefail f=bazel_tools/tools/bash/runfiles/runfiles.bash # shellcheck disable=SC1090 source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || source "$0.runfiles/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || { echo >&2 "ERROR: cannot find $f" exit 1 } f= set -e # --- end runfiles.bash initialization v2 --- assertions_sh_location=aspect_bazel_lib/shlib/lib/assertions.sh assertions_sh="$(rlocation "${assertions_sh_location}")" || (echo >&2 "Failed to locate ${assertions_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/../../../lib/assertions.sh source "${assertions_sh}" assert_fail_sh_location=aspect_bazel_lib/shlib/tests/lib_tests/assertions_tests/assert_fail.sh assert_fail_sh="$(rlocation "${assert_fail_sh_location}")" || (echo >&2 "Failed to locate ${assert_fail_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/assert_fail.sh source "${assert_fail_sh}" # MARK - Test assert_match reset_fail_err_msgs assert_match ^Begin "Begin with hello" assert_no_fail reset_fail_err_msgs reset_fail_err_msgs assert_match ^Begin "Not Begin with hello" assert_fail "Expected to match." reset_fail_err_msgs bazel-lib-2.22.5/shlib/tests/lib_tests/assertions_tests/assert_no_match_test.sh000077500000000000000000000030041513125663600300660ustar00rootroot00000000000000#!/usr/bin/env bash # --- begin runfiles.bash initialization v2 --- # Copy-pasted from the Bazel Bash runfiles library v2. set -o nounset -o pipefail f=bazel_tools/tools/bash/runfiles/runfiles.bash # shellcheck disable=SC1090 source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || source "$0.runfiles/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || { echo >&2 "ERROR: cannot find $f" exit 1 } f= set -e # --- end runfiles.bash initialization v2 --- assertions_sh_location=aspect_bazel_lib/shlib/lib/assertions.sh assertions_sh="$(rlocation "${assertions_sh_location}")" || (echo >&2 "Failed to locate ${assertions_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/../../../lib/assertions.sh source "${assertions_sh}" assert_fail_sh_location=aspect_bazel_lib/shlib/tests/lib_tests/assertions_tests/assert_fail.sh assert_fail_sh="$(rlocation "${assert_fail_sh_location}")" || (echo >&2 "Failed to locate ${assert_fail_sh_location}" && exit 1) # shellcheck source=SCRIPTDIR/assert_fail.sh source "${assert_fail_sh}" # MARK - Test assert_no_match reset_fail_err_msgs assert_no_match ^Begin "Begin with hello" assert_fail "Expected not to match." reset_fail_err_msgs reset_fail_err_msgs assert_no_match ^Begin "Not Begin with hello" assert_no_fail reset_fail_err_msgs bazel-lib-2.22.5/tools/000077500000000000000000000000001513125663600146135ustar00rootroot00000000000000bazel-lib-2.22.5/tools/BUILD.bazel000066400000000000000000000004271513125663600164740ustar00rootroot00000000000000load("@aspect_bazel_lib//:bzl_library.bzl", "bzl_library") bzl_library( name = "integrity", srcs = ["integrity.bzl"], visibility = ["//visibility:public"], ) bzl_library( name = "version", srcs = ["version.bzl"], visibility = ["//visibility:public"], ) bazel-lib-2.22.5/tools/common/000077500000000000000000000000001513125663600161035ustar00rootroot00000000000000bazel-lib-2.22.5/tools/common/BUILD.bazel000066400000000000000000000011061513125663600177570ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "common", srcs = [ "clonefile_darwin.go", "clonefile_stub.go", "copy.go", "file.go", ], importpath = "github.com/bazel-contrib/bazel-lib/tools/common", visibility = ["//visibility:public"], deps = select({ "@io_bazel_rules_go//go/platform:darwin": [ "@org_golang_x_sys//unix", ], "@io_bazel_rules_go//go/platform:ios": [ "@org_golang_x_sys//unix", ], "//conditions:default": [], }), ) bazel-lib-2.22.5/tools/common/clonefile_darwin.go000066400000000000000000000005631513125663600217420ustar00rootroot00000000000000//go:build darwin package common import ( "os" "golang.org/x/sys/unix" ) // https://keith.github.io/xcode-man-pages/clonefile.2.html func cloneFile(src, dst string) (supported bool, err error) { supported = true if err = unix.Clonefile(src, dst, 0); err != nil { err = &os.LinkError{ Op: "clonefile", Old: src, New: dst, Err: err, } } return } bazel-lib-2.22.5/tools/common/clonefile_stub.go000066400000000000000000000002121513125663600214220ustar00rootroot00000000000000//go:build !darwin package common func cloneFile(src, dst string) (supported bool, err error) { supported = false err = nil return } bazel-lib-2.22.5/tools/common/copy.go000066400000000000000000000045671513125663600174200ustar00rootroot00000000000000package common import ( "fmt" "io" "io/fs" "log" "os" "sync" "time" ) // From https://opensource.com/article/18/6/copying-files-go func CopyFile(src string, dst string) error { source, err := os.Open(src) if err != nil { return err } defer source.Close() destination, err := os.Create(dst) if err != nil { return err } defer destination.Close() _, err = io.Copy(destination, source) return err } func Copy(opts CopyOpts) { if !opts.srcInfo.Mode().IsRegular() { log.Fatalf("%s is not a regular file", opts.src) } opModifier := "" const fallback = " (fallback)" if opts.hardlink { // hardlink this file if opts.verbose { fmt.Printf("hardlink%s %v => %v\n", opModifier, opts.src, opts.dst) } err := os.Link(opts.src, opts.dst) if err != nil { if opts.verbose { fmt.Printf("hardlink failed: %v\n", err) opModifier = fallback } // fallback to clonefile or copy } else { return } } // clone this file if opts.verbose { fmt.Printf("clonefile%s %v => %v\n", opModifier, opts.src, opts.dst) } switch supported, err := cloneFile(opts.src, opts.dst); { case !supported: if opts.verbose { fmt.Print("clonefile skipped: not supported by platform\n") } // fallback to copy case supported && err == nil: return case supported && err != nil: if opts.verbose { fmt.Printf("clonefile failed: %v\n", err) opModifier = fallback } // fallback to copy } // copy this file if opts.verbose { fmt.Printf("copy%s %v => %v\n", opModifier, opts.src, opts.dst) } err := CopyFile(opts.src, opts.dst) if err != nil { log.Fatal(err) } if opts.preserveMTime { accessTime := time.Now() err := os.Chtimes(opts.dst, accessTime, opts.srcInfo.ModTime()) if err != nil { log.Fatal(err) } } } type CopyWorker struct { queue <-chan CopyOpts } func NewCopyWorker(queue <-chan CopyOpts) *CopyWorker { return &CopyWorker{queue: queue} } func (w *CopyWorker) Run(wg *sync.WaitGroup) { defer wg.Done() for opts := range w.queue { Copy(opts) } } type CopyOpts struct { src, dst string srcInfo fs.FileInfo hardlink bool verbose bool preserveMTime bool } func NewCopyOpts(src string, dst string, srcInfo fs.FileInfo, hardlink bool, verbose bool, preserveMTime bool) CopyOpts { return CopyOpts{src: src, dst: dst, srcInfo: srcInfo, hardlink: hardlink, verbose: verbose, preserveMTime: preserveMTime} } bazel-lib-2.22.5/tools/common/file.go000066400000000000000000000014531513125663600173540ustar00rootroot00000000000000package common import ( "os" "path" "path/filepath" ) // Same as filepath.Rel except that it normalizes result to forward slashes // slashes since filepath.Rel will convert to system slashes func FileRel(basepath, targpath string) (string, error) { r, err := filepath.Rel(basepath, targpath) if err != nil { return "", err } return filepath.ToSlash(r), nil } // github.com/yookoala/realpath has bugs on Windows; // this function assumes that the path passed in is a symlink func Realpath(p string) (string, error) { t, err := os.Readlink(p) if err != nil { return "", err } if !filepath.IsAbs(t) { t = path.Join(path.Dir(p), t) } info, err := os.Lstat(t) if err != nil { return "", err } if info.Mode()&os.ModeSymlink == os.ModeSymlink { return Realpath(t) } return t, nil } bazel-lib-2.22.5/tools/copy_directory/000077500000000000000000000000001513125663600176515ustar00rootroot00000000000000bazel-lib-2.22.5/tools/copy_directory/BUILD.bazel000066400000000000000000000006311513125663600215270ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") go_library( name = "copy_directory_lib", srcs = ["main.go"], importpath = "github.com/bazel-contrib/bazel-lib/tools/copy_directory", visibility = ["//visibility:public"], deps = ["//tools/common"], ) go_binary( name = "copy_directory", embed = [":copy_directory_lib"], visibility = ["//visibility:public"], ) bazel-lib-2.22.5/tools/copy_directory/main.go000066400000000000000000000052261513125663600211310ustar00rootroot00000000000000package main import ( "fmt" "io/fs" "log" "os" "path/filepath" "sync" "github.com/bazel-contrib/bazel-lib/tools/common" ) type pathSet map[string]bool var ( srcPaths = pathSet{} hardlink = false verbose = false preserveMTime = false ) type walker struct { queue chan<- common.CopyOpts } func (w *walker) copyDir(src string, dst string) error { // filepath.WalkDir walks the file tree rooted at root, calling fn for each file or directory in // the tree, including root. See https://pkg.go.dev/path/filepath#WalkDir for more info. return filepath.WalkDir(src, func(p string, dirEntry fs.DirEntry, err error) error { if err != nil { return err } r, err := common.FileRel(src, p) if err != nil { return err } d := filepath.Join(dst, r) if dirEntry.IsDir() { srcPaths[src] = true return os.MkdirAll(d, os.ModePerm) } info, err := dirEntry.Info() if err != nil { return err } if info.Mode()&os.ModeSymlink == os.ModeSymlink { // symlink to directories are intentionally never followed by filepath.Walk to avoid infinite recursion linkPath, err := common.Realpath(p) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("failed to get realpath of dangling symlink %s: %w", p, err) } return fmt.Errorf("failed to get realpath of %s: %w", p, err) } if srcPaths[linkPath] { // recursive symlink; silently ignore return nil } stat, err := os.Stat(linkPath) if err != nil { return fmt.Errorf("failed to stat file %s pointed to by symlink %s: %w", linkPath, p, err) } if stat.IsDir() { // symlink points to a directory return w.copyDir(linkPath, d) } else { // symlink points to a regular file w.queue <- common.NewCopyOpts(linkPath, d, stat, hardlink, verbose, preserveMTime) return nil } } // a regular file w.queue <- common.NewCopyOpts(p, d, info, hardlink, verbose, preserveMTime) return nil }) } func main() { args := os.Args[1:] if len(args) < 2 { fmt.Println("Usage: copy_directory src dst [--hardlink] [--verbose] [--preserve-mtime]") os.Exit(1) } src := args[0] dst := args[1] if len(args) > 2 { for _, a := range os.Args[2:] { if a == "--hardlink" { hardlink = true } else if a == "--verbose" { verbose = true } else if a == "--preserve-mtime" { preserveMTime = true } } } queue := make(chan common.CopyOpts, 100) var wg sync.WaitGroup const numWorkers = 10 wg.Add(numWorkers) for i := 0; i < numWorkers; i++ { go common.NewCopyWorker(queue).Run(&wg) } walker := &walker{queue} if err := walker.copyDir(src, dst); err != nil { log.Fatal(err) } close(queue) wg.Wait() } bazel-lib-2.22.5/tools/copy_to_directory/000077500000000000000000000000001513125663600203535ustar00rootroot00000000000000bazel-lib-2.22.5/tools/copy_to_directory/BUILD.bazel000066400000000000000000000010211513125663600222230ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") go_library( name = "copy_to_directory_lib", srcs = ["main.go"], importpath = "github.com/bazel-contrib/bazel-lib/tools/copy_to_directory", visibility = ["//visibility:public"], deps = [ "//tools/common", "@com_github_bmatcuk_doublestar_v4//:doublestar", "@org_golang_x_exp//maps", ], ) go_binary( name = "copy_to_directory", embed = [":copy_to_directory_lib"], visibility = ["//visibility:public"], ) bazel-lib-2.22.5/tools/copy_to_directory/main.go000066400000000000000000000264411513125663600216350ustar00rootroot00000000000000package main import ( "encoding/json" "fmt" "io" "io/fs" "log" "os" "path" "path/filepath" "strings" "sync" "github.com/bazel-contrib/bazel-lib/tools/common" "github.com/bmatcuk/doublestar/v4" "golang.org/x/exp/maps" ) type fileInfo struct { Package string `json:"package"` Path string `json:"path"` RootPath string `json:"root_path"` ShortPath string `json:"short_path"` Workspace string `json:"workspace"` WorkspacePath string `json:"workspace_path"` Hardlink bool `json:"hardlink"` FileInfo fs.FileInfo } type config struct { AllowOverwrites bool `json:"allow_overwrites"` Dst string `json:"dst"` ExcludeSrcsPackages []string `json:"exclude_srcs_packages"` ExcludeSrcsPatterns []string `json:"exclude_srcs_patterns"` Files []fileInfo `json:"files"` IncludeExternalRepositories []string `json:"include_external_repositories"` IncludeSrcsPackages []string `json:"include_srcs_packages"` IncludeSrcsPatterns []string `json:"include_srcs_patterns"` ReplacePrefixes map[string]string `json:"replace_prefixes"` RootPaths []string `json:"root_paths"` PreserveMTime bool `json:"preserve_mtime"` Verbose bool `json:"verbose"` ReplacePrefixesKeys []string TargetWorkspace *string } type ( copyMap map[string]fileInfo pathSet map[string]bool ) var ( copySet = copyMap{} mkdirSet = pathSet{} ) func parseConfig(configPath string, wkspName *string) (*config, error) { f, err := os.Open(configPath) if err != nil { return nil, fmt.Errorf("failed to open config file: %w", err) } defer f.Close() byteValue, err := io.ReadAll(f) if err != nil { return nil, fmt.Errorf("failed to read config file: %w", err) } var cfg config if err := json.Unmarshal([]byte(byteValue), &cfg); err != nil { return nil, fmt.Errorf("failed to parse config file: %w", err) } cfg.ReplacePrefixesKeys = maps.Keys(cfg.ReplacePrefixes) cfg.TargetWorkspace = wkspName return &cfg, nil } func anyGlobsMatch(globs []string, test string) (bool, error) { for _, g := range globs { match, err := doublestar.Match(g, test) if err != nil { return false, err } if match { return true, nil } } return false, nil } func longestGlobsMatch(globs []string, test string) (string, int, error) { result := "" index := 0 for i, g := range globs { match, err := longestGlobMatch(g, test) if err != nil { return "", 0, err } if len(match) > len(result) { result = match index = i } } return result, index, nil } func longestGlobMatch(g string, test string) (string, error) { for i := 0; i < len(test); i++ { t := test[:len(test)-i] match, err := doublestar.Match(g, t) if err != nil { return "", err } if match { return t, nil } } return "", nil } type walker struct { queue chan<- common.CopyOpts } func (w *walker) copyDir(cfg *config, srcPaths pathSet, file fileInfo) error { if srcPaths == nil { srcPaths = pathSet{} } srcPaths[file.Path] = true // filepath.WalkDir walks the file tree rooted at root, calling fn for each file or directory in // the tree, including root. See https://pkg.go.dev/path/filepath#WalkDir for more info. walkPath := file.Path return filepath.WalkDir(walkPath, func(p string, dirEntry fs.DirEntry, err error) error { if err != nil { return err } if dirEntry.IsDir() { // remember that this directory was visited to prevent infinite recursive symlink loops and // then short-circuit by returning nil since filepath.Walk will visit files contained within // this directory automatically srcPaths[p] = true return nil } info, err := dirEntry.Info() if err != nil { return err } r, err := common.FileRel(walkPath, p) if err != nil { return err } f := fileInfo{ Package: file.Package, Path: p, RootPath: file.RootPath, ShortPath: path.Join(file.ShortPath, r), Workspace: file.Workspace, WorkspacePath: path.Join(file.WorkspacePath, r), Hardlink: file.Hardlink, FileInfo: info, } outputPath, err := w.calculateOutputPath(cfg, f) if err != nil { return fmt.Errorf("failed to calculate output path for %s: %w", file.WorkspacePath, err) } if outputPath == "" { // this path is excluded return nil } // if file is a symlink, resolve its realpath if info.Mode()&os.ModeSymlink == os.ModeSymlink { realpath, err := common.Realpath(p) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("failed to get realpath of dangling symlink %s: %w", p, err) } return fmt.Errorf("failed to get realpath of %s: %w", p, err) } if srcPaths[realpath] { // recursive symlink; silently ignore return nil } stat, err := os.Stat(realpath) if err != nil { return fmt.Errorf("failed to stat file %s pointed to by symlink %s: %w", realpath, p, err) } f.Path = realpath f.FileInfo = stat if stat.IsDir() { // symlink points to a directory return w.copyDir(cfg, srcPaths, f) } } return w.copyPath(cfg, f, outputPath) }) } func (w *walker) calculateOutputPath(cfg *config, file fileInfo) (string, error) { // Apply filters and transformations in the following order: // // - `include_external_repositories` // - `include_srcs_packages` // - `exclude_srcs_packages` // - `root_paths` // - `include_srcs_patterns` // - `exclude_srcs_patterns` // - `replace_prefixes` // // If you change this order please update the docstrings in the copy_to_directory rule. outputPath := file.WorkspacePath outputRoot := path.Dir(outputPath) // apply include_external_repositories (if the file is from an external repository) // automatically include files from the same workspace as this target, even if // that is an external workspace with respect to `__main__` if file.Workspace != "" && (cfg.TargetWorkspace == nil || file.Workspace != *cfg.TargetWorkspace) { match, err := anyGlobsMatch(cfg.IncludeExternalRepositories, file.Workspace) if err != nil { return "", err } if !match { return "", nil // external workspace is not included } } // apply include_srcs_packages match, err := anyGlobsMatch(cfg.IncludeSrcsPackages, file.Package) if err != nil { return "", err } if !match { return "", nil // package is not included } // apply exclude_srcs_packages match, err = anyGlobsMatch(cfg.ExcludeSrcsPackages, file.Package) if err != nil { return "", err } if match { return "", nil // package is excluded } // apply root_paths rootPathMatch, _, err := longestGlobsMatch(cfg.RootPaths, outputRoot) if err != nil { return "", err } if rootPathMatch != "" { outputPath = strings.TrimPrefix(outputPath[len(rootPathMatch):], "/") } // apply include_srcs_patterns match, err = anyGlobsMatch(cfg.IncludeSrcsPatterns, outputPath) if err != nil { return "", err } if !match { return "", nil // outputPath is not included } // apply exclude_srcs_patterns match, err = anyGlobsMatch(cfg.ExcludeSrcsPatterns, outputPath) if err != nil { return "", err } if match { return "", nil // outputPath is excluded } // apply replace_prefixes replacePrefixMatch, replacePrefixIndex, err := longestGlobsMatch(cfg.ReplacePrefixesKeys, outputPath) if err != nil { return "", err } if replacePrefixMatch != "" { replaceWith := cfg.ReplacePrefixes[cfg.ReplacePrefixesKeys[replacePrefixIndex]] outputPath = replaceWith + outputPath[len(replacePrefixMatch):] } return path.Join(cfg.Dst, outputPath), nil } func (w *walker) copyPath(cfg *config, file fileInfo, outputPath string) error { // add this file to the copy Paths dup, exists := copySet[outputPath] if exists { if dup.ShortPath == file.ShortPath && file.FileInfo.Size() == dup.FileInfo.Size() { // this is likely the same file listed twice: the original in the source tree and the copy in the output tree return nil } else if !cfg.AllowOverwrites { return fmt.Errorf("duplicate output file '%s' configured from source files '%s' and '%s'; set 'allow_overwrites' to True to allow this overwrites but keep in mind that order matters when this is set", outputPath, dup.Path, file.Path) } } copySet[outputPath] = file outputDir := path.Dir(outputPath) if !mkdirSet[outputDir] { if err := os.MkdirAll(outputDir, os.ModePerm); err != nil { return err } // https://pkg.go.dev/path#Dir for len(outputDir) > 0 && outputDir != "/" && outputDir != "." { mkdirSet[outputDir] = true outputDir = path.Dir(outputDir) } } if !cfg.AllowOverwrites { // if we don't allow overwrites then we can start copying as soon as a copy is calculated w.queue <- common.NewCopyOpts(file.Path, outputPath, file.FileInfo, file.Hardlink, cfg.Verbose, cfg.PreserveMTime) } return nil } func (w *walker) copyPaths(cfg *config) error { for _, file := range cfg.Files { info, err := os.Lstat(file.Path) if err != nil { return fmt.Errorf("failed to lstat file %s: %w", file.Path, err) } file.FileInfo = info // if file is a directory, then short-circuit without calculating the output path if file.FileInfo.IsDir() { if err := w.copyDir(cfg, nil, file); err != nil { return err } continue } outputPath, err := w.calculateOutputPath(cfg, file) if err != nil { return fmt.Errorf("failed to calculate output path for %s: %w", file.WorkspacePath, err) } if outputPath == "" { // this path is excluded continue } // if file is a symlink, resolve its realpath if info.Mode()&os.ModeSymlink == os.ModeSymlink { realpath, err := common.Realpath(file.Path) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("failed to get realpath of dangling symlink %s: %w", file.Path, err) } return fmt.Errorf("failed to get realpath of %s: %w", file.Path, err) } stat, err := os.Stat(realpath) if err != nil { return fmt.Errorf("failed to stat file %s pointed to by symlink %s: %w", realpath, file.Path, err) } file.Path = realpath file.FileInfo = stat if file.FileInfo.IsDir() { // symlink points to a directory if err := w.copyDir(cfg, nil, file); err != nil { return err } continue } } if err := w.copyPath(cfg, file, outputPath); err != nil { return err } } return nil } func main() { args := os.Args[1:] if len(args) != 1 && len(args) != 2 { fmt.Println("Usage: copy_to_directory config_file [workspace_name]") os.Exit(1) } configFile := args[0] // Read workspace arg if present. var wksp *string = nil if len(args) >= 2 { wksp = &args[1] } cfg, err := parseConfig(configFile, wksp) if err != nil { log.Fatal(err) } queue := make(chan common.CopyOpts, 100) var wg sync.WaitGroup const numWorkers = 10 wg.Add(numWorkers) for i := 0; i < numWorkers; i++ { go common.NewCopyWorker(queue).Run(&wg) } walker := &walker{queue} if err = walker.copyPaths(cfg); err != nil { log.Fatal(err) } if cfg.AllowOverwrites { // if we allow overwrites then we must wait until all copy paths are calculated before starting // any copy operations for outputPath, file := range copySet { queue <- common.NewCopyOpts(file.Path, outputPath, file.FileInfo, file.Hardlink, cfg.Verbose, cfg.PreserveMTime) } } close(queue) wg.Wait() } bazel-lib-2.22.5/tools/coreutils_mirror_release.sh000077500000000000000000000036611513125663600222630ustar00rootroot00000000000000#!/usr/bin/env bash set -o errexit -o nounset -o pipefail JQ_FILTER='map({ "key": .tag_name, "value": .assets | map(select( (.name | startswith("coreutils-")) and ((.name | endswith(".tar.gz")) or (.name | endswith(".zip"))) and (.name | contains("i686") | not) and ( ( (.name | contains("windows")) and (.name | contains("gnu") | not) ) or ( .name | contains("musl") ) or ( .name | contains("darwin") ) ) )) | map({ key: .name | ltrimstr("coreutils-") | rtrimstr(".tar.gz") | rtrimstr(".zip") | sub("-pc"; "") | sub("-apple"; "") | sub("-unknown"; "") | sub("x86_64"; "amd64") | sub("aarch64"; "arm64") | gsub("\\d+.\\d+.\\d+-"; "") | rtrimstr("-msvc") | rtrimstr("-musl") | split("-") | reverse | join("_"), value: { filename: .name, sha256: "sha256-", } }) | from_entries }) | from_entries ' INFO="$(curl --silent -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/uutils/coreutils/releases?per_page=1 | jq "$JQ_FILTER")" for VERSION in $(jq -r 'keys | join("\n")' <<<$INFO); do for PLATFORM in $(jq -r ".[\"$VERSION\"] | keys | join(\"\n\")" <<<$INFO); do FILENAME=$(jq -r ".[\"$VERSION\"][\"$PLATFORM\"].filename" <<<$INFO) SHA256=$(curl -fLs "https://github.com/uutils/coreutils/releases/download/$VERSION/$FILENAME" | sha256sum | xxd -r -p | base64) INFO=$(jq ".[\"$VERSION\"][\"$PLATFORM\"].sha256 = \"sha256-$SHA256\"" <<<$INFO) done done echo -n "COREUTILS_VERSIONS = " echo $INFO | jq -M echo "" echo "Copy the version info into lib/private/coreutils_toolchain.bzl" bazel-lib-2.22.5/tools/expand_template/000077500000000000000000000000001513125663600177655ustar00rootroot00000000000000bazel-lib-2.22.5/tools/expand_template/BUILD.bazel000066400000000000000000000006461513125663600216510ustar00rootroot00000000000000load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") go_library( name = "expand_template_lib", srcs = ["main.go"], importpath = "github.com/bazel-contrib/bazel-lib/tools/expand_template", visibility = ["//visibility:public"], deps = ["@org_golang_x_exp//maps"], ) go_binary( name = "expand_template", embed = [":expand_template_lib"], visibility = ["//visibility:public"], ) bazel-lib-2.22.5/tools/expand_template/main.go000066400000000000000000000043701513125663600212440ustar00rootroot00000000000000package main import ( "encoding/json" "fmt" "log" "os" "regexp" "strings" "golang.org/x/exp/maps" ) func main() { args := os.Args[1:] if len(args) != 6 { fmt.Println("Usage: expand_template