instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
timestamp[ns] | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bazelbuild/bazel/14273_14313 | bazelbuild/bazel | bazelbuild/bazel/14273 | bazelbuild/bazel/14313 | [
"keyword_pr_to_issue"
] | cea5f4f499aa832cf90c68898671869ce79d63f2 | e53ae63c04a7158b78da19bc76ede57a8cc31673 | [
"A simpler workaround than setting `linkopts` as a parameter to `cc_binary` is set the `BAZEL_LINKOPTS` environment variable to `-lc++`:\r\n```shell\r\nnoa@Noas-MacBook-Air stage1 % BAZEL_LINKOPTS=-lc++ bazelisk build //main:hello-world\r\nINFO: Analyzed target //main:hello-world (0 packages loaded, 0 targets configured).\r\nINFO: Found 1 target...\r\nTarget //main:hello-world up-to-date:\r\n bazel-bin/main/hello-world\r\nINFO: Elapsed time: 0.078s, Critical Path: 0.00s\r\nINFO: 1 process: 1 internal.\r\nINFO: Build completed successfully, 1 total action\r\n% ./bazel-bin/main/hello-world\r\nHello world\r\nSun Nov 14 20:22:54 2021\r\n```",
"The `local_config_cc/BUILD` that gets generated on macOS 12 will use the `unix_cc_toolchain_config.bzl` which will silently drop any `link_libs` being passed to the cc_toolchain_config on systems that has `target_libc == \"macosx\"`.\r\n\r\nAs I don't have access to a macOS 11 Big Sur, it is a bit unclear what has changed, but it seems like a good idea to me to have the `user_link_flags_feature` be added to the features list being declared towards the end of `_impl()` in `unix_cc_toolchain_config.bzl` regardless of whether is_linux (i.e. target_libc != \"macosx\") is true or not. The consequence of user_link_flags_feature being added is that the values in the link_libs parameter list gets added to the command line arguments of the linker, which seems to me like the right thing to do.",
"On macOS, Bazel should be using `tools/cpp/osx_cc_configure.bzl` to configure the local C++ toolchain, so the problem is more likely that Bazel is picking the wrong file when building on Monterey.",
"Thanks for the fix, we should cherry-pick it for 5.0. \r\nPlease send a PR to branch https://github.com/bazelbuild/bazel/tree/release-5.0.0rc2 after https://github.com/bazelbuild/bazel/pull/14275 is merged. ",
"@meteorcloudy Can this get into a 4.2.2 as well? I believe it qualifies as OS support.",
"@meteorcloudy I cherry-picked the commit that landed to master and opened a PR to land it in `release-5.0.0rc2` https://github.com/bazelbuild/bazel/pull/14313 Please have a look.",
"@brentleyjones I agree that it looks bad that all released bazel versions fails to compile the example cpp hello world in the current stable macOS release that has been out for almost a month.\r\n\r\nOne aspect that makes macOS boxes with just the developer tools so common is that as soon as a developer types for example 'git' in a Terminal window, a popup will suggest installing the developer tools. ",
"@nresare can you submit the 4.x PR as well? Not sure if they'll accept it but it should be the exact same as the others",
"@nresare Thanks, merged!",
"Also cherry-picking this for 4.2.2"
] | [] | "2021-11-23T20:16:04Z" | [
"type: bug",
"team-Rules-CPP",
"untriaged"
] | C++ rules broken on macOS 12 Monterey and command line developer tools | ### Description of the problem / feature request:
There are mainly two ways to install the basic apple provided clang compiler toolchain on macOS. Either you install the Command Line developer tools by invoking `xcode-select --install`, or you install the full XCode development environment, which includes a graphical IDE and tooling for application development on all of Apple's operating systems. The latter is a significantly larger download at >10GiB.
Bazel 4.2.1 will detect and use the C++ compiler and linker that is available through the command line tools, but as of macOS 12 Monterey, attempting to build C++ binaries will succeed but the resulting binaries will fail on startup with a Segmentation Fault error. This is because the linker invocation generating the binary is not invoked with the -lc++ flag, indicating that the libc++ library should be loaded by the dynamic linker on startup.
The [suggested solution](https://github.com/bazelbuild/bazel/issues/14206#issuecomment-957356014) to this problem is to install the full XCode IDE, which apparently works around this problem, but it would be neat to have this work out-of-the-box
### Feature requests: what underlying problem are you trying to solve with this feature?
Make bazel more user friendly by having it build functional c++ binaries without non-obvious workarounds such as installing XCode on a pretty standard setup on one of the more common platforms.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. On a vanilla macOS 12 Monterey machine, install the command line devloper tools with `xcode-select --install`
2. download the latest stable bazel (I ran bazelisk that pulled bazel 4.2.1)
3. Clone the [bazelbuild/examples](https://github.com/bazelbuild/examples) repository
4. and build the [hello world example](https://github.com/bazelbuild/examples/tree/main/cpp-tutorial/stage1):
4.1 `cd cpp-tutorial/stage1`
4.2 `bazelisk build //main:hello-world`
5. Attempt to execute the resulting binary: `./bazel-bin/main/hello-world`
```shell
% ./bazel-bin/main/hello-world
zsh: segmentation fault ./bazel-bin/main/hello-world
```
### What operating system are you running Bazel on?
I have reproduce this with macOS 12.0.1 Monterey on an Apple Silicon M1 MacBook as well as an Intel MacBook Pro.
```shell
% gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.9)
```
### What's the output of `bazel info release`?
```shell
% bazelisk info release
release 4.2.1
```
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
```shell
% git remote get-url origin ; git rev-parse main ; git rev-parse HEAD
https://github.com/bazelbuild/examples
67b1ee057fb532c8e7f15e202c0d8ccef4b507b9
67b1ee057fb532c8e7f15e202c0d8ccef4b507b9
```
### Have you found anything relevant by searching the web?
There are a few github issues describing issues building bazel with bazel on macOS Monterey, and problems with segfaulting binaries, but they seem to be closed with the recommendation to install XCode, which seems to me like a workaround.
### Any other information, logs, or outputs that you want to share?
Running `bazel build --subcommands` reveals that the required linker flag `-lc++` is missing from the linker invocation. Adding `linkopts = ["-lc++"],` to the `cc_binary` rule will work around this problem. | [
"tools/cpp/unix_cc_toolchain_config.bzl"
] | [
"tools/cpp/unix_cc_toolchain_config.bzl"
] | [] | diff --git a/tools/cpp/unix_cc_toolchain_config.bzl b/tools/cpp/unix_cc_toolchain_config.bzl
index 1d4ee950d04980..26119141059c1f 100644
--- a/tools/cpp/unix_cc_toolchain_config.bzl
+++ b/tools/cpp/unix_cc_toolchain_config.bzl
@@ -1243,6 +1243,7 @@ def _impl(ctx):
coverage_feature,
default_compile_flags_feature,
default_link_flags_feature,
+ user_link_flags_feature,
fdo_optimize_feature,
supports_dynamic_linker_feature,
dbg_feature,
| null | train | val | 2021-11-19T15:11:10 | "2021-11-14T19:31:46Z" | nresare | test |
bazelbuild/bazel/14273_14319 | bazelbuild/bazel | bazelbuild/bazel/14273 | bazelbuild/bazel/14319 | [
"keyword_pr_to_issue"
] | 02ad3e3bc6970db11fe80f966da5707a6c389fdd | 039c72e5e25a426cbf45c582bf325dcd112af4bd | [
"A simpler workaround than setting `linkopts` as a parameter to `cc_binary` is set the `BAZEL_LINKOPTS` environment variable to `-lc++`:\r\n```shell\r\nnoa@Noas-MacBook-Air stage1 % BAZEL_LINKOPTS=-lc++ bazelisk build //main:hello-world\r\nINFO: Analyzed target //main:hello-world (0 packages loaded, 0 targets configured).\r\nINFO: Found 1 target...\r\nTarget //main:hello-world up-to-date:\r\n bazel-bin/main/hello-world\r\nINFO: Elapsed time: 0.078s, Critical Path: 0.00s\r\nINFO: 1 process: 1 internal.\r\nINFO: Build completed successfully, 1 total action\r\n% ./bazel-bin/main/hello-world\r\nHello world\r\nSun Nov 14 20:22:54 2021\r\n```",
"The `local_config_cc/BUILD` that gets generated on macOS 12 will use the `unix_cc_toolchain_config.bzl` which will silently drop any `link_libs` being passed to the cc_toolchain_config on systems that has `target_libc == \"macosx\"`.\r\n\r\nAs I don't have access to a macOS 11 Big Sur, it is a bit unclear what has changed, but it seems like a good idea to me to have the `user_link_flags_feature` be added to the features list being declared towards the end of `_impl()` in `unix_cc_toolchain_config.bzl` regardless of whether is_linux (i.e. target_libc != \"macosx\") is true or not. The consequence of user_link_flags_feature being added is that the values in the link_libs parameter list gets added to the command line arguments of the linker, which seems to me like the right thing to do.",
"On macOS, Bazel should be using `tools/cpp/osx_cc_configure.bzl` to configure the local C++ toolchain, so the problem is more likely that Bazel is picking the wrong file when building on Monterey.",
"Thanks for the fix, we should cherry-pick it for 5.0. \r\nPlease send a PR to branch https://github.com/bazelbuild/bazel/tree/release-5.0.0rc2 after https://github.com/bazelbuild/bazel/pull/14275 is merged. ",
"@meteorcloudy Can this get into a 4.2.2 as well? I believe it qualifies as OS support.",
"@meteorcloudy I cherry-picked the commit that landed to master and opened a PR to land it in `release-5.0.0rc2` https://github.com/bazelbuild/bazel/pull/14313 Please have a look.",
"@brentleyjones I agree that it looks bad that all released bazel versions fails to compile the example cpp hello world in the current stable macOS release that has been out for almost a month.\r\n\r\nOne aspect that makes macOS boxes with just the developer tools so common is that as soon as a developer types for example 'git' in a Terminal window, a popup will suggest installing the developer tools. ",
"@nresare can you submit the 4.x PR as well? Not sure if they'll accept it but it should be the exact same as the others",
"@nresare Thanks, merged!",
"Also cherry-picking this for 4.2.2"
] | [] | "2021-11-24T11:40:27Z" | [
"type: bug",
"team-Rules-CPP",
"untriaged"
] | C++ rules broken on macOS 12 Monterey and command line developer tools | ### Description of the problem / feature request:
There are mainly two ways to install the basic apple provided clang compiler toolchain on macOS. Either you install the Command Line developer tools by invoking `xcode-select --install`, or you install the full XCode development environment, which includes a graphical IDE and tooling for application development on all of Apple's operating systems. The latter is a significantly larger download at >10GiB.
Bazel 4.2.1 will detect and use the C++ compiler and linker that is available through the command line tools, but as of macOS 12 Monterey, attempting to build C++ binaries will succeed but the resulting binaries will fail on startup with a Segmentation Fault error. This is because the linker invocation generating the binary is not invoked with the -lc++ flag, indicating that the libc++ library should be loaded by the dynamic linker on startup.
The [suggested solution](https://github.com/bazelbuild/bazel/issues/14206#issuecomment-957356014) to this problem is to install the full XCode IDE, which apparently works around this problem, but it would be neat to have this work out-of-the-box
### Feature requests: what underlying problem are you trying to solve with this feature?
Make bazel more user friendly by having it build functional c++ binaries without non-obvious workarounds such as installing XCode on a pretty standard setup on one of the more common platforms.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. On a vanilla macOS 12 Monterey machine, install the command line devloper tools with `xcode-select --install`
2. download the latest stable bazel (I ran bazelisk that pulled bazel 4.2.1)
3. Clone the [bazelbuild/examples](https://github.com/bazelbuild/examples) repository
4. and build the [hello world example](https://github.com/bazelbuild/examples/tree/main/cpp-tutorial/stage1):
4.1 `cd cpp-tutorial/stage1`
4.2 `bazelisk build //main:hello-world`
5. Attempt to execute the resulting binary: `./bazel-bin/main/hello-world`
```shell
% ./bazel-bin/main/hello-world
zsh: segmentation fault ./bazel-bin/main/hello-world
```
### What operating system are you running Bazel on?
I have reproduce this with macOS 12.0.1 Monterey on an Apple Silicon M1 MacBook as well as an Intel MacBook Pro.
```shell
% gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.9)
```
### What's the output of `bazel info release`?
```shell
% bazelisk info release
release 4.2.1
```
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
```shell
% git remote get-url origin ; git rev-parse main ; git rev-parse HEAD
https://github.com/bazelbuild/examples
67b1ee057fb532c8e7f15e202c0d8ccef4b507b9
67b1ee057fb532c8e7f15e202c0d8ccef4b507b9
```
### Have you found anything relevant by searching the web?
There are a few github issues describing issues building bazel with bazel on macOS Monterey, and problems with segfaulting binaries, but they seem to be closed with the recommendation to install XCode, which seems to me like a workaround.
### Any other information, logs, or outputs that you want to share?
Running `bazel build --subcommands` reveals that the required linker flag `-lc++` is missing from the linker invocation. Adding `linkopts = ["-lc++"],` to the `cc_binary` rule will work around this problem. | [
"tools/cpp/unix_cc_toolchain_config.bzl"
] | [
"tools/cpp/unix_cc_toolchain_config.bzl"
] | [] | diff --git a/tools/cpp/unix_cc_toolchain_config.bzl b/tools/cpp/unix_cc_toolchain_config.bzl
index 5dbaa86ab2ac0b..d44b7922265950 100644
--- a/tools/cpp/unix_cc_toolchain_config.bzl
+++ b/tools/cpp/unix_cc_toolchain_config.bzl
@@ -1216,6 +1216,7 @@ def _impl(ctx):
coverage_feature,
default_compile_flags_feature,
default_link_flags_feature,
+ user_link_flags_feature,
fdo_optimize_feature,
supports_dynamic_linker_feature,
dbg_feature,
| null | test | val | 2021-08-30T15:37:00 | "2021-11-14T19:31:46Z" | nresare | test |
bazelbuild/bazel/13985_14325 | bazelbuild/bazel | bazelbuild/bazel/13985 | bazelbuild/bazel/14325 | [
"keyword_pr_to_issue"
] | af74287f125b93119415ba35429b8638d7a986ea | 748138f3d993d6ac3a1e2357865b4c7737629289 | [
"This issue also exists in the latest rolling release.",
"cc @coeuvre \r\n\r\nAlso seeing this after upgrading to 4.2.1 from 4.0.0. These are the changes that have gone in since the 4.1.0 release:\r\n```\r\n$ git log HEAD ^4.1.0 --oneline src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\nbf5e2b8ec0 Remote: Async upload (Part 8)\r\nb51b31dbe7 Remote: Fix a race when reporting action progresses.\r\n0f812eb5e5 Remote: Display download progress when actions are downloading outputs from remote cache.\r\nf0983dfddb Remote: Report checking cache status before the action is scheduled to run remotely.\r\n```\r\n\r\nIt looks like there was an attempt at fixing the UI bug in `b51b31dbe7`.\r\n\r\nBy adding the below patch you can reproduce this issue:\r\n```\r\nid 'File:[[<execution_root>]bazel-out/k8-opt/.../foo' is already finished, and event Downloading foo, 5.2 KiB / 5.2 KiB is being processed\r\n...\r\n```\r\n\r\nThe problem seems to be like @DavidANeil mentioned -- `actionProgress(ActionProgressEvent event)` is probably called in ThreadA before `actionCompletion(ActionCompletionEvent event)` in ThreadB but the ThreadA goes to sleep and when it revives it calls `getActionState()` which calls `activeActions.computeIfAbsent()` which re-adds the actions that was just removed by ThreadB. The other possibility is events are being fired out-of-order.\r\n\r\nI wonder if the right fix is for `UiEventHandler` to queue and only fire 1 in-progress event per actionId and wait for each event completion before firing the next. Presumably `computeIfAbsent` is being used because of this exact problem -- events can be processed out-of-order so `actionStarted()` cannot be assumed to have already ran & created an action in `activeActions`.\r\n\r\nPatch:\r\n```\r\n$ git diff\r\ndiff --git a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\nindex eef7ea5c64..99ae5e36d2 100644\r\n--- a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\n+++ b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\n@@ -361,6 +361,8 @@ final class UiStateTracker {\r\n \r\n private final Map<Artifact, ActionState> activeActions;\r\n \r\n+ private final Map<Artifact, Boolean> finishedActions;\r\n+\r\n // running downloads are identified by the original URL they were trying to access.\r\n private final Deque<String> runningDownloads;\r\n private final Map<String, Long> downloadNanoStartTimes;\r\n@@ -396,6 +398,7 @@ final class UiStateTracker {\r\n \r\n UiStateTracker(Clock clock, int targetWidth) {\r\n this.activeActions = new ConcurrentHashMap<>();\r\n+ this.finishedActions = new ConcurrentHashMap<>();\r\n \r\n this.actionsCompleted = new AtomicInteger();\r\n this.testActions = new ConcurrentHashMap<>();\r\n@@ -582,6 +585,9 @@ final class UiStateTracker {\r\n ActionExecutionMetadata action = event.action();\r\n Artifact actionId = event.action().getPrimaryOutput();\r\n long now = clock.nanoTime();\r\n+ if (finishedActions.containsKey(actionId)) {\r\n+ System.out.println(String.format(\"id '%s' is already finished, and event %s is being processed\", actionId, event.progress()));\r\n+ }\r\n getActionState(action, actionId, now).onProgressEvent(event, now);\r\n }\r\n \r\n@@ -589,6 +595,7 @@ final class UiStateTracker {\r\n Action action = event.getAction();\r\n Artifact actionId = action.getPrimaryOutput();\r\n checkNotNull(activeActions.remove(actionId), \"%s not active after %s\", actionId, event);\r\n+ finishedActions.put(actionId, true);\r\n \r\n // As callers to the experimental state tracker assume we will fully report the new state once\r\n // informed of an action completion, we need to make sure the progress receiver is aware of the\r\n@@ -604,6 +611,7 @@ final class UiStateTracker {\r\n Artifact actionId = action.getPrimaryOutput();\r\n \r\n checkNotNull(activeActions.remove(actionId), \"%s not active after %s\", actionId, event);\r\n+ finishedActions.put(actionId, true);\r\n \r\n if (action.getOwner() != null) {\r\n Label owner = action.getOwner().getLabel();\r\n```",
"Also for anyone who OK with compiling bazel from source and applying a patch (patch based off `4.2.1`), this fixes it for me:\r\n```\r\n$ git diff\r\ndiff --git a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\nindex eef7ea5c64..9e5570e8a7 100644\r\n--- a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\n+++ b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java\r\n@@ -526,6 +526,11 @@ final class UiStateTracker {\r\n return activeActions.computeIfAbsent(actionId, (key) -> new ActionState(action, nanoTimeNow));\r\n }\r\n \r\n+ @Nullable\r\n+ private ActionState getActionStateIfPresent(Artifact actionId) {\r\n+ return activeActions.get(actionId);\r\n+ }\r\n+\r\n void actionStarted(ActionStartedEvent event) {\r\n Action action = event.getAction();\r\n Artifact actionId = action.getPrimaryOutput();\r\n@@ -582,7 +587,10 @@ final class UiStateTracker {\r\n ActionExecutionMetadata action = event.action();\r\n Artifact actionId = event.action().getPrimaryOutput();\r\n long now = clock.nanoTime();\r\n- getActionState(action, actionId, now).onProgressEvent(event, now);\r\n+ ActionState actionState = getActionStateIfPresent(actionId);\r\n+ if (actionState != null) {\r\n+ actionState.onProgressEvent(event, now);\r\n+ }\r\n }\r\n \r\n void actionCompletion(ActionScanningCompletedEvent event) {\r\n```",
"@bjacklyn Would you mind sending your patch as a pull request?"
] | [] | "2021-11-24T23:56:08Z" | [
"type: bug",
"P1",
"team-Remote-Exec"
] | Actions stuck in "active" and thus "[Prepa]" | ### Description of the problem:
The UiStateTracker sometimes reports actions in "Preparing" status (shortened to "[Prepa]") indefinitely.
Because this "stuck" action will be the longest running, it will often be the only displayed action (when `--curses=no`).
For example, here is what a sample CI run looks like:
```
[0 / 69] [Prepa] BazelWorkspaceStatusAction stable-status.txt
[15,599 / 17,556] 5 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 13s ... (296 actions, 90 running)
[26,933 / 50,441] 34 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 29s ... (344 actions, 268 running)
[55,044 / 92,565] 89 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 46s ... (438 actions, 275 running)
[57,666 / 93,495] 101 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 66s ... (546 actions, 312 running)
[58,588 / 93,662] 111 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 89s ... (577 actions, 323 running)
[58,915 / 93,691] 111 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 116s ... (577 actions, 324 running)
[59,156 / 93,935] 121 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 147s ... (572 actions, 321 running)
[59,582 / 94,344] 149 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 182s ... (577 actions, 323 running)
[60,425 / 95,053] 168 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 223s ... (578 actions, 325 running)
[61,058 / 95,161] 203 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 270s ... (577 actions, 323 running)
[62,440 / 96,339] 351 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 324s ... (577 actions, 324 running)
[63,079 / 96,913] 420 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 386s ... (578 actions, 324 running)
[64,779 / 114,781] 485 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 457s ... (581 actions, 326 running)
[65,352 / 115,200] 543 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 539s ... (579 actions, 323 running)
[68,085 / 115,383] 589 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 633s ... (581 actions, 323 running)
[76,800 / 115,433] 652 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 741s ... (571 actions, 305 running)
[95,197 / 115,457] 654 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 866s ... (404 actions, 137 running)
[116,032 / 116,315] 828 / 877 tests; [Prepa] Compiling TypeScript (prodmode) //ts/lib:lib; 1009s ... (162 actions, 102 running)
```
Which is just ... not useful.
Note that actual action execution is not affected by this. This is purely a visual bug.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
This bug appears to be caused by a race condition, so is not easily reproducible.
I reckon it is a case where an action is added to the `activeActions` map, then removed after it completes, then re-added by a call to `computeIfAbsent` being called in a racy manner.
### What operating system are you running Bazel on?
Linux 20.04
### What's the output of `bazel info release`?
release 4.2.0
I have not been able to reproduce this issue on 4.1.0
| [
"src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java"
] | [
"src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java"
] | [
"src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
index eef7ea5c64ae7c..99f9ce1e0fe69c 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
@@ -526,6 +526,11 @@ private ActionState getActionState(
return activeActions.computeIfAbsent(actionId, (key) -> new ActionState(action, nanoTimeNow));
}
+ @Nullable
+ private ActionState getActionStateIfPresent(Artifact actionId) {
+ return activeActions.get(actionId);
+ }
+
void actionStarted(ActionStartedEvent event) {
Action action = event.getAction();
Artifact actionId = action.getPrimaryOutput();
@@ -579,10 +584,12 @@ void runningAction(RunningActionEvent event) {
}
void actionProgress(ActionProgressEvent event) {
- ActionExecutionMetadata action = event.action();
Artifact actionId = event.action().getPrimaryOutput();
long now = clock.nanoTime();
- getActionState(action, actionId, now).onProgressEvent(event, now);
+ ActionState actionState = getActionStateIfPresent(actionId);
+ if (actionState != null) {
+ actionState.onProgressEvent(event, now);
+ }
}
void actionCompletion(ActionScanningCompletedEvent event) {
| diff --git a/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
index 197ac415e72114..47cf3cc4f50508 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
@@ -601,6 +601,7 @@ public void actionProgress_visible() throws Exception {
ManualClock clock = new ManualClock();
Action action = createDummyAction("Some random action");
UiStateTracker stateTracker = new UiStateTracker(clock, /* targetWidth= */ 70);
+ stateTracker.actionStarted(new ActionStartedEvent(action, clock.nanoTime()));
stateTracker.actionProgress(
ActionProgressEvent.create(action, "action-id", "action progress", false));
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
@@ -619,6 +620,7 @@ public void actionProgress_withTooSmallWidth_progressSkipped() throws Exception
ManualClock clock = new ManualClock();
Action action = createDummyAction("Some random action");
UiStateTracker stateTracker = new UiStateTracker(clock, /* targetWidth= */ 30);
+ stateTracker.actionStarted(new ActionStartedEvent(action, clock.nanoTime()));
stateTracker.actionProgress(
ActionProgressEvent.create(action, "action-id", "action progress", false));
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
@@ -637,6 +639,7 @@ public void actionProgress_withSmallWidth_progressShortened() throws Exception {
ManualClock clock = new ManualClock();
Action action = createDummyAction("Some random action");
UiStateTracker stateTracker = new UiStateTracker(clock, /* targetWidth= */ 50);
+ stateTracker.actionStarted(new ActionStartedEvent(action, clock.nanoTime()));
stateTracker.actionProgress(
ActionProgressEvent.create(action, "action-id", "action progress", false));
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
@@ -655,6 +658,7 @@ public void actionProgress_multipleProgress_displayInOrder() throws Exception {
ManualClock clock = new ManualClock();
Action action = createDummyAction("Some random action");
UiStateTracker stateTracker = new UiStateTracker(clock, /* targetWidth= */ 70);
+ stateTracker.actionStarted(new ActionStartedEvent(action, clock.nanoTime()));
stateTracker.actionProgress(
ActionProgressEvent.create(action, "action-id1", "action progress 1", false));
stateTracker.actionProgress(
| train | val | 2021-11-24T14:10:16 | "2021-09-13T18:02:46Z" | DavidANeil | test |
bazelbuild/bazel/14685_14835 | bazelbuild/bazel | bazelbuild/bazel/14685 | bazelbuild/bazel/14835 | [
"keyword_pr_to_issue"
] | af34c452c12dae8758340dc5c284cf30f3c80302 | 65904046031325c418734dfda994bdeff4134160 | [
"I've found the need for this as well, when trying to target x86_64 macOS RBE from arm64 macOS. Repository rules incorrectly provide arm64 binaries which fail to run on RBE.",
"Also see [rules_rust](https://github.com/bazelbuild/rules_rust/blob/14468f97b9a06ab6b33e94bc87c1d24b2433e5f8/crate_universe/private/util.bzl#L18).",
"This seems like a reasonable request. It shouldn't be too hard to add a field to `repository_os`, so if anyone wants to send a PR, it would be greatly appreciated.",
"I started working on this in #14738, but then noticed that this is more subtle than expected: The natural implementation would be to just return `System.getProperty(\"os.arch\").toLowerCase(Locale.ROOT)`, but that is just the architecture of the JDK Bazel is running on, which is not necessarily the same as the architecture of the operating system Bazel is running on. For example, which value should this have in the case of an x86_64 JDK executing Bazel using Rosetta on an aarch64/arm64 M1 Mac?\r\n\r\n@uhthomas @brentleyjones Could you clarify what exactly you would want to know the architecture of? You also referred to RBE, but I think that repository rules could only ever provide the _host_ CPU, not the _exec_ CPU (which isn't even known during the loading phase since it depends on the result of toolchain resolution). Is that sufficient for your use cases?",
"For a M1 mac running through Rosetta x86_64 is right IMO, since the emulation should affect everything. ",
"The intent of this issue is to solve the multi cpu/os repository problem where rule maintainers are forced to write odd hacks to detect the exec (host?) CPU. For example the Go rules declare a signal repository, `go_sdk`, which will automatically detect the correct SDK to use. The `go_download_sdk()` rule uses [uname](https://github.com/bazelbuild/rules_go/blob/fd11dd2768669dc2cc1f3a11f2b0b81d84e81c32/go/private/sdk.bzl#L253) to do this detection.\r\n\r\nIt's been suggested that multiple repositories for the corresponding cpu and os should be declared ([ref](https://github.com/bazelbuild/bazel/issues/11655#issuecomment-734212603)), but this can be really messy and weird.\r\n\r\n`select` does not work with repository rules and there is no clear guidance on how to actually do this, which is odd considering this is extremely common.\r\n\r\nThe M1 situation is a bit weird and I don't really know what the right answer is. I think it should depend on whether the architecture of the Bazel binary, as there is no other way to differentiate between native and rosetta at current.\r\n\r\nDoes what I've written make sense, and is it clear what the goal of this issue is?",
">Could you clarify what exactly you would want to know the architecture of? You also referred to RBE, but I think that repository rules could only ever provide the host CPU, not the exec CPU (which isn't even known during the loading phase since it depends on the result of toolchain resolution). Is that sufficient for your use cases?\r\n\r\nI would like the know the architecture of `--host_platform`. If I don't run Bazel through Rosetta, all repository rules will see arm64 on an M1 Mac, even if I set `--host_platform` to a platform with `x86_64` cpu.",
"The architecture of the Bazel binary, at least assuming it uses the shipped JDK, the default `cpu` constraint on the auto-detected host platform and the value of the `os.arch` Java system property are all the same as far as I know, so @uhthomas and @keith requests would be handled by my PR.\r\n\r\n@brentleyjones I understand your use case, but this seems difficult to do: Strictly speaking, the platform specified by `--host_platform` is an opaque collection of constraint values, which may theoretically not even contain one for the constraint setting `@platforms//cpu`. And even if we come up with logic for this (admittedly very special) case, I fear getting a constraint value of a platform identified by a label from the context of a repository rule is pretty difficult.",
"Awesome @fmeum, your PR looks great. Thanks for taking a look at this! :)\r\n\r\nIs there some reference which lists the possible values of `os.arch` and `os.name`?\r\n\r\nFor my own sanity also, are repository rules executed on the host platform, or the execution platform? More specifically, will the values of `os.arch` and `os.name` be of the host platform, or execution platform?",
"Additionally, how does this all fit into platforms? If at all. I think it might be strange to use the Platforms API in most cases, but the repository_os struct in others. What are your thoughts? ",
"> Is there some reference which lists the possible values of `os.arch` and `os.name`?\r\n\r\nThe two sources I usually refer to are the OpenJDK sources and Bazel's [CPU](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/util/CPU.java) and [OS](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/util/OS.java) classes.\r\n\r\n> For my own sanity also, are repository rules executed on the host platform, or the execution platform? More specifically, will the values of `os.arch` and `os.name` be of the host platform, or execution platform?\r\n\r\n> Additionally, how does this all fit into platforms? If at all. I think it might be strange to use the Platforms API in most cases, but the repository_os struct in others. What are your thoughts?\r\n\r\nMy understanding is that repository rules are always executed locally (i.e., on the host), even with RBE, and don't really have a concept of platforms. Rather, platforms could be used to select the correct repository among the instances of a repository rule for the different platforms. Bazel would then only fetch the repository rules that are relevant for the current configuration. In this context, `repository_os` is more of a shortcut geared towards local execution, whereas sophisticated RBE setups would probably favor the approach described in https://github.com/bazelbuild/bazel/issues/11655#issuecomment-734212603.\r\n",
" I think https://github.com/bazelbuild/bazel/pull/14738 solves exactly the request of this issue. The `repository_ctx.os.name` and `repository_ctx.os.arch` return the values for the host platform (which is the one Bazel runs on), this should be enough as in most cases repository rules run locally. \r\n\r\nBut we do have a way to make `repository.execute` [run commands on RBE](https://docs.bazel.build/versions/main/skylark/lib/globals.html#repository_rule(implementation,%20attrs,%20local,%20environ,%20configure,%20remotable,%20doc)), but this is a very much experimental feature and currently unmaintained.\r\n\r\nI also agree if Bazel runs in a simulation it should just get the simulated arch. We do provide native arm64 binaries for Linux and macOS, arm64 support for Windows has also been [added](https://github.com/bazelbuild/bazel/issues/14339) recently. ",
"@bazel-io flag",
"(I miss-read what that command was for, this isn't a blocker, sorry.)",
"OK, I removed the label. But I guess we could still cherry-pick this to 5.1? @Wyverald ",
"Yeah, that was what I wanted to do. Per the process, it seems we just open the PR instead of flagging it.",
"@bazel-io fork 5.1",
"The fork command will create an associate issue to track the cherry-pick, feel free to send a PR!",
"Amazing, thank you for the work on this. I look forward to using it! I'll make contributions for the major rules to also take advantage of this new attribute when available.\n\nFor clarification; this only provides info for the host OS, correct? What happens in a remote execution context? Are those actions still executed locally? I suppose it depends on the declared toolchains.\n\nIs there any official guidance on how best to write repository rules for compatibility with remote execution? It seems to me like it may still be the case that rule authors must declare every cpu/os combination as repositories and reference them via toolchains.\n\nMaybe I'm missing something 🙂\n\n"
] | [] | "2022-02-16T14:02:37Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"help wanted"
] | Provide the host CPU to repository rules | <!--
ATTENTION! Please read and follow:
- if this is a _question_ about how to build / test / query / deploy using Bazel, or a _discussion starter_, send it to [email protected]
- if this is a _bug_ or _feature request_, fill the form below as best as you can.
-->
### Description of the problem / feature request:
Repository rules already have access to `repository_os` which allows rules to change their behaviour based on the exec OS. Repository rules should also know the exec architecture. Repository rules currently work around this limitation by `uname -m`, which isn't ideal. See [rules_go](https://github.com/bazelbuild/rules_go/blob/fd11dd2768669dc2cc1f3a11f2b0b81d84e81c32/go/private/sdk.bzl#L253).
### Feature requests: what underlying problem are you trying to solve with this feature?
Repository rules create potentially brittle and strange workarounds to get the exec CPU. There is no standardisation and no official guidance on how best to create repository rules which target multiple platforms.
### What operating system are you running Bazel on?
Linux x86_64
### What's the output of `bazel info release`?
```sh
❯ bazel info release
Starting local Bazel server and connecting to it...
release 5.0.0
```
### Have you found anything relevant by searching the web?
> Replace this line with your answer.
- https://github.com/bazelbuild/bazel/issues/11655#issuecomment-734212603
- https://github.com/bazelbuild/bazel/issues/4636 (request was target, not exec)
### Any other information, logs, or outputs that you want to share?
N/A
| [
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java",
"tools/cpp/lib_cc_configure.bzl",
"tools/jdk/local_java_repository.bzl",
"tools/osx/xcode_configure.bzl"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java",
"tools/cpp/lib_cc_configure.bzl",
"tools/jdk/local_java_repository.bzl",
"tools/osx/xcode_configure.bzl"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java
index dfd8e1209d5956..83df566cabdab9 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkOS.java
@@ -17,6 +17,7 @@
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.docgen.annot.DocCategory;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
+import java.util.Locale;
import java.util.Map;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
@@ -49,8 +50,20 @@ public ImmutableMap<String, String> getEnvironmentVariables() {
@StarlarkMethod(
name = "name",
structField = true,
- doc = "A string identifying the current system Bazel is running on.")
+ doc =
+ "A string identifying the operating system Bazel is running on (the value of the"
+ + " \"os.name\" Java property).")
public String getName() {
- return System.getProperty("os.name").toLowerCase();
+ return System.getProperty("os.name").toLowerCase(Locale.ROOT);
+ }
+
+ @StarlarkMethod(
+ name = "arch",
+ structField = true,
+ doc =
+ "A string identifying the architecture Bazel is running on (the value of the \"os.arch\""
+ + " Java property).")
+ public String getArch() {
+ return System.getProperty("os.arch").toLowerCase(Locale.ROOT);
}
}
diff --git a/tools/cpp/lib_cc_configure.bzl b/tools/cpp/lib_cc_configure.bzl
index cf602ab1b0cb76..f8689fb70b5048 100644
--- a/tools/cpp/lib_cc_configure.bzl
+++ b/tools/cpp/lib_cc_configure.bzl
@@ -179,38 +179,34 @@ def execute(
def get_cpu_value(repository_ctx):
"""Compute the cpu_value based on the OS name. Doesn't %-escape the result!"""
- os_name = repository_ctx.os.name.lower()
+ os_name = repository_ctx.os.name
+ arch = repository_ctx.os.arch
if os_name.startswith("mac os"):
# Check if we are on x86_64 or arm64 and return the corresponding cpu value.
- result = repository_ctx.execute(["uname", "-m"])
- return "darwin" + ("_arm64" if result.stdout.strip() == "arm64" else "")
+ return "darwin" + ("_arm64" if arch == "aarch64" else "")
if os_name.find("freebsd") != -1:
return "freebsd"
if os_name.find("openbsd") != -1:
return "openbsd"
if os_name.find("windows") != -1:
- arch = (get_env_var(repository_ctx, "PROCESSOR_ARCHITECTURE", "", False) or
- get_env_var(repository_ctx, "PROCESSOR_ARCHITEW6432", "", False))
- if arch == "ARM64":
+ if arch == "aarch64":
return "arm64_windows"
else:
return "x64_windows"
- # Use uname to figure out whether we are on x86_32 or x86_64
- result = repository_ctx.execute(["uname", "-m"])
- if result.stdout.strip() in ["power", "ppc64le", "ppc", "ppc64"]:
+ if arch in ["power", "ppc64le", "ppc", "ppc64"]:
return "ppc"
- if result.stdout.strip() in ["s390x"]:
+ if arch in ["s390x"]:
return "s390x"
- if result.stdout.strip() in ["mips64"]:
+ if arch in ["mips64"]:
return "mips64"
- if result.stdout.strip() in ["riscv64"]:
+ if arch in ["riscv64"]:
return "riscv64"
- if result.stdout.strip() in ["arm", "armv7l"]:
+ if arch in ["arm", "armv7l"]:
return "arm"
- if result.stdout.strip() in ["aarch64"]:
+ if arch in ["aarch64"]:
return "aarch64"
- return "k8" if result.stdout.strip() in ["amd64", "x86_64", "x64"] else "piii"
+ return "k8" if arch in ["amd64", "x86_64", "x64"] else "piii"
def is_cc_configure_debug(repository_ctx):
"""Returns True if CC_CONFIGURE_DEBUG is set to 1."""
diff --git a/tools/jdk/local_java_repository.bzl b/tools/jdk/local_java_repository.bzl
index 4c0a433f8f2a1c..12908eda765a84 100644
--- a/tools/jdk/local_java_repository.bzl
+++ b/tools/jdk/local_java_repository.bzl
@@ -132,7 +132,7 @@ def _local_java_repository_impl(repository_ctx):
"workspace(name = \"{name}\")\n".format(name = repository_ctx.name),
)
- extension = ".exe" if repository_ctx.os.name.lower().find("windows") != -1 else ""
+ extension = ".exe" if repository_ctx.os.name.find("windows") != -1 else ""
java_bin = java_home_path.get_child("bin").get_child("java" + extension)
if not java_bin.exists:
diff --git a/tools/osx/xcode_configure.bzl b/tools/osx/xcode_configure.bzl
index 2b819f07ec9f9a..94bd896c4a11aa 100644
--- a/tools/osx/xcode_configure.bzl
+++ b/tools/osx/xcode_configure.bzl
@@ -271,7 +271,7 @@ def _impl(repository_ctx):
repository_ctx: The repository context.
"""
- os_name = repository_ctx.os.name.lower()
+ os_name = repository_ctx.os.name
build_contents = "package(default_visibility = ['//visibility:public'])\n\n"
if (os_name.startswith("mac os")):
build_contents += _darwin_build_file(repository_ctx)
| null | test | val | 2022-02-14T16:11:02 | "2022-02-02T00:01:10Z" | uhthomas | test |
bazelbuild/bazel/14654_14885 | bazelbuild/bazel | bazelbuild/bazel/14654 | bazelbuild/bazel/14885 | [
"keyword_pr_to_issue"
] | 031a772acfd304fb5678e6a53e6c4ac3b99103ff | 8ebd70b0c97c8bd584647f219be8dd52217cb5cf | [
"Is `--experimental_remote_cache_compression` being used as well?",
"Actually the reason for this error seems to be `--experimental_remote_cache_compression`. From my early tests locally that flag reduced build times by 20-25%, but I see `BulkTransferException` in every single CI build. I've removed `--experimental_remote_cache_async` and only enabled `--experimental_remote_cache_compression` and the problem persists.",
"This is where those errors are thrown:\r\nhttps://github.com/bazelbuild/bazel/blob/72d525575a7a6c22abee5e7791f1072bb334340e/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java#L466-L476",
"Highlighting the relevant parts of the error:\r\n\r\n```\r\n\tSuppressed: java.io.IOException: write incomplete: committed_size 721 for 374 total\r\n\tSuppressed: java.io.IOException: write incomplete: committed_size 144 for 125 total\r\n\tSuppressed: java.io.IOException: write incomplete: committed_size 2 for 14 total\r\n```\r\n\r\nI am not super familiar with the byte stream uploader (attempting to grok it now), but is it possible that the `!chunker.hasNext()` condition does not necessarily imply that the uploader was the one who completed the upload, as the comment states? (Could it be that `chunker.hasNext()` returns false in some cases when there was only 1 chunk to flush, and the server returned that the chunk already exists, returning the blob's uncompressed size as the committed size?)\r\n\r\nAsking because those error messages look as though the server is returning uncompressed blob sizes as the committed size (e.g. a 721 byte chunk compressing to 374 bytes looks about right, and a 2 byte chunk compressing to 14 bytes looks accurate as well since the compression overhead probably requires more space than the bytes themselves).",
"CC @coeuvre , @benjaminp , @buchgr , @Wyverald ",
"CC @bazelbuild/remote-execution ",
"I started a draft PR which has a failing test illustrating the issue, and I am fairly certain that the fake ByteStream impl in the test adheres to protocol, but please correct me if I'm wrong: https://github.com/bazelbuild/bazel/pull/14655\r\n\r\nI think there is an ambiguity with the current way that the `ByteStream.Write` protocol is specified. The exact spec is here: https://github.com/bazelbuild/remote-apis/blob/636121a32fa7b9114311374e4786597d8e7a69f3/build/bazel/remote/execution/v2/remote_execution.proto#L256-L264\r\n\r\n```\r\n// When attempting an upload, if another client has already completed the upload\r\n// (which may occur in the middle of a single upload if another client uploads\r\n// the same blob concurrently), the request will terminate immediately with\r\n// a response whose `committed_size` is the full size of the uploaded file\r\n// (regardless of how much data was transmitted by the client). If the client\r\n// completes the upload but the\r\n// [Digest][build.bazel.remote.execution.v2.Digest] does not match, an\r\n// `INVALID_ARGUMENT` error will be returned. In either case, the client should\r\n// not attempt to retry the upload.\r\n```\r\n\r\nIn summary, one of two things can happen in response to clients sending their final chunk:\r\n\r\n1. The server can respond with `committed_size = client_uploaded_size` which means that the client successfully performed the upload, or\r\n2. the server can respond with `committed_size = \"full size of the uploaded file\"` \r\n\r\nBut, what does \"full size of the uploaded file\" mean?\r\n* If it means \"compressed size of the file, as uploaded by the other client,\" then the \"full size\" could be pretty arbitrary since there is more than one valid way to compress a file, and it's useless to return this to the client.\r\n* But if it means \"uncompressed size of the file\" (i.e. `Digest.size_bytes`), then the client needs to check that, once they have received a `WriteResponse` and they have already uploaded all local chunks, then _either_ the `WriteResponse.committed_size` equals `Digest.size_bytes`, _or_ it equals the total number of bytes written by the local client (`chunker.getOffset()`) -- because the protocol gives us no way of knowing whether the successful upload of the last chunk was due to the local client's chunk being accepted, or if it was due to some other client completing their upload.\r\n\r\nGiven that the former interpretation would be useless to clients, I imagine the latter interpretation is what was originally intended. If so, I think it implies that the current implementation of `ByteStreamUploader` has a bug, because it does not check whether the `committed_size` could equal `Digest.size_bytes`. The current Bazel implementation seems to have used the first interpretation, based on [this comment](https://github.com/bazelbuild/bazel/blob/90abed5a31ae75761252c7e082572babafeb0ae6/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java#L466-L468):\r\n\r\n```\r\n // Only check for matching committed size if we have completed the upload.\r\n // If another client did, they might have used a different compression\r\n // level/algorithm, so we cannot know the expected committed offset\r\n```\r\n\r\nCC @mostynb who may be able to help clarify the spec",
"You're right that `WriteResponse.committed_size` is kind of useless for compressed blobs, but I don't think clients need to check that value- the server should return an error status code if and only if the write failed, and the client can check that instead of the `committed_size` field.",
"@mostynb Thanks for your input!\r\n\r\nI would be happy to send a PR so that Bazel stops checking the `committed_size` in the `WriteResponse`, so long as the folks familiar with the ByteStreamUploader don't see any problems with removing the check. I am not 100% sure whether this would a breaking change, but it seems like it wouldn't be. If anything, it might break some expectations on the remote cache side, so it might help to have input from some remote cache impl maintainers as well.\r\n\r\nSeparately, I am trying to figure out whether the `compressed_size` check on the Bazel side is possible for a remote cache implementation to work around in the meantime. Specifically, I'm thinking about the following edge case and not sure how to handle it:\r\n\r\n```\r\n1. Bazel sends chunk #1, FinishWrite=false\r\n2. Bazel sends chunk #2, FinishWrite=true\r\n3. Server receives chunk #1, parses ResourceName, sees that the digest already exists in the cache\r\n Server immediately returns `WriteResponse{committed_size = digest_size}`\r\n4. Bazel receives WriteResponse from the server. Since it has already sent all chunks, it thinks it has completed\r\n the upload, and then asserts `committed_size == chunker.offset`. This fails.\r\n```\r\n\r\nFirstly, is this scenario is even possible? (not sure if client-streaming gRPC works the same way in Java as it does in Go, but IIUC the client does not need to wait for the server to receive and respond to each message before proceeding to send the next message)\r\n\r\nSecondly, is the only workaround on the cache side just to wait for Bazel to upload the entire stream, regardless of whether the digest already exists in cache or not, and then return the total length of the compressed stream so that it satisfies Bazel's committed_size expectation?",
"@mostynb FYI, I think this issue might affect `bazel-remote` as well:\r\n\r\nhttps://github.com/buchgr/bazel-remote/blob/a3c6189b64cff12065750073b11a116c8c1ed00a/server/grpc_bytestream.go#L415-L421\r\n\r\nIt looks like on the first WriteRequest, if the digest already exists in cache, a `WriteResponse` with `committed_size=uncompressed_size` is effectively returned.",
"Maybe the best we can do is update the REAPI spec to advise clients to ignore `committed_size` for compressed writes and to rely on the error status instead in that case?\r\n\r\nI'm not sure how the early-exit mechanism is useful in practice actually. As you mentioned the client calls `Send` until it thinks it has sent all the data, and only then calls `CloseAndRecv` to get the `WriteResponse` (at least in the go bindings). At this point the client has sent all the data even if the server decided to return early. So instead of returning early the server could have discarded all the received data and just counted how much compressed data was sent and returned that number. So maybe we should instead update the REAPI spec to advise servers to do that for compressed-blobs writes instead of returning early?",
"> instead of returning early the server could have discarded all the received data and just counted how much compressed data was sent and returned that number. \r\n\r\nThis is exactly the workaround that I'm currently implementing :+1: \r\n\r\n> advise servers to do that for compressed-blobs writes instead of returning early\r\n\r\nI think it's good advice for servers that want to be compatible with Bazel's current behavior, so it's probably worth mentioning this approach in the REAPI spec as a notable client quirk. I'm not sure whether it'd be the best advice though if/when Bazel removes the `committed_size` check, since I don't have a great intuition (nor any data) as to whether the early-exit mechanism provides significant savings in practice.",
"Let's open an REAPI issue to get more input- can you do that or would you like me to?",
"I'll go ahead and open one",
"@bazel-io fork 5.1",
"Still seeing this, removing `--experimental_remote_cache_compression` works around it",
"@keith: your remote cache might require an update- is it something opensource? If so which one and which version?",
"Using Google's 🙃 ",
"cc @bergsieker",
"This will be fixed in Bazel 5.3 😍."
] | [] | "2022-02-22T13:53:54Z" | [
"untriaged",
"team-Remote-Exec"
] | `--experimental_remote_cache_compression` causes incomplete writes | ### Description of the problem / feature request:
We upgraded to Bazel 5.0.0 and are currently trying out the `--experimental_remote_cache_async`. During our build, I see over 1000 messages printed out to stdout that look like this possibly caused by `BulkTransferException`s:
```
WARNING: Remote Cache: 3 errors during bulk transfer
com.google.devtools.build.lib.remote.common.BulkTransferException: 3 errors during bulk transfer
at com.google.devtools.build.lib.remote.util.RxUtils$BulkTransferExceptionCollector.onResult(RxUtils.java:91)
at io.reactivex.rxjava3.internal.operators.flowable.FlowableCollectSingle$CollectSubscriber.onNext(FlowableCollectSingle.java:94)
at io.reactivex.rxjava3.internal.operators.flowable.FlowableFlatMapSingle$FlatMapSingleSubscriber.innerSuccess(FlowableFlatMapSingle.java:173)
at io.reactivex.rxjava3.internal.operators.flowable.FlowableFlatMapSingle$FlatMapSingleSubscriber$InnerObserver.onSuccess(FlowableFlatMapSingle.java:342)
at io.reactivex.rxjava3.internal.operators.single.SingleDoFinally$DoFinallyObserver.onSuccess(SingleDoFinally.java:73)
at io.reactivex.rxjava3.internal.observers.ResumeSingleObserver.onSuccess(ResumeSingleObserver.java:46)
at io.reactivex.rxjava3.internal.operators.single.SingleJust.subscribeActual(SingleJust.java:30)
at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)
at io.reactivex.rxjava3.internal.operators.single.SingleResumeNext$ResumeMainSingleObserver.onError(SingleResumeNext.java:80)
at io.reactivex.rxjava3.internal.operators.completable.CompletableToSingle$ToSingle.onError(CompletableToSingle.java:73)
at io.reactivex.rxjava3.internal.operators.completable.CompletableCreate$Emitter.tryOnError(CompletableCreate.java:91)
at io.reactivex.rxjava3.internal.operators.completable.CompletableCreate$Emitter.onError(CompletableCreate.java:77)
at com.google.devtools.build.lib.remote.util.RxFutures$OnceCompletableOnSubscribe$1.onFailure(RxFutures.java:102)
at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1074)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:771)
at com.google.devtools.build.lib.remote.util.RxFutures$CompletableFuture.setException(RxFutures.java:276)
at com.google.devtools.build.lib.remote.util.RxFutures$1.onError(RxFutures.java:210)
at io.reactivex.rxjava3.internal.operators.completable.CompletableFromSingle$CompletableFromSingleObserver.onError(CompletableFromSingle.java:41)
at io.reactivex.rxjava3.internal.operators.single.SingleCreate$Emitter.tryOnError(SingleCreate.java:95)
at io.reactivex.rxjava3.internal.operators.single.SingleCreate$Emitter.onError(SingleCreate.java:81)
at com.google.devtools.build.lib.remote.util.AsyncTaskCache$1.onError(AsyncTaskCache.java:306)
at com.google.devtools.build.lib.remote.util.AsyncTaskCache$Execution.onError(AsyncTaskCache.java:197)
at io.reactivex.rxjava3.internal.operators.completable.CompletableToSingle$ToSingle.onError(CompletableToSingle.java:73)
at io.reactivex.rxjava3.internal.operators.completable.CompletableCreate$Emitter.tryOnError(CompletableCreate.java:91)
at io.reactivex.rxjava3.internal.operators.completable.CompletableCreate$Emitter.onError(CompletableCreate.java:77)
at com.google.devtools.build.lib.remote.util.RxFutures$OnceCompletableOnSubscribe$1.onFailure(RxFutures.java:102)
at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1066)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.setFuture(AbstractFuture.java:814)
at com.google.common.util.concurrent.AbstractCatchingFuture.run(AbstractCatchingFuture.java:115)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:771)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:100)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.setFuture(AbstractFuture.java:814)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.setResult(AbstractTransformFuture.java:224)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.setResult(AbstractTransformFuture.java:202)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:163)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.common.util.concurrent.AbstractCatchingFuture.run(AbstractCatchingFuture.java:110)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.common.util.concurrent.AbstractCatchingFuture.run(AbstractCatchingFuture.java:110)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.common.util.concurrent.AbstractCatchingFuture.run(AbstractCatchingFuture.java:110)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.common.util.concurrent.AbstractTransformFuture$TransformFuture.setResult(AbstractTransformFuture.java:247)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:163)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.devtools.build.lib.remote.util.RxFutures$CompletableFuture.set(RxFutures.java:270)
at com.google.devtools.build.lib.remote.util.RxFutures$2.onSuccess(RxFutures.java:233)
at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onSuccess(SingleFlatMap.java:112)
at io.reactivex.rxjava3.internal.operators.single.SingleUsing$UsingSingleObserver.onSuccess(SingleUsing.java:154)
at io.reactivex.rxjava3.internal.operators.single.SingleCreate$Emitter.onSuccess(SingleCreate.java:68)
at com.google.devtools.build.lib.remote.util.RxFutures$OnceSingleOnSubscribe$1.onSuccess(RxFutures.java:155)
at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1080)
at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:746)
at com.google.common.util.concurrent.SettableFuture.set(SettableFuture.java:47)
at com.google.devtools.build.lib.remote.ByteStreamUploader$AsyncUpload$1.onClose(ByteStreamUploader.java:579)
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
at com.google.devtools.build.lib.remote.logging.LoggingInterceptor$LoggingForwardingCall$1.onClose(LoggingInterceptor.java:157)
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557)
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717)
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Suppressed: java.io.IOException: write incomplete: committed_size 721 for 374 total
at com.google.devtools.build.lib.remote.ByteStreamUploader$AsyncUpload.lambda$start$2(ByteStreamUploader.java:448)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:213)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:202)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:118)
... 51 more
Suppressed: java.io.IOException: write incomplete: committed_size 144 for 125 total
at com.google.devtools.build.lib.remote.ByteStreamUploader$AsyncUpload.lambda$start$2(ByteStreamUploader.java:448)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:213)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:202)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:118)
... 51 more
Suppressed: java.io.IOException: write incomplete: committed_size 2 for 14 total
at com.google.devtools.build.lib.remote.ByteStreamUploader$AsyncUpload.lambda$start$2(ByteStreamUploader.java:448)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:213)
at com.google.common.util.concurrent.AbstractTransformFuture$AsyncTransformFuture.doTransform(AbstractTransformFuture.java:202)
at com.google.common.util.concurrent.AbstractTransformFuture.run(AbstractTransformFuture.java:118)
... 51 more
```
### Feature requests: what underlying problem are you trying to solve with this feature?
I'm testing the new `--experimental_remote_cache_compression` flag to speed up artifacts download and upload.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
I couldn't reproduce it yet. This is a pretty big project with a lot of flags. Maybe this flag is conflicting with one of these as well:
```
build --remote_timeout=600s
build --remote_upload_local_results
build --remote_download_toplevel
```
macOS 12.1
### What's the output of `bazel info release`?
`release 5.0.0`
| [
"CONTRIBUTORS",
"src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java"
] | [
"CONTRIBUTORS",
"src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java"
] | [] | diff --git a/CONTRIBUTORS b/CONTRIBUTORS
index a95cecd8def926..6936c814fe7bd0 100644
--- a/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -20,6 +20,7 @@ Shreya Bhattarai <[email protected]>
Kevin Bierhoff <[email protected]>
Klaas Boesche <[email protected]>
Phil Bordelon <[email protected]>
+Mostyn Bramley-Moore <[email protected]>
Jon Brandvein <[email protected]>
Volker Braun <[email protected]>
Thomas Broyer <[email protected]>
diff --git a/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java b/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
index d4aa19061c3c34..220a3046161f7c 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
@@ -440,14 +440,33 @@ ListenableFuture<Void> start() {
// level/algorithm, so we cannot know the expected committed offset
long committedSize = committedOffset.get();
long expected = chunker.getOffset();
- if (!chunker.hasNext() && committedSize != expected) {
+
+ if (committedSize == expected) {
+ // Both compressed and uncompressed uploads can succeed
+ // with this result.
+ return immediateVoidFuture();
+ }
+
+ if (chunker.isCompressed()) {
+ if (committedSize == -1) {
+ // Returned early, blob already available.
+ return immediateVoidFuture();
+ }
+
String message =
format(
- "write incomplete: committed_size %d for %d total",
+ "compressed write incomplete: committed_size %d is neither -1 nor total %d",
committedSize, expected);
return Futures.immediateFailedFuture(new IOException(message));
}
+
+ // Uncompressed upload failed.
+ String message =
+ format(
+ "write incomplete: committed_size %d for %d total", committedSize, expected);
+ return Futures.immediateFailedFuture(new IOException(message));
}
+
return immediateVoidFuture();
},
MoreExecutors.directExecutor());
| null | train | val | 2022-02-17T22:57:21 | "2022-01-27T12:32:21Z" | BalestraPatrick | test |
bazelbuild/bazel/10642_14997 | bazelbuild/bazel | bazelbuild/bazel/10642 | bazelbuild/bazel/14997 | [
"keyword_pr_to_issue"
] | 87ef5ce4103be75e8d9935e071fa215a481536e1 | 5e79972c05d89280f0cf1fa620f807366847bac6 | [
"This looks like a dupe of #8736."
] | [] | "2022-03-08T10:58:34Z" | [
"type: feature request",
"P3",
"coverage",
"team-Rules-Server"
] | _lcov_merger late-bound test attribute | I went to add `_lcov_merger` as an attribute for iOS tests here https://github.com/bazelbuild/rules_apple/pull/691 and there was some discussion about making this tool a late-bound attribute so we wouldn't incur overhead for this tool always. It doesn't seem like there's an API that currently allows us to do this.
There was also some discussion of if the attribute makes sense to be on every test rule or if it should be more global, maybe with a flag like `--lcov_merger` with this tool as the default.
I wanted to file this here so we could discuss this and unblock iOS tests supporting coverage. | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java",
"src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java",
"src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java",
"src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/BUILD",
"src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/CoverageConfigurationApi.java",
"src/test/shell/bazel/bazel_coverage_starlark_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BUILD b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
index ab553b460b52a1..4cfeb659323e79 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
@@ -254,6 +254,7 @@ java_library(
"test/AnalysisTestActionBuilder.java",
"test/BaselineCoverageAction.java",
"test/CoverageCommon.java",
+ "test/CoverageConfiguration.java",
"test/InstrumentedFileManifestAction.java",
"test/InstrumentedFilesCollector.java",
"test/TestActionBuilder.java",
@@ -287,6 +288,7 @@ java_library(
":config/build_options",
":config/config_conditions",
":config/config_matching_provider",
+ ":config/core_option_converters",
":config/core_options",
":config/execution_transition_factory",
":config/fragment",
@@ -379,6 +381,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/actions:package_roots",
"//src/main/java/com/google/devtools/build/lib/analysis/platform",
"//src/main/java/com/google/devtools/build/lib/analysis/platform:utils",
+ "//src/main/java/com/google/devtools/build/lib/analysis/starlark/annotations",
"//src/main/java/com/google/devtools/build/lib/analysis/stringtemplate",
"//src/main/java/com/google/devtools/build/lib/bugreport",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java b/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
index 861206b86c550e..6b6402f01ae4f9 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
@@ -34,6 +34,7 @@
import com.google.devtools.build.lib.analysis.config.RunUnder;
import com.google.devtools.build.lib.analysis.constraints.ConstraintConstants;
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
+import com.google.devtools.build.lib.analysis.test.CoverageConfiguration;
import com.google.devtools.build.lib.analysis.test.TestConfiguration;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Attribute;
@@ -139,9 +140,6 @@ public static LabelLateBoundDefault<TestConfiguration> coverageSupportAttribute(
public static final String DEFAULT_COVERAGE_REPORT_GENERATOR_VALUE =
"//tools/test:coverage_report_generator";
- private static final String DEFAULT_COVERAGE_OUTPUT_GENERATOR_VALUE =
- "@bazel_tools//tools/test:lcov_merger";
-
@SerializationConstant @AutoCodec.VisibleForSerialization
static final Resolver<TestConfiguration, Label> COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER =
(rule, attributes, configuration) -> configuration.getCoverageReportGenerator();
@@ -152,20 +150,14 @@ public static LabelLateBoundDefault<TestConfiguration> coverageReportGeneratorAt
TestConfiguration.class, defaultValue, COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER);
}
- public static LabelLateBoundDefault<BuildConfiguration> getCoverageOutputGeneratorLabel() {
+ public static LabelLateBoundDefault<CoverageConfiguration> getCoverageOutputGeneratorLabel() {
return LabelLateBoundDefault.fromTargetConfiguration(
- BuildConfiguration.class, null, COVERAGE_OUTPUT_GENERATOR_RESOLVER);
+ CoverageConfiguration.class, null, COVERAGE_OUTPUT_GENERATOR_RESOLVER);
}
@SerializationConstant @AutoCodec.VisibleForSerialization
- static final Resolver<BuildConfiguration, Label> COVERAGE_OUTPUT_GENERATOR_RESOLVER =
- (rule, attributes, configuration) -> {
- if (configuration.isCodeCoverageEnabled()) {
- return Label.parseAbsoluteUnchecked(DEFAULT_COVERAGE_OUTPUT_GENERATOR_VALUE);
- } else {
- return null;
- }
- };
+ static final Resolver<CoverageConfiguration, Label> COVERAGE_OUTPUT_GENERATOR_RESOLVER =
+ (rule, attributes, configuration) -> configuration.outputGenerator();
// TODO(b/65746853): provide a way to do this without passing the entire configuration
/** Implementation for the :run_under attribute. */
diff --git a/src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java b/src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java
index d2b6c6523b7c59..2908893d33c661 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/core/CoreRules.java
@@ -17,6 +17,7 @@
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider.RuleSet;
+import com.google.devtools.build.lib.analysis.test.CoverageConfiguration;
import com.google.devtools.build.lib.analysis.test.TestConfiguration;
import com.google.devtools.build.lib.analysis.test.TestTrimmingTransitionFactory;
@@ -33,6 +34,7 @@ public void init(ConfiguredRuleClassProvider.Builder builder) {
builder.setShouldInvalidateCacheForOptionDiff(
TestConfiguration.SHOULD_INVALIDATE_FOR_OPTION_DIFF);
builder.addConfigurationFragment(TestConfiguration.class);
+ builder.addConfigurationFragment(CoverageConfiguration.class);
builder.addTrimmingTransitionFactory(new TestTrimmingTransitionFactory());
builder.addRuleDefinition(new BaseRuleClasses.NativeBuildRule());
builder.addRuleDefinition(new BaseRuleClasses.NativeActionCreatingRule());
| diff --git a/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java
new file mode 100644
index 00000000000000..7aaccfa4d4eec2
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java
@@ -0,0 +1,78 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.analysis.test;
+
+import com.google.devtools.build.lib.analysis.config.BuildOptions;
+import com.google.devtools.build.lib.analysis.config.CoreOptionConverters.LabelConverter;
+import com.google.devtools.build.lib.analysis.config.CoreOptions;
+import com.google.devtools.build.lib.analysis.config.Fragment;
+import com.google.devtools.build.lib.analysis.config.FragmentOptions;
+import com.google.devtools.build.lib.analysis.config.RequiresOptions;
+import com.google.devtools.build.lib.analysis.starlark.annotations.StarlarkConfigurationField;
+import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
+import com.google.devtools.build.lib.starlarkbuildapi.test.CoverageConfigurationApi;
+import com.google.devtools.common.options.Option;
+import com.google.devtools.common.options.OptionDocumentationCategory;
+import com.google.devtools.common.options.OptionEffectTag;
+import javax.annotation.Nullable;
+
+/** The coverage configuration fragment. */
+@Immutable
+@RequiresOptions(options = {CoreOptions.class, CoverageConfiguration.CoverageOptions.class})
+public class CoverageConfiguration extends Fragment implements CoverageConfigurationApi {
+
+ /** Command-line options. */
+ public static class CoverageOptions extends FragmentOptions {
+
+ @Option(
+ name = "coverage_output_generator",
+ converter = LabelConverter.class,
+ defaultValue = "@bazel_tools//tools/test:lcov_merger",
+ documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
+ effectTags = {
+ OptionEffectTag.CHANGES_INPUTS,
+ OptionEffectTag.AFFECTS_OUTPUTS,
+ OptionEffectTag.LOADING_AND_ANALYSIS
+ },
+ help =
+ "Location of the binary that is used to postprocess raw coverage reports. This must "
+ + "currently be a filegroup that contains a single file, the binary. Defaults to "
+ + "'//tools/test:lcov_merger'.")
+ public Label coverageOutputGenerator;
+ }
+
+ private final CoverageOptions coverageOptions;
+
+ public CoverageConfiguration(BuildOptions buildOptions) {
+ if (!buildOptions.get(CoreOptions.class).collectCodeCoverage) {
+ this.coverageOptions = null;
+ return;
+ }
+ this.coverageOptions = buildOptions.get(CoverageOptions.class);
+ }
+
+ @Override
+ @StarlarkConfigurationField(
+ name = "output_generator",
+ doc = "Label for the coverage output generator.")
+ @Nullable
+ public Label outputGenerator() {
+ if (coverageOptions == null) {
+ return null;
+ }
+ return coverageOptions.coverageOutputGenerator;
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/BUILD b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/BUILD
index 7ea3da44281863..a295e6e29c4a4a 100644
--- a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/BUILD
@@ -30,5 +30,6 @@ java_library(
"//src/main/java/net/starlark/java/annot",
"//src/main/java/net/starlark/java/eval",
"//src/main/java/com/google/devtools/build/lib/starlarkbuildapi",
+ "//third_party:jsr305",
],
)
diff --git a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/CoverageConfigurationApi.java b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/CoverageConfigurationApi.java
new file mode 100644
index 00000000000000..cb342e938313ea
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test/CoverageConfigurationApi.java
@@ -0,0 +1,50 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.starlarkbuildapi.test;
+
+import com.google.devtools.build.docgen.annot.DocCategory;
+import com.google.devtools.build.lib.cmdline.Label;
+import javax.annotation.Nullable;
+import net.starlark.java.annot.StarlarkBuiltin;
+import net.starlark.java.annot.StarlarkMethod;
+import net.starlark.java.eval.StarlarkValue;
+
+/** Coverage configuration fragment API. */
+@StarlarkBuiltin(
+ name = "coverage",
+ category = DocCategory.CONFIGURATION_FRAGMENT,
+ doc = "A configuration fragment representing the coverage configuration.")
+public interface CoverageConfigurationApi extends StarlarkValue {
+
+ @StarlarkMethod(
+ name = "output_generator",
+ allowReturnNones = true,
+ structField = true,
+ doc =
+ "Returns the label pointed to by the"
+ + " <a href=\"../../user-manual.html#flag--coverage_output_generator\">"
+ + "<code>--coverage_output_generator</code></a> option if coverage collection is"
+ + " enabled, otherwise returns <code>None</code>. Can be accessed with"
+ + " <a href=\"globals.html#configuration_field\"><code>configuration_field"
+ + "</code></a>:<br/>"
+ + "<pre>attr.label(<br/>"
+ + " default = configuration_field(<br/>"
+ + " fragment = \"coverage\",<br/>"
+ + " name = \"output_generator\"<br/>"
+ + " )<br/>"
+ + ")</pre>")
+ @Nullable
+ Label outputGenerator();
+}
diff --git a/src/test/shell/bazel/bazel_coverage_starlark_test.sh b/src/test/shell/bazel/bazel_coverage_starlark_test.sh
index 0ea7e032ef5dad..e97c1500c5e14c 100755
--- a/src/test/shell/bazel/bazel_coverage_starlark_test.sh
+++ b/src/test/shell/bazel/bazel_coverage_starlark_test.sh
@@ -134,4 +134,90 @@ EOF
|| fail "Coverage report did not contain evidence of custom lcov_merger."
}
+function test_starlark_rule_with_configuration_field_lcov_merger_coverage_enabled() {
+
+ cat <<EOF > lcov_merger.sh
+for var in "\$@"
+do
+ if [[ "\$var" == "--output_file="* ]]; then
+ path="\${var##--output_file=}"
+ mkdir -p "\$(dirname \$path)"
+ echo lcov_merger_called >> \$path
+ exit 0
+ fi
+done
+EOF
+chmod +x lcov_merger.sh
+
+ cat <<EOF > rules.bzl
+def _impl(ctx):
+ output = ctx.actions.declare_file(ctx.attr.name)
+ ctx.actions.write(output, "", is_executable = True)
+ return [DefaultInfo(executable=output)]
+
+custom_test = rule(
+ implementation = _impl,
+ test = True,
+ attrs = {
+ "_lcov_merger": attr.label(
+ default = configuration_field(fragment = "coverage", name = "output_generator"),
+ cfg = "exec"
+ ),
+ },
+ fragments = ["coverage"],
+)
+EOF
+
+ cat <<EOF > BUILD
+load(":rules.bzl", "custom_test")
+
+sh_binary(
+ name = "lcov_merger",
+ srcs = ["lcov_merger.sh"],
+)
+custom_test(name = "foo_test")
+EOF
+
+ bazel coverage --test_output=all //:foo_test --combined_report=lcov --coverage_output_generator=//:lcov_merger > $TEST_log \
+ || fail "Coverage run failed but should have succeeded."
+
+ local coverage_file_path="$( get_coverage_file_path_from_test_log )"
+ cat $coverage_file_path
+ grep "lcov_merger_called" "$coverage_file_path" \
+ || fail "Coverage report did not contain evidence of custom lcov_merger."
+}
+
+function test_starlark_rule_with_configuration_field_lcov_merger_coverage_disabled() {
+
+ cat <<EOF > rules.bzl
+def _impl(ctx):
+ if ctx.attr._lcov_merger:
+ fail("Expected _lcov_merger to be None if coverage is not collected")
+ output = ctx.actions.declare_file(ctx.attr.name)
+ ctx.actions.write(output, "", is_executable = True)
+ return [DefaultInfo(executable=output)]
+
+custom_test = rule(
+ implementation = _impl,
+ test = True,
+ attrs = {
+ "_lcov_merger": attr.label(
+ default = configuration_field(fragment = "coverage", name = "output_generator"),
+ cfg = "exec"
+ ),
+ },
+ fragments = ["coverage"],
+)
+EOF
+
+ cat <<EOF > BUILD
+load(":rules.bzl", "custom_test")
+
+custom_test(name = "foo_test")
+EOF
+
+ bazel test --test_output=all //:foo_test > $TEST_log \
+ || fail "Test run failed but should have succeeded."
+}
+
run_suite "test tests"
| val | val | 2022-03-07T19:44:40 | "2020-01-23T19:07:23Z" | keith | test |
bazelbuild/bazel/15385_15471 | bazelbuild/bazel | bazelbuild/bazel/15385 | bazelbuild/bazel/15471 | [
"keyword_pr_to_issue"
] | 41df581029abc844ec5e0bb73c434b7b71562dbf | 18d1ede3044364ade23a9ce6193900074a07db8d | [
"@gregestren , FYI.\r\n\r\nWhen I next have some free time I'll work on fixing this before the refactor. This is stopping us from upgrading.",
"I should clarify that this didn't happen in 4.2.2:\r\n```console\r\n$ bazel --nohome_rc coverage //:all --javabase=@bazel_tools//tools/jdk:remote_jdk11 --combined_report=lcov\r\nWARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:\r\n/home/pschrader/.bazelrc\r\nINFO: Using default value for --instrumentation_filter: \"^//\".\r\nINFO: Override the above default with --instrumentation_filter\r\nINFO: Build options --java_runtime_version and --javabase have changed, discarding analysis cache.\r\nERROR: Cannot generate coverage report - no coverage information was collected\r\nINFO: Analyzed 2 targets (4 packages loaded, 405 targets configured).\r\nINFO: Found 1 target and 1 test target...\r\nINFO: Elapsed time: 3.302s, Critical Path: 0.05s\r\nINFO: 2 processes: 1 internal, 1 linux-sandbox.\r\nINFO: Build completed successfully, 2 total actions\r\n//:example_test SKIPPED\r\n\r\nINFO: Build completed successfully, 2 total actions\r\n```",
"This bug affects my organization, we might have to downgrade to 4.2.\r\n\r\nI just checked and the issue is in 5.0.0 as well, it's not really a \"5.1\" bug as it says in the title. But I haven't tracked further than that to find a specific commit.",
"If you compile your own version, I think you can use this as a quick hack to work around the issue:\r\n```patch\r\ndiff --git a/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java b/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java\r\nindex 581a655a65..67afcb3ab0 100644\r\n--- a/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java\r\n+++ b/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java\r\n@@ -531,8 +531,9 @@ public class BuildView {\r\n\r\n Set<ConfiguredTarget> allTargetsToTest = null;\r\n if (testsToRun != null) {\r\n- // Determine the subset of configured targets that are meant to be run as tests.\r\n+ // Determine the subset of compatible configured targets that are meant to be run as tests.\r\n allTargetsToTest = filterTestsByTargets(configuredTargets, testsToRun);\r\n+ allTargetsToTest.removeAll(targetsToSkip);\r\n }\r\n\r\n ImmutableSet.Builder<Artifact> artifactsToBuild = ImmutableSet.builder();\r\n```\r\nThe problem is that this approach doesn't pass the skipped targets information to the final test reporter (`TerminalTestResultNotifier`). That means it'll skip the incompatible tests, but not report on them. A proper fix would pass the information through farther so the test reporter reports on both executed tests and skipped tests.",
"Thanks for the update! I don't think it's likely I can get go-ahead on deploying an inofficial Bazel version internally but it's good to hear that this is being worked on and that the problem is understood.\r\n\r\nDo you think a fix will be added to a 5.1.2 release in the near future (say, a couple of weeks)?",
"I'll start investigating to identify the cause, but I can't judge on the time to fix just yet.",
"@c-mita , WDYT about #15419?",
"I would like to understand the regression better before judging a fix.\r\n\r\nBisecting indicates that 5b216b27435aeb9eb9c3bd3c552d6498e1050cc7 triggered the regression (the flag flip for\r\n`--experimental_forward_instrumentation_files_info_by_default`).\r\n\r\nUnfortunately the flag was removed in 5.0, so there's no way of disabling this behaviour in that version.\r\n\r\nThis wouldn't be the first time the change activated by that flag has broken something, but at least this gives an indication of where something might be going wrong.\r\n\r\nFWIW, the provided reproduction only starts passing properly after ed01f42a8ff533967c8850821fd8058d38377ff1 (bisecting between 4.0.0 and 4.2.0).",
"So the cause of the regression is straight-forward.\r\n\r\nWhen 21179b2a82154b870ad8c5a7ad22b4662067cb29 added the check that forwards an `InstrumentedFilesInfo`, it changed the behaviour of the case of a test that normally provides its own but didn't because it was \"incompatible\".\r\n\r\nThis trips up the coverage code down the line.\r\n\r\nThe fix could either be what you've done in https://github.com/bazelbuild/bazel/pull/15419 or to change the check in `RuleConfiguredTargetBuilder::build` to also check for the existence of an `IncompatibleTargetProvider` and not create the forwarding `InstrumentedFilesInfo` in that case.\r\n\r\nI think I prefer the former as it strikes me as a little more \"robust\".\r\n"
] | [] | "2022-05-12T02:44:23Z" | [
"type: bug",
"coverage",
"team-Rules-CPP",
"untriaged"
] | bazel 5 `coverage --combined_report=lcov` executes incompatible actions | ### Description of the bug:
Running `bazel coverage --combined_report=lcov` does not properly skip incompatible tests.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
BUILD file:
```python
genrule(
name = "generate_example_test",
outs = ["example_test.cc"],
cmd = "echo 'int main() { return 1; }' > $(OUTS)",
)
cc_test(
name = "example_test",
srcs = ["example_test.cc"],
target_compatible_with = ["@platforms//:incompatible"],
)
```
Empty WORKSPACE file.
```console
$ bazel --nohome_rc coverage //:all --java_runtime_version=remotejdk_11 --combined_report=lcov
WARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:
/home/pschrader/.bazelrc
INFO: Using default value for --instrumentation_filter: "^//".
INFO: Override the above default with --instrumentation_filter
INFO: Analyzed 2 targets (0 packages loaded, 0 targets configured).
INFO: Found 1 target and 1 test target...
ERROR: /home/pschrader/work/test_repo/BUILD:7:8: Reporting failed target //:example_test located at /home/pschrader/work/test_repo/BUILD:7:8 failed: Can't build this. This target is incompatible. Please file a bug upstream. caused by //:example_test
INFO: Elapsed time: 0.433s, Critical Path: 0.01s
INFO: 4 processes: 4 internal.
FAILED: Build did NOT complete successfully
//:example_test SKIPPED
Executed 0 out of 1 test: 1 was skipped.
All tests passed but there were other errors during the build.
FAILED: Build did NOT complete successfully
```
### Which operating system are you running Bazel on?
x86 Ubuntu 18.04
### What is the output of `bazel info release`?
release 5.1.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
N/A
```
### Have you found anything relevant by searching the web?
I couldn't find a similar bug report.
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java"
] | [
"src/test/shell/bazel/BUILD",
"src/test/shell/bazel/bazel_coverage_compatibility_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD b/src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD
index 22091e04506b65..42078ebfd4b87e 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/bazel/coverage/BUILD
@@ -24,6 +24,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/analysis:analysis_cluster",
"//src/main/java/com/google/devtools/build/lib/analysis:blaze_directories",
"//src/main/java/com/google/devtools/build/lib/analysis:configured_target",
+ "//src/main/java/com/google/devtools/build/lib/analysis:incompatible_platform_provider",
"//src/main/java/com/google/devtools/build/lib/analysis:test/coverage_report_action_factory",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
"//src/main/java/com/google/devtools/build/lib/concurrent",
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java b/src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java
index 7b9c6206b23d40..2057361cf26273 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/coverage/CoverageReportActionBuilder.java
@@ -41,6 +41,7 @@
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
+import com.google.devtools.build.lib.analysis.IncompatiblePlatformProvider;
import com.google.devtools.build.lib.analysis.RunfilesSupport;
import com.google.devtools.build.lib.analysis.actions.Compression;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
@@ -200,6 +201,10 @@ public CoverageReportActionsWrapper createCoverageActionsWrapper(
ImmutableList.Builder<Artifact> builder = ImmutableList.<Artifact>builder();
FilesToRunProvider reportGenerator = null;
for (ConfiguredTarget target : targetsToTest) {
+ // Skip incompatible tests.
+ if (target.get(IncompatiblePlatformProvider.PROVIDER) != null) {
+ continue;
+ }
TestParams testParams = target.getProvider(TestProvider.class).getTestParams();
builder.addAll(testParams.getCoverageArtifacts());
if (reportGenerator == null) {
| diff --git a/src/test/shell/bazel/BUILD b/src/test/shell/bazel/BUILD
index 9b4cc0f52bc779..dbf578a9521c8d 100644
--- a/src/test/shell/bazel/BUILD
+++ b/src/test/shell/bazel/BUILD
@@ -582,6 +582,15 @@ sh_test(
],
)
+sh_test(
+ name = "bazel_coverage_compatibility_test",
+ srcs = ["bazel_coverage_compatibility_test.sh"],
+ data = [":test-deps"],
+ tags = [
+ "no_windows",
+ ],
+)
+
sh_test(
name = "bazel_cc_code_coverage_test",
srcs = ["bazel_cc_code_coverage_test.sh"],
diff --git a/src/test/shell/bazel/bazel_coverage_compatibility_test.sh b/src/test/shell/bazel/bazel_coverage_compatibility_test.sh
new file mode 100755
index 00000000000000..cb2089e0657f00
--- /dev/null
+++ b/src/test/shell/bazel/bazel_coverage_compatibility_test.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+#
+# Copyright 2022 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.
+
+set -eu
+
+# Load the test setup defined in the parent directory
+CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${CURRENT_DIR}/../integration_test_setup.sh" \
+ || { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+
+function set_up_sh_test_coverage() {
+ cat <<EOF > BUILD
+constraint_setting(name = "incompatible_setting")
+
+constraint_value(
+ name = "incompatible",
+ constraint_setting = ":incompatible_setting",
+)
+
+sh_test(
+ name = "compatible_test",
+ srcs = ["compatible_test.sh"],
+)
+
+sh_test(
+ name = "incompatible_test",
+ srcs = ["incompatible_test.sh"],
+ target_compatible_with = [":incompatible"],
+)
+EOF
+ cat <<EOF > compatible_test.sh
+#!/bin/bash
+exit 0
+EOF
+ cat <<EOF > incompatible_test.sh
+#!/bin/bash
+exit 1
+EOF
+ chmod +x compatible_test.sh
+ chmod +x incompatible_test.sh
+}
+
+# Validates that coverage skips incompatible tests. This is a regression test for
+# https://github.com/bazelbuild/bazel/issues/15385.
+function test_sh_test_coverage() {
+ set_up_sh_test_coverage
+ bazel coverage --test_output=all --combined_report=lcov //:all &>$TEST_log \
+ || fail "Coverage for //:all failed"
+ expect_log "INFO: Build completed successfully"
+ expect_log "//:compatible_test .* PASSED"
+ expect_log "//:incompatible_test .* SKIPPED"
+}
+
+run_suite "test tests"
| train | val | 2022-05-19T17:26:17 | "2022-05-02T20:10:58Z" | philsc | test |
bazelbuild/bazel/14459_15709 | bazelbuild/bazel | bazelbuild/bazel/14459 | bazelbuild/bazel/15709 | [
"keyword_pr_to_issue"
] | 106cf0b82f6c98342732fda3bbb2986d1435ea39 | 0b72c3838b443ae2cbeef8a9161d82d1f9c60d99 | [
"I believe it was waiting for xcode-locator, that can be super long if the machine has many Xcodes. \n\nTry this hack: https://www.smileykeith.com/2021/03/08/locking-xcode-in-bazel/",
"Thanks, I will try that. Do you think that this could also be related to Issue 2?",
"It could be, since that file is only created if Xcode is successfully detected.\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/b4b0c321910bc968736ef48e8140528ea7d323cd/tools/cpp/cc_configure.bzl#L73",
"@fmeum did @thii's suggestion fix the issue?",
"I just checked again and found no new failures in the two weeks since I started using a checked-in `xcode_version_config`. I will close this now as the workaround seems to have worked and open a new issue if it should show up again.",
"@sventiffe Reopening since the exact same issue appeared again today over at [rules_jni](https://github.com/fmeum/rules_jni).\r\n\r\nI started pinning with `--xcode_version_config` in https://github.com/fmeum/rules_jni/commit/b5021809cd5ea4393291d0d592b2f195c6f4e1f5. Today, [the runs](https://github.com/fmeum/rules_jni/runs/4823744403) on macos-latest with Bazel 4.0.0 and Bazel 5.0.0rc3 failed. I attached the [CI logs](https://github.com/bazelbuild/bazel/files/7874710/logs.zip), the failing step is [here](https://github.com/fmeum/rules_jni/blob/ff4e93e428869246f4779becd56b027bb13b3003/.github/workflows/run-tests-externally.yml#L75) with the message (in the case of Bazel 5.0.0rc3 with bzlmod):\r\n\r\n```\r\n2022/01/15 00:35:14 Downloading https://releases.bazel.build/4.0.0/release/bazel-4.0.0-darwin-x86_64...\r\nExtracting Bazel installation...\r\nStarting local Bazel server and connecting to it...\r\nINFO: Invocation ID: 0e7ba86d-1a19-4b3a-a770-f0c3d58d166f\r\nLoading: \r\nLoading: 0 packages loaded\r\nLoading: 11 packages loaded\r\n currently loading: analysis/cc_jni_library ... (2 packages)\r\nLoading: 11 packages loaded\r\n currently loading: analysis/cc_jni_library ... (2 packages)\r\nAnalyzing: 21 targets (13 packages loaded, 0 targets configured)\r\nAnalyzing: 21 targets (15 packages loaded, 1 target configured)\r\nAnalyzing: 21 targets (18 packages loaded, 8 targets configured)\r\nAnalyzing: 21 targets (18 packages loaded, 8 targets configured)\r\nAnalyzing: 21 targets (19 packages loaded, 8 targets configured)\r\nAnalyzing: 21 targets (21 packages loaded, 9 targets configured)\r\nAnalyzing: 21 targets (21 packages loaded, 9 targets configured)\r\nAnalyzing: 21 targets (21 packages loaded, 9 targets configured)\r\nAnalyzing: 21 targets (21 packages loaded, 9 targets configured)\r\nAnalyzing: 21 targets (21 packages loaded, 9 targets configured)\r\nAnalyzing: 21 targets (38 packages loaded, 206 targets configured)\r\nAnalyzing: 21 targets (38 packages loaded, 206 targets configured)\r\nAnalyzing: 21 targets (38 packages loaded, 206 targets configured)\r\nERROR: /Users/runner/work/rules_jni/rules_jni/tests/native_loader/src/test/java/com/example/math/BUILD.bazel:3:17: Target '//native_loader/src/test/java/com/example/math:math_remove_this_part_' depends on toolchain '@local_config_cc//:cc-compiler-darwin', which cannot be found: error loading package '@local_config_cc//': cannot load '@local_config_cc_toolchains//:osx_archs.bzl': no such file'\r\nERROR: Analysis of target '//native_loader/src/test/java/com/example/math:math' failed; build aborted: Analysis failed\r\nINFO: Elapsed time: 216.940s\r\nINFO: 0 processes.\r\nFAILED: Build did NOT complete successfully (39 packages loaded, 206 targets configured)\r\nERROR: Couldn't start the build. Unable to run tests\r\nFAILED: Build did NOT complete successfully (39 packages loaded, 206 targets configured)\r\nError: Process completed with exit code 1.\r\n```\r\n\r\n@thii Are there any additional diagnostics that I could enable that would help diagnose the underlying issue?",
"@keith I just encountered another failure and attached the [the logs](https://github.com/bazelbuild/bazel/files/8044694/rules_jni.log). They include the content of the BUILD file, which turns out not to be empty.\r\n",
"That file actually looks pretty good to me, since yours didn't fail with osx_archs import, it's because that file doesn't contain `darwin` https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/osx_archs.bzl\r\n\r\nI'm not sure where that's coming from but it should be darwin_x86_64 probably instead",
"> That file actually looks pretty good to me, since yours didn't fail with osx_archs import, it's because that file doesn't contain `darwin` https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/osx_archs.bzl\r\n> \r\n> I'm not sure where that's coming from but it should be darwin_x86_64 probably instead\r\n\r\nNice catch. I think I found the root cause and submitted a fix as https://github.com/bazelbuild/bazel/pull/14796.",
"Nice, I'll keep an eye on that. My assumption for why this is similar to the flaky CI case is because the toolchain only falls back to this codepath on macOS when Xcode cannot be found, which could happen in the case of a timeout running the discovery logic for that. This would likely workaround that issue if folks needed full Xcode in their cases https://www.smileykeith.com/2021/03/08/locking-xcode-in-bazel/"
] | [] | "2022-06-20T19:14:58Z" | [
"type: bug",
"more data needed",
"platform: apple"
] | High rate of spurious CI failures on macOS machines | <!--
ATTENTION! Please read and follow:
- if this is a _question_ about how to build / test / query / deploy using Bazel, or a _discussion starter_, send it to [email protected]
- if this is a _bug_ or _feature request_, fill the form below as best as you can.
-->
### Description of the problem / feature request:
I run daily CI checks in my rulesets' GitHub Actions pipeline. The macOS pipelines, running on `macos-latest`, fail every few days with two kinds of spurious failures that I have never been able to reproduce locally:
Issue 1:
```
Starting local Bazel server and connecting to it...
... still trying to connect to local Bazel server after 10 seconds ...
... still trying to connect to local Bazel server after 20 seconds ...
... still trying to connect to local Bazel server after 30 seconds ...
... still trying to connect to local Bazel server after 40 seconds ...
... still trying to connect to local Bazel server after 50 seconds ...
... still trying to connect to local Bazel server after 60 seconds ...
... still trying to connect to local Bazel server after 70 seconds ...
... still trying to connect to local Bazel server after 80 seconds ...
... still trying to connect to local Bazel server after 90 seconds ...
... still trying to connect to local Bazel server after 100 seconds ...
... still trying to connect to local Bazel server after 110 seconds ...
FATAL: couldn't connect to server (1753) after 120 seconds.
Error: Process completed with exit code 37.
```
Issue 2:
```
ERROR: /Users/runner/work/rules_jni/rules_jni/tests/libjvm_stub/BUILD.bazel:116:12: Target '//libjvm_stub:HelloFromJava' depends on toolchain '@local_config_cc//:cc-compiler-darwin', which cannot be found: error loading package '@local_config_cc//': cannot load '@local_config_cc_toolchains//:osx_archs.bzl': no such file'
ERROR: Analysis of target '//libjvm_stub:HelloFromJava' failed; build aborted: Analysis failed
```
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
I have no way to consistently reproduce this issue, but it happens every few days on [rules_jni's CI schedule](https://github.com/fmeum/rules_jni/blob/main/.github/workflows/run-tests-externally.yml).
### What operating system are you running Bazel on?
macOS 10.15
### What's the output of `bazel info release`?
Over time, I have hit the issues on 4.2.2, 5.0.0rc3 and various last_green builds.
### Have you found anything relevant by searching the web?
* https://github.com/bazelbuild/rules_go/issues/2221
* https://github.com/grailbio/bazel-toolchain/pull/75#issuecomment-775818020
### Any other information, logs, or outputs that you want to share?
I can make arbitrary changes to the CI config if that helps to gather more information on the cause of these issues. | [
"tools/osx/crosstool/BUILD.tpl"
] | [
"tools/osx/crosstool/BUILD.tpl"
] | [] | diff --git a/tools/osx/crosstool/BUILD.tpl b/tools/osx/crosstool/BUILD.tpl
index e80dffbd1db909..15230207a0f357 100644
--- a/tools/osx/crosstool/BUILD.tpl
+++ b/tools/osx/crosstool/BUILD.tpl
@@ -80,6 +80,14 @@ cc_toolchain_suite(
for arch in OSX_TOOLS_ARCHS
]
+# When xcode_locator fails and causes cc_autoconf_toolchains to fall back
+# to the non-Xcode C++ toolchain, it uses the legacy cpu value to refer to
+# the toolchain, which is "darwin" for x86_64 macOS.
+alias(
+ name = "cc-compiler-darwin",
+ actual = ":cc-compiler-darwin_x86_64",
+)
+
[
cc_toolchain_config(
name = arch,
| null | test | val | 2022-06-21T17:43:39 | "2021-12-21T08:10:31Z" | fmeum | test |
bazelbuild/bazel/15729_15787 | bazelbuild/bazel | bazelbuild/bazel/15729 | bazelbuild/bazel/15787 | [
"keyword_pr_to_issue"
] | 240e3d1e1dbc74c7753dead6421d7c1b5fc28d09 | e7efa1f47905c2a96fc5b0f2fdd51d872090130a | [
"Hello @xhebox, Could you please provide complete steps to reproduce the above issue at our end. Thanks! ",
"> Hello @xhebox, Could you please provide complete steps to reproduce the above issue at our end. Thanks!\r\n\r\nEdited, it really needs nothing more than normal building instructions. You could try this on alpine linux with docker. I am on my own custom linux distro with musl libc.",
"I will send a patch removing the strdupa, since there is exactly one usage in whole of bazel.",
"@bazel-io flag",
"@bazel-io fork 5.3.0"
] | [] | "2022-07-01T15:14:49Z" | [
"P3",
"type: support / not a bug (process)",
"team-OSS",
"help wanted"
] | g++ fpermissive compilation error for strdupa on musl when buiding from source | ### Description of the bug:
g++ will report errors as follows:
```
In file included from src/main/tools/linux-sandbox-pid1.cc:34:
src/main/tools/linux-sandbox-pid1.cc: In function ‘int CreateTarget(const char*, bool)’:
src/main/tools/linux-sandbox-pid1.cc:149:28: error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
149 | if (CreateTarget(dirname(strdupa(path)), true) < 0) {
| ^
| |
| void*
In file included from src/main/tools/linux-sandbox-pid1.cc:34:
/include/string.h:33:15: note: initializing argument 1 of ‘char* strcpy(char*, const char*)’
33 | char *strcpy (char *__restrict, const char *__restrict);
| ^~~~~~~~~~~~~~~~
In file included from src/main/tools/linux-sandbox-pid1.cc:67:
src/main/tools/linux-sandbox-pid1.cc:150:36: error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
150 | DIE("CreateTarget %s", dirname(strdupa(path)));
| ^
| |
| void*
./src/main/tools/logging.h:36:51: note: in definition of macro ‘DIE’
36 | fprintf(stderr, __FILE__ ":" S__LINE__ ": \"" __VA_ARGS__); \
| ^~~~~~~~~~~
In file included from src/main/tools/linux-sandbox-pid1.cc:34:
/include/string.h:33:15: note: initializing argument 1 of ‘char* strcpy(char*, const char*)’
33 | char *strcpy (char *__restrict, const char *__restrict);
```
I've sent patches to musl, ref [this](https://www.openwall.com/lists/musl/2022/06/22/1). Despite whether musl will accept the patch, I agreed with the author of musl that using strdupa is probably not a good idea. And we have other replacement.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Build bazel 5.2.0 on musl by:
```
curl -O -L https://github.com/bazelbuild/bazel/releases/download/5.2.0/bazel-5.2.0-dist.zip
7z x bazel-5.2.0.zip
EXTRA_BAZEL_ARGS="--tool_java_runtime_version=local_jdk" ./compile.sh
```
You could try this on an docker alpine linux image.
### Which operating system are you running Bazel on?
linux with musl libc
### What is the output of `bazel info release`?
_No response_
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/tools/linux-sandbox-pid1.cc"
] | [
"src/main/tools/linux-sandbox-pid1.cc"
] | [] | diff --git a/src/main/tools/linux-sandbox-pid1.cc b/src/main/tools/linux-sandbox-pid1.cc
index b6f4f3d665a758..9ec785d03e8623 100644
--- a/src/main/tools/linux-sandbox-pid1.cc
+++ b/src/main/tools/linux-sandbox-pid1.cc
@@ -146,8 +146,17 @@ static int CreateTarget(const char *path, bool is_directory) {
}
// Create the parent directory.
- if (CreateTarget(dirname(strdupa(path)), true) < 0) {
- DIE("CreateTarget %s", dirname(strdupa(path)));
+ {
+ char *buf, *dir;
+
+ if (!(buf = strdup(path))) DIE("strdup");
+
+ dir = dirname(buf);
+ if (CreateTarget(dir, true) < 0) {
+ DIE("CreateTarget %s", dir);
+ }
+
+ free(buf);
}
if (is_directory) {
| null | train | val | 2022-07-01T23:07:36 | "2022-06-23T03:32:10Z" | xhebox | test |
bazelbuild/bazel/15682_15842 | bazelbuild/bazel | bazelbuild/bazel/15682 | bazelbuild/bazel/15842 | [
"keyword_pr_to_issue"
] | 06ca634e10f17023022ab591a55aabdd9fb57b12 | 40e485dc67d8d3a8cdda096e2dd793335a3344cf | [
"people are reporting this is causing the issue\r\n\r\nhttps://bazelbuild.slack.com/archives/CA31HN1T3/p1655638147979559?thread_ts=1655544708.176529&cid=CA31HN1T3\r\n\r\nhttps://github.com/bazelbuild/bazel/commit/4d900ceea12919ad62012830a95e51f9ec1a48bb",
"@coeuvre ",
"What's error message looks like? Does it also the case for HEAD?",
"I am not sure, it seems the cache is not uploading artifacts in certain scenarios, there are no diagnostic messages. I can't tell if people reporting the issues are only using http caching though, but the person in the slack thread and this report are both using http cache.",
"I also confirm this is a problem. We didn't notice at the beginning of the upgrade as we were using the previously populated remote cache but after a couple of days we were having mostly cache misses and less and less cache hits. The problem happens both when using the buildbuddy grpc cache or a simple GCS Bucket. Reverting to 5.1.1 makes everything working again.",
"I am not able to reproduce this locally. Do you know which actions are not uploading artifacts? ",
"@coeuvre it actually happens in rules from `rules_nodejs` we are using like `TsProject` https://github.com/bazelbuild/rules_nodejs/blob/stable/packages/typescript/index.bzl#L109",
"We reverted back to 5.1.1 due to this, however we do not use `rules_nodejs` (mainly `java_library` and `genrule`).\r\n\r\nWe noticed because the bazel-remote logs were **all** GET 404.",
"> \r\n\r\nSame error.",
"@nickbreen Are you using directory inputs/outputs? `rules_nodejs` does and 5.2 includes https://github.com/bazelbuild/bazel/commit/26f878325e915e0905626a0e4c8bbacffd72f875, but if you are facing the same issues without relying on TreeArtifacts, then that commit is less likely to be the culprit (which would make it rather likely it's actually https://github.com/bazelbuild/bazel/commit/4d900ceea12919ad62012830a95e51f9ec1a48bb).",
"We have various rules using TreeArtifacts (`ctx.actions.declare_directory`) and rules that produce a directory output using `ctx.outputs` and genrules doing the same.",
"We have also noticed this similar bug where caching seems to have broken on 5.2.0. When I was tracing the request logs something seemed odd in terms of the action cache `GET` missing and content addressable `PUT`. I could be missing a detail here, maybe this will help narrow down to what other folks might be seeing.\r\n\r\n\r\nBefore doing a build there is a miss on the action cache `GET 404 127.0.0.1 /ac/877dcafd4dc610e6cc734aa39f91aaf9a8e9a7f730e5bd1021c557c5c74bfda5` \r\nhttps://gist.github.com/adam-singer/0c73500e47d1a2410924dc5be4da0a3a#file-gistfile1-txt-L1 \r\n\r\nBazel/rules go along their business and build/calculate results, then I would assume that the next time `877dcafd4dc610e6cc734aa39f91aaf9a8e9a7f730e5bd1021c557c5c74bfda5` is seen in the request logs it would be a `PUT` to `/ac/877dcafd4dc610e6cc734aa39f91aaf9a8e9a7f730e5bd1021c557c5c74bfda5`, but what I've seen in our request logs is the remote uploader is making the request to `PUT 200 127.0.0.1 /cas/877dcafd4dc610e6cc734aa39f91aaf9a8e9a7f730e5bd1021c557c5c74bfda5` https://gist.github.com/adam-singer/0c73500e47d1a2410924dc5be4da0a3a#file-gistfile1-txt-L62 the content addressable cache.\r\n\r\nCould someone confirm or verify seeing similar behavior and if that is expected? \r\n\r\n**Edit:**\r\n\r\nhttps://github.com/bazelbuild/bazel/commit/4d900ceea12919ad62012830a95e51f9ec1a48bb#diff-5556e28152f91eac5403663774979225b86e64133da164366b56f91d1daa641cR536 The `Step` is set `action.getRemoteActionExecutionContext().setStep(Step.CHECK_ACTION_CACHE);` but when comes time to upload via `DiskAndRemoteCacheClient.uploadActionResult` https://github.com/bazelbuild/bazel/commit/4d900ceea12919ad62012830a95e51f9ec1a48bb#diff-f826b1e1a71d4a2d9f9524894df3069dcb54964998277721021093ff7d55d194R62 the check is for `Step.UPLOAD_OUTPUTS`, that seems to be the reason uploading to action cache isn't happening.\r\n\r\n<img width=\"1469\" alt=\"Screen Shot 2022-07-05 at 10 55 07 PM\" src=\"https://user-images.githubusercontent.com/654526/177479745-75124c77-c2ef-4dd5-9153-dc31b35ce19e.png\">\r\n\r\nThis patch fixed uploading to action cache https://gist.github.com/adam-singer/6500f268885f1c2c604fd4f9f1fec439, would prefer if owners verify/confirm bug."
] | [] | "2022-07-08T11:28:19Z" | [
"type: bug",
"untriaged",
"team-Remote-Exec"
] | Remote-cache not work in 5.2.0 | ### Description of the bug:
When upgrade to the latest version of bazel. Bazel remote seems not to work. Bazel can only put but can not get. When use bazel 5.1.1 bazel remote works again. More strange, bazel 5.2.0 can use the cache of 5.1.1. It seems that the artifact put by bazel 5.2 has problem.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Use bazel 5.2.0 and use `https://github.com/buchgr/bazel-remote` as remote cache like `bazel build --remote_cache=http://localhost:9090`
### Which operating system are you running Bazel on?
Ubuntu 20.04
### What is the output of `bazel info release`?
release 5.2.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java"
] | [
"src/test/shell/bazel/remote/remote_execution_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java
index 2b92eac6832932..e94875ec9e3f6a 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java
@@ -1240,6 +1240,8 @@ public void uploadOutputs(RemoteAction action, SpawnResult spawnResult)
SpawnResult.Status.SUCCESS.equals(spawnResult.status()) && spawnResult.exitCode() == 0,
"shouldn't upload outputs of failed local action");
+ action.getRemoteActionExecutionContext().setStep(Step.UPLOAD_OUTPUTS);
+
if (remoteOptions.remoteCacheAsync) {
Single.using(
remoteCache::retain,
| diff --git a/src/test/shell/bazel/remote/remote_execution_test.sh b/src/test/shell/bazel/remote/remote_execution_test.sh
index c215615c12255a..f45f93dbb2f361 100755
--- a/src/test/shell/bazel/remote/remote_execution_test.sh
+++ b/src/test/shell/bazel/remote/remote_execution_test.sh
@@ -2429,6 +2429,33 @@ EOF
rm -rf $cache
}
+function test_combined_cache_upload() {
+ mkdir -p a
+ echo 'bar' > a/bar
+ cat > a/BUILD <<'EOF'
+genrule(
+ name = "foo",
+ srcs = [":bar"],
+ outs = ["foo.txt"],
+ cmd = """
+ echo $(location :bar) > "$@"
+ """,
+)
+EOF
+
+ CACHEDIR=$(mktemp -d)
+
+ bazel build \
+ --disk_cache=$CACHEDIR \
+ --remote_cache=grpc://localhost:${worker_port} \
+ //a:foo >& $TEST_log || "Failed to build //a:foo"
+
+ remote_ac_files="$(count_remote_ac_files)"
+ [[ "$remote_ac_files" == 1 ]] || fail "Expected 1 remote action cache entries, not $remote_ac_files"
+ remote_cas_files="$(count_remote_cas_files)"
+ [[ "$remote_cas_files" == 3 ]] || fail "Expected 3 remote cas entries, not $remote_cas_files"
+}
+
function test_combined_cache_with_no_remote_cache_tag_remote_cache() {
# Test that actions with no-remote-cache tag can hit disk cache of a combined cache but
# remote cache is disabled.
| val | val | 2022-07-14T06:24:32 | "2022-06-15T13:00:28Z" | Smile-Autra | test |
bazelbuild/bazel/14526_15883 | bazelbuild/bazel | bazelbuild/bazel/14526 | bazelbuild/bazel/15883 | [
"keyword_pr_to_issue"
] | 78af34f9f25b0c8fbf597a794a5162f0014629c5 | dc65cffdc050993aab1ffb6373e1498810a92e81 | [
"@meteorcloudy ",
"/cc @Wyverald ",
"Yeah there's a bunch of quality-of-life changes we should make around the Starlark-running part of bzlmod before official launch.",
"This goes even further: If a module extension specifies incorrect attributes for a repository rule, an error is printed but the build doesn't fail."
] | [] | "2022-07-14T16:33:45Z" | [
"type: feature request",
"P3",
"team-ExternalDeps",
"area-Bzlmod"
] | `print` in a module appears to be different from `print` in a workspace rule | ### Description of the problem / feature request:
`print` appears to behave differently between workspace rules and when used in a module.
When called from a workspace, the output of `print` is prefixed by a `DEBUG` statement, and then the path to the file, whereas this is missing when the same function is called from a module.
### What's the output of `bazel info release`?
5.0.0rc3
### Any other information, logs, or outputs that you want to share?
The way that `print` works when called from a workspace is nicer: it makes the output easy to identify and it's easy to grep for. | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
index 889f85ef5f40ab..cd85ff18046bbb 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
@@ -86,6 +86,7 @@ public void setRepositoryRemoteExecutor(RepositoryRemoteExecutor repositoryRemot
this.repositoryRemoteExecutor = repositoryRemoteExecutor;
}
+ @Nullable
@Override
public SkyValue compute(SkyKey skyKey, Environment env)
throws SkyFunctionException, InterruptedException {
@@ -161,6 +162,7 @@ public SkyValue compute(SkyKey skyKey, Environment env)
try (Mutability mu =
Mutability.create("module extension", usagesValue.getExtensionUniqueName())) {
StarlarkThread thread = new StarlarkThread(mu, starlarkSemantics);
+ thread.setPrintHandler(Event.makeDebugPrintHandler(env.getListener()));
ModuleExtensionContext moduleContext =
createContext(env, usagesValue, starlarkSemantics, extension);
threadContext.storeInThread(thread);
| null | train | val | 2022-07-14T21:24:53 | "2022-01-07T16:27:02Z" | shs96c | test |
bazelbuild/bazel/15856_15900 | bazelbuild/bazel | bazelbuild/bazel/15856 | bazelbuild/bazel/15900 | [
"keyword_pr_to_issue"
] | dc65cffdc050993aab1ffb6373e1498810a92e81 | 7bbdddd1f6148bc2d2efcbff761404bbadea2f9e | [
"@bazel-io flag",
"@bazel-io fork 5.3.0",
"Since this feature is implemented and cherry picked to 5.3.0, should we close this one?",
"The proposal hasn't been fully implemented yet (e.g. we're missing support for repository fetching).",
"Marking this as a release blocker since we want the repository fetching support to make it into 6.0.0 if possible.",
"@tjgq What's the ETA for implementing this? Ideally, we don't want to delay the 6.0 release further more, and since this should be a backwards compatible feature, we can cherry pick it in 6.x releases?",
"I was planning to get this submitted in time for 6.0.0, but other things got in the way. Let's do it for a 6.x release instead.",
"This has been fully implemented in 7.x and backported to 6.x."
] | [] | "2022-07-18T07:01:13Z" | [
"type: feature request",
"P2",
"team-Remote-Exec"
] | Implement the credential helpers proposal | ### Description of the feature request:
Tracking issue for implementing https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md.
### What underlying problem are you trying to solve with this feature?
N/A
### Which operating system are you running Bazel on?
N/A
### What is the output of `bazel info release`?
N/A
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
N/A
```
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java"
] | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperEnvironment.java",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java"
] | [
"src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD",
"src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperTest.java",
"src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/test_credential_helper.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
index 745e6eaebae2b7..8b11bce467a160 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
@@ -14,6 +14,8 @@ java_library(
name = "credentialhelper",
srcs = glob(["*.java"]),
deps = [
+ "//src/main/java/com/google/devtools/build/lib/events",
+ "//src/main/java/com/google/devtools/build/lib/shell",
"//src/main/java/com/google/devtools/build/lib/vfs",
"//third_party:auto_value",
"//third_party:error_prone_annotations",
diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
index c6b60b1fb1a0b4..c82417b0034383 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
@@ -14,14 +14,32 @@
package com.google.devtools.build.lib.authandtls.credentialhelper;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.CharStreams;
+import com.google.devtools.build.lib.shell.Subprocess;
+import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.vfs.Path;
import com.google.errorprone.annotations.Immutable;
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.URI;
+import java.util.Locale;
+import java.util.Objects;
/** Wraps an external tool used to obtain credentials. */
@Immutable
public final class CredentialHelper {
+ private static final Gson GSON = new Gson();
+
// `Path` is immutable, but not annotated.
@SuppressWarnings("Immutable")
private final Path path;
@@ -35,5 +53,101 @@ Path getPath() {
return path;
}
- // TODO(yannic): Implement running the helper subprocess.
+ /**
+ * Fetches credentials for the specified {@link URI} by invoking the credential helper as
+ * subprocess according to the <a
+ * href="https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md">credential
+ * helper protocol</a>.
+ *
+ * @param environment The environment to run the subprocess in.
+ * @param uri The {@link URI} to fetch credentials for.
+ * @return The response from the subprocess.
+ */
+ public GetCredentialsResponse getCredentials(CredentialHelperEnvironment environment, URI uri)
+ throws InterruptedException, IOException {
+ Preconditions.checkNotNull(environment);
+ Preconditions.checkNotNull(uri);
+
+ Subprocess process = spawnSubprocess(environment, "get");
+ try (Reader stdout = new InputStreamReader(process.getInputStream(), UTF_8);
+ Reader stderr = new InputStreamReader(process.getErrorStream(), UTF_8)) {
+ try (Writer stdin = new OutputStreamWriter(process.getOutputStream(), UTF_8)) {
+ GSON.toJson(GetCredentialsRequest.newBuilder().setUri(uri).build(), stdin);
+ }
+
+ process.waitFor();
+ if (process.timedout()) {
+ throw new IOException(
+ String.format(
+ Locale.US,
+ "Failed to get credentials for '%s' from helper '%s': process timed out",
+ uri,
+ path));
+ }
+ if (process.exitValue() != 0) {
+ throw new IOException(
+ String.format(
+ Locale.US,
+ "Failed to get credentials for '%s' from helper '%s': process exited with code %d."
+ + " stderr: %s",
+ uri,
+ path,
+ process.exitValue(),
+ CharStreams.toString(stderr)));
+ }
+
+ try {
+ GetCredentialsResponse response = GSON.fromJson(stdout, GetCredentialsResponse.class);
+ if (response == null) {
+ throw new IOException(
+ String.format(
+ Locale.US,
+ "Failed to get credentials for '%s' from helper '%s': process exited without"
+ + " output. stderr: %s",
+ uri,
+ path,
+ CharStreams.toString(stderr)));
+ }
+ return response;
+ } catch (JsonSyntaxException e) {
+ throw new IOException(
+ String.format(
+ Locale.US,
+ "Failed to get credentials for '%s' from helper '%s': error parsing output. stderr:"
+ + " %s",
+ uri,
+ path,
+ CharStreams.toString(stderr)),
+ e);
+ }
+ }
+ }
+
+ private Subprocess spawnSubprocess(CredentialHelperEnvironment environment, String... args)
+ throws IOException {
+ Preconditions.checkNotNull(environment);
+ Preconditions.checkNotNull(args);
+
+ return new SubprocessBuilder()
+ .setArgv(ImmutableList.<String>builder().add(path.getPathString()).add(args).build())
+ .setWorkingDirectory(environment.getWorkspacePath().getPathFile())
+ .setEnv(environment.getClientEnvironment())
+ .setTimeoutMillis(environment.getHelperExecutionTimeout().toMillis())
+ .start();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof CredentialHelper) {
+ CredentialHelper that = (CredentialHelper) o;
+ return Objects.equals(this.getPath(), that.getPath());
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(getPath());
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperEnvironment.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperEnvironment.java
new file mode 100644
index 00000000000000..e2ae01c190b3da
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperEnvironment.java
@@ -0,0 +1,75 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.authandtls.credentialhelper;
+
+import com.google.auto.value.AutoValue;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.events.Reporter;
+import com.google.devtools.build.lib.vfs.Path;
+import java.time.Duration;
+
+/** Environment for running {@link CredentialHelper}s in. */
+@AutoValue
+public abstract class CredentialHelperEnvironment {
+ /** Returns the reporter for reporting events related to {@link CredentialHelper}s. */
+ public abstract Reporter getEventReporter();
+
+ /**
+ * Returns the (absolute) path to the workspace.
+ *
+ * <p>Used as working directory when invoking the subprocess.
+ */
+ public abstract Path getWorkspacePath();
+
+ /**
+ * Returns the environment from the Bazel client.
+ *
+ * <p>Passed as environment variables to the subprocess.
+ */
+ public abstract ImmutableMap<String, String> getClientEnvironment();
+
+ /** Returns the execution timeout for the helper subprocess. */
+ public abstract Duration getHelperExecutionTimeout();
+
+ /** Returns a new builder for {@link CredentialHelperEnvironment}. */
+ public static CredentialHelperEnvironment.Builder newBuilder() {
+ return new AutoValue_CredentialHelperEnvironment.Builder();
+ }
+
+ /** Builder for {@link CredentialHelperEnvironment}. */
+ @AutoValue.Builder
+ public abstract static class Builder {
+ /** Sets the reporter for reporting events related to {@link CredentialHelper}s. */
+ public abstract Builder setEventReporter(Reporter reporter);
+
+ /**
+ * Sets the (absolute) path to the workspace to use as working directory when invoking the
+ * subprocess.
+ */
+ public abstract Builder setWorkspacePath(Path path);
+
+ /**
+ * Sets the environment from the Bazel client to pass as environment variables to the
+ * subprocess.
+ */
+ public abstract Builder setClientEnvironment(ImmutableMap<String, String> environment);
+
+ /** Sets the execution timeout for the helper subprocess. */
+ public abstract Builder setHelperExecutionTimeout(Duration timeout);
+
+ /** Returns the newly constructed {@link CredentialHelperEnvironment}. */
+ public abstract CredentialHelperEnvironment build();
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java
index 72f25cf4ddf196..6d450e001fb682 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/GetCredentialsResponse.java
@@ -50,7 +50,7 @@ public static Builder newBuilder() {
/** Builder for {@link GetCredentialsResponse}. */
@AutoValue.Builder
public abstract static class Builder {
- protected abstract ImmutableMap.Builder<String, ImmutableList<String>> headersBuilder();
+ public abstract ImmutableMap.Builder<String, ImmutableList<String>> headersBuilder();
/** Returns the newly constructed {@link GetCredentialsResponse}. */
public abstract GetCredentialsResponse build();
| diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
index 95b3ee4483cdc9..024763f7c1dd63 100644
--- a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/BUILD
@@ -17,12 +17,17 @@ filegroup(
java_test(
name = "credentialhelper",
srcs = glob(["*.java"]),
+ data = [
+ ":test_credential_helper",
+ ],
test_class = "com.google.devtools.build.lib.AllTests",
runtime_deps = [
"//src/test/java/com/google/devtools/build/lib:test_runner",
],
deps = [
"//src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper",
+ "//src/main/java/com/google/devtools/build/lib/events",
+ "//src/main/java/com/google/devtools/build/lib/util:os",
"//src/main/java/com/google/devtools/build/lib/vfs",
"//src/main/java/com/google/devtools/build/lib/vfs:pathfragment",
"//src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs",
@@ -30,5 +35,11 @@ java_test(
"//third_party:guava",
"//third_party:junit4",
"//third_party:truth",
+ "@bazel_tools//tools/java/runfiles",
],
)
+
+py_binary(
+ name = "test_credential_helper",
+ srcs = ["test_credential_helper.py"],
+)
diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperTest.java b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperTest.java
new file mode 100644
index 00000000000000..4aeb4595b084d0
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperTest.java
@@ -0,0 +1,143 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.authandtls.credentialhelper;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertThrows;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.eventbus.EventBus;
+import com.google.devtools.build.lib.events.Reporter;
+import com.google.devtools.build.lib.util.OS;
+import com.google.devtools.build.lib.vfs.DigestHashFunction;
+import com.google.devtools.build.lib.vfs.FileSystem;
+import com.google.devtools.build.lib.vfs.PathFragment;
+import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
+import com.google.devtools.build.runfiles.Runfiles;
+import java.io.IOException;
+import java.net.URI;
+import java.time.Duration;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class CredentialHelperTest {
+ private static final PathFragment TEST_WORKSPACE_PATH =
+ PathFragment.create(System.getenv("TEST_TMPDIR"));
+ private static final PathFragment TEST_CREDENTIAL_HELPER_PATH =
+ PathFragment.create(
+ "io_bazel/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/test_credential_helper"
+ + (OS.getCurrent() == OS.WINDOWS ? ".exe" : ""));
+
+ private static final Reporter reporter = new Reporter(new EventBus());
+
+ private GetCredentialsResponse getCredentialsFromHelper(
+ String uri, ImmutableMap<String, String> env) throws Exception {
+ Preconditions.checkNotNull(uri);
+ Preconditions.checkNotNull(env);
+
+ FileSystem fs = new InMemoryFileSystem(DigestHashFunction.SHA256);
+
+ CredentialHelper credentialHelper =
+ new CredentialHelper(
+ fs.getPath(
+ Runfiles.create().rlocation(TEST_CREDENTIAL_HELPER_PATH.getSafePathString())));
+ return credentialHelper.getCredentials(
+ CredentialHelperEnvironment.newBuilder()
+ .setEventReporter(reporter)
+ .setWorkspacePath(fs.getPath(TEST_WORKSPACE_PATH))
+ .setClientEnvironment(env)
+ .setHelperExecutionTimeout(Duration.ofSeconds(5))
+ .build(),
+ URI.create(uri));
+ }
+
+ private GetCredentialsResponse getCredentialsFromHelper(String uri) throws Exception {
+ Preconditions.checkNotNull(uri);
+
+ return getCredentialsFromHelper(uri, ImmutableMap.of());
+ }
+
+ @Test
+ public void knownUriWithSingleHeader() throws Exception {
+ GetCredentialsResponse response = getCredentialsFromHelper("https://singleheader.example.com");
+ assertThat(response.getHeaders()).containsExactly("header1", ImmutableList.of("value1"));
+ }
+
+ @Test
+ public void knownUriWithMultipleHeaders() throws Exception {
+ GetCredentialsResponse response =
+ getCredentialsFromHelper("https://multipleheaders.example.com");
+ assertThat(response.getHeaders())
+ .containsExactly(
+ "header1",
+ ImmutableList.of("value1"),
+ "header2",
+ ImmutableList.of("value1", "value2"),
+ "header3",
+ ImmutableList.of("value1", "value2", "value3"));
+ }
+
+ @Test
+ public void unknownUri() {
+ IOException ioException =
+ assertThrows(
+ IOException.class, () -> getCredentialsFromHelper("https://unknown.example.com"));
+ assertThat(ioException).hasMessageThat().contains("Unknown uri 'https://unknown.example.com'");
+ }
+
+ @Test
+ public void credentialHelperOutputsNothing() throws Exception {
+ IOException ioException =
+ assertThrows(
+ IOException.class, () -> getCredentialsFromHelper("https://printnothing.example.com"));
+ assertThat(ioException).hasMessageThat().contains("exited without output");
+ }
+
+ @Test
+ public void credentialHelperOutputsExtraFields() throws Exception {
+ GetCredentialsResponse response = getCredentialsFromHelper("https://extrafields.example.com");
+ assertThat(response.getHeaders()).containsExactly("header1", ImmutableList.of("value1"));
+ }
+
+ @Test
+ public void helperRunsInWorkspace() throws Exception {
+ GetCredentialsResponse response = getCredentialsFromHelper("https://cwd.example.com");
+ ImmutableMap<String, ImmutableList<String>> headers = response.getHeaders();
+ assertThat(PathFragment.create(headers.get("cwd").get(0))).isEqualTo(TEST_WORKSPACE_PATH);
+ }
+
+ @Test
+ public void helperGetEnvironment() throws Exception {
+ GetCredentialsResponse response =
+ getCredentialsFromHelper(
+ "https://env.example.com", ImmutableMap.of("FOO", "BAR!", "BAR", "123"));
+ assertThat(response.getHeaders())
+ .containsExactly(
+ "foo", ImmutableList.of("BAR!"),
+ "bar", ImmutableList.of("123"));
+ }
+
+ @Test
+ public void helperTimeout() throws Exception {
+ IOException ioException =
+ assertThrows(
+ IOException.class, () -> getCredentialsFromHelper("https://timeout.example.com"));
+ assertThat(ioException).hasMessageThat().contains("process timed out");
+ }
+}
diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/test_credential_helper.py b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/test_credential_helper.py
new file mode 100644
index 00000000000000..c21fd7b22524e6
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/test_credential_helper.py
@@ -0,0 +1,92 @@
+# Copyright 2022 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.
+"""Credential helper for testing."""
+
+import json
+import os
+import sys
+import time
+
+
+def eprint(*args, **kargs):
+ print(*args, file=sys.stderr, **kargs)
+
+
+def main(argv):
+ if len(argv) != 2:
+ eprint("Usage: test_credential_helper <command>")
+ return 1
+
+ if argv[1] != "get":
+ eprint("Unknown command '{}'".format(argv[1]))
+ return 1
+
+ request = json.load(sys.stdin)
+ if request["uri"] == "https://singleheader.example.com":
+ response = {
+ "headers": {
+ "header1": ["value1"],
+ },
+ }
+ elif request["uri"] == "https://multipleheaders.example.com":
+ response = {
+ "headers": {
+ "header1": ["value1"],
+ "header2": ["value1", "value2"],
+ "header3": ["value1", "value2", "value3"],
+ },
+ }
+ elif request["uri"] == "https://extrafields.example.com":
+ response = {
+ "foo": "YES",
+ "headers": {
+ "header1": ["value1"],
+ },
+ "umlaut": [
+ "ß",
+ "å",
+ ],
+ }
+ elif request["uri"] == "https://printnothing.example.com":
+ return 0
+ elif request["uri"] == "https://cwd.example.com":
+ response = {
+ "headers": {
+ "cwd": [os.getcwd()],
+ },
+ }
+ elif request["uri"] == "https://env.example.com":
+ response = {
+ "headers": {
+ "foo": [os.getenv("FOO")],
+ "bar": [os.getenv("BAR")],
+ },
+ }
+ elif request["uri"] == "https://timeout.example.com":
+ # We expect the subprocess to be killed after 5s.
+ time.sleep(10)
+ response = {
+ "headers": {
+ "header1": ["value1"],
+ },
+ }
+ else:
+ eprint("Unknown uri '{}'".format(request["uri"]))
+ return 1
+ json.dump(response, sys.stdout)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
| train | val | 2022-07-15T07:13:13 | "2022-07-11T15:16:11Z" | tjgq | test |
bazelbuild/bazel/15856_15929 | bazelbuild/bazel | bazelbuild/bazel/15856 | bazelbuild/bazel/15929 | [
"keyword_pr_to_issue"
] | 9c2c3dee089231b0aac3de9f62bc80a896d531b8 | 05e758d4bc18fc9d9e189526381a06e4399056a2 | [
"@bazel-io flag",
"@bazel-io fork 5.3.0",
"Since this feature is implemented and cherry picked to 5.3.0, should we close this one?",
"The proposal hasn't been fully implemented yet (e.g. we're missing support for repository fetching).",
"Marking this as a release blocker since we want the repository fetching support to make it into 6.0.0 if possible.",
"@tjgq What's the ETA for implementing this? Ideally, we don't want to delay the 6.0 release further more, and since this should be a backwards compatible feature, we can cherry pick it in 6.x releases?",
"I was planning to get this submitted in time for 6.0.0, but other things got in the way. Let's do it for a 6.x release instead.",
"This has been fully implemented in 7.x and backported to 6.x."
] | [] | "2022-07-20T11:22:45Z" | [
"type: feature request",
"P2",
"team-Remote-Exec"
] | Implement the credential helpers proposal | ### Description of the feature request:
Tracking issue for implementing https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md.
### What underlying problem are you trying to solve with this feature?
N/A
### Which operating system are you running Bazel on?
N/A
### What is the output of `bazel info release`?
N/A
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
N/A
```
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java",
"src/main/java/com/google/devtools/build/lib/remote/BUILD",
"src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java",
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java",
"src/main/java/com/google/devtools/build/lib/remote/BUILD",
"src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java"
] | [
"src/test/java/com/google/devtools/build/lib/authandtls/BUILD",
"src/test/java/com/google/devtools/build/lib/authandtls/UnresolvedScopedCredentialHelperConverterTest.java",
"src/test/java/com/google/devtools/build/lib/remote/BUILD",
"src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java b/src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java
index 2a54e3d7f96297..8641d1c1f8c23e 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/AuthAndTLSOptions.java
@@ -14,6 +14,10 @@
package com.google.devtools.build.lib.authandtls;
+import com.google.auto.value.AutoValue;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.devtools.common.options.Converter;
import com.google.devtools.common.options.Converters.CommaSeparatedOptionListConverter;
import com.google.devtools.common.options.Converters.DurationConverter;
import com.google.devtools.common.options.Option;
@@ -21,8 +25,11 @@
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionMetadataTag;
import com.google.devtools.common.options.OptionsBase;
+import com.google.devtools.common.options.OptionsParsingException;
import java.time.Duration;
import java.util.List;
+import java.util.Optional;
+import javax.annotation.Nullable;
/**
* Common options for authentication and TLS.
@@ -131,4 +138,53 @@ public class AuthAndTLSOptions extends OptionsBase {
+ "granularity; it is an error to set a value less than one second. If keep-alive "
+ "pings are disabled, then this setting is ignored.")
public Duration grpcKeepaliveTimeout;
+
+ /** One of the values of the `--credential_helper` flag. */
+ @AutoValue
+ public abstract static class UnresolvedScopedCredentialHelper {
+ /** Returns the scope of the credential helper (if any). */
+ public abstract Optional<String> getScope();
+
+ /** Returns the (unparsed) path of the credential helper. */
+ public abstract String getPath();
+ }
+
+ /** A {@link Converter} for the `--credential_helper` flag. */
+ public static final class UnresolvedScopedCredentialHelperConverter
+ implements Converter<UnresolvedScopedCredentialHelper> {
+ public static final UnresolvedScopedCredentialHelperConverter INSTANCE =
+ new UnresolvedScopedCredentialHelperConverter();
+
+ @Override
+ public String getTypeDescription() {
+ return "An (unresolved) path to a credential helper for a scope.";
+ }
+
+ @Override
+ public UnresolvedScopedCredentialHelper convert(String input) throws OptionsParsingException {
+ Preconditions.checkNotNull(input);
+
+ int pos = input.indexOf('=');
+ if (pos >= 0) {
+ String scope = input.substring(0, pos);
+ if (Strings.isNullOrEmpty(scope)) {
+ throw new OptionsParsingException("Scope of credential helper must not be empty");
+ }
+ String path = checkPath(input.substring(pos + 1));
+ return new AutoValue_AuthAndTLSOptions_UnresolvedScopedCredentialHelper(
+ Optional.of(scope), path);
+ }
+
+ // `input` does not specify a scope.
+ return new AutoValue_AuthAndTLSOptions_UnresolvedScopedCredentialHelper(
+ Optional.empty(), checkPath(input));
+ }
+
+ private String checkPath(@Nullable String input) throws OptionsParsingException {
+ if (Strings.isNullOrEmpty(input)) {
+ throw new OptionsParsingException("Path to credential helper must not be empty");
+ }
+ return input;
+ }
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
index c82417b0034383..e410c0b52bc771 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelper.java
@@ -49,7 +49,7 @@ public final class CredentialHelper {
}
@VisibleForTesting
- Path getPath() {
+ public Path getPath() {
return path;
}
diff --git a/src/main/java/com/google/devtools/build/lib/remote/BUILD b/src/main/java/com/google/devtools/build/lib/remote/BUILD
index 849e4c23fb0f53..60b32486cb14e8 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/remote/BUILD
@@ -57,6 +57,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/analysis:top_level_artifact_context",
"//src/main/java/com/google/devtools/build/lib/analysis/platform:platform_utils",
"//src/main/java/com/google/devtools/build/lib/authandtls",
+ "//src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/downloader",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
"//src/main/java/com/google/devtools/build/lib/clock",
@@ -99,6 +100,7 @@ java_library(
"//src/main/java/com/google/devtools/common/options",
"//src/main/protobuf:failure_details_java_proto",
"//third_party:auth",
+ "//third_party:auto_value",
"//third_party:caffeine",
"//third_party:flogger",
"//third_party:guava",
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
index 871a9d42e6a4d7..0122226f23a59e 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
@@ -19,6 +19,7 @@
import build.bazel.remote.execution.v2.DigestFunction;
import build.bazel.remote.execution.v2.ServerCapabilities;
import com.google.auth.Credentials;
+import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
@@ -45,11 +46,14 @@
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget;
import com.google.devtools.build.lib.analysis.test.TestProvider;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions;
+import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelper;
import com.google.devtools.build.lib.authandtls.CallCredentialsProvider;
import com.google.devtools.build.lib.authandtls.GoogleAuthUtils;
import com.google.devtools.build.lib.authandtls.Netrc;
import com.google.devtools.build.lib.authandtls.NetrcCredentials;
import com.google.devtools.build.lib.authandtls.NetrcParser;
+import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperEnvironment;
+import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperProvider;
import com.google.devtools.build.lib.bazel.repository.downloader.Downloader;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.LocalFilesArtifactUploader;
@@ -77,6 +81,7 @@
import com.google.devtools.build.lib.runtime.BuildEventArtifactUploaderFactory;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
+import com.google.devtools.build.lib.runtime.CommandLinePathFactory;
import com.google.devtools.build.lib.runtime.RepositoryRemoteExecutor;
import com.google.devtools.build.lib.runtime.RepositoryRemoteExecutorFactory;
import com.google.devtools.build.lib.runtime.ServerBuilder;
@@ -1134,4 +1139,37 @@ static Credentials newCredentials(
return creds;
}
+
+ @VisibleForTesting
+ static CredentialHelperProvider newCredentialHelperProvider(
+ CredentialHelperEnvironment environment,
+ CommandLinePathFactory pathFactory,
+ List<UnresolvedScopedCredentialHelper> helpers)
+ throws IOException {
+ Preconditions.checkNotNull(environment);
+ Preconditions.checkNotNull(pathFactory);
+ Preconditions.checkNotNull(helpers);
+
+ CredentialHelperProvider.Builder builder = CredentialHelperProvider.builder();
+ for (UnresolvedScopedCredentialHelper helper : helpers) {
+ Optional<String> scope = helper.getScope();
+ Path path = pathFactory.create(environment.getClientEnvironment(), helper.getPath());
+ if (scope.isPresent()) {
+ builder.add(scope.get(), path);
+ } else {
+ builder.add(path);
+ }
+ }
+ return builder.build();
+ }
+
+ @VisibleForTesting
+ @AutoValue
+ abstract static class ScopedCredentialHelper {
+ /** Returns the scope of the credential helper (if any). */
+ public abstract Optional<String> getScope();
+
+ /** Returns the path of the credential helper. */
+ public abstract Path getPath();
+ }
}
| diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/BUILD b/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
index 724726bd61e8e4..b2fbbd60ec8b8e 100644
--- a/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
@@ -25,6 +25,7 @@ java_library(
),
deps = [
"//src/main/java/com/google/devtools/build/lib/authandtls",
+ "//src/main/java/com/google/devtools/common/options",
"//third_party:guava",
"//third_party:junit4",
"//third_party:mockito",
diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/UnresolvedScopedCredentialHelperConverterTest.java b/src/test/java/com/google/devtools/build/lib/authandtls/UnresolvedScopedCredentialHelperConverterTest.java
new file mode 100644
index 00000000000000..e4708348719207
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/UnresolvedScopedCredentialHelperConverterTest.java
@@ -0,0 +1,108 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.authandtls;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
+import static org.junit.Assert.assertThrows;
+
+import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelper;
+import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelperConverter;
+import com.google.devtools.common.options.OptionsParsingException;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Test for {@link UnresolvedScopedCredentialHelperConverter}. */
+@RunWith(JUnit4.class)
+public class UnresolvedScopedCredentialHelperConverterTest {
+ @Test
+ public void convertAbsolutePath() throws Exception {
+ UnresolvedScopedCredentialHelper helper1 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("/absolute/path");
+ assertThat(helper1.getScope()).isEmpty();
+ assertThat(helper1.getPath()).isEqualTo("/absolute/path");
+
+ UnresolvedScopedCredentialHelper helper2 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("example.com=/absolute/path");
+ assertThat(helper2.getScope()).hasValue("example.com");
+ assertThat(helper2.getPath()).isEqualTo("/absolute/path");
+
+ UnresolvedScopedCredentialHelper helper3 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("*.example.com=/absolute/path");
+ assertThat(helper3.getScope()).hasValue("*.example.com");
+ assertThat(helper3.getPath()).isEqualTo("/absolute/path");
+ }
+
+ @Test
+ public void convertRootRelativePath() throws Exception {
+ UnresolvedScopedCredentialHelper helper1 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("%workspace%/path");
+ assertThat(helper1.getScope()).isEmpty();
+ assertThat(helper1.getPath()).isEqualTo("%workspace%/path");
+
+ UnresolvedScopedCredentialHelper helper2 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("example.com=%workspace%/path");
+ assertThat(helper2.getScope()).hasValue("example.com");
+ assertThat(helper2.getPath()).isEqualTo("%workspace%/path");
+
+ UnresolvedScopedCredentialHelper helper3 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert(
+ "*.example.com=%workspace%/path");
+ assertThat(helper3.getScope()).hasValue("*.example.com");
+ assertThat(helper3.getPath()).isEqualTo("%workspace%/path");
+ }
+
+ @Test
+ public void convertPathLookup() throws Exception {
+ UnresolvedScopedCredentialHelper helper1 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("foo");
+ assertThat(helper1.getScope()).isEmpty();
+ assertThat(helper1.getPath()).isEqualTo("foo");
+
+ UnresolvedScopedCredentialHelper helper2 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("example.com=foo");
+ assertThat(helper2.getScope()).hasValue("example.com");
+ assertThat(helper2.getPath()).isEqualTo("foo");
+
+ UnresolvedScopedCredentialHelper helper3 =
+ UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("*.example.com=foo");
+ assertThat(helper3.getScope()).hasValue("*.example.com");
+ assertThat(helper3.getPath()).isEqualTo("foo");
+ }
+
+ @Test
+ public void emptyPath() {
+ assertThrows(
+ OptionsParsingException.class,
+ () -> UnresolvedScopedCredentialHelperConverter.INSTANCE.convert(""));
+ assertThrows(
+ OptionsParsingException.class,
+ () -> UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("foo="));
+ assertThrows(
+ OptionsParsingException.class,
+ () -> UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("="));
+ }
+
+ @Test
+ public void emptyScope() {
+ assertThrows(
+ OptionsParsingException.class,
+ () -> UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("=/foo"));
+ assertThrows(
+ OptionsParsingException.class,
+ () -> UnresolvedScopedCredentialHelperConverter.INSTANCE.convert("="));
+ }
+}
diff --git a/src/test/java/com/google/devtools/build/lib/remote/BUILD b/src/test/java/com/google/devtools/build/lib/remote/BUILD
index 34a317a3915a1e..88d69b7436bf37 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/remote/BUILD
@@ -56,6 +56,7 @@ java_test(
"//src/main/java/com/google/devtools/build/lib/analysis:server_directories",
"//src/main/java/com/google/devtools/build/lib/analysis/platform:platform_utils",
"//src/main/java/com/google/devtools/build/lib/authandtls",
+ "//src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
"//src/main/java/com/google/devtools/build/lib/clock",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
index bfc0171b6b84f6..e15cdf3ecbe2c4 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
@@ -14,6 +14,7 @@
package com.google.devtools.build.lib.remote;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
@@ -27,6 +28,7 @@
import build.bazel.remote.execution.v2.GetCapabilitiesRequest;
import build.bazel.remote.execution.v2.ServerCapabilities;
import com.google.auth.Credentials;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
@@ -35,7 +37,10 @@
import com.google.devtools.build.lib.analysis.ServerDirectories;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions;
+import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelper;
import com.google.devtools.build.lib.authandtls.BasicHttpAuthenticationEncoder;
+import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperEnvironment;
+import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperProvider;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.exec.BinTools;
import com.google.devtools.build.lib.exec.ExecutionOptions;
@@ -47,15 +52,18 @@
import com.google.devtools.build.lib.runtime.ClientOptions;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
+import com.google.devtools.build.lib.runtime.CommandLinePathFactory;
import com.google.devtools.build.lib.runtime.CommonCommandOptions;
import com.google.devtools.build.lib.runtime.commands.BuildCommand;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystem;
+import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.devtools.common.options.Options;
import com.google.devtools.common.options.OptionsParser;
+import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.OptionsParsingResult;
import io.grpc.BindableService;
import io.grpc.Server;
@@ -65,7 +73,9 @@
import io.grpc.stub.StreamObserver;
import io.grpc.util.MutableHandlerRegistry;
import java.io.IOException;
+import java.io.OutputStream;
import java.net.URI;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -576,4 +586,258 @@ private static void assertRequestMetadata(
assertThat(Iterables.getOnlyElement(requestMetadata.values()))
.containsExactly(BasicHttpAuthenticationEncoder.encode(username, password, UTF_8));
}
+
+ @Test
+ public void testCredentialHelperProvider() throws Exception {
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+
+ Path workspace = fileSystem.getPath("/workspace");
+ Path pathValue = fileSystem.getPath("/usr/local/bin");
+ pathValue.createDirectoryAndParents();
+
+ CredentialHelperEnvironment credentialHelperEnvironment =
+ CredentialHelperEnvironment.newBuilder()
+ .setEventReporter(new Reporter(new EventBus()))
+ .setWorkspacePath(workspace)
+ .setClientEnvironment(ImmutableMap.of("PATH", pathValue.getPathString()))
+ .setHelperExecutionTimeout(Duration.ZERO)
+ .build();
+ CommandLinePathFactory commandLinePathFactory =
+ new CommandLinePathFactory(fileSystem, ImmutableMap.of("workspace", workspace));
+
+ Path unusedHelper = createExecutable(fileSystem, "/unused/helper");
+
+ Path defaultHelper = createExecutable(fileSystem, "/default/helper");
+ Path exampleComHelper = createExecutable(fileSystem, "/example/com/helper");
+ Path fooExampleComHelper = createExecutable(fileSystem, "/foo/example/com/helper");
+ Path exampleComWildcardHelper = createExecutable(fileSystem, "/example/com/wildcard/helper");
+
+ Path exampleOrgHelper = createExecutable(workspace.getRelative("helpers/example-org"));
+
+ // No helpers.
+ CredentialHelperProvider credentialHelperProvider1 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment, commandLinePathFactory, ImmutableList.of());
+ assertThat(credentialHelperProvider1.findCredentialHelper(URI.create("https://example.com")))
+ .isEmpty();
+ assertThat(
+ credentialHelperProvider1.findCredentialHelper(URI.create("https://foo.example.com")))
+ .isEmpty();
+
+ // Default helper only.
+ CredentialHelperProvider credentialHelperProvider2 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.of(defaultHelper.getPathString()));
+ assertThat(
+ credentialHelperProvider2
+ .findCredentialHelper(URI.create("https://example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(defaultHelper);
+ assertThat(
+ credentialHelperProvider2
+ .findCredentialHelper(URI.create("https://foo.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(defaultHelper);
+
+ // Default and exact match.
+ CredentialHelperProvider credentialHelperProvider3 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.of(
+ defaultHelper.getPathString(), "example.com=" + exampleComHelper.getPathString()));
+ assertThat(
+ credentialHelperProvider3
+ .findCredentialHelper(URI.create("https://example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComHelper);
+ assertThat(
+ credentialHelperProvider3
+ .findCredentialHelper(URI.create("https://foo.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(defaultHelper);
+
+ // Exact match without default.
+ CredentialHelperProvider credentialHelperProvider4 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.of("example.com=" + exampleComHelper.getPathString()));
+ assertThat(
+ credentialHelperProvider4
+ .findCredentialHelper(URI.create("https://example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComHelper);
+ assertThat(
+ credentialHelperProvider4.findCredentialHelper(URI.create("https://foo.example.com")))
+ .isEmpty();
+
+ // Multiple scoped helpers with default.
+ CredentialHelperProvider credentialHelperProvider5 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.of(
+ defaultHelper.getPathString(),
+ "example.com=" + exampleComHelper.getPathString(),
+ "*.foo.example.com=" + fooExampleComHelper.getPathString(),
+ "*.example.com=" + exampleComWildcardHelper.getPathString(),
+ "example.org=%workspace%/helpers/example-org"));
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://anotherdomain.com"))
+ .get()
+ .getPath())
+ .isEqualTo(defaultHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://foo.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(fooExampleComHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://abc.foo.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(fooExampleComHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://bar.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComWildcardHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://abc.bar.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComWildcardHelper);
+ assertThat(
+ credentialHelperProvider5
+ .findCredentialHelper(URI.create("https://example.org"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleOrgHelper);
+
+ // Helpers override.
+ CredentialHelperProvider credentialHelperProvider6 =
+ newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.of(
+ // <system .bazelrc>
+ unusedHelper.getPathString(),
+
+ // <user .bazelrc>
+ defaultHelper.getPathString(),
+ "example.com=" + unusedHelper.getPathString(),
+ "*.example.com=" + unusedHelper.getPathString(),
+ "example.org=" + unusedHelper.getPathString(),
+ "*.example.org=" + exampleOrgHelper.getPathString(),
+
+ // <workspace .bazelrc>
+ "*.example.com=" + exampleComWildcardHelper.getPathString(),
+ "example.org=" + exampleOrgHelper.getPathString(),
+ "*.foo.example.com=" + unusedHelper.getPathString(),
+
+ // <command-line>
+ "example.com=" + exampleComHelper.getPathString(),
+ "*.foo.example.com=" + fooExampleComHelper.getPathString()));
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://anotherdomain.com"))
+ .get()
+ .getPath())
+ .isEqualTo(defaultHelper);
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComHelper);
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://foo.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(fooExampleComHelper);
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://bar.example.com"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleComWildcardHelper);
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://example.org"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleOrgHelper);
+ assertThat(
+ credentialHelperProvider6
+ .findCredentialHelper(URI.create("https://foo.example.org"))
+ .get()
+ .getPath())
+ .isEqualTo(exampleOrgHelper);
+ }
+
+ private static Path createExecutable(FileSystem fileSystem, String path) throws IOException {
+ Preconditions.checkNotNull(fileSystem);
+ Preconditions.checkNotNull(path);
+
+ return createExecutable(fileSystem.getPath(path));
+ }
+
+ private static Path createExecutable(Path path) throws IOException {
+ Preconditions.checkNotNull(path);
+
+ path.getParentDirectory().createDirectoryAndParents();
+ try (OutputStream unused = path.getOutputStream()) {
+ // Nothing to do.
+ }
+ path.setExecutable(true);
+
+ return path;
+ }
+
+ private static CredentialHelperProvider newCredentialHelperProvider(
+ CredentialHelperEnvironment credentialHelperEnvironment,
+ CommandLinePathFactory commandLinePathFactory,
+ ImmutableList<String> inputs)
+ throws Exception {
+ Preconditions.checkNotNull(credentialHelperEnvironment);
+ Preconditions.checkNotNull(commandLinePathFactory);
+ Preconditions.checkNotNull(inputs);
+
+ return RemoteModule.newCredentialHelperProvider(
+ credentialHelperEnvironment,
+ commandLinePathFactory,
+ ImmutableList.copyOf(
+ Iterables.transform(inputs, s -> createUnresolvedScopedCredentialHelper(s))));
+ }
+
+ private static UnresolvedScopedCredentialHelper createUnresolvedScopedCredentialHelper(
+ String input) {
+ Preconditions.checkNotNull(input);
+
+ try {
+ return AuthAndTLSOptions.UnresolvedScopedCredentialHelperConverter.INSTANCE.convert(input);
+ } catch (OptionsParsingException e) {
+ throw new IllegalStateException(e);
+ }
+ }
}
| train | val | 2022-07-22T06:30:40 | "2022-07-11T15:16:11Z" | tjgq | test |
bazelbuild/bazel/13817_15943 | bazelbuild/bazel | bazelbuild/bazel/13817 | bazelbuild/bazel/15943 | [
"keyword_pr_to_issue"
] | aaf19a832133cf6a4c278e4e201405e347867db3 | 9c2c3dee089231b0aac3de9f62bc80a896d531b8 | [
"Interesting. Are you comfortable if it still uses the same syntax `build_setting_default=\"\"`? And that semantically means an empty list?\r\n\r\nI get your point, and agree this is worth addressing. I'd want to be cautious to make sure whatever solution doesn't create some unknown other consistency in some other API piece with different expectations.",
"@gregestren What would you think of allowing both `list of <type>` and `<type>` as default values, with the latter continuing to be converted to a singleton list for backwards compatibility? Since there is already a `string_list` type, having the `BuildSetting` return a type that dynamically depends on the value of its `allowMultiple` member may actually not be that much work.\r\n\r\nEdit: I now see that the problem is not that `BuildSetting` can't return a different type, it's that `build_setting_default` has to go through the usual `attr`, which does not allow for this kind of fallback behavior.",
"I ultimately came to the conclusion that the source of issues is that repeatable string flags should be represented as `string_list` flags with a different CLI argument passing style rather than `string` flags that conditionally provide a list value. I created #14911 to create a replacement for the current `allow_multiple` flag that requires significantly less special casing internally and should also be more transparent to users.",
"Thanks. I'll take a look. Also cc @aranguyen FYI who's been looking recently at flag parsing logic in general.",
"@fmeum thanks for sending out the proposal. I don't know how to make comments on the proposal you linked so I'm dropping them here instead.\r\n1) Have you considered what the overriding/accumulating behavior would look like if users do the following `bazel build --flag=[\"a\", \"b\"] --flag=[\"c\", \"d\"]`? Would the final evaluation be `--flag=[\"c\", \"d\"]` or would it be `--flag=[\"a\", \"b\", \"c\", \"d\"]`? \r\n2) If the answer to the previous question is `--flag=[\"c\", \"d\"]`. Would it break for the case of inheritance (test inheriting from build for example)? Some users might want to pass in additional flags for testing. \r\n",
"@aranguyen My proposal doesn't allow for this syntax, so it (luckily) doesn't have to specify this interaction. My proposal only affects how repeated flags are represented in Starlark, not how they are specified on the command-line: You still either specify a `string_list` as `--flag=first,second` (where later occurrences of `--flag` override all previous occurrences) or as `--flag=first --first=second`, depending on the flag style. The starlark value would be `[\"first\", \"second\"]` in both cases."
] | [] | "2022-07-21T17:59:57Z" | [
"P2",
"type: support / not a bug (process)",
"team-Configurability"
] | config.string with allow_multiple=True should use list for build_setting_default | I'm trying to migrate a native flag (`--protocopt`) to a Starlark flag. For this, we need a flag that a) can be supplied multiple times (like with `allow_multiple=True` - `config.string_list` doesn't allow this) and b) has an empty default.
Today, it's impossible to get an empty list or a list with multiple elements as `ctx.build_setting_value` when using `config.string` with `allow_multiple=True`.
```starlark
# foo.bzl
def _impl(ctx):
pass
foo = rule(
implementation = _impl,
build_setting = config.string(flag = True, allow_multiple = True),
)
# BUILD
load(":foo.bzl", "foo")
foo(name="foo", build_setting_default="") # <-- `ctx.build_setting_value` becomes `[""]`.
```
There are ways to work around this (i.e. setting `build_setting_default` to a nonsensical value and checking for `ctx.build_setting_value` with one element that is the specified default value), but that seems unnecessarily complex.
From a technical perspective, changing the allowed type for `build_setting_default` when `allow_multiple=True` looks pretty straight forward to me.
`allow_multiple` was added in https://cs.opensource.google/bazel/bazel/+/a13f590b69bcbcaa10b1a49bfd9a4607dfbd8f47 after cutting Bazel 4.0.0, so its usage in the wild should be low.
| [
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java",
"src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java",
"src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java",
"src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java",
"src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java",
"src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java",
"src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/config/ConfigSettingTest.java",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkOptionsParsingTest.java",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleContextTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java
index 96584b184e7bd1..d583cb09514828 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkConfig.java
@@ -22,6 +22,7 @@
import com.google.devtools.build.lib.analysis.config.ExecutionTransitionFactory;
import com.google.devtools.build.lib.packages.BuildSetting;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkConfigApi;
+import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Starlark;
@@ -40,12 +41,15 @@ public BuildSetting boolSetting(Boolean flag) {
@Override
public BuildSetting stringSetting(Boolean flag, Boolean allowMultiple) {
- return BuildSetting.create(flag, STRING, allowMultiple);
+ return BuildSetting.create(flag, STRING, allowMultiple, false);
}
@Override
- public BuildSetting stringListSetting(Boolean flag) {
- return BuildSetting.create(flag, STRING_LIST);
+ public BuildSetting stringListSetting(Boolean flag, Boolean repeatable) throws EvalException {
+ if (repeatable && !flag) {
+ throw Starlark.errorf("'repeatable' can only be set for a setting with 'flag = True'");
+ }
+ return BuildSetting.create(flag, STRING_LIST, false, repeatable);
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java b/src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java
index c64e81f657e1d0..d9b01dcca86316 100644
--- a/src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java
+++ b/src/main/java/com/google/devtools/build/lib/packages/BuildSetting.java
@@ -27,22 +27,25 @@ public class BuildSetting implements BuildSettingApi {
private final boolean isFlag;
private final Type<?> type;
private final boolean allowMultiple;
+ private final boolean repeatable;
- private BuildSetting(boolean isFlag, Type<?> type, boolean allowMultiple) {
+ private BuildSetting(boolean isFlag, Type<?> type, boolean allowMultiple, boolean repeatable) {
this.isFlag = isFlag;
this.type = type;
this.allowMultiple = allowMultiple;
+ this.repeatable = repeatable;
}
- public static BuildSetting create(boolean isFlag, Type<?> type, boolean allowMultiple) {
- return new BuildSetting(isFlag, type, allowMultiple);
+ public static BuildSetting create(
+ boolean isFlag, Type<?> type, boolean allowMultiple, boolean repeatable) {
+ return new BuildSetting(isFlag, type, allowMultiple, repeatable);
}
public static BuildSetting create(boolean isFlag, Type<?> type) {
Preconditions.checkState(
type.getLabelClass() != LabelClass.DEPENDENCY,
"Build settings should not create a dependency with their default attribute");
- return new BuildSetting(isFlag, type, /* allowMultiple= */ false);
+ return new BuildSetting(isFlag, type, /* allowMultiple= */ false, false);
}
public Type<?> getType() {
@@ -58,6 +61,10 @@ public boolean allowsMultiple() {
return allowMultiple;
}
+ public boolean isRepeatableFlag() {
+ return repeatable;
+ }
+
@Override
public void repr(Printer printer) {
printer.append("<build_setting." + type + ">");
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java b/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
index 1d9eb89d490305..0c60ee576e0541 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
@@ -168,6 +168,9 @@ public void parse(ExtendedEventHandler eventHandler) throws OptionsParsingExcept
String.format("Unrecognized option: %s=%s", loadedFlag, unparsedValue));
}
Type<?> type = buildSetting.getType();
+ if (buildSetting.isRepeatableFlag()) {
+ type = Preconditions.checkNotNull(type.getListElementType());
+ }
Converter<?> converter = BUILD_SETTING_CONVERTERS.get(type);
Object value;
try {
@@ -179,7 +182,7 @@ public void parse(ExtendedEventHandler eventHandler) throws OptionsParsingExcept
loadedFlag, unparsedValue, unparsedValue, type),
e);
}
- if (buildSetting.allowsMultiple()) {
+ if (buildSetting.allowsMultiple() || buildSetting.isRepeatableFlag()) {
List<Object> newValue;
if (buildSettingWithTargetAndValue.containsKey(loadedFlag)) {
newValue =
@@ -371,7 +374,8 @@ public OptionsParser getNativeOptionsParserFortesting() {
}
public boolean checkIfParsedOptionAllowsMultiple(String option) {
- return parsedBuildSettings.get(option).allowsMultiple();
+ BuildSetting setting = parsedBuildSettings.get(option);
+ return setting.allowsMultiple() || setting.isRepeatableFlag();
}
public Type<?> getParsedOptionType(String option) {
diff --git a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java
index 1b5b9e79d2808b..bba02e72ea9b5e 100644
--- a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java
+++ b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/StarlarkConfigApi.java
@@ -19,6 +19,7 @@
import net.starlark.java.annot.ParamType;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
+import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.NoneType;
import net.starlark.java.eval.StarlarkValue;
@@ -90,11 +91,13 @@ public interface StarlarkConfigApi extends StarlarkValue {
name = "allow_multiple",
defaultValue = "False",
doc =
- "If set, this flag is allowed to be set multiple times on the command line. The"
- + " Value of the flag as accessed in transitions and build setting"
- + " implementation function will be a list of strings. Insertion order and"
- + " repeated values are both maintained. This list can be post-processed in the"
- + " build setting implementation function if different behavior is desired.",
+ "Deprecated, use a <code>string_list</code> setting with"
+ + " <code>repeatable = True</code> instead. If set, this flag is allowed to be"
+ + " set multiple times on the command line. The Value of the flag as accessed"
+ + " in transitions and build setting implementation function will be a list of"
+ + " strings. Insertion order and repeated values are both maintained. This list"
+ + " can be post-processed in the build setting implementation function if"
+ + " different behavior is desired.",
named = true,
positional = false)
})
@@ -111,9 +114,20 @@ public interface StarlarkConfigApi extends StarlarkValue {
defaultValue = "False",
doc = FLAG_ARG_DOC,
named = true,
+ positional = false),
+ @Param(
+ name = "repeatable",
+ defaultValue = "False",
+ doc =
+ "If set, instead of expecting a comma-separated value, this flag is allowed to be"
+ + " set multiple times on the command line with each individual value treated"
+ + " as a single string to add to the list value. Insertion order and repeated"
+ + " values are both maintained. This list can be post-processed in the build"
+ + " setting implementation function if different behavior is desired.",
+ named = true,
positional = false)
})
- BuildSettingApi stringListSetting(Boolean flag);
+ BuildSettingApi stringListSetting(Boolean flag, Boolean repeatable) throws EvalException;
/** The API for build setting descriptors. */
@StarlarkBuiltin(
diff --git a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java
index f40afe104280dd..0582beb4d71b73 100644
--- a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java
+++ b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/FakeConfigApi.java
@@ -38,7 +38,7 @@ public BuildSettingApi stringSetting(Boolean flag, Boolean allowMultiple) {
}
@Override
- public BuildSettingApi stringListSetting(Boolean flag) {
+ public BuildSettingApi stringListSetting(Boolean flag, Boolean repeated) {
return new FakeBuildSettingDescriptor();
}
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/config/ConfigSettingTest.java b/src/test/java/com/google/devtools/build/lib/rules/config/ConfigSettingTest.java
index 02813807ab0e05..d6f5782143e727 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/config/ConfigSettingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/config/ConfigSettingTest.java
@@ -1534,6 +1534,51 @@ public void buildsettings_allowMultipleWorks() throws Exception {
assertThat(getConfigMatchingProvider("//test:match").matches()).isTrue();
}
+ @Test
+ public void buildsettings_repeatableWorks() throws Exception {
+ scratch.file(
+ "test/build_settings.bzl",
+ "def _impl(ctx):",
+ " return []",
+ "string_list_flag = rule(",
+ " implementation = _impl,",
+ " build_setting = config.string_list(flag = True, repeatable = True),",
+ ")");
+ scratch.file(
+ "test/BUILD",
+ "load('//test:build_settings.bzl', 'string_list_flag')",
+ "config_setting(",
+ " name = 'match',",
+ " flag_values = {",
+ " ':cheese': 'pepperjack',",
+ " },",
+ ")",
+ "string_list_flag(name = 'cheese', build_setting_default = ['gouda'])");
+
+ useConfiguration(ImmutableMap.of("//test:cheese", ImmutableList.of("pepperjack", "brie")));
+ assertThat(getConfigMatchingProvider("//test:match").matches()).isTrue();
+ }
+
+ @Test
+ public void buildsettings_repeatableWithoutFlagErrors() throws Exception {
+ scratch.file(
+ "test/build_settings.bzl",
+ "def _impl(ctx):",
+ " return []",
+ "string_list_setting = rule(",
+ " implementation = _impl,",
+ " build_setting = config.string_list(repeatable = True),",
+ ")");
+ scratch.file(
+ "test/BUILD",
+ "load('//test:build_settings.bzl', 'string_list_setting')",
+ "string_list_setting(name = 'cheese', build_setting_default = ['gouda'])");
+
+ reporter.removeHandler(failFastHandler);
+ getConfiguredTarget("//test:cheese");
+ assertContainsEvent("'repeatable' can only be set for a setting with 'flag = True'");
+ }
+
@Test
public void notBuildSettingOrFeatureFlag() throws Exception {
scratch.file(
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkOptionsParsingTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkOptionsParsingTest.java
index 0e93717352e940..6579eec0c1b3a5 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkOptionsParsingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkOptionsParsingTest.java
@@ -478,4 +478,27 @@ public void testAllowMultipleStringFlag() throws Exception {
assertThat((List<String>) result.getStarlarkOptions().get("//test:cats"))
.containsExactly("calico", "bengal");
}
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testRepeatedStringListFlag() throws Exception {
+ scratch.file(
+ "test/build_setting.bzl",
+ "def _build_setting_impl(ctx):",
+ " return []",
+ "repeated_flag = rule(",
+ " implementation = _build_setting_impl,",
+ " build_setting = config.string_list(flag=True, repeatable=True)",
+ ")");
+ scratch.file(
+ "test/BUILD",
+ "load('//test:build_setting.bzl', 'repeated_flag')",
+ "repeated_flag(name = 'cats', build_setting_default = ['tabby'])");
+
+ OptionsParsingResult result = parseStarlarkOptions("--//test:cats=calico --//test:cats=bengal");
+
+ assertThat(result.getStarlarkOptions().keySet()).containsExactly("//test:cats");
+ assertThat((List<String>) result.getStarlarkOptions().get("//test:cats"))
+ .containsExactly("calico", "bengal");
+ }
}
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleContextTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleContextTest.java
index 94964936fa1ae1..b87da48480fdc2 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleContextTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleContextTest.java
@@ -2960,6 +2960,66 @@ public void testBuildSettingValue_allowMultipleSetting() throws Exception {
.containsExactly("some-other-value", "some-other-other-value");
}
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testBuildSettingValue_isRepeatedSetting() throws Exception {
+ scratch.file(
+ "test/build_setting.bzl",
+ "BuildSettingInfo = provider(fields = ['name', 'value'])",
+ "def _impl(ctx):",
+ " return [BuildSettingInfo(name = ctx.attr.name, value = ctx.build_setting_value)]",
+ "",
+ "string_list_flag = rule(",
+ " implementation = _impl,",
+ " build_setting = config.string_list(flag = True, repeatable = True),",
+ ")");
+ scratch.file(
+ "test/BUILD",
+ "load('//test:build_setting.bzl', 'string_list_flag')",
+ "string_list_flag(name = 'string_list_flag', build_setting_default = ['some-value'])");
+
+ // from default
+ ConfiguredTarget buildSetting = getConfiguredTarget("//test:string_list_flag");
+ Provider.Key key =
+ new StarlarkProvider.Key(
+ Label.create(buildSetting.getLabel().getPackageIdentifier(), "build_setting.bzl"),
+ "BuildSettingInfo");
+ StructImpl buildSettingInfo = (StructImpl) buildSetting.get(key);
+
+ assertThat(buildSettingInfo.getValue("value")).isInstanceOf(List.class);
+ assertThat((List<String>) buildSettingInfo.getValue("value")).containsExactly("some-value");
+
+ // Set multiple times
+ useConfiguration(
+ ImmutableMap.of(
+ "//test:string_list_flag",
+ ImmutableList.of("some-other-value", "some-other-other-value")));
+ buildSetting = getConfiguredTarget("//test:string_list_flag");
+ key =
+ new StarlarkProvider.Key(
+ Label.create(buildSetting.getLabel().getPackageIdentifier(), "build_setting.bzl"),
+ "BuildSettingInfo");
+ buildSettingInfo = (StructImpl) buildSetting.get(key);
+
+ assertThat(buildSettingInfo.getValue("value")).isInstanceOf(List.class);
+ assertThat((List<String>) buildSettingInfo.getValue("value"))
+ .containsExactly("some-other-value", "some-other-other-value");
+
+ // No splitting on comma.
+ useConfiguration(
+ ImmutableMap.of("//test:string_list_flag", ImmutableList.of("a,b,c", "a", "b,c")));
+ buildSetting = getConfiguredTarget("//test:string_list_flag");
+ key =
+ new StarlarkProvider.Key(
+ Label.create(buildSetting.getLabel().getPackageIdentifier(), "build_setting.bzl"),
+ "BuildSettingInfo");
+ buildSettingInfo = (StructImpl) buildSetting.get(key);
+
+ assertThat(buildSettingInfo.getValue("value")).isInstanceOf(List.class);
+ assertThat((List<String>) buildSettingInfo.getValue("value"))
+ .containsExactly("a,b,c", "a", "b,c");
+ }
+
@Test
public void testBuildSettingValue_nonBuildSettingRule() throws Exception {
scratch.file(
| test | val | 2022-07-21T22:28:39 | "2021-08-08T17:14:03Z" | Yannic | test |
bazelbuild/bazel/15928_15970 | bazelbuild/bazel | bazelbuild/bazel/15928 | bazelbuild/bazel/15970 | [
"keyword_pr_to_issue"
] | e4ee34416ef18094496ab54446e70cb62cd509e6 | 96d23d30cc80912b82a8fbab31c902e9db74b6ab | [
"cc @tjgq "
] | [] | "2022-07-25T16:13:11Z" | [
"type: feature request",
"untriaged",
"team-Remote-Exec"
] | --bes_backend doesn't support reading credentials from .netrc | `--remote_{downloader,cache,executor}` all support reading credentials from `.netrc`: https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java;l=1098;drc=1bc1ce3e0d73c35047c29ef85e832db041e0f238
`--bes_backend` doesn't: https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java;l=79;drc=4cd266aa1dfa53d8c8de44f7895edcfd46f74725 calling into https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java;l=194;drc=4cd266aa1dfa53d8c8de44f7895edcfd46f74725
Found while working on #15856 | [
"src/main/java/com/google/devtools/build/lib/authandtls/BUILD",
"src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/authandtls/BUILD",
"src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java"
] | [
"src/test/java/com/google/devtools/build/lib/authandtls/BUILD",
"src/test/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtilsTest.java",
"src/test/java/com/google/devtools/build/lib/remote/BUILD",
"src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteServerCapabilitiesTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerWithGrpcRemoteExecutorTest.java",
"src/test/shell/bazel/remote/remote_execution_http_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/BUILD b/src/main/java/com/google/devtools/build/lib/authandtls/BUILD
index 29250880640ff0..e22da5887e456b 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/BUILD
@@ -15,6 +15,8 @@ java_library(
srcs = glob(["*.java"]),
deps = [
"//src/main/java/com/google/devtools/build/lib/concurrent",
+ "//src/main/java/com/google/devtools/build/lib/events",
+ "//src/main/java/com/google/devtools/build/lib/vfs",
"//src/main/java/com/google/devtools/common/options",
"//third_party:auth",
"//third_party:auto_value",
diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java b/src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java
index bf640f1bfc2aef..67e0d9e9195684 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtils.java
@@ -19,6 +19,10 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
+import com.google.devtools.build.lib.events.Event;
+import com.google.devtools.build.lib.events.Reporter;
+import com.google.devtools.build.lib.vfs.FileSystem;
+import com.google.devtools.build.lib.vfs.Path;
import io.grpc.CallCredentials;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
@@ -41,6 +45,8 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import java.util.Map;
+import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
@@ -186,14 +192,17 @@ private static NettyChannelBuilder newNettyChannelBuilder(String targetUrl, Stri
}
/**
- * Create a new {@link CallCredentials} object.
+ * Create a new {@link CallCredentials} object from the authentication flags, or null if no flags
+ * are set.
*
- * @throws IOException in case the call credentials can't be constructed.
+ * @throws IOException in case the credentials can't be constructed.
*/
- public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
- Credentials creds = newCredentials(options);
- if (creds != null) {
- return MoreCallCredentials.from(creds);
+ @Nullable
+ public static CallCredentials newGoogleCallCredentials(AuthAndTLSOptions options)
+ throws IOException {
+ Optional<Credentials> creds = newGoogleCredentials(options);
+ if (creds.isPresent()) {
+ return MoreCallCredentials.from(creds.get());
}
return null;
}
@@ -210,18 +219,52 @@ public static CallCredentialsProvider newCallCredentialsProvider(@Nullable Crede
}
/**
- * Create a new {@link Credentials} object, or {@code null} if no options are provided.
+ * Create a new {@link Credentials} with following order:
+ *
+ * <ol>
+ * <li>If authentication enabled by flags, use it to create credentials
+ * <li>Use .netrc to provide credentials if exists
+ * <li>Otherwise, return {@code null}
+ * </ol>
*
* @throws IOException in case the credentials can't be constructed.
*/
@Nullable
- public static Credentials newCredentials(@Nullable AuthAndTLSOptions options) throws IOException {
+ public static Credentials newCredentials(
+ Reporter reporter,
+ Map<String, String> clientEnv,
+ FileSystem fileSystem,
+ AuthAndTLSOptions authAndTlsOptions)
+ throws IOException {
+ Optional<Credentials> credentials = newGoogleCredentials(authAndTlsOptions);
+
+ if (credentials.isEmpty()) {
+ // Fallback to .netrc if it exists.
+ try {
+ credentials = newCredentialsFromNetrc(clientEnv, fileSystem);
+ } catch (IOException e) {
+ // TODO(yannic): Make this fail the build.
+ reporter.handle(Event.warn(e.getMessage()));
+ }
+ }
+
+ return credentials.orElse(null);
+ }
+
+ /**
+ * Create a new {@link Credentials} object from the authentication flags, or null if no flags are
+ * set.
+ *
+ * @throws IOException in case the credentials can't be constructed.
+ */
+ public static Optional<Credentials> newGoogleCredentials(@Nullable AuthAndTLSOptions options)
+ throws IOException {
if (options == null) {
- return null;
+ return Optional.empty();
} else if (options.googleCredentials != null) {
// Credentials from file
try (InputStream authFile = new FileInputStream(options.googleCredentials)) {
- return newCredentials(authFile, options.googleAuthScopes);
+ return Optional.of(newGoogleCredentialsFromFile(authFile, options.googleAuthScopes));
} catch (FileNotFoundException e) {
String message =
String.format(
@@ -230,10 +273,11 @@ public static Credentials newCredentials(@Nullable AuthAndTLSOptions options) th
throw new IOException(message, e);
}
} else if (options.useGoogleDefaultCredentials) {
- return newCredentials(
- null /* Google Application Default Credentials */, options.googleAuthScopes);
+ return Optional.of(
+ newGoogleCredentialsFromFile(
+ null /* Google Application Default Credentials */, options.googleAuthScopes));
}
- return null;
+ return Optional.empty();
}
/**
@@ -242,7 +286,7 @@ public static Credentials newCredentials(@Nullable AuthAndTLSOptions options) th
* @throws IOException in case the credentials can't be constructed.
*/
@VisibleForTesting
- public static Credentials newCredentials(
+ public static Credentials newGoogleCredentialsFromFile(
@Nullable InputStream credentialsFile, List<String> authScopes) throws IOException {
try {
GoogleCredentials creds =
@@ -258,4 +302,40 @@ public static Credentials newCredentials(
throw new IOException(message, e);
}
}
+
+ /**
+ * Create a new {@link Credentials} object by parsing the .netrc file with following order to
+ * search it:
+ *
+ * <ol>
+ * <li>If environment variable $NETRC exists, use it as the path to the .netrc file
+ * <li>Fallback to $HOME/.netrc
+ * </ol>
+ *
+ * @return the {@link Credentials} object or {@code null} if there is no .netrc file.
+ * @throws IOException in case the credentials can't be constructed.
+ */
+ @VisibleForTesting
+ static Optional<Credentials> newCredentialsFromNetrc(
+ Map<String, String> clientEnv, FileSystem fileSystem) throws IOException {
+ Optional<String> netrcFileString =
+ Optional.ofNullable(clientEnv.get("NETRC"))
+ .or(() -> Optional.ofNullable(clientEnv.get("HOME")).map(home -> home + "/.netrc"));
+ if (netrcFileString.isEmpty()) {
+ return Optional.empty();
+ }
+
+ Path netrcFile = fileSystem.getPath(netrcFileString.get());
+ if (!netrcFile.exists()) {
+ return Optional.empty();
+ }
+
+ try {
+ Netrc netrc = NetrcParser.parseAndClose(netrcFile.getInputStream());
+ return Optional.of(new NetrcCredentials(netrc));
+ } catch (IOException e) {
+ throw new IOException(
+ "Failed to parse " + netrcFile.getPathString() + ": " + e.getMessage(), e);
+ }
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD b/src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD
index 31ff6dd5600e85..bfe3f367142f6f 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/buildeventservice/BUILD
@@ -57,6 +57,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/util/io:out-err",
"//src/main/java/com/google/devtools/common/options",
"//src/main/protobuf:failure_details_java_proto",
+ "//third_party:auth",
"//third_party:auto_value",
"//third_party:flogger",
"//third_party:guava",
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java b/src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java
index e76b0ecf5c83a2..49878218bca925 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java
@@ -14,8 +14,10 @@
package com.google.devtools.build.lib.buildeventservice;
+import com.google.auth.Credentials;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -24,9 +26,11 @@
import com.google.devtools.build.lib.authandtls.GoogleAuthUtils;
import com.google.devtools.build.lib.buildeventservice.client.BuildEventServiceClient;
import com.google.devtools.build.lib.buildeventservice.client.BuildEventServiceGrpcClient;
+import com.google.devtools.build.lib.runtime.CommandEnvironment;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
+import io.grpc.auth.MoreCallCredentials;
import io.grpc.stub.MetadataUtils;
import java.io.IOException;
import java.util.Map;
@@ -70,15 +74,28 @@ protected Class<BuildEventServiceOptions> optionsClass() {
@Override
protected BuildEventServiceClient getBesClient(
- BuildEventServiceOptions besOptions, AuthAndTLSOptions authAndTLSOptions) throws IOException {
+ CommandEnvironment env,
+ BuildEventServiceOptions besOptions,
+ AuthAndTLSOptions authAndTLSOptions)
+ throws IOException {
BackendConfig newConfig = BackendConfig.create(besOptions, authAndTLSOptions);
if (client == null || !Objects.equals(config, newConfig)) {
clearBesClient();
+ Preconditions.checkState(config == null);
+ Preconditions.checkState(client == null);
+
+ Credentials credentials =
+ GoogleAuthUtils.newCredentials(
+ env.getReporter(),
+ env.getClientEnv(),
+ env.getRuntime().getFileSystem(),
+ newConfig.authAndTLSOptions());
+
config = newConfig;
client =
new BuildEventServiceGrpcClient(
newGrpcChannel(config),
- GoogleAuthUtils.newCallCredentials(config.authAndTLSOptions()),
+ credentials != null ? MoreCallCredentials.from(credentials) : null,
makeGrpcInterceptor(config));
}
return client;
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
index b352779c72d8d5..e8bc7d3c2cb06a 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
@@ -677,7 +677,7 @@ private BuildEventServiceTransport createBesTransport(
final BuildEventServiceClient besClient;
try {
- besClient = getBesClient(besOptions, authTlsOptions);
+ besClient = getBesClient(cmdEnv, besOptions, authTlsOptions);
} catch (IOException | OptionsParsingException e) {
reportError(
reporter,
@@ -822,7 +822,7 @@ private static AbruptExitException createAbruptExitException(
protected abstract Class<BESOptionsT> optionsClass();
protected abstract BuildEventServiceClient getBesClient(
- BESOptionsT besOptions, AuthAndTLSOptions authAndTLSOptions)
+ CommandEnvironment env, BESOptionsT besOptions, AuthAndTLSOptions authAndTLSOptions)
throws IOException, OptionsParsingException;
protected abstract void clearBesClient();
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
index 0122226f23a59e..60e9b391c4b43f 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
@@ -49,9 +49,6 @@
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelper;
import com.google.devtools.build.lib.authandtls.CallCredentialsProvider;
import com.google.devtools.build.lib.authandtls.GoogleAuthUtils;
-import com.google.devtools.build.lib.authandtls.Netrc;
-import com.google.devtools.build.lib.authandtls.NetrcCredentials;
-import com.google.devtools.build.lib.authandtls.NetrcParser;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperEnvironment;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperProvider;
import com.google.devtools.build.lib.bazel.repository.downloader.Downloader;
@@ -1052,94 +1049,6 @@ RemoteActionContextProvider getActionContextProvider() {
return actionContextProvider;
}
- /**
- * Create a new {@link Credentials} object by parsing the .netrc file with following order to
- * search it:
- *
- * <ol>
- * <li>If environment variable $NETRC exists, use it as the path to the .netrc file
- * <li>Fallback to $HOME/.netrc
- * </ol>
- *
- * @return the {@link Credentials} object or {@code null} if there is no .netrc file.
- * @throws IOException in case the credentials can't be constructed.
- */
- @VisibleForTesting
- static Credentials newCredentialsFromNetrc(Map<String, String> clientEnv, FileSystem fileSystem)
- throws IOException {
- String netrcFileString =
- Optional.ofNullable(clientEnv.get("NETRC"))
- .orElseGet(
- () ->
- Optional.ofNullable(clientEnv.get("HOME"))
- .map(home -> home + "/.netrc")
- .orElse(null));
- if (netrcFileString == null) {
- return null;
- }
-
- Path netrcFile = fileSystem.getPath(netrcFileString);
- if (netrcFile.exists()) {
- try {
- Netrc netrc = NetrcParser.parseAndClose(netrcFile.getInputStream());
- return new NetrcCredentials(netrc);
- } catch (IOException e) {
- throw new IOException(
- "Failed to parse " + netrcFile.getPathString() + ": " + e.getMessage(), e);
- }
- } else {
- return null;
- }
- }
-
- /**
- * Create a new {@link Credentials} with following order:
- *
- * <ol>
- * <li>If authentication enabled by flags, use it to create credentials
- * <li>Use .netrc to provide credentials if exists
- * <li>Otherwise, return {@code null}
- * </ol>
- *
- * @throws IOException in case the credentials can't be constructed.
- */
- @VisibleForTesting
- static Credentials newCredentials(
- Map<String, String> clientEnv,
- FileSystem fileSystem,
- Reporter reporter,
- AuthAndTLSOptions authAndTlsOptions,
- RemoteOptions remoteOptions)
- throws IOException {
- Credentials creds = GoogleAuthUtils.newCredentials(authAndTlsOptions);
-
- // Fallback to .netrc if it exists
- if (creds == null) {
- try {
- creds = newCredentialsFromNetrc(clientEnv, fileSystem);
- } catch (IOException e) {
- reporter.handle(Event.warn(e.getMessage()));
- }
-
- try {
- if (creds != null
- && remoteOptions.remoteCache != null
- && Ascii.toLowerCase(remoteOptions.remoteCache).startsWith("http://")
- && !creds.getRequestMetadata(new URI(remoteOptions.remoteCache)).isEmpty()) {
- reporter.handle(
- Event.warn(
- "Username and password from .netrc is transmitted in plaintext to "
- + remoteOptions.remoteCache
- + ". Please consider using an HTTPS endpoint."));
- }
- } catch (URISyntaxException e) {
- throw new IOException(e.getMessage(), e);
- }
- }
-
- return creds;
- }
-
@VisibleForTesting
static CredentialHelperProvider newCredentialHelperProvider(
CredentialHelperEnvironment environment,
@@ -1163,6 +1072,35 @@ static CredentialHelperProvider newCredentialHelperProvider(
return builder.build();
}
+ static Credentials newCredentials(
+ Map<String, String> clientEnv,
+ FileSystem fileSystem,
+ Reporter reporter,
+ AuthAndTLSOptions authAndTlsOptions,
+ RemoteOptions remoteOptions)
+ throws IOException {
+ Credentials credentials =
+ GoogleAuthUtils.newCredentials(reporter, clientEnv, fileSystem, authAndTlsOptions);
+
+ try {
+ if (credentials != null
+ && remoteOptions.remoteCache != null
+ && Ascii.toLowerCase(remoteOptions.remoteCache).startsWith("http://")
+ && !credentials.getRequestMetadata(new URI(remoteOptions.remoteCache)).isEmpty()) {
+ // TODO(yannic): Make this a error aborting the build.
+ reporter.handle(
+ Event.warn(
+ "Credentials are transmitted in plaintext to "
+ + remoteOptions.remoteCache
+ + ". Please consider using an HTTPS endpoint."));
+ }
+ } catch (URISyntaxException e) {
+ throw new IOException(e.getMessage(), e);
+ }
+
+ return credentials;
+ }
+
@VisibleForTesting
@AutoValue
abstract static class ScopedCredentialHelper {
| diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/BUILD b/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
index b2fbbd60ec8b8e..1e498ca33c4db3 100644
--- a/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/BUILD
@@ -25,7 +25,11 @@ java_library(
),
deps = [
"//src/main/java/com/google/devtools/build/lib/authandtls",
+ "//src/main/java/com/google/devtools/build/lib/vfs",
+ "//src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs",
"//src/main/java/com/google/devtools/common/options",
+ "//src/test/java/com/google/devtools/build/lib/testutil",
+ "//third_party:auth",
"//third_party:guava",
"//third_party:junit4",
"//third_party:mockito",
diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtilsTest.java b/src/test/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtilsTest.java
new file mode 100644
index 00000000000000..a3dc50273d82ae
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/GoogleAuthUtilsTest.java
@@ -0,0 +1,111 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.lib.authandtls;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import com.google.auth.Credentials;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.devtools.build.lib.testutil.Scratch;
+import com.google.devtools.build.lib.vfs.DigestHashFunction;
+import com.google.devtools.build.lib.vfs.FileSystem;
+import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class GoogleAuthUtilsTest {
+ @Test
+ public void testNetrc_emptyEnv_shouldIgnore() throws Exception {
+ ImmutableMap<String, String> clientEnv = ImmutableMap.of();
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+
+ assertThat(GoogleAuthUtils.newCredentialsFromNetrc(clientEnv, fileSystem)).isEmpty();
+ }
+
+ @Test
+ public void testNetrc_netrcNotExist_shouldIgnore() throws Exception {
+ String home = "/home/foo";
+ ImmutableMap<String, String> clientEnv = ImmutableMap.of("HOME", home);
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+
+ assertThat(GoogleAuthUtils.newCredentialsFromNetrc(clientEnv, fileSystem)).isEmpty();
+ }
+
+ @Test
+ public void testNetrc_netrcExist_shouldUse() throws Exception {
+ String home = "/home/foo";
+ ImmutableMap<String, String> clientEnv = ImmutableMap.of("HOME", home);
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+ Scratch scratch = new Scratch(fileSystem);
+ scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
+
+ Optional<Credentials> credentials =
+ GoogleAuthUtils.newCredentialsFromNetrc(clientEnv, fileSystem);
+
+ assertThat(credentials).isPresent();
+ assertRequestMetadata(
+ credentials.get().getRequestMetadata(URI.create("https://foo.example.org")),
+ "foouser",
+ "foopass");
+ }
+
+ @Test
+ public void testNetrc_netrcFromNetrcEnvExist_shouldUse() throws Exception {
+ String home = "/home/foo";
+ String netrc = "/.netrc";
+ ImmutableMap<String, String> clientEnv = ImmutableMap.of("HOME", home, "NETRC", netrc);
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+ Scratch scratch = new Scratch(fileSystem);
+ scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
+ scratch.file(netrc, "machine foo.example.org login baruser password barpass");
+
+ Optional<Credentials> credentials =
+ GoogleAuthUtils.newCredentialsFromNetrc(clientEnv, fileSystem);
+
+ assertThat(credentials).isPresent();
+ assertRequestMetadata(
+ credentials.get().getRequestMetadata(URI.create("https://foo.example.org")),
+ "baruser",
+ "barpass");
+ }
+
+ @Test
+ public void testNetrc_netrcFromNetrcEnvNotExist_shouldIgnore() throws Exception {
+ String home = "/home/foo";
+ String netrc = "/.netrc";
+ ImmutableMap<String, String> clientEnv = ImmutableMap.of("HOME", home, "NETRC", netrc);
+ FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
+ Scratch scratch = new Scratch(fileSystem);
+ scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
+
+ assertThat(GoogleAuthUtils.newCredentialsFromNetrc(clientEnv, fileSystem)).isEmpty();
+ }
+
+ private static void assertRequestMetadata(
+ Map<String, List<String>> requestMetadata, String username, String password) {
+ assertThat(requestMetadata.keySet()).containsExactly("Authorization");
+ assertThat(Iterables.getOnlyElement(requestMetadata.values()))
+ .containsExactly(BasicHttpAuthenticationEncoder.encode(username, password, UTF_8));
+ }
+}
diff --git a/src/test/java/com/google/devtools/build/lib/remote/BUILD b/src/test/java/com/google/devtools/build/lib/remote/BUILD
index 88d69b7436bf37..e0e9aadb50a40f 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/remote/BUILD
@@ -44,17 +44,14 @@ java_test(
"//src/main/java/com/google/devtools/build/lib:runtime",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:action_input_helper",
- "//src/main/java/com/google/devtools/build/lib/actions:action_lookup_data",
"//src/main/java/com/google/devtools/build/lib/actions:artifacts",
"//src/main/java/com/google/devtools/build/lib/actions:execution_requirements",
"//src/main/java/com/google/devtools/build/lib/actions:file_metadata",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
"//src/main/java/com/google/devtools/build/lib/analysis:blaze_directories",
"//src/main/java/com/google/devtools/build/lib/analysis:blaze_version_info",
- "//src/main/java/com/google/devtools/build/lib/analysis:config/build_options",
"//src/main/java/com/google/devtools/build/lib/analysis:config/core_options",
"//src/main/java/com/google/devtools/build/lib/analysis:server_directories",
- "//src/main/java/com/google/devtools/build/lib/analysis/platform:platform_utils",
"//src/main/java/com/google/devtools/build/lib/authandtls",
"//src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
@@ -79,7 +76,6 @@ java_test(
"//src/main/java/com/google/devtools/build/lib/remote/util",
"//src/main/java/com/google/devtools/build/lib/runtime/commands",
"//src/main/java/com/google/devtools/build/lib/skyframe:tree_artifact_value",
- "//src/main/java/com/google/devtools/build/lib/util",
"//src/main/java/com/google/devtools/build/lib/util:abrupt_exit_exception",
"//src/main/java/com/google/devtools/build/lib/util:exit_code",
"//src/main/java/com/google/devtools/build/lib/util/io",
@@ -95,7 +91,6 @@ java_test(
"//src/test/java/com/google/devtools/build/lib/exec/util",
"//src/test/java/com/google/devtools/build/lib/remote/util",
"//src/test/java/com/google/devtools/build/lib/testutil",
- "//src/test/java/com/google/devtools/build/lib/testutil:JunitUtils",
"//src/test/java/com/google/devtools/build/lib/testutil:TestUtils",
"//third_party:api_client",
"//third_party:auth",
diff --git a/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java b/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
index 28d4997c39f523..2048f0c0214fe8 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
@@ -219,7 +219,7 @@ protected GrpcCacheClient newClient(
try (InputStream in = scratch.resolve(authTlsOptions.googleCredentials).getInputStream()) {
callCredentialsProvider =
GoogleAuthUtils.newCallCredentialsProvider(
- GoogleAuthUtils.newCredentials(in, authTlsOptions.googleAuthScopes));
+ GoogleAuthUtils.newGoogleCredentialsFromFile(in, authTlsOptions.googleAuthScopes));
}
CallCredentials creds = callCredentialsProvider.getCallCredentials();
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
index e15cdf3ecbe2c4..94479e9ad7544c 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteModuleTest.java
@@ -15,7 +15,6 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
-import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,7 +37,6 @@
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions.UnresolvedScopedCredentialHelper;
-import com.google.devtools.build.lib.authandtls.BasicHttpAuthenticationEncoder;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperEnvironment;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperProvider;
import com.google.devtools.build.lib.events.Reporter;
@@ -77,7 +75,6 @@
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
-import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -489,77 +486,6 @@ public void getCapabilities(
}
}
- @Test
- public void testNetrc_emptyEnv_shouldIgnore() throws Exception {
- Map<String, String> clientEnv = ImmutableMap.of();
- FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
-
- Credentials credentials = RemoteModule.newCredentialsFromNetrc(clientEnv, fileSystem);
-
- assertThat(credentials).isNull();
- }
-
- @Test
- public void testNetrc_netrcNotExist_shouldIgnore() throws Exception {
- String home = "/home/foo";
- Map<String, String> clientEnv = ImmutableMap.of("HOME", home);
- FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
-
- Credentials credentials = RemoteModule.newCredentialsFromNetrc(clientEnv, fileSystem);
-
- assertThat(credentials).isNull();
- }
-
- @Test
- public void testNetrc_netrcExist_shouldUse() throws Exception {
- String home = "/home/foo";
- Map<String, String> clientEnv = ImmutableMap.of("HOME", home);
- FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
- Scratch scratch = new Scratch(fileSystem);
- scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
-
- Credentials credentials = RemoteModule.newCredentialsFromNetrc(clientEnv, fileSystem);
-
- assertThat(credentials).isNotNull();
- assertRequestMetadata(
- credentials.getRequestMetadata(URI.create("https://foo.example.org")),
- "foouser",
- "foopass");
- }
-
- @Test
- public void testNetrc_netrcFromNetrcEnvExist_shouldUse() throws Exception {
- String home = "/home/foo";
- String netrc = "/.netrc";
- Map<String, String> clientEnv = ImmutableMap.of("HOME", home, "NETRC", netrc);
- FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
- Scratch scratch = new Scratch(fileSystem);
- scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
- scratch.file(netrc, "machine foo.example.org login baruser password barpass");
-
- Credentials credentials = RemoteModule.newCredentialsFromNetrc(clientEnv, fileSystem);
-
- assertThat(credentials).isNotNull();
- assertRequestMetadata(
- credentials.getRequestMetadata(URI.create("https://foo.example.org")),
- "baruser",
- "barpass");
- }
-
- @Test
- public void testNetrc_netrcFromNetrcEnvNotExist_shouldIgnore() throws Exception {
- String home = "/home/foo";
- String netrc = "/.netrc";
- Map<String, String> clientEnv = ImmutableMap.of("HOME", home, "NETRC", netrc);
- FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
- Scratch scratch = new Scratch(fileSystem);
- scratch.file(home + "/.netrc", "machine foo.example.org login foouser password foopass");
-
- Credentials credentials = RemoteModule.newCredentialsFromNetrc(clientEnv, fileSystem);
-
- assertThat(credentials).isNull();
- }
-
@Test
public void testNetrc_netrcWithoutRemoteCache() throws Exception {
String netrc = "/.netrc";
@@ -580,13 +506,6 @@ public void testNetrc_netrcWithoutRemoteCache() throws Exception {
assertThat(credentials.getRequestMetadata(URI.create("https://bar.example.org"))).isEmpty();
}
- private static void assertRequestMetadata(
- Map<String, List<String>> requestMetadata, String username, String password) {
- assertThat(requestMetadata.keySet()).containsExactly("Authorization");
- assertThat(Iterables.getOnlyElement(requestMetadata.values()))
- .containsExactly(BasicHttpAuthenticationEncoder.encode(username, password, UTF_8));
- }
-
@Test
public void testCredentialHelperProvider() throws Exception {
FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteServerCapabilitiesTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteServerCapabilitiesTest.java
index 33e4bcf346dd84..0948fe4a419963 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteServerCapabilitiesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteServerCapabilitiesTest.java
@@ -224,7 +224,7 @@ public int maxConcurrency() {
}
});
CallCredentials creds =
- GoogleAuthUtils.newCallCredentials(Options.getDefaults(AuthAndTLSOptions.class));
+ GoogleAuthUtils.newGoogleCallCredentials(Options.getDefaults(AuthAndTLSOptions.class));
RemoteServerCapabilities client =
new RemoteServerCapabilities("instance", channel.retain(), creds, 3, retrier);
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerWithGrpcRemoteExecutorTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerWithGrpcRemoteExecutorTest.java
index bcb5c9c2d15f30..de8fb3a84544b7 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerWithGrpcRemoteExecutorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerWithGrpcRemoteExecutorTest.java
@@ -286,7 +286,8 @@ public int maxConcurrency() {
new GrpcRemoteExecutor(channel.retain(), CallCredentialsProvider.NO_CREDENTIALS, retrier);
CallCredentialsProvider callCredentialsProvider =
GoogleAuthUtils.newCallCredentialsProvider(
- GoogleAuthUtils.newCredentials(Options.getDefaults(AuthAndTLSOptions.class)));
+ GoogleAuthUtils.newGoogleCredentials(Options.getDefaults(AuthAndTLSOptions.class))
+ .orElse(null));
ByteStreamUploader uploader =
new ByteStreamUploader(
remoteOptions.remoteInstanceName,
diff --git a/src/test/shell/bazel/remote/remote_execution_http_test.sh b/src/test/shell/bazel/remote/remote_execution_http_test.sh
index 262170ff9e6c15..0565d4dd8142f9 100755
--- a/src/test/shell/bazel/remote/remote_execution_http_test.sh
+++ b/src/test/shell/bazel/remote/remote_execution_http_test.sh
@@ -545,7 +545,7 @@ EOF
--remote_cache=http://localhost:${http_port} \
//a:foo &> $TEST_log \
|| fail "Failed to build //a:foo"
- expect_not_log "WARNING: Username and password from .netrc is transmitted in plaintext" "Should not print warning"
+ expect_not_log "WARNING: Credentials are transmitted in plaintext" "Should not print warning"
}
function test_remote_http_cache_with_netrc_warning() {
@@ -565,7 +565,7 @@ EOF
--remote_cache=http://localhost:${http_port} \
//a:foo &> $TEST_log \
|| fail "Failed to build //a:foo"
- expect_log "WARNING: Username and password from .netrc is transmitted in plaintext"
+ expect_log "WARNING: Credentials are transmitted in plaintext"
}
run_suite "Remote execution and remote cache tests"
| train | val | 2022-07-25T07:14:18 | "2022-07-20T08:03:24Z" | Yannic | test |
bazelbuild/bazel/15856_15971 | bazelbuild/bazel | bazelbuild/bazel/15856 | bazelbuild/bazel/15971 | [
"keyword_pr_to_issue"
] | 96d23d30cc80912b82a8fbab31c902e9db74b6ab | c5bc34e5f1dd92703dd8f15f9f0409c49b778837 | [
"@bazel-io flag",
"@bazel-io fork 5.3.0",
"Since this feature is implemented and cherry picked to 5.3.0, should we close this one?",
"The proposal hasn't been fully implemented yet (e.g. we're missing support for repository fetching).",
"Marking this as a release blocker since we want the repository fetching support to make it into 6.0.0 if possible.",
"@tjgq What's the ETA for implementing this? Ideally, we don't want to delay the 6.0 release further more, and since this should be a backwards compatible feature, we can cherry pick it in 6.x releases?",
"I was planning to get this submitted in time for 6.0.0, but other things got in the way. Let's do it for a 6.x release instead.",
"This has been fully implemented in 7.x and backported to 6.x."
] | [] | "2022-07-25T16:30:57Z" | [
"type: feature request",
"P2",
"team-Remote-Exec"
] | Implement the credential helpers proposal | ### Description of the feature request:
Tracking issue for implementing https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md.
### What underlying problem are you trying to solve with this feature?
N/A
### Which operating system are you running Bazel on?
N/A
### What is the output of `bazel info release`?
N/A
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
N/A
```
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java",
"src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java"
] | [
"src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java",
"src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java b/src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java
index 9d6919cf83c10d..967ac115f213f5 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java
@@ -104,6 +104,7 @@ public class CommandEnvironment {
private final ImmutableList<Any> commandExtensions;
private final ImmutableList.Builder<Any> responseExtensions = ImmutableList.builder();
private final Consumer<String> shutdownReasonConsumer;
+ private final CommandLinePathFactory commandLinePathFactory;
private OutputService outputService;
private TopDownActionCache topDownActionCache;
@@ -266,6 +267,9 @@ public void exit(AbruptExitException exception) {
repoEnvFromOptions.put(name, value);
}
}
+
+ this.commandLinePathFactory =
+ CommandLinePathFactory.create(runtime.getFileSystem(), directories);
}
private Path computeWorkingDirectory(CommonCommandOptions commandOptions)
@@ -840,4 +844,8 @@ public ImmutableList<Any> getResponseExtensions() {
public void addResponseExtensions(Iterable<Any> extensions) {
responseExtensions.addAll(extensions);
}
+
+ public CommandLinePathFactory getCommandLinePathFactory() {
+ return commandLinePathFactory;
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java b/src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java
index e39bf074b2d91c..074bda748af98d 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/CommandLinePathFactory.java
@@ -13,10 +13,12 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
@@ -44,11 +46,27 @@ public final class CommandLinePathFactory {
private final FileSystem fileSystem;
private final ImmutableMap<String, Path> roots;
+ @VisibleForTesting
public CommandLinePathFactory(FileSystem fileSystem, ImmutableMap<String, Path> roots) {
this.fileSystem = Preconditions.checkNotNull(fileSystem);
this.roots = Preconditions.checkNotNull(roots);
}
+ static CommandLinePathFactory create(FileSystem fileSystem, BlazeDirectories directories) {
+ Preconditions.checkNotNull(fileSystem);
+ Preconditions.checkNotNull(directories);
+
+ ImmutableMap.Builder<String, Path> wellKnownRoots = ImmutableMap.builder();
+
+ // This is necessary because some tests don't have a workspace set.
+ Path workspace = directories.getWorkspace();
+ if (workspace != null) {
+ wellKnownRoots.put("workspace", workspace);
+ }
+
+ return new CommandLinePathFactory(fileSystem, wellKnownRoots.build());
+ }
+
/** Creates a {@link Path}. */
public Path create(Map<String, String> env, String value) throws IOException {
Preconditions.checkNotNull(env);
| null | train | val | 2022-07-25T18:46:36 | "2022-07-11T15:16:11Z" | tjgq | test |
bazelbuild/bazel/15271_15984 | bazelbuild/bazel | bazelbuild/bazel/15271 | bazelbuild/bazel/15984 | [
"keyword_pr_to_issue"
] | a24d1bc30ded24af0fd33646dcbd62a9a07e98b7 | 4ae85387e69db73e507b4f18b36d3e2f799e5d34 | [
"@gregestren , FYI.\r\n\r\nI'll work on this once the robotics season is over at the end of this month and after I finish with #14096.",
"Makes total sense, and I agree. Thanks for the report and commitment, and good luck with robotics!"
] | [] | "2022-07-26T23:03:27Z" | [
"P2",
"team-Configurability"
] | Aspects get falsely evaluated against incompatible targets | ### Description of the bug:
It looks like aspects run on incompatible targets when they shouldn't.
I think the answer here is that the aspects should not run and instead just provide the `IncompatiblePlatformProvider` to signify that it's incompatible as well.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
The absolute minimal example:
`example.bzl`:
```python
def _custom_rule_impl(ctx):
pass
custom_rule = rule(
implementation = _custom_rule_impl,
)
def _example_aspect_impl(target, ctx):
print("Running aspect on " + str(target))
return []
_example_aspect = aspect(
implementation = _example_aspect_impl,
attr_aspects = ["dep"],
)
def _basic_rule_with_aspect_impl(ctx):
pass
basic_rule_with_aspect = rule(
implementation = _basic_rule_with_aspect_impl,
attrs = {
"dep": attr.label(
aspects = [_example_aspect],
),
},
)
```
`BUILD`:
```python
load(":example.bzl", "basic_rule_with_aspect", "custom_rule")
custom_rule(
name = "target1",
target_compatible_with = ["@platforms//:incompatible"],
)
basic_rule_with_aspect(
name = "target2",
dep = ":target1",
)
```
When you build this target, you'll see that the `print()` statement in the aspect gets executed:
```console
$ bazel build //:target2
DEBUG: /home/pschrader/work/test_repo/example.bzl:9:10: Running aspect on <target //:target1>
ERROR: Target //:target2 is incompatible and cannot be built, but was explicitly requested.
Dependency chain:
//:target2
//:target1 <-- target platform (@local_config_platform//:host) didn't satisfy constraint @platforms//:incompatible
INFO: Elapsed time: 0.070s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (1 packages loaded, 2 targets configured)
```
This can lead to undesirable effects. Largely because the aspect evaluation can generate errors before bazel gets a chance to tell the user about the incompatible target being requested.
### Which operating system are you running Bazel on?
Ubuntu 18.04
### What is the output of `bazel info release`?
release 5.1.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
N/A
```
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/BUILD"
] | [
"src/test/shell/integration/target_compatible_with_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java
index 2633d473afdea4..bb0446dba09d9b 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java
@@ -36,6 +36,7 @@
import com.google.devtools.build.lib.analysis.DependencyKind;
import com.google.devtools.build.lib.analysis.DuplicateException;
import com.google.devtools.build.lib.analysis.ExecGroupCollection.InvalidExecGroupException;
+import com.google.devtools.build.lib.analysis.IncompatiblePlatformProvider;
import com.google.devtools.build.lib.analysis.InconsistentAspectOrderException;
import com.google.devtools.build.lib.analysis.PlatformOptions;
import com.google.devtools.build.lib.analysis.ResolvedToolchainContext;
@@ -292,6 +293,20 @@ public SkyValue compute(SkyKey skyKey, Environment env)
throw new IllegalStateException("Name already verified", e);
}
+ // If the target is incompatible, then there's not much to do. The intent here is to create an
+ // AspectValue that doesn't trigger any of the associated target's dependencies to be evaluated
+ // against this aspect.
+ if (associatedTarget.get(IncompatiblePlatformProvider.PROVIDER) != null) {
+ return new AspectValue(
+ key,
+ aspect,
+ target.getLocation(),
+ ConfiguredAspect.forNonapplicableTarget(),
+ /*transitivePackagesForPackageRootResolution=*/ NestedSetBuilder
+ .<Package>stableOrder()
+ .build());
+ }
+
if (AliasProvider.isAlias(associatedTarget)) {
return createAliasAspect(
env,
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/BUILD b/src/main/java/com/google/devtools/build/lib/skyframe/BUILD
index 468b1290e45e5b..e8b8287413765d 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/BUILD
@@ -258,6 +258,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/analysis:duplicate_exception",
"//src/main/java/com/google/devtools/build/lib/analysis:exec_group_collection",
"//src/main/java/com/google/devtools/build/lib/analysis:extra_action_artifacts_provider",
+ "//src/main/java/com/google/devtools/build/lib/analysis:incompatible_platform_provider",
"//src/main/java/com/google/devtools/build/lib/analysis:inconsistent_aspect_order_exception",
"//src/main/java/com/google/devtools/build/lib/analysis:platform_configuration",
"//src/main/java/com/google/devtools/build/lib/analysis:platform_options",
| diff --git a/src/test/shell/integration/target_compatible_with_test.sh b/src/test/shell/integration/target_compatible_with_test.sh
index fd432689c736be..d00895b6e302e4 100755
--- a/src/test/shell/integration/target_compatible_with_test.sh
+++ b/src/test/shell/integration/target_compatible_with_test.sh
@@ -1066,4 +1066,163 @@ function test_aquery_incompatible_target() {
expect_log "target platform (//target_skipping:foo3_platform) didn't satisfy constraint //target_skipping:foo1"
}
+# Use aspects to interact with incompatible targets and validate the behaviour.
+function test_aspect_skipping() {
+ cat >> target_skipping/BUILD <<EOF
+load(":defs.bzl", "basic_rule", "rule_with_aspect")
+# This target is compatible with all platforms and configurations. This target
+# exists to validate the behaviour of aspects running against incompatible
+# targets. The expectation is that the aspect should _not_ propagate to this
+# compatible target from an incomaptible target. I.e. an aspect should _not_
+# evaluate this target if "basic_foo3_target" is incompatible.
+basic_rule(
+ name = "basic_universal_target",
+)
+# An alias to validate that incompatible target skipping works as expected with
+# aliases and aspects.
+alias(
+ name = "aliased_basic_universal_target",
+ actual = ":basic_universal_target",
+)
+basic_rule(
+ name = "basic_foo3_target",
+ deps = [
+ ":aliased_basic_universal_target",
+ ],
+ target_compatible_with = [
+ ":foo3",
+ ],
+)
+# This target is only compatible when "basic_foo3_target" is compatible. This
+# target exists to validate the behaviour of aspects running against
+# incompatible targets. The expectation is that the aspect should _not_
+# evaluate this target when "basic_foo3_target" is incompatible.
+basic_rule(
+ name = "other_basic_target",
+ deps = [
+ ":basic_foo3_target",
+ ],
+)
+alias(
+ name = "aliased_other_basic_target",
+ actual = ":other_basic_target",
+)
+rule_with_aspect(
+ name = "inspected_foo3_target",
+ inspect = ":aliased_other_basic_target",
+)
+basic_rule(
+ name = "previously_inspected_basic_target",
+ deps = [
+ ":inspected_foo3_target",
+ ],
+)
+rule_with_aspect(
+ name = "twice_inspected_foo3_target",
+ inspect = ":previously_inspected_basic_target",
+)
+genrule(
+ name = "generated_file",
+ outs = ["generated_file.txt"],
+ cmd = "echo '' > \$(OUTS)",
+ target_compatible_with = [
+ ":foo1",
+ ],
+)
+rule_with_aspect(
+ name = "inspected_generated_file",
+ inspect = ":generated_file",
+)
+EOF
+ cat > target_skipping/defs.bzl <<EOF
+BasicProvider = provider()
+def _basic_rule_impl(ctx):
+ return [DefaultInfo(), BasicProvider()]
+basic_rule = rule(
+ implementation = _basic_rule_impl,
+ attrs = {
+ "deps": attr.label_list(
+ providers = [BasicProvider],
+ ),
+ },
+)
+def _inspecting_aspect_impl(target, ctx):
+ print("Running aspect on " + str(target))
+ return []
+_inspecting_aspect = aspect(
+ implementation = _inspecting_aspect_impl,
+ attr_aspects = ["deps"],
+)
+def _rule_with_aspect_impl(ctx):
+ out = ctx.actions.declare_file(ctx.label.name)
+ ctx.actions.write(out, "")
+ return [
+ DefaultInfo(files=depset([out])),
+ BasicProvider(),
+ ]
+rule_with_aspect = rule(
+ implementation = _rule_with_aspect_impl,
+ attrs = {
+ "inspect": attr.label(
+ aspects = [_inspecting_aspect],
+ ),
+ },
+)
+EOF
+ cd target_skipping || fail "couldn't cd into workspace"
+ local debug_message1="Running aspect on <target //target_skipping:basic_universal_target>"
+ local debug_message2="Running aspect on <target //target_skipping:basic_foo3_target>"
+ local debug_message3="Running aspect on <target //target_skipping:other_basic_target>"
+ local debug_message4="Running aspect on <target //target_skipping:previously_inspected_basic_target>"
+ local debug_message5="Running aspect on <target //target_skipping:generated_file>"
+ # Validate that aspects run against compatible targets.
+ bazel build \
+ --show_result=10 \
+ --host_platform=@//target_skipping:foo3_platform \
+ --platforms=@//target_skipping:foo3_platform \
+ //target_skipping:all &> "${TEST_log}" \
+ || fail "Bazel failed unexpectedly."
+ expect_log "${debug_message1}"
+ expect_log "${debug_message2}"
+ expect_log "${debug_message3}"
+ expect_log "${debug_message4}"
+ expect_not_log "${debug_message5}"
+ # Invert the compatibility and validate that aspects run on the other targets
+ # now.
+ bazel build \
+ --show_result=10 \
+ --host_platform=@//target_skipping:foo1_bar1_platform \
+ --platforms=@//target_skipping:foo1_bar1_platform \
+ //target_skipping:all &> "${TEST_log}" \
+ || fail "Bazel failed unexpectedly."
+ expect_not_log "${debug_message1}"
+ expect_not_log "${debug_message2}"
+ expect_not_log "${debug_message3}"
+ expect_not_log "${debug_message4}"
+ expect_log "${debug_message5}"
+ # Validate that explicitly trying to build a target with an aspect against an
+ # incompatible target produces the normal error message.
+ bazel build \
+ --show_result=10 \
+ --host_platform=@//target_skipping:foo1_bar1_platform \
+ --platforms=@//target_skipping:foo1_bar1_platform \
+ //target_skipping:twice_inspected_foo3_target &> "${TEST_log}" \
+ && fail "Bazel passed unexpectedly."
+ # TODO(#15427): Should use expect_log_once here when the issue is fixed.
+ expect_log 'ERROR: Target //target_skipping:twice_inspected_foo3_target is incompatible and cannot be built, but was explicitly requested.'
+ expect_log '^Dependency chain:$'
+ expect_log '^ //target_skipping:twice_inspected_foo3_target$'
+ expect_log '^ //target_skipping:previously_inspected_basic_target$'
+ expect_log '^ //target_skipping:inspected_foo3_target$'
+ expect_log '^ //target_skipping:aliased_other_basic_target$'
+ expect_log '^ //target_skipping:other_basic_target$'
+ expect_log " //target_skipping:basic_foo3_target <-- target platform (//target_skipping:foo1_bar1_platform) didn't satisfy constraint //target_skipping:foo3$"
+ expect_log 'FAILED: Build did NOT complete successfully'
+ expect_not_log "${debug_message1}"
+ expect_not_log "${debug_message2}"
+ expect_not_log "${debug_message3}"
+ expect_not_log "${debug_message4}"
+ expect_not_log "${debug_message5}"
+}
+
run_suite "target_compatible_with tests"
| test | val | 2022-07-27T09:36:17 | "2022-04-16T00:31:28Z" | philsc | test |
bazelbuild/bazel/16003_16079 | bazelbuild/bazel | bazelbuild/bazel/16003 | bazelbuild/bazel/16079 | [
"keyword_pr_to_issue"
] | 82452c7c372fb28485b0b5e0a98b471648f0dfd0 | e745468461f93839491a4f80d0c1883d9007f9c0 | [
"Does https://github.com/bazelbuild/bazel/pull/14600 fix this issue?",
"Aw, I was hopeful. I fixed some merge conflicts (looks like \"../\".replace() -> Strings.replace(\"../\", ...) and I still get the same failure.\r\n\r\n```\r\n==================== Test output for @aos//aos:condition_test:\r\n/var/lib/worker/work/3/exec/bazel-out/k8-opt/bin/external/aos/aos/condition_test.runfiles/repo/../aos/aos/condition_test: error while loading shared libraries: libexternal_Saos_Saos_Slibcondition.so: cannot open shared object file: No such file or directory\r\n```",
"Could you check whether https://github.com/bazelbuild/bazel/pull/16008 fixes the issue? It includes an integration test that I distilled from your reproducer.",
"It does! Great work, thanks for the prompt response and prompt resolution. I really appreciate it.\r\n\r\nFYI, there's the same merge conflict with Strings.replace. Not a hard thing to fix though.",
"Assigning to @oquenchil since the linked fix is about cc rules.",
"Aw, @fmeum , looks like this fixed almost all of the tests except one which expects $(location) and RPATH to agree on the path to the shared libraries. https://github.com/bazelbuild/bazel/issues/16108 is the issue since it smells different enough to be a new bug.",
"@bazel-io fork 5.3.1",
"The fix introduced a regression (see https://github.com/bazelbuild/bazel/pull/16008#issuecomment-1224267553), which we will probably need a patch release for.",
"Seeing a very similar problem when upgrading from 5.2.0 to 5.3.0:\r\n```\r\nerror while loading shared libraries: libexternal_Sopenvkl_Slibispc_Uutil_Uispc.so: cannot open shared object file: No such file or directory\r\n```\r\nBut trying out 5.3.1rc2, it looks like that particular problem is resolved for us.",
"Hello @AustinSchuh, Are you still seeing this issue with Release 5.3.1 ? ",
"5.3.1 works for me. I'm hitting https://github.com/bazelbuild/bazel/issues/16108 but that feels separate.",
"Thanks for the update @AustinSchuh!"
] | [] | "2022-08-10T12:22:08Z" | [
"type: bug",
"P2",
"team-Rules-CPP"
] | Bazel 5.3 fails to run external tests | ### Description of the bug:
Bazel fails to run C++ tests in external repositories on remote execution.
Running locally passes, even with linux-sandbox. Bazel 5.0 worked. This has broken bazel > 5.0 for us, and is blocking all upgrades.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
`bazel test -c opt --config=engflow --config=build_without_the_bytes @aos//aos:condition_test`
Run a c++ test for an external repository on remote execution. (I can't give you a remote execution cluster)
### Which operating system are you running Bazel on?
Debian Bullseye
### What is the output of `bazel info release`?
release 5.3.0-202207291633+f440f8ec3f
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
```
#!/bin/bash
# This script builds a Debian package from a Bazel source tree with the
# correct version.
# The only argument is the path to a Bazel source tree.
set -e
set -u
BAZEL_SOURCE="$1"
VERSION="5.3.0-$(date +%Y%m%d%H%M)+$(GIT_DIR="${BAZEL_SOURCE}/.git" git rev-parse --short HEAD)"
OUTPUT="bazel_${VERSION}"
(
cd "${BAZEL_SOURCE}"
bazel build -c opt //src:bazel --embed_label="${VERSION}" --stamp=yes
)
cp "${BAZEL_SOURCE}/bazel-bin/src/bazel" "${OUTPUT}"
echo "Output is at ${OUTPUT}"
```
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
austin[504] cmbr (release-5.3.0) ~/local/bazel
$ git remote get-url origin; git rev-parse master; git rev-parse HEAD
https://github.com/bazelbuild/bazel
master
fatal: ambiguous argument 'master': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
f440f8ec3f63e5d663e1f9d9614f05a39422102a
```
### Have you found anything relevant by searching the web?
Reverting https://github.com/bazelbuild/bazel/commit/00805727b867d33fd922e63ca82b0d9825ad79fe fixes it. https://github.com/bazelbuild/bazel/issues/12821 suggested that I add linkstatic to every C++ test we want to run, which seems like 1k's of lines of diffs off upstream, since no reasonable upstream would accept that patch.
### Any other information, logs, or outputs that you want to share?
```
bazel test -c opt --config=remote_execution --config=build_without_the_bytes @aos//aos:condition_test
INFO: Invocation ID: d91e1b30-a290-4282-99c6-029e4102ed35
INFO: Analyzed target @aos//aos:condition_test (86 packages loaded, 20904 targets configured).
INFO: Found 1 test target...
FAIL: @aos//aos:condition_test (see /home/austin/.cache/bazel/_bazel_austin/f5b123ff4a0d503fd09f4c4da36644a6/execroot/repo/bazel-out/k8-opt/testlogs/external/aos/aos/condition_test/test.log)
INFO: From Testing @aos//aos:condition_test:
==================== Test output for @aos//aos:condition_test:
/var/lib/worker/work/1/exec/bazel-out/k8-opt/bin/external/aos/aos/condition_test.runfiles/repo/../aos/aos/condition_test: error while loading shared libraries: libexternal_Saos_Saos_Slibcondition.so: cannot open shared object file: No such file or directory
================================================================================
Target @aos//aos:condition_test up-to-date:
bazel-bin/external/aos/aos/condition_test
INFO: Elapsed time: 166.038s, Critical Path: 153.48s
INFO: 52 processes: 50 remote cache hit, 2 remote.
@aos//aos:condition_test FAILED in 127.2s
/home/austin/.cache/bazel/_bazel_austin/f5b123ff4a0d503fd09f4c4da36644a6/execroot/repo/bazel-out/k8-opt/testlogs/external/aos/aos/condition_test/test.log
Executed 1 out of 1 test: 1 fails remotely.
INFO: Build completed, 1 test FAILED, 52 total actions
```
And to prove I'm not crazy:
```
bazel test -c opt -k @aos//aos:condition_test
INFO: Build options --experimental_inmemory_dotd_files, --experimental_inmemory_jdeps_files, --extra_execution_platforms, and 2 more have changed, discarding analysis cache.
INFO: Analyzed target @aos//aos:condition_test (0 packages loaded, 20897 targets configured).
INFO: Found 1 test target...
Target @aos//aos:condition_test up-to-date:
bazel-bin/external/aos/aos/condition_test
INFO: Elapsed time: 12.246s, Critical Path: 10.91s
INFO: 120 processes: 42 internal, 78 linux-sandbox.
INFO: Build completed successfully, 120 total actions
@aos//aos:condition_test PASSED in 2.3s
Executed 1 out of 1 test: 1 test passes.
INFO: Build completed successfully, 120 total actions
``` | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java",
"src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java",
"src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java"
] | [
"src/test/shell/bazel/remote/remote_execution_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java
index 330bcdce43b2cd..6624c1c5b4c4be 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkActionBuilder.java
@@ -26,6 +26,7 @@
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ParameterFile;
+import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RuleErrorConsumer;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
@@ -798,7 +799,8 @@ public CppLinkAction build() throws InterruptedException, RuleErrorException {
allowLtoIndexing,
nonExpandedLinkerInputs,
needWholeArchive,
- ruleErrorConsumer);
+ ruleErrorConsumer,
+ ((RuleContext) actionConstructionContext).getWorkspaceName());
CollectedLibrariesToLink collectedLibrariesToLink =
librariesToLinkCollector.collectLibrariesToLink();
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
index a1bb3b99d64b2d..27be6f49d23b6f 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
@@ -20,6 +20,7 @@
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleErrorConsumer;
+import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration;
@@ -69,7 +70,8 @@ public LibrariesToLinkCollector(
boolean allowLtoIndexing,
Iterable<LinkerInput> linkerInputs,
boolean needWholeArchive,
- RuleErrorConsumer ruleErrorConsumer) {
+ RuleErrorConsumer ruleErrorConsumer,
+ String workspaceName) {
this.isNativeDeps = isNativeDeps;
this.cppConfiguration = cppConfiguration;
this.ccToolchainProvider = toolchain;
@@ -106,10 +108,20 @@ public LibrariesToLinkCollector(
// there's no *one* RPATH setting that fits all targets involved in the sharing.
rpathRoot = ccToolchainProvider.getSolibDirectory() + "/";
} else {
- rpathRoot =
- Strings.repeat("../", outputArtifact.getRootRelativePath().segmentCount() - 1)
- + ccToolchainProvider.getSolibDirectory()
- + "/";
+ // When executed from within a runfiles directory, the binary lies under a path such as
+ // target.runfiles/some_repo/pkg/file, whereas the solib directory is located under
+ // target.runfiles/main_repo.
+ PathFragment runfilesPath = outputArtifact.getRunfilesPath();
+ String runfilesExecRoot;
+ if (runfilesPath.startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX)) {
+ // runfilesPath is of the form ../some_repo/pkg/file, walk back some_repo/pkg and then
+ // descend into the main workspace.
+ runfilesExecRoot = Strings.repeat("../", runfilesPath.segmentCount() - 2) + workspaceName + "/";
+ } else {
+ // runfilesPath is of the form pkg/file, walk back pkg to reach the main workspace.
+ runfilesExecRoot = Strings.repeat("../", runfilesPath.segmentCount() - 1);
+ }
+ rpathRoot = runfilesExecRoot + ccToolchainProvider.getSolibDirectory() + "/";
}
ltoMap = generateLtoMap();
| diff --git a/src/test/shell/bazel/remote/remote_execution_test.sh b/src/test/shell/bazel/remote/remote_execution_test.sh
index e79b2dfe4f4d49..318fdccd25cd54 100755
--- a/src/test/shell/bazel/remote/remote_execution_test.sh
+++ b/src/test/shell/bazel/remote/remote_execution_test.sh
@@ -3811,4 +3811,62 @@ EOF
expect_log "Executing genrule .* failed: (Exit 1):"
}
+function test_external_cc_test() {
+ if [[ "$PLATFORM" == "darwin" ]]; then
+ # TODO(b/37355380): This test is disabled due to RemoteWorker not supporting
+ # setting SDKROOT and DEVELOPER_DIR appropriately, as is required of
+ # action executors in order to select the appropriate Xcode toolchain.
+ return 0
+ fi
+
+ cat >> WORKSPACE <<'EOF'
+local_repository(
+ name = "other_repo",
+ path = "other_repo",
+)
+EOF
+
+ mkdir -p other_repo
+ touch other_repo/WORKSPACE
+
+ mkdir -p other_repo/lib
+ cat > other_repo/lib/BUILD <<'EOF'
+cc_library(
+ name = "lib",
+ srcs = ["lib.cpp"],
+ hdrs = ["lib.h"],
+ visibility = ["//visibility:public"],
+)
+EOF
+ cat > other_repo/lib/lib.h <<'EOF'
+void print_greeting();
+EOF
+ cat > other_repo/lib/lib.cpp <<'EOF'
+#include <cstdio>
+void print_greeting() {
+ printf("Hello, world!\n");
+}
+EOF
+
+ mkdir -p other_repo/test
+ cat > other_repo/test/BUILD <<'EOF'
+cc_test(
+ name = "test",
+ srcs = ["test.cpp"],
+ deps = ["//lib"],
+)
+EOF
+ cat > other_repo/test/test.cpp <<'EOF'
+#include "lib/lib.h"
+int main() {
+ print_greeting();
+}
+EOF
+
+ bazel test \
+ --test_output=errors \
+ --remote_executor=grpc://localhost:${worker_port} \
+ @other_repo//test >& $TEST_log || fail "Test should pass"
+}
+
run_suite "Remote execution and remote cache tests"
| train | val | 2022-08-04T15:35:24 | "2022-07-29T23:41:11Z" | AustinSchuh | test |
bazelbuild/bazel/16171_16199 | bazelbuild/bazel | bazelbuild/bazel/16171 | bazelbuild/bazel/16199 | [
"keyword_pr_to_issue"
] | c62496f7b76da473cb1102798373f552ba2f434d | e8037c194c56c82ec5565a40288c14d1fbddac7f | [
"@bazel-io flag",
"Sorry about that. This corner of Bazel is poorly tested; I guess something like this was bound to happen.\r\n\r\n> When enabling verbose failures, the stack trace pointed to a failed precondition because the host portion of the URI was null\r\n\r\nCould you please share the full stack trace and the exact values of `--remote_executor` and `--remote_cache` you're using?",
"Here's the command line and stack trace. The line numbers might be off a bit -- I recompiled bazel from the head and added a couple printf statements.\r\n```\r\n$ bazel build --remote_cache=unix:///home/coder/.cache/fax/3a162c244f546dff591bc0d335e9c174/jail.sock --remote_executor=unix:///home/coder/.cache/fax/3a162c244f546dff591bc0d335e9c174/jail.sock :all --verbose_failures\r\nExtracting Bazel installation...\r\nStarting local Bazel server and connecting to it...\r\nINFO: Invocation ID: 55dd5c7b-43ea-4a6f-a6cf-0c05ce656dbe\r\nERROR: java.io.IOException: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Failed computing credential metadata\r\n at com.google.devtools.build.lib.remote.RemoteServerCapabilities.get(RemoteServerCapabilities.java:90)\r\n at com.google.devtools.build.lib.remote.RemoteModule.verifyServerCapabilities(RemoteModule.java:196)\r\n at com.google.devtools.build.lib.remote.RemoteModule.beforeCommand(RemoteModule.java:492)\r\n at com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:378)\r\n at com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:232)\r\n at com.google.devtools.build.lib.server.GrpcServerImpl.executeCommand(GrpcServerImpl.java:550)\r\n at com.google.devtools.build.lib.server.GrpcServerImpl.lambda$run$1(GrpcServerImpl.java:614)\r\n at io.grpc.Context$1.run(Context.java:566)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)\r\n at java.base/java.lang.Thread.run(Unknown Source)\r\nCaused by: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Failed computing credential metadata\r\n at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:262)\r\n at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:243)\r\n at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:156)\r\n at build.bazel.remote.execution.v2.CapabilitiesGrpc$CapabilitiesBlockingStub.getCapabilities(CapabilitiesGrpc.java:215)\r\n at com.google.devtools.build.lib.remote.RemoteServerCapabilities.lambda$get$0(RemoteServerCapabilities.java:85)\r\n at com.google.devtools.build.lib.remote.ReferenceCountedChannel.lambda$withChannelBlocking$2(ReferenceCountedChannel.java:85)\r\n at com.google.devtools.build.lib.remote.ReferenceCountedChannel.lambda$withChannel$4(ReferenceCountedChannel.java:108)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleUsing.subscribeActual(SingleUsing.java:59)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap$SingleFlatMapCallback.onSuccess(SingleFlatMap.java:85)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onSuccess(SingleFlatMap.java:112)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleMap$MapSingleObserver.onSuccess(SingleMap.java:65)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleDoOnDispose$DoOnDisposeObserver.onSuccess(SingleDoOnDispose.java:84)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleDoOnError$DoOnError.onSuccess(SingleDoOnError.java:52)\r\n at io.reactivex.rxjava3.internal.operators.observable.ObservableSingleSingle$SingleElementObserver.onComplete(ObservableSingleSingle.java:110)\r\n at io.reactivex.rxjava3.internal.observers.DeferredScalarDisposable.complete(DeferredScalarDisposable.java:85)\r\n at io.reactivex.rxjava3.subjects.AsyncSubject.subscribeActual(AsyncSubject.java:233)\r\n at io.reactivex.rxjava3.core.Observable.subscribe(Observable.java:13176)\r\n at io.reactivex.rxjava3.internal.operators.observable.ObservableSingleSingle.subscribeActual(ObservableSingleSingle.java:36)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleDoOnError.subscribeActual(SingleDoOnError.java:35)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleDoOnDispose.subscribeActual(SingleDoOnDispose.java:38)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleMap.subscribeActual(SingleMap.java:35)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap$SingleFlatMapCallback.onSuccess(SingleFlatMap.java:85)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleCreate$Emitter.onSuccess(SingleCreate.java:68)\r\n at com.google.devtools.build.lib.remote.grpc.TokenBucket$1.onNext(TokenBucket.java:79)\r\n at io.reactivex.rxjava3.internal.util.NotificationLite.accept(NotificationLite.java:247)\r\n at io.reactivex.rxjava3.subjects.BehaviorSubject$BehaviorDisposable.test(BehaviorSubject.java:507)\r\n at io.reactivex.rxjava3.subjects.BehaviorSubject$BehaviorDisposable.emitFirst(BehaviorSubject.java:468)\r\n at io.reactivex.rxjava3.subjects.BehaviorSubject.subscribeActual(BehaviorSubject.java:224)\r\n at io.reactivex.rxjava3.core.Observable.subscribe(Observable.java:13176)\r\n at com.google.devtools.build.lib.remote.grpc.TokenBucket.lambda$acquireToken$0(TokenBucket.java:64)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleCreate.subscribeActual(SingleCreate.java:40)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap.subscribeActual(SingleFlatMap.java:37)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleDefer.subscribeActual(SingleDefer.java:43)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.internal.operators.single.SingleFlatMap.subscribeActual(SingleFlatMap.java:37)\r\n at io.reactivex.rxjava3.core.Single.subscribe(Single.java:4855)\r\n at io.reactivex.rxjava3.core.Single.blockingGet(Single.java:3644)\r\n at com.google.devtools.build.lib.remote.ReferenceCountedChannel.withChannelBlocking(ReferenceCountedChannel.java:85)\r\n at com.google.devtools.build.lib.remote.RemoteServerCapabilities.lambda$get$1(RemoteServerCapabilities.java:84)\r\n at com.google.devtools.build.lib.remote.Retrier.execute(Retrier.java:244)\r\n at com.google.devtools.build.lib.remote.RemoteRetrier.execute(RemoteRetrier.java:125)\r\n at com.google.devtools.build.lib.remote.RemoteRetrier.execute(RemoteRetrier.java:114)\r\n at com.google.devtools.build.lib.remote.RemoteServerCapabilities.get(RemoteServerCapabilities.java:82)\r\n ... 10 more\r\nCaused by: java.lang.NullPointerException\r\n at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:889)\r\n at com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperProvider.findCredentialHelper(CredentialHelperProvider.java:74)\r\n at com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperCredentials$CredentialHelperCacheLoader.load(CredentialHelperCredentials.java:132)\r\n at com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperCredentials$CredentialHelperCacheLoader.load(CredentialHelperCredentials.java:114)\r\n at com.github.benmanes.caffeine.cache.LocalLoadingCache.lambda$newMappingFunction$2(LocalLoadingCache.java:141)\r\n at com.github.benmanes.caffeine.cache.BoundedLocalCache.lambda$doComputeIfAbsent$14(BoundedLocalCache.java:2413)\r\n at java.base/java.util.concurrent.ConcurrentHashMap.compute(Unknown Source)\r\n at com.github.benmanes.caffeine.cache.BoundedLocalCache.doComputeIfAbsent(BoundedLocalCache.java:2411)\r\n at com.github.benmanes.caffeine.cache.BoundedLocalCache.computeIfAbsent(BoundedLocalCache.java:2394)\r\n at com.github.benmanes.caffeine.cache.LocalCache.computeIfAbsent(LocalCache.java:108)\r\n at com.github.benmanes.caffeine.cache.LocalLoadingCache.get(LocalLoadingCache.java:54)\r\n at com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperCredentials.getRequestMetadataFromCredentialHelper(CredentialHelperCredentials.java:90)\r\n at com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperCredentials.getRequestMetadata(CredentialHelperCredentials.java:74)\r\n at com.google.auth.Credentials.blockingGetToCallback(Credentials.java:112)\r\n at com.google.auth.Credentials$1.run(Credentials.java:98)\r\n at io.grpc.stub.ClientCalls$ThreadlessExecutor.waitAndDrain(ClientCalls.java:740)\r\n at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:149)\r\n ... 57 more\r\n\r\nERROR: Failed to query remote execution capabilities: UNAUTHENTICATED: Failed computing credential metadata\r\n```",
"Thanks, this is helpful. It appears that `new URI(\"unix:///foo/bar).getHost() == null` and `new URI(\"unix:/foo/bar\").getHost() == null`, but `new URI(\"unix://foo/bar\").getHost() == \"foo\"`. I wonder if using one or two slashes after `unix:` instead of three is a valid workaround. Hopefully the gRPC library isn't too picky...\r\n\r\nThat being said, I totally agree that we shouldn't crash here! I think the right fix is to replace the precondition check in `findCredentialHelper` with an early exit if the host part is empty/null. That way we don't have to make any assumptions about URI schemes. I'll put a fix together on Monday.",
"Regardless of the number of slashes, it used to work with versions of bazel older than 5.3. I've used it on 5.2.0, 5.1.0, 5.0.0, and 4.2.2 to name a few. But I'll look into seeing how it behaves when we have only 1 slash and let you know what I find.",
"Yep, regardless of the number of slashes, it fails at the same precondition check. (I tried 1, 2, and 3.) Also, for unix domain sockets, there is no host -- the entire remainder of the string is the pathname of the socket file, so getHost() probably should return null when the scheme is \"unix:\".",
"@tjgq do you think this warrants a patch release?",
"@Wyverald It's a regression that affects existing users and there doesn't seem to be a workaround for it, so probably yes? (I don't know what's our patch release policy.)\r\n\r\n@srago I'd like to go with #16184 as the fix. Could you please confirm that it works for you?\r\n\r\ncc @Yannic - until #16185 is fixed, we should manually verify that a UDS proxy works when making changes to credential helpers.",
"@bazel-io fork 5.3.1",
"Confirmed #16184 fixes the problem with Unix domain sockets. Thanks for the quick response time!"
] | [] | "2022-08-31T20:34:54Z" | [
"type: bug",
"untriaged",
"team-Remote-Exec"
] | CredentialHelper change broke unix domain socket support | We use a unix domain socket for our remote_executor and remote_cache endpoints, because we use a side-car proxy to handle SPIFFE mTLS negotiation. This stopped working with the release of bazel 5.3.0. With 5.3.0, bazel fails before issuing its first GetCapabilitiesRequest. The error message was "ERROR: Failed to query remote execution capabilities: UNAUTHENTICATED: Failed computing credential metadata." When enabling verbose failures, the stack trace pointed to a failed precondition because the host portion of the URI was null. I played around with the code and got it working again, but the fix isn't production-quality -- it doesn't handle the case where the remote cache endpoint differs from the remote executor endpoint, and might need different credentials. Because we're using unix domain sockets, this shouldn't affect us at all. Anyway, consider the following patch a place to start the conversation about what the correct fix might look like.
```diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
index a7d793ad56..d7db02bd6f 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteModule.java
@@ -1055,6 +1055,22 @@ public final class RemoteModule extends BlazeModule {
AuthAndTLSOptions authAndTlsOptions,
RemoteOptions remoteOptions)
throws IOException {
+
+ // TODO: this is a temporary hack. Because remoteCache and remoteExecutor could be different, they might need
+ // different credentials. If the endpoints used to access remote services are unix domain sockets, credential
+ // helpers aren't needed -- the service is running on the same machine.
+ //
+ // Also note that URI("unix://...") will replace "unix" with "https" for some reason that escapes me, but that
+ // makes it tricky to use. Somewhere (not here because of the checks in the try clause below), that was
+ // happening, because by the time findCredentialHelper() is called, these URIs have been changed from "unix://"
+ // to "https://". According to the bazel documentation, the "unix:" scheme is supposed to disable TLS.
+ if (remoteOptions.remoteCache != null && Ascii.toLowerCase(remoteOptions.remoteCache).startsWith("unix:/")) {
+ return null;
+ }
+ if (remoteOptions.remoteExecutor != null && Ascii.toLowerCase(remoteOptions.remoteExecutor).startsWith("unix:/")) {
+ return null;
+ }
+
Credentials credentials =
GoogleAuthUtils.newCredentials(
credentialHelperEnvironment, commandLinePathFactory, fileSystem, authAndTlsOptions);
``` | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java"
] | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java"
] | [
"src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
index ded7e5eab3c0d0..e13d1b40385a8b 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
@@ -16,6 +16,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.vfs.Path;
import com.google.errorprone.annotations.Immutable;
@@ -66,7 +67,12 @@ private CredentialHelperProvider(
public Optional<CredentialHelper> findCredentialHelper(URI uri) {
Preconditions.checkNotNull(uri);
- String host = Preconditions.checkNotNull(uri.getHost());
+ String host = uri.getHost();
+ if (Strings.isNullOrEmpty(host)) {
+ // Some URIs (e.g. unix://) legitimately have no host component.
+ return Optional.empty();
+ }
+
Optional<Path> credentialHelper =
findHostCredentialHelper(host)
.or(() -> findWildcardCredentialHelper(host))
| diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
index 25b6c03ff8e6b2..89b6dbc6396b75 100644
--- a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
@@ -104,6 +104,15 @@ public void invalidPattern() throws Exception {
assertInvalidPattern("foo-*.münchen.de");
}
+ @Test
+ public void uriWithoutHostComponent() throws Exception {
+ Path helper = fileSystem.getPath(EXAMPLE_COM_HELPER_PATH);
+ CredentialHelperProvider provider =
+ CredentialHelperProvider.builder().add("example.com", helper).build();
+
+ assertThat(provider.findCredentialHelper(URI.create("unix:///path/to/socket"))).isEmpty();
+ }
+
@Test
public void addNonExecutableDefaultHelper() throws Exception {
Path helper = fileSystem.getPath("/path/to/non/executable");
| train | val | 2022-08-16T19:04:04 | "2022-08-26T17:16:37Z" | srago | test |
bazelbuild/bazel/16185_16199 | bazelbuild/bazel | bazelbuild/bazel/16185 | bazelbuild/bazel/16199 | [
"keyword_pr_to_issue"
] | c62496f7b76da473cb1102798373f552ba2f434d | e8037c194c56c82ec5565a40288c14d1fbddac7f | [] | [] | "2022-08-31T20:34:54Z" | [
"type: feature request",
"P2",
"team-Remote-Exec"
] | Reenable tests for gRPC UDS proxy | https://cs.opensource.google/bazel/bazel/+/master:src/test/shell/bazel/remote/remote_execution_test.sh;l=161;drc=b303cd128d9f1d913749927f4a1cd942b10b1ae2
https://cs.opensource.google/bazel/bazel/+/master:src/test/shell/bazel/remote/remote_execution_test.sh;l=200;drc=b303cd128d9f1d913749927f4a1cd942b10b1ae2
They were disabled due to flakiness in 8e3c0df. As a consequence, we introduced an undetected regression in 5.3 (#16171). | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java"
] | [
"src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java"
] | [
"src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
index ded7e5eab3c0d0..e13d1b40385a8b 100644
--- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
+++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProvider.java
@@ -16,6 +16,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.vfs.Path;
import com.google.errorprone.annotations.Immutable;
@@ -66,7 +67,12 @@ private CredentialHelperProvider(
public Optional<CredentialHelper> findCredentialHelper(URI uri) {
Preconditions.checkNotNull(uri);
- String host = Preconditions.checkNotNull(uri.getHost());
+ String host = uri.getHost();
+ if (Strings.isNullOrEmpty(host)) {
+ // Some URIs (e.g. unix://) legitimately have no host component.
+ return Optional.empty();
+ }
+
Optional<Path> credentialHelper =
findHostCredentialHelper(host)
.or(() -> findWildcardCredentialHelper(host))
| diff --git a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
index 25b6c03ff8e6b2..89b6dbc6396b75 100644
--- a/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialHelperProviderTest.java
@@ -104,6 +104,15 @@ public void invalidPattern() throws Exception {
assertInvalidPattern("foo-*.münchen.de");
}
+ @Test
+ public void uriWithoutHostComponent() throws Exception {
+ Path helper = fileSystem.getPath(EXAMPLE_COM_HELPER_PATH);
+ CredentialHelperProvider provider =
+ CredentialHelperProvider.builder().add("example.com", helper).build();
+
+ assertThat(provider.findCredentialHelper(URI.create("unix:///path/to/socket"))).isEmpty();
+ }
+
@Test
public void addNonExecutableDefaultHelper() throws Exception {
Path helper = fileSystem.getPath("/path/to/non/executable");
| train | val | 2022-08-16T19:04:04 | "2022-08-29T12:14:42Z" | tjgq | test |
bazelbuild/bazel/16257_16258 | bazelbuild/bazel | bazelbuild/bazel/16257 | bazelbuild/bazel/16258 | [
"keyword_pr_to_issue"
] | 1e25152906b668bbe56aa4c1773186af85335315 | ceed7f1a72634ae63e1d63ca038bbddab604b113 | [
"@beasleyr-vmw If you would like to see this fix in 5.3.1, you could cherry-pick it onto the `release-5.3.1` branch and submit a PR.",
"Exactly what @fmeum said. Please send a PR."
] | [] | "2022-09-12T23:51:03Z" | [
"type: bug",
"team-Configurability",
"untriaged"
] | [5.3.x] 'bazel info' reports 'unknown key(s)' when specifying '--no//flag' | ### Description of the bug:
Looks like this was already fixed by a Googler at f6cccae5b6f9c0ad0e7d0bf7bd31ea1263449316 and would be a trivial backport to 5.3.x.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
(NOTE: It doesn't matter if WORKSPACE contains a repository rule for bazel_skylib.)
```console
$ cd $(mktemp -d)
$ touch WORKSPACE
$ cat >BUILD <<EOF
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
bool_flag(
name = "example",
build_setting_default = True,
)
EOF
$ USE_BAZEL_VERSION=5.3.0 bazelisk info --no//:example
ERROR: unknown key(s): '--no//:example'
```
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
release 5.3.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
- https://github.com/bazelbuild/bazel/commit/f6cccae5b6f9c0ad0e7d0bf7bd31ea1263449316
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java"
] | [
"src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java b/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
index 0c60ee576e0541..9a0685c6ac30ae 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/StarlarkOptionsParser.java
@@ -333,7 +333,7 @@ public static Pair<ImmutableList<String>, ImmutableList<String>> removeStarlarkO
String potentialStarlarkFlag = name.substring(2);
// Check if the string uses the "no" prefix for setting boolean flags to false, trim
// off "no" if so.
- if (name.startsWith("no")) {
+ if (potentialStarlarkFlag.startsWith("no")) {
potentialStarlarkFlag = potentialStarlarkFlag.substring(2);
}
// Check if the string contains a value, trim off the value if so.
| null | test | val | 2022-09-12T17:24:27 | "2022-09-12T21:25:24Z" | ghost | test |
bazelbuild/bazel/16124_16544 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16544 | [
"keyword_pr_to_issue"
] | 490f8badf4f6f4ae8b96697f08267fdb083ccf5f | ce2476bc5a5b75f669666615b5b143db53c24211 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-10-25T11:31:07Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesLibraryInfo.java",
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java",
"src/main/java/com/google/devtools/build/lib/starlarkbuildapi/RunfilesLibraryInfoApi.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java"
] | [
"src/test/java/com/google/devtools/build/lib/starlark/BUILD",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BUILD b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
index b630ac7daeac91..4f5328526e0724 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
@@ -341,7 +341,6 @@ java_library(
":rule_configured_object_value",
":rule_definition_environment",
":run_environment_info",
- ":runfiles_library_info",
":starlark/args",
":starlark/bazel_build_api_globals",
":starlark/function_transition_util",
@@ -1033,16 +1032,6 @@ java_library(
],
)
-java_library(
- name = "runfiles_library_info",
- srcs = ["RunfilesLibraryInfo.java"],
- deps = [
- "//src/main/java/com/google/devtools/build/lib/concurrent",
- "//src/main/java/com/google/devtools/build/lib/packages",
- "//src/main/java/com/google/devtools/build/lib/starlarkbuildapi",
- ],
-)
-
java_library(
name = "rule_definition_environment",
srcs = ["RuleDefinitionEnvironment.java"],
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesLibraryInfo.java b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesLibraryInfo.java
deleted file mode 100644
index 5e3107e2ea4f7e..00000000000000
--- a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesLibraryInfo.java
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2022 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.
-
-package com.google.devtools.build.lib.analysis;
-
-import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
-import com.google.devtools.build.lib.packages.BuiltinProvider;
-import com.google.devtools.build.lib.packages.NativeInfo;
-import com.google.devtools.build.lib.starlarkbuildapi.RunfilesLibraryInfoApi;
-
-/**
- * Data-less provider that signals to direct dependents that this target is a runfiles library.
- *
- * <p>Rules that find this provider advertised by a dependency may use this as a signal to generate
- * code that helps with runfiles discovery, e.g., by providing a constant containing the name of the
- * repository that defines the rule.
- *
- * <p>Bazel itself uses the presence of this provider on a rule as a sign that it should include the
- * repository mapping of the repository containing the rule in the repository mapping manifest of
- * executable transitive dependents.
- */
-@Immutable
-public final class RunfilesLibraryInfo extends NativeInfo implements RunfilesLibraryInfoApi {
-
- public static final RunfilesLibraryInfoProvider PROVIDER = new RunfilesLibraryInfoProvider();
-
- @Override
- public RunfilesLibraryInfoProvider getProvider() {
- return PROVIDER;
- }
-
- /** Provider for {@link RunfilesLibraryInfo}. */
- public static class RunfilesLibraryInfoProvider extends BuiltinProvider<RunfilesLibraryInfo>
- implements RunfilesLibraryInfoApi.RunfilesLibraryInfoApiProvider {
-
- private RunfilesLibraryInfoProvider() {
- super("RunfilesLibraryInfo", RunfilesLibraryInfo.class);
- }
-
- @Override
- public RunfilesLibraryInfoApi constructor() {
- return new RunfilesLibraryInfo();
- }
- }
-}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java
index a9007d783c404e..a77ff194bb82dd 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkModules.java
@@ -19,7 +19,6 @@
import com.google.devtools.build.lib.analysis.DefaultInfo;
import com.google.devtools.build.lib.analysis.OutputGroupInfo;
import com.google.devtools.build.lib.analysis.RunEnvironmentInfo;
-import com.google.devtools.build.lib.analysis.RunfilesLibraryInfo;
import com.google.devtools.build.lib.packages.StarlarkLibrary;
import com.google.devtools.build.lib.packages.StarlarkLibrary.SelectLibrary;
import com.google.devtools.build.lib.packages.StructProvider;
@@ -49,6 +48,5 @@ public static void addPredeclared(ImmutableMap.Builder<String, Object> predeclar
predeclared.put("Actions", ActionsProvider.INSTANCE);
predeclared.put("DefaultInfo", DefaultInfo.PROVIDER);
predeclared.put("RunEnvironmentInfo", RunEnvironmentInfo.PROVIDER);
- predeclared.put("RunfilesLibraryInfo", RunfilesLibraryInfo.PROVIDER);
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/RunfilesLibraryInfoApi.java b/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/RunfilesLibraryInfoApi.java
deleted file mode 100644
index 191b539f57c63a..00000000000000
--- a/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/RunfilesLibraryInfoApi.java
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2022 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.
-
-package com.google.devtools.build.lib.starlarkbuildapi;
-
-import com.google.devtools.build.docgen.annot.DocCategory;
-import com.google.devtools.build.docgen.annot.StarlarkConstructor;
-import com.google.devtools.build.lib.starlarkbuildapi.core.ProviderApi;
-import com.google.devtools.build.lib.starlarkbuildapi.core.StructApi;
-import net.starlark.java.annot.StarlarkBuiltin;
-import net.starlark.java.annot.StarlarkMethod;
-
-/** Interface for runfiles library info. */
-@StarlarkBuiltin(
- name = "RunfilesLibraryInfo",
- category = DocCategory.PROVIDER,
- doc =
- "Signals to direct dependents as well as Bazel itself that this target is a runfiles"
- + " library. For example, rules for compiled languages may choose to generate and"
- + " compile additional code that gives access to the name of the repository defining"
- + " the current target if they find this provider advertised by a direct"
- + " dependency.<p>This provider carries no data.")
-public interface RunfilesLibraryInfoApi extends StructApi {
-
- /** Interface for runfiles library info provider. */
- @StarlarkBuiltin(name = "Provider", category = DocCategory.PROVIDER, documented = false)
- interface RunfilesLibraryInfoApiProvider extends ProviderApi {
-
- @StarlarkMethod(
- name = "RunfilesLibraryInfo",
- doc = "The <code>RunfilesLibraryInfo</code> constructor.",
- selfCall = true)
- @StarlarkConstructor
- RunfilesLibraryInfoApi constructor();
- }
-}
| diff --git a/src/test/java/com/google/devtools/build/lib/starlark/BUILD b/src/test/java/com/google/devtools/build/lib/starlark/BUILD
index c0e25bae180ae3..0ab20ce6319a18 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/starlark/BUILD
@@ -46,7 +46,6 @@ java_test(
"//src/main/java/com/google/devtools/build/lib/analysis:file_provider",
"//src/main/java/com/google/devtools/build/lib/analysis:resolved_toolchain_context",
"//src/main/java/com/google/devtools/build/lib/analysis:run_environment_info",
- "//src/main/java/com/google/devtools/build/lib/analysis:runfiles_library_info",
"//src/main/java/com/google/devtools/build/lib/analysis:starlark/args",
"//src/main/java/com/google/devtools/build/lib/analysis:starlark/starlark_exec_group_collection",
"//src/main/java/com/google/devtools/build/lib/analysis:test/analysis_test_result_info",
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
index 21526932b03694..8ba84526fd64b9 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
@@ -30,7 +30,6 @@
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupInfo;
import com.google.devtools.build.lib.analysis.RunEnvironmentInfo;
-import com.google.devtools.build.lib.analysis.RunfilesLibraryInfo;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition;
import com.google.devtools.build.lib.analysis.configuredtargets.FileConfiguredTarget;
@@ -3653,34 +3652,4 @@ public void nonExecutableStarlarkRuleReturningTestEnvironmentProducesAWarning()
+ " non-test target has no effect",
ImmutableSet.of(EventKind.WARNING));
}
-
- @Test
- public void runfilesLibraryInfoCanBeReturnedAndQueried() throws Exception {
- scratch.file(
- "examples/rules.bzl",
- "def my_runfiles_library_impl(ctx):",
- " return [RunfilesLibraryInfo()]",
- "my_runfiles_library = rule(implementation = my_runfiles_library_impl)",
- "def language_rule_impl(ctx):",
- " if RunfilesLibraryInfo not in ctx.attr.dep:",
- " fail('dep does not advertise RunfilesLibraryInfo')",
- "language_rule = rule(",
- " implementation = language_rule_impl,",
- " attrs = {'dep': attr.label()},",
- ")");
- scratch.file(
- "examples/BUILD",
- "load(':rules.bzl', 'language_rule', 'my_runfiles_library')",
- "my_runfiles_library(name = 'runfiles_library')",
- "language_rule(",
- " name = 'target',",
- " dep = ':runfiles_library',",
- ")");
-
- ConfiguredTarget runfilesLibrary = getConfiguredTarget("//examples:runfiles_library");
- assertThat(runfilesLibrary.get(RunfilesLibraryInfo.PROVIDER)).isNotNull();
-
- // Succeeds only if targets can be queried for the presence of RunfilesLibraryInfo in Starlark.
- getConfiguredTarget("//examples:target");
- }
}
| train | val | 2022-10-25T13:25:49 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16124_16653 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16653 | [
"keyword_pr_to_issue"
] | 5eb506bd03348343a6b886104d51e2ea2a01426c | 1b52f5320814dcbf2164b3efd550ce03c6011c63 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-03T19:12:08Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java",
"src/test/py/bazel/runfiles_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
index 096a6eac0aea0d..f5ac7d1c84abcf 100644
--- a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
+++ b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
@@ -262,15 +262,15 @@
</p>
<p>
Output files are staged similarly, but are also prefixed with the subpath
- <code>bazel-out/cpu-compilation_mode/bin</code> (or for certain outputs:
- <code>bazel-out/cpu-compilation_mode/genfiles</code>, or for the outputs
- of host tools: <code>bazel-out/host/bin</code>). In the above example,
- <code>//testapp:app</code> is a host tool because it appears in
+ <code>bazel-out/cpu-compilation_mode/bin</code> (or for the outputs of
+ tools: <code>bazel-out/cpu-opt-exec-hash/bin</code>). In the above example,
+ <code>//testapp:app</code> is a tool because it appears in
<code>show_app_output</code>'s <code><a
href="$expander.expandRef("genrule.tools")">tools</a></code> attribute.
So its output file <code>app</code> is written to
- <code>bazel-myproject/bazel-out/host/bin/testapp/app</code>. The exec path
- is thus <code>bazel-out/host/bin/testapp/app</code>. This extra prefix
+ <code>bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>.
+ The exec path is thus <code>
+ bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>. This extra prefix
makes it possible to build the same target for, say, two different CPUs in
the same build without the results clobbering each other.
</p>
@@ -284,15 +284,57 @@
<li>
<p>
- <code>rootpath</code>: Denotes the runfiles path that a built binary can
- use to find its dependencies at runtime.
- </p>
+ <code>rootpath</code>: Denotes the path that a built binary can use to
+ find a dependency at runtime relative to the subdirectory of its runfiles
+ directory corresponding to the main repository.
+ <strong>Note:</strong> This only works if <a
+ href="/reference/command-line-reference#flag--enable_runfiles">
+ <code>--enable_runfiles</code></a> is enabled, which is not the case on
+ Windows by default. Use <code>rlocationpath</code> instead for
+ cross-platform support.
<p>
- This is the same as <code>execpath</code> but strips the output prefixes
- described above. In the above example this means both
+ This is similar to <code>execpath</code> but strips the configuration
+ prefixes described above. In the example from above this means both
<code>empty.source</code> and <code>app</code> use pure workspace-relative
paths: <code>testapp/empty.source</code> and <code>testapp/app</code>.
</p>
+ <p>
+ The <code>rootpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>../repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ This has the same "one output only" requirements as <code>execpath</code>.
+ </p>
+ </li>
+
+ <li>
+ <p>
+ <code>rlocationpath</code>: The path a built binary can pass to the <code>
+ Rlocation</code> function of a runfiles library to find a dependency at
+ runtime, either in the runfiles directory (if available) or using the
+ runfiles manifest.
+ </p>
+ <p>
+ This is similar to <code>rootpath</code> in that it does not contain
+ configuration prefixes, but differs in that it always starts with the
+ name of the repository. In the example from above this means that <code>
+ empty.source</code> and <code>app</code> result in the following
+ paths: <code>myproject/testapp/empty.source</code> and <code>
+ myproject/testapp/app</code>.
+ </p>
+ <p>
+ The <code>rlocationpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ 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 <code>rootpath</code>, it has the advantage that it
+ works on all platforms and even if the runfiles directory is not
+ available.
+ </p>
<p>
This has the same "one output only" requirements as <code>execpath</code>.
</p>
@@ -303,24 +345,25 @@
<code>rootpath</code>, depending on the attribute being expanded. This is
legacy pre-Starlark behavior and not recommended unless you really know what
it does for a particular rule. See <a
- href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
+ href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
for details.
</li>
</ul>
<p>
- <code>execpaths</code>, <code>rootpaths</code>, and <code>locations</code> are
- the plural variations of <code>execpath</code>, <code>rootpath</code>, and
- <code>location</code>, respectively. They support labels producing multiple
- outputs, in which case each output is listed separated by a space. Zero-output
- rules and malformed labels produce build errors.
+ <code>execpaths</code>, <code>rootpaths</code>, <code>rlocationpaths</code>,
+ and <code>locations</code> are the plural variations of <code>execpath</code>,
+ <code>rootpath</code>, <code>rlocationpaths</code>, and<code>location</code>,
+ respectively. They support labels producing multiple outputs, in which case
+ each output is listed separated by a space. Zero-output rules and malformed
+ labels produce build errors.
</p>
<p>
All referenced labels must appear in the consuming target's <code>srcs</code>,
output files, or <code>deps</code>. Otherwise the build fails. C++ targets can
also reference labels in <code><a
- href="$expander.expandRef("cc_binary.data")">data</a></code>.
+ href="$expander.expandRef("cc_binary.data")">data</a></code>.
</p>
<p>
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
index d82d3de89a0f7d..ddcf5510ac174d 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
@@ -17,6 +17,7 @@
import static java.util.stream.Collectors.joining;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableCollection;
@@ -26,7 +27,9 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Artifact;
+import com.google.devtools.build.lib.analysis.LocationExpander.LocationFunction.PathType;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.packages.BuildType;
@@ -63,34 +66,35 @@ public final class LocationExpander {
private static final boolean EXACTLY_ONE = false;
private static final boolean ALLOW_MULTIPLE = true;
- private static final boolean USE_LOCATION_PATHS = false;
- private static final boolean USE_EXEC_PATHS = true;
-
private final RuleErrorConsumer ruleErrorConsumer;
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
+ private final String workspaceRunfilesDirectory;
@VisibleForTesting
LocationExpander(
RuleErrorConsumer ruleErrorConsumer,
Map<String, LocationFunction> functions,
- RepositoryMapping repositoryMapping) {
+ RepositoryMapping repositoryMapping,
+ String workspaceRunfilesDirectory) {
this.ruleErrorConsumer = ruleErrorConsumer;
this.functions = ImmutableMap.copyOf(functions);
this.repositoryMapping = repositoryMapping;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
private LocationExpander(
- RuleErrorConsumer ruleErrorConsumer,
+ RuleContext ruleContext,
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMap,
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping) {
this(
- ruleErrorConsumer,
+ ruleContext,
allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles),
- repositoryMapping);
+ repositoryMapping,
+ ruleContext.getWorkspaceName());
}
/**
@@ -204,7 +208,10 @@ private String expand(String value, ErrorReporter reporter) {
// (2) Call appropriate function to obtain string replacement.
String functionValue = value.substring(nextWhitespace + 1, end).trim();
try {
- String replacement = functions.get(fname).apply(functionValue, repositoryMapping);
+ String replacement =
+ functions
+ .get(fname)
+ .apply(functionValue, repositoryMapping, workspaceRunfilesDirectory);
result.append(replacement);
} catch (IllegalStateException ise) {
reporter.report(ise.getMessage());
@@ -232,23 +239,29 @@ public String expandAttribute(String attrName, String attrValue) {
@VisibleForTesting
static final class LocationFunction {
+ enum PathType {
+ LOCATION,
+ EXEC,
+ RLOCATION,
+ }
+
private static final int MAX_PATHS_SHOWN = 5;
private final Label root;
private final Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier;
- private final boolean execPaths;
+ private final PathType pathType;
private final boolean legacyExternalRunfiles;
private final boolean multiple;
LocationFunction(
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier,
- boolean execPaths,
+ PathType pathType,
boolean legacyExternalRunfiles,
boolean multiple) {
this.root = root;
this.locationMapSupplier = locationMapSupplier;
- this.execPaths = execPaths;
+ this.pathType = Preconditions.checkNotNull(pathType);
this.legacyExternalRunfiles = legacyExternalRunfiles;
this.multiple = multiple;
}
@@ -259,10 +272,13 @@ static final class LocationFunction {
* using the {@code repositoryMapping}.
*
* @param arg The label-like string to be expanded, e.g. ":foo" or "//foo:bar"
- * @param repositoryMapping map of {@code RepositoryName}s defined in the main workspace
+ * @param repositoryMapping map of apparent repository names to {@code RepositoryName}s
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return The expanded value
*/
- public String apply(String arg, RepositoryMapping repositoryMapping) {
+ public String apply(
+ String arg, RepositoryMapping repositoryMapping, String workspaceRunfilesDirectory) {
Label label;
try {
label = root.getRelativeWithRemapping(arg, repositoryMapping);
@@ -271,14 +287,13 @@ public String apply(String arg, RepositoryMapping repositoryMapping) {
String.format(
"invalid label in %s expression: %s", functionName(), e.getMessage()), e);
}
- Collection<String> paths = resolveLabel(label);
+ Set<String> paths = resolveLabel(label, workspaceRunfilesDirectory);
return joinPaths(paths);
}
- /**
- * Returns all target location(s) of the given label.
- */
- private Collection<String> resolveLabel(Label unresolved) throws IllegalStateException {
+ /** Returns all target location(s) of the given label. */
+ private Set<String> resolveLabel(Label unresolved, String workspaceRunfilesDirectory)
+ throws IllegalStateException {
Collection<Artifact> artifacts = locationMapSupplier.get().get(unresolved);
if (artifacts == null) {
@@ -288,7 +303,7 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
unresolved, functionName()));
}
- Set<String> paths = getPaths(artifacts);
+ Set<String> paths = getPaths(artifacts, workspaceRunfilesDirectory);
if (paths.isEmpty()) {
throw new IllegalStateException(
String.format(
@@ -313,24 +328,41 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
* Extracts list of all executables associated with given collection of label artifacts.
*
* @param artifacts to get the paths of
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return all associated executable paths
*/
- private Set<String> getPaths(Collection<Artifact> artifacts) {
+ private Set<String> getPaths(
+ Collection<Artifact> artifacts, String workspaceRunfilesDirectory) {
TreeSet<String> paths = Sets.newTreeSet();
for (Artifact artifact : artifacts) {
- PathFragment execPath =
- execPaths
- ? artifact.getExecPath()
- : legacyExternalRunfiles
- ? artifact.getPathForLocationExpansion()
- : artifact.getRunfilesPath();
- if (execPath != null) { // omit middlemen etc
- paths.add(execPath.getCallablePathString());
+ PathFragment path = getPath(artifact, workspaceRunfilesDirectory);
+ if (path != null) { // omit middlemen etc
+ paths.add(path.getCallablePathString());
}
}
return paths;
}
+ private PathFragment getPath(Artifact artifact, String workspaceRunfilesDirectory) {
+ switch (pathType) {
+ case LOCATION:
+ return legacyExternalRunfiles
+ ? artifact.getPathForLocationExpansion()
+ : artifact.getRunfilesPath();
+ case EXEC:
+ return artifact.getExecPath();
+ case RLOCATION:
+ PathFragment runfilesPath = artifact.getRunfilesPath();
+ if (runfilesPath.startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX)) {
+ return runfilesPath.relativeTo(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
+ } else {
+ return PathFragment.create(workspaceRunfilesDirectory).getRelative(runfilesPath);
+ }
+ }
+ throw new IllegalStateException("Unexpected PathType: " + pathType);
+ }
+
private String joinPaths(Collection<String> paths) {
return paths.stream().map(ShellEscaper::escapeString).collect(joining(" "));
}
@@ -348,27 +380,44 @@ static ImmutableMap<String, LocationFunction> allLocationFunctions(
return new ImmutableMap.Builder<String, LocationFunction>()
.put(
"location",
- new LocationFunction(root, locationMap, execPaths, legacyExternalRunfiles, EXACTLY_ONE))
+ new LocationFunction(
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ EXACTLY_ONE))
.put(
"locations",
new LocationFunction(
- root, locationMap, execPaths, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ ALLOW_MULTIPLE))
.put(
"rootpath",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"rootpaths",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.put(
"execpath",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"execpaths",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ .put(
+ "rlocationpath",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, EXACTLY_ONE))
+ .put(
+ "rlocationpaths",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.buildOrThrow();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
index f3e66781c7dec3..0de4a4e498c49b 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
@@ -50,6 +50,7 @@ final class LocationTemplateContext implements TemplateContext {
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
private final boolean windowsPath;
+ private final String workspaceRunfilesDirectory;
private LocationTemplateContext(
TemplateContext delegate,
@@ -58,12 +59,14 @@ private LocationTemplateContext(
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping,
- boolean windowsPath) {
+ boolean windowsPath,
+ String workspaceRunfilesDirectory) {
this.delegate = delegate;
this.functions =
LocationExpander.allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles);
this.repositoryMapping = repositoryMapping;
this.windowsPath = windowsPath;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
public LocationTemplateContext(
@@ -83,7 +86,8 @@ public LocationTemplateContext(
execPaths,
ruleContext.getConfiguration().legacyExternalRunfiles(),
ruleContext.getRule().getPackage().getRepositoryMapping(),
- windowsPath);
+ windowsPath,
+ ruleContext.getWorkspaceName());
}
@Override
@@ -108,7 +112,7 @@ private String lookupFunctionImpl(String name, String param) throws ExpansionExc
try {
LocationFunction f = functions.get(name);
if (f != null) {
- return f.apply(param, repositoryMapping);
+ return f.apply(param, repositoryMapping, workspaceRunfilesDirectory);
}
} catch (IllegalStateException e) {
throw new ExpansionException(e.getMessage(), e);
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
index 4f40434ea75b74..7a31156694281c 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
@@ -17,6 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Root;
@@ -121,6 +122,12 @@ public void otherPathExpansion() throws Exception {
"genrule(name='foo', outs=['foo.txt'], cmd='never executed')",
"sh_library(name='lib', srcs=[':foo'])");
+ FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"), "workspace(name='workspace')");
+ // Invalidate WORKSPACE to pick up the name.
+ getSkyframeExecutor()
+ .invalidateFilesUnderPathForTesting(
+ reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
+
LocationExpander expander = makeExpander("//expansion:lib");
assertThat(expander.expand("foo $(execpath :foo) bar"))
.matches("foo .*-out/.*/expansion/foo\\.txt bar");
@@ -130,6 +137,22 @@ public void otherPathExpansion() throws Exception {
.matches("foo expansion/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
}
@Test
@@ -158,6 +181,10 @@ public void otherPathExternalExpansion() throws Exception {
.matches("foo external/r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar"))
.matches("foo external/r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -183,6 +210,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfiles() throws Exceptio
.matches("foo .*-out/.*/external/r/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -210,6 +241,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfilesSiblingRepositoryL
.matches("foo .*-out/r/.*/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -224,5 +259,9 @@ public void otherPathMultiExpansion() throws Exception {
.matches("foo .*-out/.*/expansion/bar\\.txt .*-out/.*/expansion/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/bar.txt expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo(
+ "foo __main__/expansion/bar.txt __main__/expansion/foo.txt bar"
+ .replace("__main__", TestConstants.WORKSPACE_NAME));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
index abdeb1ed742df4..9e6b63490ef638 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
@@ -59,22 +59,25 @@ public boolean hasErrors() {
}
private LocationExpander makeExpander(RuleErrorConsumer ruleErrorConsumer) throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("//a", "/exec/src/a")
- .build();
-
- LocationFunction f2 = new LocationFunctionBuilder("//b", true)
- .setExecPaths(false)
- .add("//b", "/exec/src/b")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//a", "/exec/src/a")
+ .build();
+
+ LocationFunction f2 =
+ new LocationFunctionBuilder("//b", true)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//b", "/exec/src/b")
+ .build();
return new LocationExpander(
ruleErrorConsumer,
ImmutableMap.<String, LocationFunction>of(
"location", f1,
"locations", f2),
- RepositoryMapping.ALWAYS_FALLBACK);
+ RepositoryMapping.ALWAYS_FALLBACK,
+ "workspace");
}
private String expand(String input) throws Exception {
@@ -125,10 +128,11 @@ public void noExpansionOnError() throws Exception {
@Test
public void expansionWithRepositoryMapping() throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("@bar//a", "/exec/src/a")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("@bar//a", "/exec/src/a")
+ .build();
ImmutableMap<String, RepositoryName> repositoryMapping =
ImmutableMap.of("foo", RepositoryName.create("bar"));
@@ -137,7 +141,8 @@ public void expansionWithRepositoryMapping() throws Exception {
new LocationExpander(
new Capture(),
ImmutableMap.<String, LocationFunction>of("location", f1),
- RepositoryMapping.createAllowingFallback(repositoryMapping));
+ RepositoryMapping.createAllowingFallback(repositoryMapping),
+ "workspace");
String value = locationExpander.expand("$(location @foo//a)");
assertThat(value).isEqualTo("src/a");
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
index 38addac4979d01..608b39b34fa105 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
@@ -49,16 +49,16 @@ public class LocationFunctionTest {
public void absoluteAndRelativeLabels() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/src/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
}
@Test
public void pathUnderExecRootUsesDotSlash() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("./bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("./bar");
}
@Test
@@ -67,7 +67,7 @@ public void noSuchLabel() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -81,7 +81,7 @@ public void emptyList() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo("label '//foo:foo' in $(location) expression expands to no files");
@@ -94,7 +94,7 @@ public void tooMany() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -109,7 +109,7 @@ public void noSuchLabelMultiple() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -121,7 +121,7 @@ public void noSuchLabelMultiple() throws Exception {
public void fileWithSpace() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/file/with space").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space'");
}
@@ -130,7 +130,7 @@ public void multipleFiles() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/foo/bar", "/exec/out/foo/foobar")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("foo/bar foo/foobar");
}
@@ -139,27 +139,41 @@ public void filesWithSpace() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/file/with space", "/exec/file/with spaces ")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space' 'file/with spaces '");
}
@Test
public void execPath() throws Exception {
- LocationFunction func = new LocationFunctionBuilder("//foo", true)
- .setExecPaths(true)
- .add("//foo", "/exec/bar", "/exec/out/foobar")
- .build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.EXEC)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("./bar out/foobar");
}
+ @Test
+ public void rlocationPath() throws Exception {
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.RLOCATION)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, "workspace"))
+ .isEqualTo("workspace/bar workspace/foobar");
+ }
+
@Test
public void locationFunctionWithMappingReplace() throws Exception {
RepositoryName b = RepositoryName.create("b");
ImmutableMap<String, RepositoryName> repositoryMapping = ImmutableMap.of("a", b);
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@b//foo", "/exec/src/bar").build();
- assertThat(func.apply("@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ assertThat(
+ func.apply(
+ "@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
@@ -170,7 +184,8 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@potato//foo", "/exec/src/bar").build();
assertThat(
- func.apply("@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ func.apply(
+ "@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
}
@@ -178,7 +193,7 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
final class LocationFunctionBuilder {
private final Label root;
private final boolean multiple;
- private boolean execPaths;
+ private LocationFunction.PathType pathType = LocationFunction.PathType.LOCATION;
private boolean legacyExternalRunfiles;
private final Map<Label, Collection<Artifact>> labelMap = new HashMap<>();
@@ -189,12 +204,12 @@ final class LocationFunctionBuilder {
public LocationFunction build() {
return new LocationFunction(
- root, Suppliers.ofInstance(labelMap), execPaths, legacyExternalRunfiles, multiple);
+ root, Suppliers.ofInstance(labelMap), pathType, legacyExternalRunfiles, multiple);
}
@CanIgnoreReturnValue
- public LocationFunctionBuilder setExecPaths(boolean execPaths) {
- this.execPaths = execPaths;
+ public LocationFunctionBuilder setPathType(LocationFunction.PathType pathType) {
+ this.pathType = pathType;
return this;
}
diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index cb37929531360e..6c2692e58b1098 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -312,6 +312,41 @@ def testLegacyExternalRunfilesOption(self):
"bin/bin.runfiles_manifest")
self.AssertFileContentNotContains(manifest_path, "__main__/external/A")
+ def testRunfilesLibrariesFindRlocationpathExpansion(self):
+ self.ScratchDir("A")
+ self.ScratchFile("A/WORKSPACE")
+ self.ScratchFile("A/p/BUILD", ["exports_files(['foo.txt'])"])
+ self.ScratchFile("A/p/foo.txt", ["Hello, World!"])
+ self.ScratchFile("WORKSPACE", ["local_repository(name = 'A', path='A')"])
+ self.ScratchFile("pkg/BUILD", [
+ "py_binary(",
+ " name = 'bin',",
+ " srcs = ['bin.py'],",
+ " args = [",
+ " '$(rlocationpath bar.txt)',",
+ " '$(rlocationpath @A//p:foo.txt)',",
+ " ],",
+ " data = [",
+ " 'bar.txt',",
+ " '@A//p:foo.txt'",
+ " ],",
+ " deps = ['@bazel_tools//tools/python/runfiles'],",
+ ")",
+ ])
+ self.ScratchFile("pkg/bar.txt", ["Hello, Bazel!"])
+ self.ScratchFile("pkg/bin.py", [
+ "import sys",
+ "from tools.python.runfiles import runfiles",
+ "r = runfiles.Create()",
+ "for arg in sys.argv[1:]:",
+ " print(open(r.Rlocation(arg)).read().strip())",
+ ])
+ _, stdout, _ = self.RunBazel(["run", "//pkg:bin"])
+ if len(stdout) != 2:
+ self.fail("stdout: %s" % stdout)
+ self.assertEqual(stdout[0], "Hello, Bazel!")
+ self.assertEqual(stdout[1], "Hello, World!")
+
if __name__ == "__main__":
unittest.main()
| train | val | 2022-11-03T17:42:28 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/10923_16653 | bazelbuild/bazel | bazelbuild/bazel/10923 | bazelbuild/bazel/16653 | [
"keyword_pr_to_issue"
] | 5eb506bd03348343a6b886104d51e2ea2a01426c | 1b52f5320814dcbf2164b3efd550ce03c6011c63 | [
"As a workaround I wrote the following repository rule:\r\n```python\r\ndef _define_repository_name_impl(repository_ctx):\r\n repository_ctx.file(\"BUILD.bazel\",\r\n \"\"\"package(default_visibility = [\"//visibility:public\"])\r\n \"\"\")\r\n repository_ctx.file(\"defs.bzl\",\r\n \"\"\"main_repository_name=\"{}\"\r\n \"\"\".format(repository_ctx.attr.repo_name))\r\n\r\n_define_repository_name = repository_rule(\r\n implementation = _define_repository_name_impl,\r\n attrs={\"repo_name\": attr.string(mandatory=True)}\r\n )\r\n\r\ndef define_repository_name(repo_name):\r\n _define_repository_name(name = \"main_repository_name\",repo_name = repo_name)\r\n\r\n```\r\n\r\nwhich allows me to load the main repository name by calling:\r\n```python\r\nload(\"@main_repository_name//:defs.bzl\",\"main_repository_name\")\r\n```\r\n\r\nThe `WORKSPACE` file looks like this:\r\n```python\r\nrepository_name = \"xxx\"\r\nworkspace(name = repository_name)\r\n\r\nload(\"@bazel_tooling//rules:define_repository_name.bzl\",\"define_repository_name\")\r\ndefine_repository_name(repository_name)\r\n```\r\n\r\nI don't like it... given that `workspace()` call should be the first line of the WORKSPACE file. But it works (`bazel 2.1.0`)",
"hey @laurentlb ... May I ask for your opinion on this matter? :-)",
"@or-shachar I have the same issue, did you ever find a resolution to this?",
"@or-shachar @jheaff1 Could you describe in more detail what you want to use the name declared in the `WORKSPACE` file for in a macro? Knowing more about the actual problem you are trying to solve would help me answer these questions.",
"You most likely want just \"@\" instead. With the recent fixes on repo mapping, \"@workspace_name//:foo\" is equivalent to \"@//:foo\".\r\n\r\n(Unless you're doing exec path or runfiles shenanigans, in which case refer to @fmeum's comment.)",
"@fmeum I am trying to write a sh_binary target for the rules_foreign_cc repo that wraps around an executable binary (built by rules_foreign_cc) with shared library dependencies. This would allow such a binary to be used as a build tool, eg the protobuf compiler or various generators part of the Qt framework.\r\n\r\nI would like to use the `rlocation` bash function provided here:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/a76cf2f4c3aa514dffa1ddc038c196103ae4583c/tools/bash/runfiles/runfiles.bash#L68\r\n\r\nThe `rlocation` bash function requires the workspace name, which I would like to obtain programatically in a macro.\r\n\r\nI’ve tried to use native.repository_name() but that returns `@` rather than the name of the repository.\r\n\r\n",
"@jheaff1 Would an analogue of `$(location //foo)` that returns the correct path for `rlocation` help you realize this? I could see that being more user-friendly than yet another \"some type of name of a repo\" thing.",
"@fmeum Absolutely that would be very useful. Ive found that using `$(rootpath` rather than `$(location` provides exactly what `$(rlocation` requires apart from the workspace name.",
"@lberki I have been thinking about proposing a `$(location ...)` variant that returns the correct path for Rlocation for a while. The way runfiles work with Bzlmod would almost make this a requirement for location expansion to remain useful in `args`. What do you think?",
"@fmeum without taking sides on the `$(location) question, it's a feature orthogonal to the one proposed in this bug.\r\n\r\nre: this bug in particular, what is the argument *against* introducing `repository_name()`? Naively, one would think that it's a very logical extension to `package_name()`. @Wyverald maybe you can think of a counter-argument?",
"> this bug in particular, what is the argument against introducing repository_name()? Naively, one would think that it's a very logical extension to package_name(). @Wyverald maybe you can think of a counter-argument?\r\n\r\nWe already have `native.repository_name` and it does what it says on the tin (https://bazel.build/rules/lib/native#repository_name). @fmeum's & @jheaff1's question is more about the runfiles/execpath use case, where we sometimes need the *workspace name*, which is only accessible right now in a rule ctx object (https://bazel.build/rules/lib/ctx#workspace_name; also to note, *not* the same as [Label.workspace_name](https://bazel.build/rules/lib/Label#workspace_name)...)",
"@Wyverald I'm embarrassed! I specifically looked for the identifier called `repository_name` and didn't find it in the source code. My bad.",
"The issue with making the (global) workspace name available in Starlark code is that then the evaluation of BUILD files in external repositories would be a function of the content of the main repository, which isn't too intuitive (it's problematic enough for `ctx.workspace_name()`, but we can't help that because that's how runfiles work at the moment.",
"@lberki That plus the fact that having yet another `workspace_name` would be confusing made me think that being able to get Rlocation paths out of location expansion may indeed be the best solution to this issue (see also the comment by @jheaff1). Since `native.repository_name` returns the right identifier for everything *except* runfiles discovery, why not add a way for users to get the full runfiles path right away without having them stitch it together themselves?",
"The reason why I was confused is that for some reason, I thought `$(rlocation)` is already a thing in Bazel so I went on a wild goose chase trying to figure out what *else* you want :)\r\n\r\nI think both adding `$(rlocation)` and the same method to File is reasonable. @Wyverald , it looks like you also agree? ",
"@lberki `$(rlocation)` seems reasonably easy to do, but `File.rlocation_path` is difficult: Without `--experimental_sibling_repository_layout`, that function needs to know the workspace name. I'm not sure how the API for that would look like, should we just let the user pass in `ctx`?",
"Not necessarily; there is `BazelStarlarkContext`, which is available to the Java implementations of Starlark functions without an extra argument and it, weirdly, already contains the repository name of the tools repository. So I could imagine plumbing the workspace name in there that way, too. Rule implementations need to know the name of the main workspace anyway, so it would probably not require too much extra plumbing.",
"@lberki I will give that a try. We will have to make a concession though: Using `StarlarkThread` is incompatible with `structField = True`, so this will have to be a function instead.",
"Today I Learned. It seems to be an artificial choice and not an inherent limitation of how Starlark works, though, and I don't see an immediate reason for this limitation. @c-parsons , do you remember why you prohibited setting `useStarlarkThread` and `structField` to true at the same time in 73e1016 ?"
] | [] | "2022-11-03T19:12:08Z" | [
"type: feature request",
"P3",
"team-ExternalDeps"
] | Get the name of current repository from macro | ### Description of the problem / feature request:
I am trying to get the name of the current repository from a macro.
```
.
├── a
│ ├── BUILD.bazel
│ ├── WORKSPACE
│ ├── empty.txt
│ └── txt_files.bzl
└── b
├── BUILD.bazel
├── WORKSPACE
└── empty2.txt
```
_(see full example [here](https://github.com/or-shachar/bazel_repository_name_issue) )_
I want that if repo `b` will call the macro in `@a//:txt_files.bzl` then somehow I'd be able to retrieve that it was called from repo `b`.
Right now (not sure if it's a bug or work as intended) - calling `native.repository_name()` will return `@` and not the name of repo as declared in its `WORKSPACE` file.
### Feature requests: what underlying problem are you trying to solve with this feature?
I want to change the behavior of a macro based on the callee repository.
Can we allow `native.repository_name()` to return the explicit name of the repository and not `@`? To maintain backward compatibility - I assume it would be better if we add a flag to this method that will be turned off by default.
| [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java",
"src/test/py/bazel/runfiles_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
index 096a6eac0aea0d..f5ac7d1c84abcf 100644
--- a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
+++ b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
@@ -262,15 +262,15 @@
</p>
<p>
Output files are staged similarly, but are also prefixed with the subpath
- <code>bazel-out/cpu-compilation_mode/bin</code> (or for certain outputs:
- <code>bazel-out/cpu-compilation_mode/genfiles</code>, or for the outputs
- of host tools: <code>bazel-out/host/bin</code>). In the above example,
- <code>//testapp:app</code> is a host tool because it appears in
+ <code>bazel-out/cpu-compilation_mode/bin</code> (or for the outputs of
+ tools: <code>bazel-out/cpu-opt-exec-hash/bin</code>). In the above example,
+ <code>//testapp:app</code> is a tool because it appears in
<code>show_app_output</code>'s <code><a
href="$expander.expandRef("genrule.tools")">tools</a></code> attribute.
So its output file <code>app</code> is written to
- <code>bazel-myproject/bazel-out/host/bin/testapp/app</code>. The exec path
- is thus <code>bazel-out/host/bin/testapp/app</code>. This extra prefix
+ <code>bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>.
+ The exec path is thus <code>
+ bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>. This extra prefix
makes it possible to build the same target for, say, two different CPUs in
the same build without the results clobbering each other.
</p>
@@ -284,15 +284,57 @@
<li>
<p>
- <code>rootpath</code>: Denotes the runfiles path that a built binary can
- use to find its dependencies at runtime.
- </p>
+ <code>rootpath</code>: Denotes the path that a built binary can use to
+ find a dependency at runtime relative to the subdirectory of its runfiles
+ directory corresponding to the main repository.
+ <strong>Note:</strong> This only works if <a
+ href="/reference/command-line-reference#flag--enable_runfiles">
+ <code>--enable_runfiles</code></a> is enabled, which is not the case on
+ Windows by default. Use <code>rlocationpath</code> instead for
+ cross-platform support.
<p>
- This is the same as <code>execpath</code> but strips the output prefixes
- described above. In the above example this means both
+ This is similar to <code>execpath</code> but strips the configuration
+ prefixes described above. In the example from above this means both
<code>empty.source</code> and <code>app</code> use pure workspace-relative
paths: <code>testapp/empty.source</code> and <code>testapp/app</code>.
</p>
+ <p>
+ The <code>rootpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>../repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ This has the same "one output only" requirements as <code>execpath</code>.
+ </p>
+ </li>
+
+ <li>
+ <p>
+ <code>rlocationpath</code>: The path a built binary can pass to the <code>
+ Rlocation</code> function of a runfiles library to find a dependency at
+ runtime, either in the runfiles directory (if available) or using the
+ runfiles manifest.
+ </p>
+ <p>
+ This is similar to <code>rootpath</code> in that it does not contain
+ configuration prefixes, but differs in that it always starts with the
+ name of the repository. In the example from above this means that <code>
+ empty.source</code> and <code>app</code> result in the following
+ paths: <code>myproject/testapp/empty.source</code> and <code>
+ myproject/testapp/app</code>.
+ </p>
+ <p>
+ The <code>rlocationpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ 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 <code>rootpath</code>, it has the advantage that it
+ works on all platforms and even if the runfiles directory is not
+ available.
+ </p>
<p>
This has the same "one output only" requirements as <code>execpath</code>.
</p>
@@ -303,24 +345,25 @@
<code>rootpath</code>, depending on the attribute being expanded. This is
legacy pre-Starlark behavior and not recommended unless you really know what
it does for a particular rule. See <a
- href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
+ href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
for details.
</li>
</ul>
<p>
- <code>execpaths</code>, <code>rootpaths</code>, and <code>locations</code> are
- the plural variations of <code>execpath</code>, <code>rootpath</code>, and
- <code>location</code>, respectively. They support labels producing multiple
- outputs, in which case each output is listed separated by a space. Zero-output
- rules and malformed labels produce build errors.
+ <code>execpaths</code>, <code>rootpaths</code>, <code>rlocationpaths</code>,
+ and <code>locations</code> are the plural variations of <code>execpath</code>,
+ <code>rootpath</code>, <code>rlocationpaths</code>, and<code>location</code>,
+ respectively. They support labels producing multiple outputs, in which case
+ each output is listed separated by a space. Zero-output rules and malformed
+ labels produce build errors.
</p>
<p>
All referenced labels must appear in the consuming target's <code>srcs</code>,
output files, or <code>deps</code>. Otherwise the build fails. C++ targets can
also reference labels in <code><a
- href="$expander.expandRef("cc_binary.data")">data</a></code>.
+ href="$expander.expandRef("cc_binary.data")">data</a></code>.
</p>
<p>
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
index d82d3de89a0f7d..ddcf5510ac174d 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
@@ -17,6 +17,7 @@
import static java.util.stream.Collectors.joining;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableCollection;
@@ -26,7 +27,9 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Artifact;
+import com.google.devtools.build.lib.analysis.LocationExpander.LocationFunction.PathType;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.packages.BuildType;
@@ -63,34 +66,35 @@ public final class LocationExpander {
private static final boolean EXACTLY_ONE = false;
private static final boolean ALLOW_MULTIPLE = true;
- private static final boolean USE_LOCATION_PATHS = false;
- private static final boolean USE_EXEC_PATHS = true;
-
private final RuleErrorConsumer ruleErrorConsumer;
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
+ private final String workspaceRunfilesDirectory;
@VisibleForTesting
LocationExpander(
RuleErrorConsumer ruleErrorConsumer,
Map<String, LocationFunction> functions,
- RepositoryMapping repositoryMapping) {
+ RepositoryMapping repositoryMapping,
+ String workspaceRunfilesDirectory) {
this.ruleErrorConsumer = ruleErrorConsumer;
this.functions = ImmutableMap.copyOf(functions);
this.repositoryMapping = repositoryMapping;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
private LocationExpander(
- RuleErrorConsumer ruleErrorConsumer,
+ RuleContext ruleContext,
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMap,
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping) {
this(
- ruleErrorConsumer,
+ ruleContext,
allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles),
- repositoryMapping);
+ repositoryMapping,
+ ruleContext.getWorkspaceName());
}
/**
@@ -204,7 +208,10 @@ private String expand(String value, ErrorReporter reporter) {
// (2) Call appropriate function to obtain string replacement.
String functionValue = value.substring(nextWhitespace + 1, end).trim();
try {
- String replacement = functions.get(fname).apply(functionValue, repositoryMapping);
+ String replacement =
+ functions
+ .get(fname)
+ .apply(functionValue, repositoryMapping, workspaceRunfilesDirectory);
result.append(replacement);
} catch (IllegalStateException ise) {
reporter.report(ise.getMessage());
@@ -232,23 +239,29 @@ public String expandAttribute(String attrName, String attrValue) {
@VisibleForTesting
static final class LocationFunction {
+ enum PathType {
+ LOCATION,
+ EXEC,
+ RLOCATION,
+ }
+
private static final int MAX_PATHS_SHOWN = 5;
private final Label root;
private final Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier;
- private final boolean execPaths;
+ private final PathType pathType;
private final boolean legacyExternalRunfiles;
private final boolean multiple;
LocationFunction(
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier,
- boolean execPaths,
+ PathType pathType,
boolean legacyExternalRunfiles,
boolean multiple) {
this.root = root;
this.locationMapSupplier = locationMapSupplier;
- this.execPaths = execPaths;
+ this.pathType = Preconditions.checkNotNull(pathType);
this.legacyExternalRunfiles = legacyExternalRunfiles;
this.multiple = multiple;
}
@@ -259,10 +272,13 @@ static final class LocationFunction {
* using the {@code repositoryMapping}.
*
* @param arg The label-like string to be expanded, e.g. ":foo" or "//foo:bar"
- * @param repositoryMapping map of {@code RepositoryName}s defined in the main workspace
+ * @param repositoryMapping map of apparent repository names to {@code RepositoryName}s
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return The expanded value
*/
- public String apply(String arg, RepositoryMapping repositoryMapping) {
+ public String apply(
+ String arg, RepositoryMapping repositoryMapping, String workspaceRunfilesDirectory) {
Label label;
try {
label = root.getRelativeWithRemapping(arg, repositoryMapping);
@@ -271,14 +287,13 @@ public String apply(String arg, RepositoryMapping repositoryMapping) {
String.format(
"invalid label in %s expression: %s", functionName(), e.getMessage()), e);
}
- Collection<String> paths = resolveLabel(label);
+ Set<String> paths = resolveLabel(label, workspaceRunfilesDirectory);
return joinPaths(paths);
}
- /**
- * Returns all target location(s) of the given label.
- */
- private Collection<String> resolveLabel(Label unresolved) throws IllegalStateException {
+ /** Returns all target location(s) of the given label. */
+ private Set<String> resolveLabel(Label unresolved, String workspaceRunfilesDirectory)
+ throws IllegalStateException {
Collection<Artifact> artifacts = locationMapSupplier.get().get(unresolved);
if (artifacts == null) {
@@ -288,7 +303,7 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
unresolved, functionName()));
}
- Set<String> paths = getPaths(artifacts);
+ Set<String> paths = getPaths(artifacts, workspaceRunfilesDirectory);
if (paths.isEmpty()) {
throw new IllegalStateException(
String.format(
@@ -313,24 +328,41 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
* Extracts list of all executables associated with given collection of label artifacts.
*
* @param artifacts to get the paths of
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return all associated executable paths
*/
- private Set<String> getPaths(Collection<Artifact> artifacts) {
+ private Set<String> getPaths(
+ Collection<Artifact> artifacts, String workspaceRunfilesDirectory) {
TreeSet<String> paths = Sets.newTreeSet();
for (Artifact artifact : artifacts) {
- PathFragment execPath =
- execPaths
- ? artifact.getExecPath()
- : legacyExternalRunfiles
- ? artifact.getPathForLocationExpansion()
- : artifact.getRunfilesPath();
- if (execPath != null) { // omit middlemen etc
- paths.add(execPath.getCallablePathString());
+ PathFragment path = getPath(artifact, workspaceRunfilesDirectory);
+ if (path != null) { // omit middlemen etc
+ paths.add(path.getCallablePathString());
}
}
return paths;
}
+ private PathFragment getPath(Artifact artifact, String workspaceRunfilesDirectory) {
+ switch (pathType) {
+ case LOCATION:
+ return legacyExternalRunfiles
+ ? artifact.getPathForLocationExpansion()
+ : artifact.getRunfilesPath();
+ case EXEC:
+ return artifact.getExecPath();
+ case RLOCATION:
+ PathFragment runfilesPath = artifact.getRunfilesPath();
+ if (runfilesPath.startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX)) {
+ return runfilesPath.relativeTo(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
+ } else {
+ return PathFragment.create(workspaceRunfilesDirectory).getRelative(runfilesPath);
+ }
+ }
+ throw new IllegalStateException("Unexpected PathType: " + pathType);
+ }
+
private String joinPaths(Collection<String> paths) {
return paths.stream().map(ShellEscaper::escapeString).collect(joining(" "));
}
@@ -348,27 +380,44 @@ static ImmutableMap<String, LocationFunction> allLocationFunctions(
return new ImmutableMap.Builder<String, LocationFunction>()
.put(
"location",
- new LocationFunction(root, locationMap, execPaths, legacyExternalRunfiles, EXACTLY_ONE))
+ new LocationFunction(
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ EXACTLY_ONE))
.put(
"locations",
new LocationFunction(
- root, locationMap, execPaths, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ ALLOW_MULTIPLE))
.put(
"rootpath",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"rootpaths",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.put(
"execpath",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"execpaths",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ .put(
+ "rlocationpath",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, EXACTLY_ONE))
+ .put(
+ "rlocationpaths",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.buildOrThrow();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
index f3e66781c7dec3..0de4a4e498c49b 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
@@ -50,6 +50,7 @@ final class LocationTemplateContext implements TemplateContext {
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
private final boolean windowsPath;
+ private final String workspaceRunfilesDirectory;
private LocationTemplateContext(
TemplateContext delegate,
@@ -58,12 +59,14 @@ private LocationTemplateContext(
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping,
- boolean windowsPath) {
+ boolean windowsPath,
+ String workspaceRunfilesDirectory) {
this.delegate = delegate;
this.functions =
LocationExpander.allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles);
this.repositoryMapping = repositoryMapping;
this.windowsPath = windowsPath;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
public LocationTemplateContext(
@@ -83,7 +86,8 @@ public LocationTemplateContext(
execPaths,
ruleContext.getConfiguration().legacyExternalRunfiles(),
ruleContext.getRule().getPackage().getRepositoryMapping(),
- windowsPath);
+ windowsPath,
+ ruleContext.getWorkspaceName());
}
@Override
@@ -108,7 +112,7 @@ private String lookupFunctionImpl(String name, String param) throws ExpansionExc
try {
LocationFunction f = functions.get(name);
if (f != null) {
- return f.apply(param, repositoryMapping);
+ return f.apply(param, repositoryMapping, workspaceRunfilesDirectory);
}
} catch (IllegalStateException e) {
throw new ExpansionException(e.getMessage(), e);
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
index 4f40434ea75b74..7a31156694281c 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
@@ -17,6 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Root;
@@ -121,6 +122,12 @@ public void otherPathExpansion() throws Exception {
"genrule(name='foo', outs=['foo.txt'], cmd='never executed')",
"sh_library(name='lib', srcs=[':foo'])");
+ FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"), "workspace(name='workspace')");
+ // Invalidate WORKSPACE to pick up the name.
+ getSkyframeExecutor()
+ .invalidateFilesUnderPathForTesting(
+ reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
+
LocationExpander expander = makeExpander("//expansion:lib");
assertThat(expander.expand("foo $(execpath :foo) bar"))
.matches("foo .*-out/.*/expansion/foo\\.txt bar");
@@ -130,6 +137,22 @@ public void otherPathExpansion() throws Exception {
.matches("foo expansion/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
}
@Test
@@ -158,6 +181,10 @@ public void otherPathExternalExpansion() throws Exception {
.matches("foo external/r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar"))
.matches("foo external/r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -183,6 +210,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfiles() throws Exceptio
.matches("foo .*-out/.*/external/r/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -210,6 +241,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfilesSiblingRepositoryL
.matches("foo .*-out/r/.*/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -224,5 +259,9 @@ public void otherPathMultiExpansion() throws Exception {
.matches("foo .*-out/.*/expansion/bar\\.txt .*-out/.*/expansion/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/bar.txt expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo(
+ "foo __main__/expansion/bar.txt __main__/expansion/foo.txt bar"
+ .replace("__main__", TestConstants.WORKSPACE_NAME));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
index abdeb1ed742df4..9e6b63490ef638 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
@@ -59,22 +59,25 @@ public boolean hasErrors() {
}
private LocationExpander makeExpander(RuleErrorConsumer ruleErrorConsumer) throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("//a", "/exec/src/a")
- .build();
-
- LocationFunction f2 = new LocationFunctionBuilder("//b", true)
- .setExecPaths(false)
- .add("//b", "/exec/src/b")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//a", "/exec/src/a")
+ .build();
+
+ LocationFunction f2 =
+ new LocationFunctionBuilder("//b", true)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//b", "/exec/src/b")
+ .build();
return new LocationExpander(
ruleErrorConsumer,
ImmutableMap.<String, LocationFunction>of(
"location", f1,
"locations", f2),
- RepositoryMapping.ALWAYS_FALLBACK);
+ RepositoryMapping.ALWAYS_FALLBACK,
+ "workspace");
}
private String expand(String input) throws Exception {
@@ -125,10 +128,11 @@ public void noExpansionOnError() throws Exception {
@Test
public void expansionWithRepositoryMapping() throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("@bar//a", "/exec/src/a")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("@bar//a", "/exec/src/a")
+ .build();
ImmutableMap<String, RepositoryName> repositoryMapping =
ImmutableMap.of("foo", RepositoryName.create("bar"));
@@ -137,7 +141,8 @@ public void expansionWithRepositoryMapping() throws Exception {
new LocationExpander(
new Capture(),
ImmutableMap.<String, LocationFunction>of("location", f1),
- RepositoryMapping.createAllowingFallback(repositoryMapping));
+ RepositoryMapping.createAllowingFallback(repositoryMapping),
+ "workspace");
String value = locationExpander.expand("$(location @foo//a)");
assertThat(value).isEqualTo("src/a");
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
index 38addac4979d01..608b39b34fa105 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
@@ -49,16 +49,16 @@ public class LocationFunctionTest {
public void absoluteAndRelativeLabels() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/src/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
}
@Test
public void pathUnderExecRootUsesDotSlash() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("./bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("./bar");
}
@Test
@@ -67,7 +67,7 @@ public void noSuchLabel() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -81,7 +81,7 @@ public void emptyList() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo("label '//foo:foo' in $(location) expression expands to no files");
@@ -94,7 +94,7 @@ public void tooMany() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -109,7 +109,7 @@ public void noSuchLabelMultiple() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -121,7 +121,7 @@ public void noSuchLabelMultiple() throws Exception {
public void fileWithSpace() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/file/with space").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space'");
}
@@ -130,7 +130,7 @@ public void multipleFiles() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/foo/bar", "/exec/out/foo/foobar")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("foo/bar foo/foobar");
}
@@ -139,27 +139,41 @@ public void filesWithSpace() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/file/with space", "/exec/file/with spaces ")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space' 'file/with spaces '");
}
@Test
public void execPath() throws Exception {
- LocationFunction func = new LocationFunctionBuilder("//foo", true)
- .setExecPaths(true)
- .add("//foo", "/exec/bar", "/exec/out/foobar")
- .build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.EXEC)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("./bar out/foobar");
}
+ @Test
+ public void rlocationPath() throws Exception {
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.RLOCATION)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, "workspace"))
+ .isEqualTo("workspace/bar workspace/foobar");
+ }
+
@Test
public void locationFunctionWithMappingReplace() throws Exception {
RepositoryName b = RepositoryName.create("b");
ImmutableMap<String, RepositoryName> repositoryMapping = ImmutableMap.of("a", b);
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@b//foo", "/exec/src/bar").build();
- assertThat(func.apply("@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ assertThat(
+ func.apply(
+ "@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
@@ -170,7 +184,8 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@potato//foo", "/exec/src/bar").build();
assertThat(
- func.apply("@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ func.apply(
+ "@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
}
@@ -178,7 +193,7 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
final class LocationFunctionBuilder {
private final Label root;
private final boolean multiple;
- private boolean execPaths;
+ private LocationFunction.PathType pathType = LocationFunction.PathType.LOCATION;
private boolean legacyExternalRunfiles;
private final Map<Label, Collection<Artifact>> labelMap = new HashMap<>();
@@ -189,12 +204,12 @@ final class LocationFunctionBuilder {
public LocationFunction build() {
return new LocationFunction(
- root, Suppliers.ofInstance(labelMap), execPaths, legacyExternalRunfiles, multiple);
+ root, Suppliers.ofInstance(labelMap), pathType, legacyExternalRunfiles, multiple);
}
@CanIgnoreReturnValue
- public LocationFunctionBuilder setExecPaths(boolean execPaths) {
- this.execPaths = execPaths;
+ public LocationFunctionBuilder setPathType(LocationFunction.PathType pathType) {
+ this.pathType = pathType;
return this;
}
diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index cb37929531360e..6c2692e58b1098 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -312,6 +312,41 @@ def testLegacyExternalRunfilesOption(self):
"bin/bin.runfiles_manifest")
self.AssertFileContentNotContains(manifest_path, "__main__/external/A")
+ def testRunfilesLibrariesFindRlocationpathExpansion(self):
+ self.ScratchDir("A")
+ self.ScratchFile("A/WORKSPACE")
+ self.ScratchFile("A/p/BUILD", ["exports_files(['foo.txt'])"])
+ self.ScratchFile("A/p/foo.txt", ["Hello, World!"])
+ self.ScratchFile("WORKSPACE", ["local_repository(name = 'A', path='A')"])
+ self.ScratchFile("pkg/BUILD", [
+ "py_binary(",
+ " name = 'bin',",
+ " srcs = ['bin.py'],",
+ " args = [",
+ " '$(rlocationpath bar.txt)',",
+ " '$(rlocationpath @A//p:foo.txt)',",
+ " ],",
+ " data = [",
+ " 'bar.txt',",
+ " '@A//p:foo.txt'",
+ " ],",
+ " deps = ['@bazel_tools//tools/python/runfiles'],",
+ ")",
+ ])
+ self.ScratchFile("pkg/bar.txt", ["Hello, Bazel!"])
+ self.ScratchFile("pkg/bin.py", [
+ "import sys",
+ "from tools.python.runfiles import runfiles",
+ "r = runfiles.Create()",
+ "for arg in sys.argv[1:]:",
+ " print(open(r.Rlocation(arg)).read().strip())",
+ ])
+ _, stdout, _ = self.RunBazel(["run", "//pkg:bin"])
+ if len(stdout) != 2:
+ self.fail("stdout: %s" % stdout)
+ self.assertEqual(stdout[0], "Hello, Bazel!")
+ self.assertEqual(stdout[1], "Hello, World!")
+
if __name__ == "__main__":
unittest.main()
| test | val | 2022-11-03T17:42:28 | "2020-03-08T11:43:50Z" | or-shachar | test |
bazelbuild/bazel/16124_16668 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16668 | [
"keyword_pr_to_issue"
] | 8c80ef8c95dfd68f0ddd28ee56e7cc805f7b479c | ece17d5d4e74d67dd869cbd1951ca1001423b472 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-04T22:20:01Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java",
"src/test/py/bazel/runfiles_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
index 96f3cfacacb19b..b5dc2f88b9dae1 100644
--- a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
+++ b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
@@ -262,15 +262,15 @@ title: Make Variables
</p>
<p>
Output files are staged similarly, but are also prefixed with the subpath
- <code>bazel-out/cpu-compilation_mode/bin</code> (or for certain outputs:
- <code>bazel-out/cpu-compilation_mode/genfiles</code>, or for the outputs
- of host tools: <code>bazel-out/host/bin</code>). In the above example,
- <code>//testapp:app</code> is a host tool because it appears in
+ <code>bazel-out/cpu-compilation_mode/bin</code> (or for the outputs of
+ tools: <code>bazel-out/cpu-opt-exec-hash/bin</code>). In the above example,
+ <code>//testapp:app</code> is a tool because it appears in
<code>show_app_output</code>'s <code><a
href="$expander.expandRef("genrule.tools")">tools</a></code> attribute.
So its output file <code>app</code> is written to
- <code>bazel-myproject/bazel-out/host/bin/testapp/app</code>. The exec path
- is thus <code>bazel-out/host/bin/testapp/app</code>. This extra prefix
+ <code>bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>.
+ The exec path is thus <code>
+ bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>. This extra prefix
makes it possible to build the same target for, say, two different CPUs in
the same build without the results clobbering each other.
</p>
@@ -284,15 +284,57 @@ title: Make Variables
<li>
<p>
- <code>rootpath</code>: Denotes the runfiles path that a built binary can
- use to find its dependencies at runtime.
- </p>
+ <code>rootpath</code>: Denotes the path that a built binary can use to
+ find a dependency at runtime relative to the subdirectory of its runfiles
+ directory corresponding to the main repository.
+ <strong>Note:</strong> This only works if <a
+ href="/reference/command-line-reference#flag--enable_runfiles">
+ <code>--enable_runfiles</code></a> is enabled, which is not the case on
+ Windows by default. Use <code>rlocationpath</code> instead for
+ cross-platform support.
<p>
- This is the same as <code>execpath</code> but strips the output prefixes
- described above. In the above example this means both
+ This is similar to <code>execpath</code> but strips the configuration
+ prefixes described above. In the example from above this means both
<code>empty.source</code> and <code>app</code> use pure workspace-relative
paths: <code>testapp/empty.source</code> and <code>testapp/app</code>.
</p>
+ <p>
+ The <code>rootpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>../repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ This has the same "one output only" requirements as <code>execpath</code>.
+ </p>
+ </li>
+
+ <li>
+ <p>
+ <code>rlocationpath</code>: The path a built binary can pass to the <code>
+ Rlocation</code> function of a runfiles library to find a dependency at
+ runtime, either in the runfiles directory (if available) or using the
+ runfiles manifest.
+ </p>
+ <p>
+ This is similar to <code>rootpath</code> in that it does not contain
+ configuration prefixes, but differs in that it always starts with the
+ name of the repository. In the example from above this means that <code>
+ empty.source</code> and <code>app</code> result in the following
+ paths: <code>myproject/testapp/empty.source</code> and <code>
+ myproject/testapp/app</code>.
+ </p>
+ <p>
+ The <code>rlocationpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ 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 <code>rootpath</code>, it has the advantage that it
+ works on all platforms and even if the runfiles directory is not
+ available.
+ </p>
<p>
This has the same "one output only" requirements as <code>execpath</code>.
</p>
@@ -303,24 +345,25 @@ title: Make Variables
<code>rootpath</code>, depending on the attribute being expanded. This is
legacy pre-Starlark behavior and not recommended unless you really know what
it does for a particular rule. See <a
- href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
+ href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
for details.
</li>
</ul>
<p>
- <code>execpaths</code>, <code>rootpaths</code>, and <code>locations</code> are
- the plural variations of <code>execpath</code>, <code>rootpath</code>, and
- <code>location</code>, respectively. They support labels producing multiple
- outputs, in which case each output is listed separated by a space. Zero-output
- rules and malformed labels produce build errors.
+ <code>execpaths</code>, <code>rootpaths</code>, <code>rlocationpaths</code>,
+ and <code>locations</code> are the plural variations of <code>execpath</code>,
+ <code>rootpath</code>, <code>rlocationpaths</code>, and<code>location</code>,
+ respectively. They support labels producing multiple outputs, in which case
+ each output is listed separated by a space. Zero-output rules and malformed
+ labels produce build errors.
</p>
<p>
All referenced labels must appear in the consuming target's <code>srcs</code>,
output files, or <code>deps</code>. Otherwise the build fails. C++ targets can
also reference labels in <code><a
- href="$expander.expandRef("cc_binary.data")">data</a></code>.
+ href="$expander.expandRef("cc_binary.data")">data</a></code>.
</p>
<p>
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
index f8f5b7885e384e..3323927e89691e 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
@@ -17,6 +17,7 @@
import static java.util.stream.Collectors.joining;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableCollection;
@@ -26,7 +27,9 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Artifact;
+import com.google.devtools.build.lib.analysis.LocationExpander.LocationFunction.PathType;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.packages.BuildType;
@@ -63,34 +66,35 @@ public final class LocationExpander {
private static final boolean EXACTLY_ONE = false;
private static final boolean ALLOW_MULTIPLE = true;
- private static final boolean USE_LOCATION_PATHS = false;
- private static final boolean USE_EXEC_PATHS = true;
-
private final RuleErrorConsumer ruleErrorConsumer;
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
+ private final String workspaceRunfilesDirectory;
@VisibleForTesting
LocationExpander(
RuleErrorConsumer ruleErrorConsumer,
Map<String, LocationFunction> functions,
- RepositoryMapping repositoryMapping) {
+ RepositoryMapping repositoryMapping,
+ String workspaceRunfilesDirectory) {
this.ruleErrorConsumer = ruleErrorConsumer;
this.functions = ImmutableMap.copyOf(functions);
this.repositoryMapping = repositoryMapping;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
private LocationExpander(
- RuleErrorConsumer ruleErrorConsumer,
+ RuleContext ruleContext,
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMap,
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping) {
this(
- ruleErrorConsumer,
+ ruleContext,
allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles),
- repositoryMapping);
+ repositoryMapping,
+ ruleContext.getWorkspaceName());
}
/**
@@ -215,7 +219,10 @@ private String expand(String value, ErrorReporter reporter) {
// (2) Call appropriate function to obtain string replacement.
String functionValue = value.substring(nextWhitespace + 1, end).trim();
try {
- String replacement = functions.get(fname).apply(functionValue, repositoryMapping);
+ String replacement =
+ functions
+ .get(fname)
+ .apply(functionValue, repositoryMapping, workspaceRunfilesDirectory);
result.append(replacement);
} catch (IllegalStateException ise) {
reporter.report(ise.getMessage());
@@ -230,23 +237,29 @@ private String expand(String value, ErrorReporter reporter) {
@VisibleForTesting
static final class LocationFunction {
+ enum PathType {
+ LOCATION,
+ EXEC,
+ RLOCATION,
+ }
+
private static final int MAX_PATHS_SHOWN = 5;
private final Label root;
private final Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier;
- private final boolean execPaths;
+ private final PathType pathType;
private final boolean legacyExternalRunfiles;
private final boolean multiple;
LocationFunction(
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier,
- boolean execPaths,
+ PathType pathType,
boolean legacyExternalRunfiles,
boolean multiple) {
this.root = root;
this.locationMapSupplier = locationMapSupplier;
- this.execPaths = execPaths;
+ this.pathType = Preconditions.checkNotNull(pathType);
this.legacyExternalRunfiles = legacyExternalRunfiles;
this.multiple = multiple;
}
@@ -257,10 +270,13 @@ static final class LocationFunction {
* using the {@code repositoryMapping}.
*
* @param arg The label-like string to be expanded, e.g. ":foo" or "//foo:bar"
- * @param repositoryMapping map of {@code RepositoryName}s defined in the main workspace
+ * @param repositoryMapping map of apparent repository names to {@code RepositoryName}s
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return The expanded value
*/
- public String apply(String arg, RepositoryMapping repositoryMapping) {
+ public String apply(
+ String arg, RepositoryMapping repositoryMapping, String workspaceRunfilesDirectory) {
Label label;
try {
label = root.getRelativeWithRemapping(arg, repositoryMapping);
@@ -269,14 +285,13 @@ public String apply(String arg, RepositoryMapping repositoryMapping) {
String.format(
"invalid label in %s expression: %s", functionName(), e.getMessage()), e);
}
- Collection<String> paths = resolveLabel(label);
+ Set<String> paths = resolveLabel(label, workspaceRunfilesDirectory);
return joinPaths(paths);
}
- /**
- * Returns all target location(s) of the given label.
- */
- private Collection<String> resolveLabel(Label unresolved) throws IllegalStateException {
+ /** Returns all target location(s) of the given label. */
+ private Set<String> resolveLabel(Label unresolved, String workspaceRunfilesDirectory)
+ throws IllegalStateException {
Collection<Artifact> artifacts = locationMapSupplier.get().get(unresolved);
if (artifacts == null) {
@@ -286,7 +301,7 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
unresolved, functionName()));
}
- Set<String> paths = getPaths(artifacts);
+ Set<String> paths = getPaths(artifacts, workspaceRunfilesDirectory);
if (paths.isEmpty()) {
throw new IllegalStateException(
String.format(
@@ -311,24 +326,41 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
* Extracts list of all executables associated with given collection of label artifacts.
*
* @param artifacts to get the paths of
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return all associated executable paths
*/
- private Set<String> getPaths(Collection<Artifact> artifacts) {
+ private Set<String> getPaths(
+ Collection<Artifact> artifacts, String workspaceRunfilesDirectory) {
TreeSet<String> paths = Sets.newTreeSet();
for (Artifact artifact : artifacts) {
- PathFragment execPath =
- execPaths
- ? artifact.getExecPath()
- : legacyExternalRunfiles
- ? artifact.getPathForLocationExpansion()
- : artifact.getRunfilesPath();
- if (execPath != null) { // omit middlemen etc
- paths.add(execPath.getCallablePathString());
+ PathFragment path = getPath(artifact, workspaceRunfilesDirectory);
+ if (path != null) { // omit middlemen etc
+ paths.add(path.getCallablePathString());
}
}
return paths;
}
+ private PathFragment getPath(Artifact artifact, String workspaceRunfilesDirectory) {
+ switch (pathType) {
+ case LOCATION:
+ return legacyExternalRunfiles
+ ? artifact.getPathForLocationExpansion()
+ : artifact.getRunfilesPath();
+ case EXEC:
+ return artifact.getExecPath();
+ case RLOCATION:
+ PathFragment runfilesPath = artifact.getRunfilesPath();
+ if (runfilesPath.startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX)) {
+ return runfilesPath.relativeTo(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
+ } else {
+ return PathFragment.create(workspaceRunfilesDirectory).getRelative(runfilesPath);
+ }
+ }
+ throw new IllegalStateException("Unexpected PathType: " + pathType);
+ }
+
private String joinPaths(Collection<String> paths) {
return paths.stream().map(ShellEscaper::escapeString).collect(joining(" "));
}
@@ -346,27 +378,44 @@ static ImmutableMap<String, LocationFunction> allLocationFunctions(
return new ImmutableMap.Builder<String, LocationFunction>()
.put(
"location",
- new LocationFunction(root, locationMap, execPaths, legacyExternalRunfiles, EXACTLY_ONE))
+ new LocationFunction(
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ EXACTLY_ONE))
.put(
"locations",
new LocationFunction(
- root, locationMap, execPaths, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ ALLOW_MULTIPLE))
.put(
"rootpath",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"rootpaths",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.put(
"execpath",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"execpaths",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ .put(
+ "rlocationpath",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, EXACTLY_ONE))
+ .put(
+ "rlocationpaths",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
index 22d0097eb0133c..0abe2bf58575dd 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
@@ -50,6 +50,7 @@ final class LocationTemplateContext implements TemplateContext {
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
private final boolean windowsPath;
+ private final String workspaceRunfilesDirectory;
private LocationTemplateContext(
TemplateContext delegate,
@@ -58,12 +59,14 @@ private LocationTemplateContext(
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping,
- boolean windowsPath) {
+ boolean windowsPath,
+ String workspaceRunfilesDirectory) {
this.delegate = delegate;
this.functions =
LocationExpander.allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles);
this.repositoryMapping = repositoryMapping;
this.windowsPath = windowsPath;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
public LocationTemplateContext(
@@ -82,7 +85,8 @@ public LocationTemplateContext(
execPaths,
ruleContext.getConfiguration().legacyExternalRunfiles(),
ruleContext.getRule().getPackage().getRepositoryMapping(),
- windowsPath);
+ windowsPath,
+ ruleContext.getWorkspaceName());
}
@Override
@@ -107,7 +111,7 @@ private String lookupFunctionImpl(String name, String param) throws ExpansionExc
try {
LocationFunction f = functions.get(name);
if (f != null) {
- return f.apply(param, repositoryMapping);
+ return f.apply(param, repositoryMapping, workspaceRunfilesDirectory);
}
} catch (IllegalStateException e) {
throw new ExpansionException(e.getMessage(), e);
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
index 1e5e6312b2b2bd..537276102df374 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
@@ -17,6 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Root;
@@ -121,6 +122,12 @@ public void otherPathExpansion() throws Exception {
"genrule(name='foo', outs=['foo.txt'], cmd='never executed')",
"sh_library(name='lib', srcs=[':foo'])");
+ FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"), "workspace(name='workspace')");
+ // Invalidate WORKSPACE to pick up the name.
+ getSkyframeExecutor()
+ .invalidateFilesUnderPathForTesting(
+ reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
+
LocationExpander expander = makeExpander("//expansion:lib");
assertThat(expander.expand("foo $(execpath :foo) bar"))
.matches("foo .*-out/.*/expansion/foo\\.txt bar");
@@ -130,6 +137,22 @@ public void otherPathExpansion() throws Exception {
.matches("foo expansion/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
}
@Test
@@ -158,6 +181,10 @@ public void otherPathExternalExpansion() throws Exception {
.matches("foo external/r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar"))
.matches("foo external/r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -183,6 +210,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfiles() throws Exceptio
.matches("foo .*-out/.*/external/r/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -210,6 +241,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfilesSiblingRepositoryL
.matches("foo .*-out/r/.*/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -224,5 +259,9 @@ public void otherPathMultiExpansion() throws Exception {
.matches("foo .*-out/.*/expansion/bar\\.txt .*-out/.*/expansion/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/bar.txt expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo(
+ "foo __main__/expansion/bar.txt __main__/expansion/foo.txt bar"
+ .replace("__main__", TestConstants.WORKSPACE_NAME));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
index fdf64e68b9be3c..78885e0e9f49f0 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
@@ -59,22 +59,25 @@ public boolean hasErrors() {
}
private LocationExpander makeExpander(RuleErrorConsumer ruleErrorConsumer) throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("//a", "/exec/src/a")
- .build();
-
- LocationFunction f2 = new LocationFunctionBuilder("//b", true)
- .setExecPaths(false)
- .add("//b", "/exec/src/b")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//a", "/exec/src/a")
+ .build();
+
+ LocationFunction f2 =
+ new LocationFunctionBuilder("//b", true)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//b", "/exec/src/b")
+ .build();
return new LocationExpander(
ruleErrorConsumer,
ImmutableMap.<String, LocationFunction>of(
"location", f1,
"locations", f2),
- RepositoryMapping.ALWAYS_FALLBACK);
+ RepositoryMapping.ALWAYS_FALLBACK,
+ "workspace");
}
private String expand(String input) throws Exception {
@@ -125,10 +128,11 @@ public void noExpansionOnError() throws Exception {
@Test
public void expansionWithRepositoryMapping() throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("@bar//a", "/exec/src/a")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("@bar//a", "/exec/src/a")
+ .build();
ImmutableMap<RepositoryName, RepositoryName> repositoryMapping = ImmutableMap.of(
RepositoryName.create("@foo"),
@@ -138,7 +142,8 @@ public void expansionWithRepositoryMapping() throws Exception {
new LocationExpander(
new Capture(),
ImmutableMap.<String, LocationFunction>of("location", f1),
- RepositoryMapping.createAllowingFallback(repositoryMapping));
+ RepositoryMapping.createAllowingFallback(repositoryMapping),
+ "workspace");
String value = locationExpander.expand("$(location @foo//a)");
assertThat(value).isEqualTo("src/a");
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
index c333ad7473398e..3d7fde1e3d6a0a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
@@ -48,16 +48,16 @@ public class LocationFunctionTest {
public void absoluteAndRelativeLabels() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/src/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
}
@Test
public void pathUnderExecRootUsesDotSlash() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("./bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("./bar");
}
@Test
@@ -66,7 +66,7 @@ public void noSuchLabel() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -80,7 +80,7 @@ public void emptyList() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo("label '//foo:foo' in $(location) expression expands to no files");
@@ -93,7 +93,7 @@ public void tooMany() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -108,7 +108,7 @@ public void noSuchLabelMultiple() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -120,7 +120,7 @@ public void noSuchLabelMultiple() throws Exception {
public void fileWithSpace() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/file/with space").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space'");
}
@@ -129,7 +129,7 @@ public void multipleFiles() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/foo/bar", "/exec/out/foo/foobar")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("foo/bar foo/foobar");
}
@@ -138,20 +138,32 @@ public void filesWithSpace() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/file/with space", "/exec/file/with spaces ")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space' 'file/with spaces '");
}
@Test
public void execPath() throws Exception {
- LocationFunction func = new LocationFunctionBuilder("//foo", true)
- .setExecPaths(true)
- .add("//foo", "/exec/bar", "/exec/out/foobar")
- .build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.EXEC)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("./bar out/foobar");
}
+ @Test
+ public void rlocationPath() throws Exception {
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.RLOCATION)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, "workspace"))
+ .isEqualTo("workspace/bar workspace/foobar");
+ }
+
@Test
public void locationFunctionWithMappingReplace() throws Exception {
RepositoryName a = RepositoryName.create("@a");
@@ -159,7 +171,9 @@ public void locationFunctionWithMappingReplace() throws Exception {
ImmutableMap<RepositoryName, RepositoryName> repositoryMapping = ImmutableMap.of(a, b);
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@b//foo", "/exec/src/bar").build();
- assertThat(func.apply("@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ assertThat(
+ func.apply(
+ "@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
@@ -171,7 +185,8 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@potato//foo", "/exec/src/bar").build();
assertThat(
- func.apply("@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ func.apply(
+ "@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
}
@@ -179,7 +194,7 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
final class LocationFunctionBuilder {
private final Label root;
private final boolean multiple;
- private boolean execPaths;
+ private LocationFunction.PathType pathType = LocationFunction.PathType.LOCATION;
private boolean legacyExternalRunfiles;
private final Map<Label, Collection<Artifact>> labelMap = new HashMap<>();
@@ -190,11 +205,11 @@ final class LocationFunctionBuilder {
public LocationFunction build() {
return new LocationFunction(
- root, Suppliers.ofInstance(labelMap), execPaths, legacyExternalRunfiles, multiple);
+ root, Suppliers.ofInstance(labelMap), pathType, legacyExternalRunfiles, multiple);
}
- public LocationFunctionBuilder setExecPaths(boolean execPaths) {
- this.execPaths = execPaths;
+ public LocationFunctionBuilder setPathType(LocationFunction.PathType pathType) {
+ this.pathType = pathType;
return this;
}
diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index 30196366aea9b9..b5edeed445c01e 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -313,6 +313,41 @@ def testLegacyExternalRunfilesOption(self):
"host/bin/bin.runfiles_manifest")
self.AssertFileContentNotContains(manifest_path, "__main__/external/A")
+ def testRunfilesLibrariesFindRlocationpathExpansion(self):
+ self.ScratchDir("A")
+ self.ScratchFile("A/WORKSPACE")
+ self.ScratchFile("A/p/BUILD", ["exports_files(['foo.txt'])"])
+ self.ScratchFile("A/p/foo.txt", ["Hello, World!"])
+ self.ScratchFile("WORKSPACE", ["local_repository(name = 'A', path='A')"])
+ self.ScratchFile("pkg/BUILD", [
+ "py_binary(",
+ " name = 'bin',",
+ " srcs = ['bin.py'],",
+ " args = [",
+ " '$(rlocationpath bar.txt)',",
+ " '$(rlocationpath @A//p:foo.txt)',",
+ " ],",
+ " data = [",
+ " 'bar.txt',",
+ " '@A//p:foo.txt'",
+ " ],",
+ " deps = ['@bazel_tools//tools/python/runfiles'],",
+ ")",
+ ])
+ self.ScratchFile("pkg/bar.txt", ["Hello, Bazel!"])
+ self.ScratchFile("pkg/bin.py", [
+ "import sys",
+ "from tools.python.runfiles import runfiles",
+ "r = runfiles.Create()",
+ "for arg in sys.argv[1:]:",
+ " print(open(r.Rlocation(arg)).read().strip())",
+ ])
+ _, stdout, _ = self.RunBazel(["run", "//pkg:bin"])
+ if len(stdout) != 2:
+ self.fail("stdout: %s" % stdout)
+ self.assertEqual(stdout[0], "Hello, Bazel!")
+ self.assertEqual(stdout[1], "Hello, World!")
+
if __name__ == "__main__":
unittest.main()
| val | val | 2022-11-07T15:39:53 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/10923_16668 | bazelbuild/bazel | bazelbuild/bazel/10923 | bazelbuild/bazel/16668 | [
"keyword_pr_to_issue"
] | 8c80ef8c95dfd68f0ddd28ee56e7cc805f7b479c | ece17d5d4e74d67dd869cbd1951ca1001423b472 | [
"As a workaround I wrote the following repository rule:\r\n```python\r\ndef _define_repository_name_impl(repository_ctx):\r\n repository_ctx.file(\"BUILD.bazel\",\r\n \"\"\"package(default_visibility = [\"//visibility:public\"])\r\n \"\"\")\r\n repository_ctx.file(\"defs.bzl\",\r\n \"\"\"main_repository_name=\"{}\"\r\n \"\"\".format(repository_ctx.attr.repo_name))\r\n\r\n_define_repository_name = repository_rule(\r\n implementation = _define_repository_name_impl,\r\n attrs={\"repo_name\": attr.string(mandatory=True)}\r\n )\r\n\r\ndef define_repository_name(repo_name):\r\n _define_repository_name(name = \"main_repository_name\",repo_name = repo_name)\r\n\r\n```\r\n\r\nwhich allows me to load the main repository name by calling:\r\n```python\r\nload(\"@main_repository_name//:defs.bzl\",\"main_repository_name\")\r\n```\r\n\r\nThe `WORKSPACE` file looks like this:\r\n```python\r\nrepository_name = \"xxx\"\r\nworkspace(name = repository_name)\r\n\r\nload(\"@bazel_tooling//rules:define_repository_name.bzl\",\"define_repository_name\")\r\ndefine_repository_name(repository_name)\r\n```\r\n\r\nI don't like it... given that `workspace()` call should be the first line of the WORKSPACE file. But it works (`bazel 2.1.0`)",
"hey @laurentlb ... May I ask for your opinion on this matter? :-)",
"@or-shachar I have the same issue, did you ever find a resolution to this?",
"@or-shachar @jheaff1 Could you describe in more detail what you want to use the name declared in the `WORKSPACE` file for in a macro? Knowing more about the actual problem you are trying to solve would help me answer these questions.",
"You most likely want just \"@\" instead. With the recent fixes on repo mapping, \"@workspace_name//:foo\" is equivalent to \"@//:foo\".\r\n\r\n(Unless you're doing exec path or runfiles shenanigans, in which case refer to @fmeum's comment.)",
"@fmeum I am trying to write a sh_binary target for the rules_foreign_cc repo that wraps around an executable binary (built by rules_foreign_cc) with shared library dependencies. This would allow such a binary to be used as a build tool, eg the protobuf compiler or various generators part of the Qt framework.\r\n\r\nI would like to use the `rlocation` bash function provided here:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/a76cf2f4c3aa514dffa1ddc038c196103ae4583c/tools/bash/runfiles/runfiles.bash#L68\r\n\r\nThe `rlocation` bash function requires the workspace name, which I would like to obtain programatically in a macro.\r\n\r\nI’ve tried to use native.repository_name() but that returns `@` rather than the name of the repository.\r\n\r\n",
"@jheaff1 Would an analogue of `$(location //foo)` that returns the correct path for `rlocation` help you realize this? I could see that being more user-friendly than yet another \"some type of name of a repo\" thing.",
"@fmeum Absolutely that would be very useful. Ive found that using `$(rootpath` rather than `$(location` provides exactly what `$(rlocation` requires apart from the workspace name.",
"@lberki I have been thinking about proposing a `$(location ...)` variant that returns the correct path for Rlocation for a while. The way runfiles work with Bzlmod would almost make this a requirement for location expansion to remain useful in `args`. What do you think?",
"@fmeum without taking sides on the `$(location) question, it's a feature orthogonal to the one proposed in this bug.\r\n\r\nre: this bug in particular, what is the argument *against* introducing `repository_name()`? Naively, one would think that it's a very logical extension to `package_name()`. @Wyverald maybe you can think of a counter-argument?",
"> this bug in particular, what is the argument against introducing repository_name()? Naively, one would think that it's a very logical extension to package_name(). @Wyverald maybe you can think of a counter-argument?\r\n\r\nWe already have `native.repository_name` and it does what it says on the tin (https://bazel.build/rules/lib/native#repository_name). @fmeum's & @jheaff1's question is more about the runfiles/execpath use case, where we sometimes need the *workspace name*, which is only accessible right now in a rule ctx object (https://bazel.build/rules/lib/ctx#workspace_name; also to note, *not* the same as [Label.workspace_name](https://bazel.build/rules/lib/Label#workspace_name)...)",
"@Wyverald I'm embarrassed! I specifically looked for the identifier called `repository_name` and didn't find it in the source code. My bad.",
"The issue with making the (global) workspace name available in Starlark code is that then the evaluation of BUILD files in external repositories would be a function of the content of the main repository, which isn't too intuitive (it's problematic enough for `ctx.workspace_name()`, but we can't help that because that's how runfiles work at the moment.",
"@lberki That plus the fact that having yet another `workspace_name` would be confusing made me think that being able to get Rlocation paths out of location expansion may indeed be the best solution to this issue (see also the comment by @jheaff1). Since `native.repository_name` returns the right identifier for everything *except* runfiles discovery, why not add a way for users to get the full runfiles path right away without having them stitch it together themselves?",
"The reason why I was confused is that for some reason, I thought `$(rlocation)` is already a thing in Bazel so I went on a wild goose chase trying to figure out what *else* you want :)\r\n\r\nI think both adding `$(rlocation)` and the same method to File is reasonable. @Wyverald , it looks like you also agree? ",
"@lberki `$(rlocation)` seems reasonably easy to do, but `File.rlocation_path` is difficult: Without `--experimental_sibling_repository_layout`, that function needs to know the workspace name. I'm not sure how the API for that would look like, should we just let the user pass in `ctx`?",
"Not necessarily; there is `BazelStarlarkContext`, which is available to the Java implementations of Starlark functions without an extra argument and it, weirdly, already contains the repository name of the tools repository. So I could imagine plumbing the workspace name in there that way, too. Rule implementations need to know the name of the main workspace anyway, so it would probably not require too much extra plumbing.",
"@lberki I will give that a try. We will have to make a concession though: Using `StarlarkThread` is incompatible with `structField = True`, so this will have to be a function instead.",
"Today I Learned. It seems to be an artificial choice and not an inherent limitation of how Starlark works, though, and I don't see an immediate reason for this limitation. @c-parsons , do you remember why you prohibited setting `useStarlarkThread` and `structField` to true at the same time in 73e1016 ?"
] | [] | "2022-11-04T22:20:01Z" | [
"type: feature request",
"P3",
"team-ExternalDeps"
] | Get the name of current repository from macro | ### Description of the problem / feature request:
I am trying to get the name of the current repository from a macro.
```
.
├── a
│ ├── BUILD.bazel
│ ├── WORKSPACE
│ ├── empty.txt
│ └── txt_files.bzl
└── b
├── BUILD.bazel
├── WORKSPACE
└── empty2.txt
```
_(see full example [here](https://github.com/or-shachar/bazel_repository_name_issue) )_
I want that if repo `b` will call the macro in `@a//:txt_files.bzl` then somehow I'd be able to retrieve that it was called from repo `b`.
Right now (not sure if it's a bug or work as intended) - calling `native.repository_name()` will return `@` and not the name of repo as declared in its `WORKSPACE` file.
### Feature requests: what underlying problem are you trying to solve with this feature?
I want to change the behavior of a macro based on the callee repository.
Can we allow `native.repository_name()` to return the explicit name of the repository and not `@`? To maintain backward compatibility - I assume it would be better if we add a flag to this method that will be turned off by default.
| [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm",
"src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java",
"src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java",
"src/test/py/bazel/runfiles_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
index 96f3cfacacb19b..b5dc2f88b9dae1 100644
--- a/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
+++ b/src/main/java/com/google/devtools/build/docgen/templates/be/make-variables.vm
@@ -262,15 +262,15 @@ title: Make Variables
</p>
<p>
Output files are staged similarly, but are also prefixed with the subpath
- <code>bazel-out/cpu-compilation_mode/bin</code> (or for certain outputs:
- <code>bazel-out/cpu-compilation_mode/genfiles</code>, or for the outputs
- of host tools: <code>bazel-out/host/bin</code>). In the above example,
- <code>//testapp:app</code> is a host tool because it appears in
+ <code>bazel-out/cpu-compilation_mode/bin</code> (or for the outputs of
+ tools: <code>bazel-out/cpu-opt-exec-hash/bin</code>). In the above example,
+ <code>//testapp:app</code> is a tool because it appears in
<code>show_app_output</code>'s <code><a
href="$expander.expandRef("genrule.tools")">tools</a></code> attribute.
So its output file <code>app</code> is written to
- <code>bazel-myproject/bazel-out/host/bin/testapp/app</code>. The exec path
- is thus <code>bazel-out/host/bin/testapp/app</code>. This extra prefix
+ <code>bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>.
+ The exec path is thus <code>
+ bazel-out/cpu-opt-exec-hash/bin/testapp/app</code>. This extra prefix
makes it possible to build the same target for, say, two different CPUs in
the same build without the results clobbering each other.
</p>
@@ -284,15 +284,57 @@ title: Make Variables
<li>
<p>
- <code>rootpath</code>: Denotes the runfiles path that a built binary can
- use to find its dependencies at runtime.
- </p>
+ <code>rootpath</code>: Denotes the path that a built binary can use to
+ find a dependency at runtime relative to the subdirectory of its runfiles
+ directory corresponding to the main repository.
+ <strong>Note:</strong> This only works if <a
+ href="/reference/command-line-reference#flag--enable_runfiles">
+ <code>--enable_runfiles</code></a> is enabled, which is not the case on
+ Windows by default. Use <code>rlocationpath</code> instead for
+ cross-platform support.
<p>
- This is the same as <code>execpath</code> but strips the output prefixes
- described above. In the above example this means both
+ This is similar to <code>execpath</code> but strips the configuration
+ prefixes described above. In the example from above this means both
<code>empty.source</code> and <code>app</code> use pure workspace-relative
paths: <code>testapp/empty.source</code> and <code>testapp/app</code>.
</p>
+ <p>
+ The <code>rootpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>../repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ This has the same "one output only" requirements as <code>execpath</code>.
+ </p>
+ </li>
+
+ <li>
+ <p>
+ <code>rlocationpath</code>: The path a built binary can pass to the <code>
+ Rlocation</code> function of a runfiles library to find a dependency at
+ runtime, either in the runfiles directory (if available) or using the
+ runfiles manifest.
+ </p>
+ <p>
+ This is similar to <code>rootpath</code> in that it does not contain
+ configuration prefixes, but differs in that it always starts with the
+ name of the repository. In the example from above this means that <code>
+ empty.source</code> and <code>app</code> result in the following
+ paths: <code>myproject/testapp/empty.source</code> and <code>
+ myproject/testapp/app</code>.
+ </p>
+ <p>
+ The <code>rlocationpath</code> of a file in an external repository
+ <code>repo</code> will start with <code>repo/</code>, followed by the
+ repository-relative path.
+ </p>
+ <p>
+ 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 <code>rootpath</code>, it has the advantage that it
+ works on all platforms and even if the runfiles directory is not
+ available.
+ </p>
<p>
This has the same "one output only" requirements as <code>execpath</code>.
</p>
@@ -303,24 +345,25 @@ title: Make Variables
<code>rootpath</code>, depending on the attribute being expanded. This is
legacy pre-Starlark behavior and not recommended unless you really know what
it does for a particular rule. See <a
- href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
+ href="https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016">#2475</a>
for details.
</li>
</ul>
<p>
- <code>execpaths</code>, <code>rootpaths</code>, and <code>locations</code> are
- the plural variations of <code>execpath</code>, <code>rootpath</code>, and
- <code>location</code>, respectively. They support labels producing multiple
- outputs, in which case each output is listed separated by a space. Zero-output
- rules and malformed labels produce build errors.
+ <code>execpaths</code>, <code>rootpaths</code>, <code>rlocationpaths</code>,
+ and <code>locations</code> are the plural variations of <code>execpath</code>,
+ <code>rootpath</code>, <code>rlocationpaths</code>, and<code>location</code>,
+ respectively. They support labels producing multiple outputs, in which case
+ each output is listed separated by a space. Zero-output rules and malformed
+ labels produce build errors.
</p>
<p>
All referenced labels must appear in the consuming target's <code>srcs</code>,
output files, or <code>deps</code>. Otherwise the build fails. C++ targets can
also reference labels in <code><a
- href="$expander.expandRef("cc_binary.data")">data</a></code>.
+ href="$expander.expandRef("cc_binary.data")">data</a></code>.
</p>
<p>
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
index f8f5b7885e384e..3323927e89691e 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationExpander.java
@@ -17,6 +17,7 @@
import static java.util.stream.Collectors.joining;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableCollection;
@@ -26,7 +27,9 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Artifact;
+import com.google.devtools.build.lib.analysis.LocationExpander.LocationFunction.PathType;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.packages.BuildType;
@@ -63,34 +66,35 @@ public final class LocationExpander {
private static final boolean EXACTLY_ONE = false;
private static final boolean ALLOW_MULTIPLE = true;
- private static final boolean USE_LOCATION_PATHS = false;
- private static final boolean USE_EXEC_PATHS = true;
-
private final RuleErrorConsumer ruleErrorConsumer;
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
+ private final String workspaceRunfilesDirectory;
@VisibleForTesting
LocationExpander(
RuleErrorConsumer ruleErrorConsumer,
Map<String, LocationFunction> functions,
- RepositoryMapping repositoryMapping) {
+ RepositoryMapping repositoryMapping,
+ String workspaceRunfilesDirectory) {
this.ruleErrorConsumer = ruleErrorConsumer;
this.functions = ImmutableMap.copyOf(functions);
this.repositoryMapping = repositoryMapping;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
private LocationExpander(
- RuleErrorConsumer ruleErrorConsumer,
+ RuleContext ruleContext,
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMap,
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping) {
this(
- ruleErrorConsumer,
+ ruleContext,
allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles),
- repositoryMapping);
+ repositoryMapping,
+ ruleContext.getWorkspaceName());
}
/**
@@ -215,7 +219,10 @@ private String expand(String value, ErrorReporter reporter) {
// (2) Call appropriate function to obtain string replacement.
String functionValue = value.substring(nextWhitespace + 1, end).trim();
try {
- String replacement = functions.get(fname).apply(functionValue, repositoryMapping);
+ String replacement =
+ functions
+ .get(fname)
+ .apply(functionValue, repositoryMapping, workspaceRunfilesDirectory);
result.append(replacement);
} catch (IllegalStateException ise) {
reporter.report(ise.getMessage());
@@ -230,23 +237,29 @@ private String expand(String value, ErrorReporter reporter) {
@VisibleForTesting
static final class LocationFunction {
+ enum PathType {
+ LOCATION,
+ EXEC,
+ RLOCATION,
+ }
+
private static final int MAX_PATHS_SHOWN = 5;
private final Label root;
private final Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier;
- private final boolean execPaths;
+ private final PathType pathType;
private final boolean legacyExternalRunfiles;
private final boolean multiple;
LocationFunction(
Label root,
Supplier<Map<Label, Collection<Artifact>>> locationMapSupplier,
- boolean execPaths,
+ PathType pathType,
boolean legacyExternalRunfiles,
boolean multiple) {
this.root = root;
this.locationMapSupplier = locationMapSupplier;
- this.execPaths = execPaths;
+ this.pathType = Preconditions.checkNotNull(pathType);
this.legacyExternalRunfiles = legacyExternalRunfiles;
this.multiple = multiple;
}
@@ -257,10 +270,13 @@ static final class LocationFunction {
* using the {@code repositoryMapping}.
*
* @param arg The label-like string to be expanded, e.g. ":foo" or "//foo:bar"
- * @param repositoryMapping map of {@code RepositoryName}s defined in the main workspace
+ * @param repositoryMapping map of apparent repository names to {@code RepositoryName}s
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return The expanded value
*/
- public String apply(String arg, RepositoryMapping repositoryMapping) {
+ public String apply(
+ String arg, RepositoryMapping repositoryMapping, String workspaceRunfilesDirectory) {
Label label;
try {
label = root.getRelativeWithRemapping(arg, repositoryMapping);
@@ -269,14 +285,13 @@ public String apply(String arg, RepositoryMapping repositoryMapping) {
String.format(
"invalid label in %s expression: %s", functionName(), e.getMessage()), e);
}
- Collection<String> paths = resolveLabel(label);
+ Set<String> paths = resolveLabel(label, workspaceRunfilesDirectory);
return joinPaths(paths);
}
- /**
- * Returns all target location(s) of the given label.
- */
- private Collection<String> resolveLabel(Label unresolved) throws IllegalStateException {
+ /** Returns all target location(s) of the given label. */
+ private Set<String> resolveLabel(Label unresolved, String workspaceRunfilesDirectory)
+ throws IllegalStateException {
Collection<Artifact> artifacts = locationMapSupplier.get().get(unresolved);
if (artifacts == null) {
@@ -286,7 +301,7 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
unresolved, functionName()));
}
- Set<String> paths = getPaths(artifacts);
+ Set<String> paths = getPaths(artifacts, workspaceRunfilesDirectory);
if (paths.isEmpty()) {
throw new IllegalStateException(
String.format(
@@ -311,24 +326,41 @@ private Collection<String> resolveLabel(Label unresolved) throws IllegalStateExc
* Extracts list of all executables associated with given collection of label artifacts.
*
* @param artifacts to get the paths of
+ * @param workspaceRunfilesDirectory name of the runfiles directory corresponding to the main
+ * repository
* @return all associated executable paths
*/
- private Set<String> getPaths(Collection<Artifact> artifacts) {
+ private Set<String> getPaths(
+ Collection<Artifact> artifacts, String workspaceRunfilesDirectory) {
TreeSet<String> paths = Sets.newTreeSet();
for (Artifact artifact : artifacts) {
- PathFragment execPath =
- execPaths
- ? artifact.getExecPath()
- : legacyExternalRunfiles
- ? artifact.getPathForLocationExpansion()
- : artifact.getRunfilesPath();
- if (execPath != null) { // omit middlemen etc
- paths.add(execPath.getCallablePathString());
+ PathFragment path = getPath(artifact, workspaceRunfilesDirectory);
+ if (path != null) { // omit middlemen etc
+ paths.add(path.getCallablePathString());
}
}
return paths;
}
+ private PathFragment getPath(Artifact artifact, String workspaceRunfilesDirectory) {
+ switch (pathType) {
+ case LOCATION:
+ return legacyExternalRunfiles
+ ? artifact.getPathForLocationExpansion()
+ : artifact.getRunfilesPath();
+ case EXEC:
+ return artifact.getExecPath();
+ case RLOCATION:
+ PathFragment runfilesPath = artifact.getRunfilesPath();
+ if (runfilesPath.startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX)) {
+ return runfilesPath.relativeTo(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
+ } else {
+ return PathFragment.create(workspaceRunfilesDirectory).getRelative(runfilesPath);
+ }
+ }
+ throw new IllegalStateException("Unexpected PathType: " + pathType);
+ }
+
private String joinPaths(Collection<String> paths) {
return paths.stream().map(ShellEscaper::escapeString).collect(joining(" "));
}
@@ -346,27 +378,44 @@ static ImmutableMap<String, LocationFunction> allLocationFunctions(
return new ImmutableMap.Builder<String, LocationFunction>()
.put(
"location",
- new LocationFunction(root, locationMap, execPaths, legacyExternalRunfiles, EXACTLY_ONE))
+ new LocationFunction(
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ EXACTLY_ONE))
.put(
"locations",
new LocationFunction(
- root, locationMap, execPaths, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root,
+ locationMap,
+ execPaths ? PathType.EXEC : PathType.LOCATION,
+ legacyExternalRunfiles,
+ ALLOW_MULTIPLE))
.put(
"rootpath",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"rootpaths",
new LocationFunction(
- root, locationMap, USE_LOCATION_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.LOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.put(
"execpath",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, EXACTLY_ONE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, EXACTLY_ONE))
.put(
"execpaths",
new LocationFunction(
- root, locationMap, USE_EXEC_PATHS, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ root, locationMap, PathType.EXEC, legacyExternalRunfiles, ALLOW_MULTIPLE))
+ .put(
+ "rlocationpath",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, EXACTLY_ONE))
+ .put(
+ "rlocationpaths",
+ new LocationFunction(
+ root, locationMap, PathType.RLOCATION, legacyExternalRunfiles, ALLOW_MULTIPLE))
.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
index 22d0097eb0133c..0abe2bf58575dd 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/LocationTemplateContext.java
@@ -50,6 +50,7 @@ final class LocationTemplateContext implements TemplateContext {
private final ImmutableMap<String, LocationFunction> functions;
private final RepositoryMapping repositoryMapping;
private final boolean windowsPath;
+ private final String workspaceRunfilesDirectory;
private LocationTemplateContext(
TemplateContext delegate,
@@ -58,12 +59,14 @@ private LocationTemplateContext(
boolean execPaths,
boolean legacyExternalRunfiles,
RepositoryMapping repositoryMapping,
- boolean windowsPath) {
+ boolean windowsPath,
+ String workspaceRunfilesDirectory) {
this.delegate = delegate;
this.functions =
LocationExpander.allLocationFunctions(root, locationMap, execPaths, legacyExternalRunfiles);
this.repositoryMapping = repositoryMapping;
this.windowsPath = windowsPath;
+ this.workspaceRunfilesDirectory = workspaceRunfilesDirectory;
}
public LocationTemplateContext(
@@ -82,7 +85,8 @@ public LocationTemplateContext(
execPaths,
ruleContext.getConfiguration().legacyExternalRunfiles(),
ruleContext.getRule().getPackage().getRepositoryMapping(),
- windowsPath);
+ windowsPath,
+ ruleContext.getWorkspaceName());
}
@Override
@@ -107,7 +111,7 @@ private String lookupFunctionImpl(String name, String param) throws ExpansionExc
try {
LocationFunction f = functions.get(name);
if (f != null) {
- return f.apply(param, repositoryMapping);
+ return f.apply(param, repositoryMapping, workspaceRunfilesDirectory);
}
} catch (IllegalStateException e) {
throw new ExpansionException(e.getMessage(), e);
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
index 1e5e6312b2b2bd..537276102df374 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderIntegrationTest.java
@@ -17,6 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Root;
@@ -121,6 +122,12 @@ public void otherPathExpansion() throws Exception {
"genrule(name='foo', outs=['foo.txt'], cmd='never executed')",
"sh_library(name='lib', srcs=[':foo'])");
+ FileSystemUtils.appendIsoLatin1(scratch.resolve("WORKSPACE"), "workspace(name='workspace')");
+ // Invalidate WORKSPACE to pick up the name.
+ getSkyframeExecutor()
+ .invalidateFilesUnderPathForTesting(
+ reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
+
LocationExpander expander = makeExpander("//expansion:lib");
assertThat(expander.expand("foo $(execpath :foo) bar"))
.matches("foo .*-out/.*/expansion/foo\\.txt bar");
@@ -130,6 +137,22 @@ public void otherPathExpansion() throws Exception {
.matches("foo expansion/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths //expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @workspace//expansion:foo) bar"))
+ .isEqualTo("foo workspace/expansion/foo.txt bar");
}
@Test
@@ -158,6 +181,10 @@ public void otherPathExternalExpansion() throws Exception {
.matches("foo external/r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar"))
.matches("foo external/r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -183,6 +210,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfiles() throws Exceptio
.matches("foo .*-out/.*/external/r/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -210,6 +241,10 @@ public void otherPathExternalExpansionNoLegacyExternalRunfilesSiblingRepositoryL
.matches("foo .*-out/r/.*/p/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpath @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
assertThat(expander.expand("foo $(rootpaths @r//p:foo) bar")).matches("foo ../r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpath @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths @r//p:foo) bar"))
+ .isEqualTo("foo r/p/foo.txt bar");
}
@Test
@@ -224,5 +259,9 @@ public void otherPathMultiExpansion() throws Exception {
.matches("foo .*-out/.*/expansion/bar\\.txt .*-out/.*/expansion/foo\\.txt bar");
assertThat(expander.expand("foo $(rootpaths :foo) bar"))
.matches("foo expansion/bar.txt expansion/foo.txt bar");
+ assertThat(expander.expand("foo $(rlocationpaths :foo) bar"))
+ .isEqualTo(
+ "foo __main__/expansion/bar.txt __main__/expansion/foo.txt bar"
+ .replace("__main__", TestConstants.WORKSPACE_NAME));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
index fdf64e68b9be3c..78885e0e9f49f0 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationExpanderTest.java
@@ -59,22 +59,25 @@ public boolean hasErrors() {
}
private LocationExpander makeExpander(RuleErrorConsumer ruleErrorConsumer) throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("//a", "/exec/src/a")
- .build();
-
- LocationFunction f2 = new LocationFunctionBuilder("//b", true)
- .setExecPaths(false)
- .add("//b", "/exec/src/b")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//a", "/exec/src/a")
+ .build();
+
+ LocationFunction f2 =
+ new LocationFunctionBuilder("//b", true)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("//b", "/exec/src/b")
+ .build();
return new LocationExpander(
ruleErrorConsumer,
ImmutableMap.<String, LocationFunction>of(
"location", f1,
"locations", f2),
- RepositoryMapping.ALWAYS_FALLBACK);
+ RepositoryMapping.ALWAYS_FALLBACK,
+ "workspace");
}
private String expand(String input) throws Exception {
@@ -125,10 +128,11 @@ public void noExpansionOnError() throws Exception {
@Test
public void expansionWithRepositoryMapping() throws Exception {
- LocationFunction f1 = new LocationFunctionBuilder("//a", false)
- .setExecPaths(false)
- .add("@bar//a", "/exec/src/a")
- .build();
+ LocationFunction f1 =
+ new LocationFunctionBuilder("//a", false)
+ .setPathType(LocationFunction.PathType.LOCATION)
+ .add("@bar//a", "/exec/src/a")
+ .build();
ImmutableMap<RepositoryName, RepositoryName> repositoryMapping = ImmutableMap.of(
RepositoryName.create("@foo"),
@@ -138,7 +142,8 @@ public void expansionWithRepositoryMapping() throws Exception {
new LocationExpander(
new Capture(),
ImmutableMap.<String, LocationFunction>of("location", f1),
- RepositoryMapping.createAllowingFallback(repositoryMapping));
+ RepositoryMapping.createAllowingFallback(repositoryMapping),
+ "workspace");
String value = locationExpander.expand("$(location @foo//a)");
assertThat(value).isEqualTo("src/a");
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
index c333ad7473398e..3d7fde1e3d6a0a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LocationFunctionTest.java
@@ -48,16 +48,16 @@ public class LocationFunctionTest {
public void absoluteAndRelativeLabels() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/src/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
- assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("src/bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply(":foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
+ assertThat(func.apply("foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("src/bar");
}
@Test
public void pathUnderExecRootUsesDotSlash() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/bar").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK)).isEqualTo("./bar");
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null)).isEqualTo("./bar");
}
@Test
@@ -66,7 +66,7 @@ public void noSuchLabel() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -80,7 +80,7 @@ public void emptyList() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo("label '//foo:foo' in $(location) expression expands to no files");
@@ -93,7 +93,7 @@ public void tooMany() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -108,7 +108,7 @@ public void noSuchLabelMultiple() throws Exception {
IllegalStateException expected =
assertThrows(
IllegalStateException.class,
- () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK));
+ () -> func.apply("//bar", RepositoryMapping.ALWAYS_FALLBACK, null));
assertThat(expected)
.hasMessageThat()
.isEqualTo(
@@ -120,7 +120,7 @@ public void noSuchLabelMultiple() throws Exception {
public void fileWithSpace() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("//foo", "/exec/file/with space").build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space'");
}
@@ -129,7 +129,7 @@ public void multipleFiles() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/foo/bar", "/exec/out/foo/foobar")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("foo/bar foo/foobar");
}
@@ -138,20 +138,32 @@ public void filesWithSpace() throws Exception {
LocationFunction func = new LocationFunctionBuilder("//foo", true)
.add("//foo", "/exec/file/with space", "/exec/file/with spaces ")
.build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("'file/with space' 'file/with spaces '");
}
@Test
public void execPath() throws Exception {
- LocationFunction func = new LocationFunctionBuilder("//foo", true)
- .setExecPaths(true)
- .add("//foo", "/exec/bar", "/exec/out/foobar")
- .build();
- assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK))
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.EXEC)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, null))
.isEqualTo("./bar out/foobar");
}
+ @Test
+ public void rlocationPath() throws Exception {
+ LocationFunction func =
+ new LocationFunctionBuilder("//foo", true)
+ .setPathType(LocationFunction.PathType.RLOCATION)
+ .add("//foo", "/exec/bar", "/exec/out/foobar")
+ .build();
+ assertThat(func.apply("//foo", RepositoryMapping.ALWAYS_FALLBACK, "workspace"))
+ .isEqualTo("workspace/bar workspace/foobar");
+ }
+
@Test
public void locationFunctionWithMappingReplace() throws Exception {
RepositoryName a = RepositoryName.create("@a");
@@ -159,7 +171,9 @@ public void locationFunctionWithMappingReplace() throws Exception {
ImmutableMap<RepositoryName, RepositoryName> repositoryMapping = ImmutableMap.of(a, b);
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@b//foo", "/exec/src/bar").build();
- assertThat(func.apply("@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ assertThat(
+ func.apply(
+ "@a//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
@@ -171,7 +185,8 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
LocationFunction func =
new LocationFunctionBuilder("//foo", false).add("@potato//foo", "/exec/src/bar").build();
assertThat(
- func.apply("@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping)))
+ func.apply(
+ "@potato//foo", RepositoryMapping.createAllowingFallback(repositoryMapping), null))
.isEqualTo("src/bar");
}
}
@@ -179,7 +194,7 @@ public void locationFunctionWithMappingIgnoreRepo() throws Exception {
final class LocationFunctionBuilder {
private final Label root;
private final boolean multiple;
- private boolean execPaths;
+ private LocationFunction.PathType pathType = LocationFunction.PathType.LOCATION;
private boolean legacyExternalRunfiles;
private final Map<Label, Collection<Artifact>> labelMap = new HashMap<>();
@@ -190,11 +205,11 @@ final class LocationFunctionBuilder {
public LocationFunction build() {
return new LocationFunction(
- root, Suppliers.ofInstance(labelMap), execPaths, legacyExternalRunfiles, multiple);
+ root, Suppliers.ofInstance(labelMap), pathType, legacyExternalRunfiles, multiple);
}
- public LocationFunctionBuilder setExecPaths(boolean execPaths) {
- this.execPaths = execPaths;
+ public LocationFunctionBuilder setPathType(LocationFunction.PathType pathType) {
+ this.pathType = pathType;
return this;
}
diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index 30196366aea9b9..b5edeed445c01e 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -313,6 +313,41 @@ def testLegacyExternalRunfilesOption(self):
"host/bin/bin.runfiles_manifest")
self.AssertFileContentNotContains(manifest_path, "__main__/external/A")
+ def testRunfilesLibrariesFindRlocationpathExpansion(self):
+ self.ScratchDir("A")
+ self.ScratchFile("A/WORKSPACE")
+ self.ScratchFile("A/p/BUILD", ["exports_files(['foo.txt'])"])
+ self.ScratchFile("A/p/foo.txt", ["Hello, World!"])
+ self.ScratchFile("WORKSPACE", ["local_repository(name = 'A', path='A')"])
+ self.ScratchFile("pkg/BUILD", [
+ "py_binary(",
+ " name = 'bin',",
+ " srcs = ['bin.py'],",
+ " args = [",
+ " '$(rlocationpath bar.txt)',",
+ " '$(rlocationpath @A//p:foo.txt)',",
+ " ],",
+ " data = [",
+ " 'bar.txt',",
+ " '@A//p:foo.txt'",
+ " ],",
+ " deps = ['@bazel_tools//tools/python/runfiles'],",
+ ")",
+ ])
+ self.ScratchFile("pkg/bar.txt", ["Hello, Bazel!"])
+ self.ScratchFile("pkg/bin.py", [
+ "import sys",
+ "from tools.python.runfiles import runfiles",
+ "r = runfiles.Create()",
+ "for arg in sys.argv[1:]:",
+ " print(open(r.Rlocation(arg)).read().strip())",
+ ])
+ _, stdout, _ = self.RunBazel(["run", "//pkg:bin"])
+ if len(stdout) != 2:
+ self.fail("stdout: %s" % stdout)
+ self.assertEqual(stdout[0], "Hello, Bazel!")
+ self.assertEqual(stdout[1], "Hello, World!")
+
if __name__ == "__main__":
unittest.main()
| train | val | 2022-11-07T15:39:53 | "2020-03-08T11:43:50Z" | or-shachar | test |
bazelbuild/bazel/16124_16675 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16675 | [
"keyword_pr_to_issue"
] | 72e6e948d30dec9dec60d78efef4eeda5b764a8f | 3dd01cbd44205c9157819ac77304354d08b8964a | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-07T16:53:43Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"tools/cpp/runfiles/runfiles_src.cc",
"tools/cpp/runfiles/runfiles_src.h",
"tools/cpp/runfiles/runfiles_test.cc"
] | [
"tools/cpp/runfiles/runfiles_src.cc",
"tools/cpp/runfiles/runfiles_src.h",
"tools/cpp/runfiles/runfiles_test.cc"
] | [] | diff --git a/tools/cpp/runfiles/runfiles_src.cc b/tools/cpp/runfiles/runfiles_src.cc
index 2d3078065b5f78..f35dd969949f4a 100644
--- a/tools/cpp/runfiles/runfiles_src.cc
+++ b/tools/cpp/runfiles/runfiles_src.cc
@@ -96,25 +96,30 @@ bool IsDirectory(const string& path) {
bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
std::string runfiles_dir, std::string* out_manifest,
- std::string* out_directory);
+ std::string* out_directory, std::string* out_repo_mapping);
bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
std::string runfiles_dir,
std::function<bool(const std::string&)> is_runfiles_manifest,
std::function<bool(const std::string&)> is_runfiles_directory,
- std::string* out_manifest, std::string* out_directory);
+ std::function<bool(const std::string&)> is_repo_mapping,
+ std::string* out_manifest, std::string* out_directory,
+ std::string* out_repo_mapping);
bool ParseManifest(const string& path, map<string, string>* result,
string* error);
+bool ParseRepoMapping(const string& path,
+ map<pair<string, string>, string>* result, string* error);
} // namespace
Runfiles* Runfiles::Create(const string& argv0,
const string& runfiles_manifest_file,
- const string& runfiles_dir, string* error) {
- string manifest, directory;
+ const string& runfiles_dir,
+ const string& source_repository, string* error) {
+ string manifest, directory, repo_mapping;
if (!PathsFrom(argv0, runfiles_manifest_file, runfiles_dir, &manifest,
- &directory)) {
+ &directory, &repo_mapping)) {
if (error) {
std::ostringstream err;
err << "ERROR: " << __FILE__ << "(" << __LINE__
@@ -124,7 +129,7 @@ Runfiles* Runfiles::Create(const string& argv0,
return nullptr;
}
- const vector<pair<string, string> > envvars = {
+ vector<pair<string, string> > envvars = {
{"RUNFILES_MANIFEST_FILE", manifest},
{"RUNFILES_DIR", directory},
// TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can
@@ -138,8 +143,16 @@ Runfiles* Runfiles::Create(const string& argv0,
}
}
+ map<pair<string, string>, string> mapping;
+ if (!repo_mapping.empty()) {
+ if (!ParseRepoMapping(repo_mapping, &mapping, error)) {
+ return nullptr;
+ }
+ }
+
return new Runfiles(std::move(runfiles), std::move(directory),
- std::move(envvars));
+ std::move(mapping), std::move(envvars),
+ string(source_repository));
}
bool IsAbsolute(const string& path) {
@@ -169,6 +182,11 @@ string GetEnv(const string& key) {
}
string Runfiles::Rlocation(const string& path) const {
+ return Rlocation(path, source_repository_);
+}
+
+string Runfiles::Rlocation(const string& path,
+ const string& source_repo) const {
if (path.empty() || starts_with(path, "../") || contains(path, "/..") ||
starts_with(path, "./") || contains(path, "/./") ||
ends_with(path, "/.") || contains(path, "//")) {
@@ -177,6 +195,24 @@ string Runfiles::Rlocation(const string& path) const {
if (IsAbsolute(path)) {
return path;
}
+
+ if (repo_mapping_.empty()) {
+ return RlocationUnchecked(path);
+ }
+ string::size_type first_slash = path.find_first_of('/');
+ if (first_slash == string::npos) {
+ return RlocationUnchecked(path);
+ }
+ string target_apparent = path.substr(0, first_slash);
+ auto target =
+ repo_mapping_.find(std::make_pair(source_repo, target_apparent));
+ if (target == repo_mapping_.cend()) {
+ return RlocationUnchecked(path);
+ }
+ return RlocationUnchecked(target->second + path.substr(first_slash));
+}
+
+string Runfiles::RlocationUnchecked(const string& path) const {
const auto exact_match = runfiles_map_.find(path);
if (exact_match != runfiles_map_.end()) {
return exact_match->second;
@@ -238,6 +274,58 @@ bool ParseManifest(const string& path, map<string, string>* result,
return true;
}
+bool ParseRepoMapping(const string& path,
+ map<pair<string, string>, string>* result,
+ string* error) {
+ std::ifstream stm(path);
+ if (!stm.is_open()) {
+ if (error) {
+ std::ostringstream err;
+ err << "ERROR: " << __FILE__ << "(" << __LINE__
+ << "): cannot open repository mapping \"" << path << "\"";
+ *error = err.str();
+ }
+ return false;
+ }
+ string line;
+ std::getline(stm, line);
+ size_t line_count = 1;
+ while (!line.empty()) {
+ string::size_type first_comma = line.find_first_of(',');
+ if (first_comma == string::npos) {
+ if (error) {
+ std::ostringstream err;
+ err << "ERROR: " << __FILE__ << "(" << __LINE__
+ << "): bad repository mapping entry in \"" << path << "\" line #"
+ << line_count << ": \"" << line << "\"";
+ *error = err.str();
+ }
+ return false;
+ }
+ string::size_type second_comma = line.find_first_of(',', first_comma + 1);
+ if (second_comma == string::npos) {
+ if (error) {
+ std::ostringstream err;
+ err << "ERROR: " << __FILE__ << "(" << __LINE__
+ << "): bad repository mapping entry in \"" << path << "\" line #"
+ << line_count << ": \"" << line << "\"";
+ *error = err.str();
+ }
+ return false;
+ }
+
+ string source = line.substr(0, first_comma);
+ string target_apparent =
+ line.substr(first_comma + 1, second_comma - (first_comma + 1));
+ string target = line.substr(second_comma + 1);
+
+ (*result)[std::make_pair(source, target_apparent)] = target;
+ std::getline(stm, line);
+ ++line_count;
+ }
+ return true;
+}
+
} // namespace
namespace testing {
@@ -245,41 +333,66 @@ namespace testing {
bool TestOnly_PathsFrom(const string& argv0, string mf, string dir,
function<bool(const string&)> is_runfiles_manifest,
function<bool(const string&)> is_runfiles_directory,
- string* out_manifest, string* out_directory) {
+ function<bool(const string&)> is_repo_mapping,
+ string* out_manifest, string* out_directory,
+ string* out_repo_mapping) {
return PathsFrom(argv0, mf, dir, is_runfiles_manifest, is_runfiles_directory,
- out_manifest, out_directory);
+ is_repo_mapping, out_manifest, out_directory,
+ out_repo_mapping);
}
bool TestOnly_IsAbsolute(const string& path) { return IsAbsolute(path); }
} // namespace testing
-Runfiles* Runfiles::Create(const string& argv0, string* error) {
+Runfiles* Runfiles::Create(const std::string& argv0,
+ const std::string& runfiles_manifest_file,
+ const std::string& runfiles_dir,
+ std::string* error) {
+ return Runfiles::Create(argv0, runfiles_manifest_file, runfiles_dir, "",
+ error);
+}
+
+Runfiles* Runfiles::Create(const string& argv0, const string& source_repository,
+ string* error) {
return Runfiles::Create(argv0, GetEnv("RUNFILES_MANIFEST_FILE"),
- GetEnv("RUNFILES_DIR"), error);
+ GetEnv("RUNFILES_DIR"), source_repository, error);
}
-Runfiles* Runfiles::CreateForTest(std::string* error) {
+Runfiles* Runfiles::Create(const string& argv0, string* error) {
+ return Runfiles::Create(argv0, "", error);
+}
+
+Runfiles* Runfiles::CreateForTest(const string& source_repository,
+ std::string* error) {
return Runfiles::Create(std::string(), GetEnv("RUNFILES_MANIFEST_FILE"),
- GetEnv("TEST_SRCDIR"), error);
+ GetEnv("TEST_SRCDIR"), source_repository, error);
+}
+
+Runfiles* Runfiles::CreateForTest(std::string* error) {
+ return Runfiles::CreateForTest("", error);
}
namespace {
bool PathsFrom(const string& argv0, string mf, string dir, string* out_manifest,
- string* out_directory) {
- return PathsFrom(argv0, mf, dir,
- [](const string& path) { return IsReadableFile(path); },
- [](const string& path) { return IsDirectory(path); },
- out_manifest, out_directory);
+ string* out_directory, string* out_repo_mapping) {
+ return PathsFrom(
+ argv0, mf, dir, [](const string& path) { return IsReadableFile(path); },
+ [](const string& path) { return IsDirectory(path); },
+ [](const string& path) { return IsReadableFile(path); }, out_manifest,
+ out_directory, out_repo_mapping);
}
bool PathsFrom(const string& argv0, string mf, string dir,
function<bool(const string&)> is_runfiles_manifest,
function<bool(const string&)> is_runfiles_directory,
- string* out_manifest, string* out_directory) {
+ function<bool(const string&)> is_repo_mapping,
+ string* out_manifest, string* out_directory,
+ string* out_repo_mapping) {
out_manifest->clear();
out_directory->clear();
+ out_repo_mapping->clear();
bool mfValid = is_runfiles_manifest(mf);
bool dirValid = is_runfiles_directory(dir);
@@ -315,6 +428,21 @@ bool PathsFrom(const string& argv0, string mf, string dir,
dirValid = is_runfiles_directory(dir);
}
+ string rm;
+ bool rmValid = false;
+
+ if (dirValid && ends_with(dir, ".runfiles")) {
+ rm = dir.substr(0, dir.size() - 9) + ".repo_mapping";
+ rmValid = is_repo_mapping(rm);
+ }
+
+ if (!rmValid && mfValid &&
+ (ends_with(mf, ".runfiles_manifest") ||
+ ends_with(mf, ".runfiles/MANIFEST"))) {
+ rm = mf.substr(0, mf.size() - 18) + ".repo_mapping";
+ rmValid = is_repo_mapping(rm);
+ }
+
if (mfValid) {
*out_manifest = mf;
}
@@ -323,6 +451,10 @@ bool PathsFrom(const string& argv0, string mf, string dir,
*out_directory = dir;
}
+ if (rmValid) {
+ *out_repo_mapping = rm;
+ }
+
return true;
}
diff --git a/tools/cpp/runfiles/runfiles_src.h b/tools/cpp/runfiles/runfiles_src.h
index 0929b4594fee82..6e0a0c2f203556 100644
--- a/tools/cpp/runfiles/runfiles_src.h
+++ b/tools/cpp/runfiles/runfiles_src.h
@@ -34,12 +34,11 @@
// int main(int argc, char** argv) {
// std::string error;
// std::unique_ptr<Runfiles> runfiles(
-// Runfiles::Create(argv[0], &error));
+// Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY, &error));
//
// // Important:
-// // If this is a test, use Runfiles::CreateForTest(&error).
-// // Otherwise, if you don't have the value for argv[0] for whatever
-// // reason, then use Runfiles::Create(&error).
+// // If this is a test, use
+// // Runfiles::CreateForTest(BAZEL_CURRENT_REPOSITORY, &error).
//
// if (runfiles == nullptr) {
// ... // error handling
@@ -58,7 +57,8 @@
// To start child processes that also need runfiles, you need to set the right
// environment variables for them:
//
-// std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
+// std::unique_ptr<Runfiles> runfiles(Runfiles::Create(
+// argv[0], BAZEL_CURRENT_REPOSITORY, &error));
//
// std::string path = runfiles->Rlocation("path/to/binary"));
// if (!path.empty()) {
@@ -102,7 +102,12 @@ class Runfiles {
//
// This method looks at the RUNFILES_MANIFEST_FILE and TEST_SRCDIR
// environment variables.
+ //
+ // If source_repository is not provided, it defaults to the main repository
+ // (also known as the workspace).
static Runfiles* CreateForTest(std::string* error = nullptr);
+ static Runfiles* CreateForTest(const std::string& source_repository,
+ std::string* error = nullptr);
// Returns a new `Runfiles` instance.
//
@@ -116,7 +121,13 @@ class Runfiles {
// environment variables. If either is empty, the method looks for the
// manifest or directory using the other environment variable, or using argv0
// (unless it's empty).
+ //
+ // If source_repository is not provided, it defaults to the main repository
+ // (also known as the workspace).
+ static Runfiles* Create(const std::string& argv0,
+ std::string* error = nullptr);
static Runfiles* Create(const std::string& argv0,
+ const std::string& source_repository,
std::string* error = nullptr);
// Returns a new `Runfiles` instance.
@@ -133,6 +144,11 @@ class Runfiles {
const std::string& runfiles_manifest_file,
const std::string& runfiles_dir,
std::string* error = nullptr);
+ static Runfiles* Create(const std::string& argv0,
+ const std::string& runfiles_manifest_file,
+ const std::string& runfiles_dir,
+ const std::string& source_repository,
+ std::string* error = nullptr);
// Returns the runtime path of a runfile.
//
@@ -146,10 +162,14 @@ class Runfiles {
// Args:
// path: runfiles-root-relative path of the runfile; must not be empty and
// must not contain uplevel references.
+ // source_repository: if provided, overrides the source repository set when
+ // this Runfiles instance was created.
// Returns:
// the path to the runfile, which the caller should check for existence, or
// an empty string if the method doesn't know about this runfile
std::string Rlocation(const std::string& path) const;
+ std::string Rlocation(const std::string& path,
+ const std::string& source_repository) const;
// Returns environment variables for subprocesses.
//
@@ -160,13 +180,27 @@ class Runfiles {
return envvars_;
}
+ // Returns a new Runfiles instance that by default uses the provided source
+ // repository as a default for all calls to Rlocation.
+ //
+ // The current instance remains valid.
+ std::unique_ptr<Runfiles> WithSourceRepository(
+ const std::string& source_repository) const {
+ return std::unique_ptr<Runfiles>(new Runfiles(
+ runfiles_map_, directory_, repo_mapping_, envvars_, source_repository));
+ }
+
private:
- Runfiles(const std::map<std::string, std::string>&& runfiles_map,
- const std::string&& directory,
- const std::vector<std::pair<std::string, std::string> >&& envvars)
+ Runfiles(
+ std::map<std::string, std::string> runfiles_map, std::string directory,
+ std::map<std::pair<std::string, std::string>, std::string> repo_mapping,
+ std::vector<std::pair<std::string, std::string> > envvars,
+ std::string source_repository_)
: runfiles_map_(std::move(runfiles_map)),
directory_(std::move(directory)),
- envvars_(std::move(envvars)) {}
+ repo_mapping_(std::move(repo_mapping)),
+ envvars_(std::move(envvars)),
+ source_repository_(std::move(source_repository_)) {}
Runfiles(const Runfiles&) = delete;
Runfiles(Runfiles&&) = delete;
Runfiles& operator=(const Runfiles&) = delete;
@@ -174,7 +208,12 @@ class Runfiles {
const std::map<std::string, std::string> runfiles_map_;
const std::string directory_;
+ const std::map<std::pair<std::string, std::string>, std::string>
+ repo_mapping_;
const std::vector<std::pair<std::string, std::string> > envvars_;
+ const std::string source_repository_;
+
+ std::string RlocationUnchecked(const std::string& path) const;
};
// The "testing" namespace contains functions that allow unit testing the code.
@@ -204,7 +243,9 @@ bool TestOnly_PathsFrom(
std::string runfiles_dir,
std::function<bool(const std::string&)> is_runfiles_manifest,
std::function<bool(const std::string&)> is_runfiles_directory,
- std::string* out_manifest, std::string* out_directory);
+ std::function<bool(const std::string&)> is_repo_mapping,
+ std::string* out_manifest, std::string* out_directory,
+ std::string* out_repo_mapping);
// For testing only.
// Returns true if `path` is an absolute Unix or Windows path.
diff --git a/tools/cpp/runfiles/runfiles_test.cc b/tools/cpp/runfiles/runfiles_test.cc
index cbe2952c1904cd..771510112ad28d 100644
--- a/tools/cpp/runfiles/runfiles_test.cc
+++ b/tools/cpp/runfiles/runfiles_test.cc
@@ -488,96 +488,395 @@ TEST_F(RunfilesTest, IsAbsolute) {
}
TEST_F(RunfilesTest, PathsFromEnvVars) {
- string mf, dir;
+ string mf, dir, rm;
// Both envvars have a valid value.
EXPECT_TRUE(TestOnly_PathsFrom(
- "argv0", "mock1/MANIFEST", "mock2",
- [](const string& path) { return path == "mock1/MANIFEST"; },
- [](const string& path) { return path == "mock2"; }, &mf, &dir));
- EXPECT_EQ(mf, "mock1/MANIFEST");
- EXPECT_EQ(dir, "mock2");
+ "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
+ [](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
+ [](const string& path) { return path == "mock2.runfiles"; },
+ [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
+ &dir, &rm));
+ EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
+ EXPECT_EQ(dir, "mock2.runfiles");
+ EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good and there's a
// runfiles manifest in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
- "argv0", "mock1/MANIFEST", "mock2",
- [](const string& path) { return path == "mock2/MANIFEST"; },
- [](const string& path) { return path == "mock2"; }, &mf, &dir));
- EXPECT_EQ(mf, "mock2/MANIFEST");
- EXPECT_EQ(dir, "mock2");
+ "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
+ [](const string& path) { return path == "mock2.runfiles/MANIFEST"; },
+ [](const string& path) { return path == "mock2.runfiles"; },
+ [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
+ &dir, &rm));
+ EXPECT_EQ(mf, "mock2.runfiles/MANIFEST");
+ EXPECT_EQ(dir, "mock2.runfiles");
+ EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good, but there's no
// runfiles manifest in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
- "argv0", "mock1/MANIFEST", "mock2",
+ "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
[](const string& path) { return false; },
- [](const string& path) { return path == "mock2"; }, &mf, &dir));
+ [](const string& path) { return path == "mock2.runfiles"; },
+ [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "");
- EXPECT_EQ(dir, "mock2");
+ EXPECT_EQ(dir, "mock2.runfiles");
+ EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, and it is in
// a valid-looking runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
- "argv0", "mock1/MANIFEST", "mock2",
- [](const string& path) { return path == "mock1/MANIFEST"; },
- [](const string& path) { return path == "mock1"; }, &mf, &dir));
- EXPECT_EQ(mf, "mock1/MANIFEST");
- EXPECT_EQ(dir, "mock1");
+ "argv0", "mock1.runfiles/MANIFEST", "mock2",
+ [](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
+ [](const string& path) { return path == "mock1.runfiles"; },
+ [](const string& path) { return path == "mock1.repo_mapping"; }, &mf,
+ &dir, &rm));
+ EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
+ EXPECT_EQ(dir, "mock1.runfiles");
+ EXPECT_EQ(rm, "mock1.repo_mapping");
// RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, but it is not
// in any valid-looking runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "mock1/MANIFEST"; },
- [](const string& path) { return false; }, &mf, &dir));
+ [](const string& path) { return false; },
+ [](const string& path) { return true; }, &mf, &dir, &rm));
EXPECT_EQ(mf, "mock1/MANIFEST");
EXPECT_EQ(dir, "");
+ EXPECT_EQ(rm, "");
// Both envvars are invalid, but there's a manifest in a runfiles directory
// next to argv0, however there's no other content in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
- [](const string& path) { return false; }, &mf, &dir));
+ [](const string& path) { return false; },
+ [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
EXPECT_EQ(dir, "");
+ EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a manifest next to argv0. There's
// no runfiles tree anywhere.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles_manifest"; },
- [](const string& path) { return false; }, &mf, &dir));
+ [](const string& path) { return false; },
+ [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "argv0.runfiles_manifest");
EXPECT_EQ(dir, "");
+ EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid manifest next to argv0, and a
// valid runfiles directory (without a manifest in it).
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles_manifest"; },
- [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
+ [](const string& path) { return path == "argv0.runfiles"; },
+ [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "argv0.runfiles_manifest");
EXPECT_EQ(dir, "argv0.runfiles");
+ EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid runfiles directory next to
// argv0, though no manifest in it.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return false; },
- [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
+ [](const string& path) { return path == "argv0.runfiles"; },
+ [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "");
EXPECT_EQ(dir, "argv0.runfiles");
+ EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid runfiles directory next to
// argv0 with a valid manifest in it.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
- [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
+ [](const string& path) { return path == "argv0.runfiles"; },
+ [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
+ &dir, &rm));
EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
EXPECT_EQ(dir, "argv0.runfiles");
+ EXPECT_EQ(rm, "argv0.repo_mapping");
+}
+
+TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromMain) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> mf(MockFile::Create(
+ "foo" + uid + ".runfiles_manifest",
+ {"config.json /etc/config.json",
+ "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
+ "_main/bar/runfile /the/path/./to/other//other runfile.txt",
+ "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
+ EXPECT_TRUE(mf != nullptr);
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(mf->Path().substr(
+ 0, mf->Path().size() - string(".runfiles_manifest").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
+ ASSERT_NE(r, nullptr);
+ EXPECT_TRUE(error.empty());
+
+ EXPECT_EQ(r->Rlocation("my_module/bar/runfile"),
+ "/the/path/./to/other//other runfile.txt");
+ EXPECT_EQ(r->Rlocation("my_workspace/bar/runfile"),
+ "/the/path/./to/other//other runfile.txt");
+ EXPECT_EQ(r->Rlocation("my_protobuf/foo/runfile"),
+ "C:/Actual Path\\protobuf\\runfile");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir"), "E:\\Actual Path\\Directory");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/file"),
+ "E:\\Actual Path\\Directory/file");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"),
+ "E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("protobuf/foo/runfile"), "");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir"), "");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/file"), "");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le"), "");
+
+ EXPECT_EQ(r->Rlocation("_main/bar/runfile"),
+ "/the/path/./to/other//other runfile.txt");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/foo/runfile"),
+ "C:/Actual Path\\protobuf\\runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir"),
+ "E:\\Actual Path\\Directory");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/file"),
+ "E:\\Actual Path\\Directory/file");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"),
+ "E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("config.json"), "/etc/config.json");
+ EXPECT_EQ(r->Rlocation("_main"), "");
+ EXPECT_EQ(r->Rlocation("my_module"), "");
+ EXPECT_EQ(r->Rlocation("protobuf"), "");
+}
+
+TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromOtherRepo) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> mf(MockFile::Create(
+ "foo" + uid + ".runfiles_manifest",
+ {"config.json /etc/config.json",
+ "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
+ "_main/bar/runfile /the/path/./to/other//other runfile.txt",
+ "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
+ EXPECT_TRUE(mf != nullptr);
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(mf->Path().substr(
+ 0, mf->Path().size() - string(".runfiles_manifest").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(
+ Runfiles::Create(argv0, "", "", "protobuf~3.19.2", &error));
+ ASSERT_NE(r, nullptr);
+ EXPECT_TRUE(error.empty());
+
+ EXPECT_EQ(r->Rlocation("protobuf/foo/runfile"),
+ "C:/Actual Path\\protobuf\\runfile");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir"), "E:\\Actual Path\\Directory");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/file"),
+ "E:\\Actual Path\\Directory/file");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/de eply/nes ted/fi~le"),
+ "E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("my_module/bar/runfile"), "");
+ EXPECT_EQ(r->Rlocation("my_protobuf/foo/runfile"), "");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir"), "");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/file"), "");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"), "");
+
+ EXPECT_EQ(r->Rlocation("_main/bar/runfile"),
+ "/the/path/./to/other//other runfile.txt");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/foo/runfile"),
+ "C:/Actual Path\\protobuf\\runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir"),
+ "E:\\Actual Path\\Directory");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/file"),
+ "E:\\Actual Path\\Directory/file");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"),
+ "E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("config.json"), "/etc/config.json");
+ EXPECT_EQ(r->Rlocation("_main"), "");
+ EXPECT_EQ(r->Rlocation("my_module"), "");
+ EXPECT_EQ(r->Rlocation("protobuf"), "");
+}
+
+TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromMain) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> dir_marker(
+ MockFile::Create("foo" + uid + ".runfiles/marker"), {});
+ EXPECT_TRUE(dir_marker != nullptr);
+ string dir = dir_marker->DirName();
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(
+ rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
+ ASSERT_NE(r, nullptr);
+ EXPECT_TRUE(error.empty());
+
+ EXPECT_EQ(r->Rlocation("my_module/bar/runfile"), dir + "/_main/bar/runfile");
+ EXPECT_EQ(r->Rlocation("my_workspace/bar/runfile"),
+ dir + "/_main/bar/runfile");
+ EXPECT_EQ(r->Rlocation("my_protobuf/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir"),
+ dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("protobuf/foo/runfile"),
+ dir + "/protobuf/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf/bar/dir/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("_main/bar/runfile"), dir + "/_main/bar/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir"),
+ dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("config.json"), dir + "/config.json");
+}
+
+TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromOtherRepo) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> dir_marker(
+ MockFile::Create("foo" + uid + ".runfiles/marker"), {});
+ EXPECT_TRUE(dir_marker != nullptr);
+ string dir = dir_marker->DirName();
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(
+ rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(
+ Runfiles::Create(argv0, "", "", "protobuf~3.19.2", &error));
+ ASSERT_NE(r, nullptr);
+ EXPECT_TRUE(error.empty());
+
+ EXPECT_EQ(r->Rlocation("protobuf/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir"), dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("my_module/bar/runfile"),
+ dir + "/my_module/bar/runfile");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/my_protobuf/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("_main/bar/runfile"), dir + "/_main/bar/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir"),
+ dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("config.json"), dir + "/config.json");
+}
+
+TEST_F(RunfilesTest,
+ DirectoryBasedRlocationWithRepoMapping_fromOtherRepo_withSourceRepo) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> dir_marker(
+ MockFile::Create("foo" + uid + ".runfiles/marker"), {});
+ EXPECT_TRUE(dir_marker != nullptr);
+ string dir = dir_marker->DirName();
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(
+ rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
+ r = r->WithSourceRepository("protobuf~3.19.2");
+ ASSERT_NE(r, nullptr);
+ EXPECT_TRUE(error.empty());
+
+ EXPECT_EQ(r->Rlocation("protobuf/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir"), dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("protobuf/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("my_module/bar/runfile"),
+ dir + "/my_module/bar/runfile");
+ EXPECT_EQ(r->Rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/my_protobuf/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("_main/bar/runfile"), dir + "/_main/bar/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/foo/runfile"),
+ dir + "/protobuf~3.19.2/foo/runfile");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir"),
+ dir + "/protobuf~3.19.2/bar/dir");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/file"),
+ dir + "/protobuf~3.19.2/bar/dir/file");
+ EXPECT_EQ(r->Rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"),
+ dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ EXPECT_EQ(r->Rlocation("config.json"), dir + "/config.json");
+}
+
+TEST_F(RunfilesTest, InvalidRepoMapping) {
+ string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> dir_marker(
+ MockFile::Create("foo" + uid + ".runfiles/marker"), {});
+ EXPECT_TRUE(dir_marker != nullptr);
+ string dir = dir_marker->DirName();
+ unique_ptr<MockFile> rm(
+ MockFile::Create("foo" + uid + ".repo_mapping", {"a,b"}));
+ EXPECT_TRUE(rm != nullptr);
+ string argv0(
+ rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+
+ string error;
+ unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
+ ASSERT_EQ(r, nullptr);
+ EXPECT_TRUE(error.find("bad repository mapping") != string::npos);
}
} // namespace
| null | train | val | 2022-11-04T20:06:24 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/15043_16680 | bazelbuild/bazel | bazelbuild/bazel/15043 | bazelbuild/bazel/16680 | [
"keyword_pr_to_issue"
] | 3dd01cbd44205c9157819ac77304354d08b8964a | 7cc786ab51dacc7e2eade2ab9c2b440bf9d29972 | [
"I think that the root cause is a more fundamental inconsistency between how Starlark and native rules collect and declare data dependencies:\r\n\r\nAs per the [Starlark rules guidelines](https://docs.bazel.build/versions/main/skylark/rules.html#runfiles-features-to-avoid), Starlark rules should handle targets in `data`-like attributes by merging in both the files produced by these targets as well as their default runfiles. As a result, Starlark rules often return some files in their `DefaultInfo`'s `files` attribute that are not also contained in its `runfiles`.\r\n\r\nHowever, native rules only collect transitive runfiles and not the output files from rule targets (see [addTargetIncludingFileTargets](https://github.com/bazelbuild/bazel/blob/4c56447fe18e31098ac14a80e2a98253de9c190d/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java#L931), which only adds output files for file targets). \r\n\r\n@linzhp Could you check whether https://github.com/bazelbuild/bazel/pull/15052 fixes the issue? It adapts the native logic to collect runfiles in the same way as is recommended for Starlark rules, but of course that may very well regress performance for native rules in general. I do not know whether changing this behavior that is so fundamental to Bazel's native rules is realistically possible. But if it doesn't fail too many tests, maybe there is a way to restrict it to Starlark rule targets or otherwise limit its impact on native rule targets.\r\n",
"Sorry for the delay. I pull from #15052, and built `//src:bazel-dev`. But when I used the built binary to build `//docs:update` of rules_docker, I got:\r\n\r\n```\r\nDEBUG: /private/var/tmp/_bazel_zplin/d6323f9e3146540840037c805ccd73ff/external/bazel_toolchains/rules/rbe_repo/version_check.bzl:59:14: \r\nCurrent running Bazel is not a release version and one was not defined explicitly in rbe_autoconfig target. Falling back to '4.0.0'\r\nERROR: /private/var/tmp/_bazel_zplin/d6323f9e3146540840037c805ccd73ff/external/bazel_tools/src/tools/launcher/BUILD:9:14: While resolving toolchains for target @bazel_tools//src/tools/launcher:launcher: No matching toolchains found for types @bazel_tools//tools/cpp:toolchain_type. Maybe --incompatible_use_cc_configure_from_rules_cc has been flipped and there is no default C++ toolchain added in the WORKSPACE file? See https://github.com/bazelbuild/bazel/issues/10134 for details and migration instructions.\r\nERROR: Analysis of target '//docs:update' failed; build aborted: \r\nINFO: Elapsed time: 6.538s\r\nINFO: 0 processes.\r\nFAILED: Build did NOT complete successfully (50 packages loaded, 309 targets configured)\r\n```",
"@linzhp The build succeeds for me following the instructions from your initial post. Are you on Linux and does `bazel build //...` succeed for you on the repo on the commit prior to mine? The change may cause building new transitive dependencies for `//docs:update`, but if those weren't broken before, they shouldn't be now. The result of rerunning the command with `--toolchain_resolution_debug='.*'` would also be useful to figure out what broke.",
"Switched to macOS for Intel and tried your fix again. It worked. Thanks!\r\n\r\nI was on macOS for Apple Silicon before. The commit before yours fails too, but Bazel 5.0.0 works. I saw:\r\n\r\n```\r\nINFO: ToolchainResolution: Type @bazel_tools//tools/cpp:toolchain_type: target platform @local_config_platform//:host: Rejected toolchain @local_config_cc//:cc-compiler-darwin_arm64; mismatching values: arm64\r\n```\r\n",
"That looks more like an unrelated regression. Could you create a separate issue and perhaps rerun the test with 5.1.0rc2? 5.1.0 will be released soon.",
"Is this bug a dup (though more clearly restating the issue) of https://github.com/bazelbuild/bazel/issues/12348 ?",
"> Is this bug a dup (though more clearly restating the issue) of https://github.com/bazelbuild/bazel/issues/12348 ?\n\nPretty sure it is.",
"Dupping against #12348.",
"Sorry, I missed that #15052 is being actively developed, so I'll keep this issue alive as the author's preferred tracking bug.",
"As an FYI, there may be some dependencies on this behavior between the Python rules and some other Google-internal rules. i.e. enabling the flag introduced by this will likely show failures in the Google global regression tests (TGP). See the large comment block in blaze/python/common.bzl#collect_runfiles for more details. The gist, though, is some Google-internal rules have different default outputs vs data/default runfiles, and have come to rely on this so that otherwise unused outputs (some of which can be very large) don't get included in the runfiles.",
"@rickeylev Thanks for mentioning this. I added a workaround to the migration guide at https://github.com/bazelbuild/bazel/issues/16654. Could that even work for Google?"
] | [] | "2022-11-07T17:58:08Z" | [
"type: bug",
"P3",
"team-Rules-Server"
] | sh_binary's data dependencies are not triggered during the build | <!--
ATTENTION! Please read and follow:
- if this is a _question_ about how to build / test / query / deploy using Bazel, or a _discussion starter_, send it to [email protected]
- if this is a _bug_ or _feature request_, fill the form below as best as you can.
-->
### Description of the problem / feature request:
When a `sh_binary` has a target in the `data` attribute, the target is not built automatically when the `sh_binary` target is built.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
* Check out [rules_docker](https://github.com/bazelbuild/rules_docker/tree/0b1a033eff28eeff474573c7ed2d5b9d9bec4af1)
* `bazel clean`
* `bazel build //docs:update`
* `ls bazel-bin/docs/container.md_`
Although `bazel-bin/docs/container.md_` is the output of `//docs:container_doc`, which is depended by `//docs:update`, it is not built.
### What operating system are you running Bazel on?
macOS
### What's the output of `bazel info release`?
release 5.0.0-homebrew
| [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java",
"src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java",
"src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java",
"src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java",
"src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/test/TestSuite.java",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
index 9d8b10955fa52d..d9933d60b19561 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
@@ -935,7 +935,10 @@ public Builder add(
/** Collects runfiles from data dependencies of a target. */
@CanIgnoreReturnValue
public Builder addDataDeps(RuleContext ruleContext) {
- addTargets(getPrerequisites(ruleContext, "data"), RunfilesProvider.DATA_RUNFILES);
+ addTargets(
+ getPrerequisites(ruleContext, "data"),
+ RunfilesProvider.DATA_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
return this;
}
@@ -952,16 +955,20 @@ public Builder addNonDataDeps(
@CanIgnoreReturnValue
public Builder addTargets(
Iterable<? extends TransitiveInfoCollection> targets,
- Function<TransitiveInfoCollection, Runfiles> mapping) {
+ Function<TransitiveInfoCollection, Runfiles> mapping,
+ boolean alwaysIncludeFilesToBuildInData) {
for (TransitiveInfoCollection target : targets) {
- addTarget(target, mapping);
+ addTarget(target, mapping, alwaysIncludeFilesToBuildInData);
}
return this;
}
- public Builder addTarget(TransitiveInfoCollection target,
- Function<TransitiveInfoCollection, Runfiles> mapping) {
- return addTargetIncludingFileTargets(target, mapping);
+ @CanIgnoreReturnValue
+ public Builder addTarget(
+ TransitiveInfoCollection target,
+ Function<TransitiveInfoCollection, Runfiles> mapping,
+ boolean alwaysIncludeFilesToBuildInData) {
+ return addTargetIncludingFileTargets(target, mapping, alwaysIncludeFilesToBuildInData);
}
@CanIgnoreReturnValue
@@ -975,8 +982,10 @@ private Builder addTargetExceptFileTargets(
return this;
}
- private Builder addTargetIncludingFileTargets(TransitiveInfoCollection target,
- Function<TransitiveInfoCollection, Runfiles> mapping) {
+ private Builder addTargetIncludingFileTargets(
+ TransitiveInfoCollection target,
+ Function<TransitiveInfoCollection, Runfiles> mapping,
+ boolean alwaysIncludeFilesToBuildInData) {
if (target.getProvider(RunfilesProvider.class) == null
&& mapping == RunfilesProvider.DATA_RUNFILES) {
// RuleConfiguredTarget implements RunfilesProvider, so this will only be called on
@@ -988,6 +997,17 @@ private Builder addTargetIncludingFileTargets(TransitiveInfoCollection target,
return this;
}
+ if (alwaysIncludeFilesToBuildInData && mapping == RunfilesProvider.DATA_RUNFILES) {
+ // Ensure that `DefaultInfo.files` of Starlark rules is merged in so that native rules
+ // interoperate well with idiomatic Starlark rules..
+ // https://bazel.build/extending/rules#runfiles_features_to_avoid
+ // Internal tests fail if the order of filesToBuild is preserved.
+ addTransitiveArtifacts(
+ NestedSetBuilder.<Artifact>stableOrder()
+ .addTransitive(target.getProvider(FileProvider.class).getFilesToBuild())
+ .build());
+ }
+
return addTargetExceptFileTargets(target, mapping);
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
index 9a59733973261b..19597cc44c23d8 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
@@ -636,6 +636,13 @@ public boolean legacyExternalRunfiles() {
return options.legacyExternalRunfiles;
}
+ /**
+ * Returns true if Runfiles should merge in FilesToBuild from deps when collecting data runfiles.
+ */
+ public boolean alwaysIncludeFilesToBuildInData() {
+ return options.alwaysIncludeFilesToBuildInData;
+ }
+
/**
* Returns user-specified test environment variables and their values, as set by the --test_env
* options.
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java b/src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java
index f4f83bb319ff78..a7fbb8be55f51a 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/CoreOptions.java
@@ -433,6 +433,18 @@ public ExecConfigurationDistinguisherSchemeConverter() {
+ ".runfiles/wsname/external/repo (in addition to .runfiles/repo).")
public boolean legacyExternalRunfiles;
+ @Option(
+ name = "incompatible_always_include_files_in_data",
+ defaultValue = "false",
+ documentationCategory = OptionDocumentationCategory.OUTPUT_SELECTION,
+ effectTags = {OptionEffectTag.AFFECTS_OUTPUTS},
+ metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
+ help =
+ "If true, native rules add <code>DefaultInfo.files</code> of data dependencies to "
+ + "their runfiles, which matches the recommended behavior for Starlark rules ("
+ + "https://bazel.build/extending/rules#runfiles_features_to_avoid).")
+ public boolean alwaysIncludeFilesToBuildInData;
+
@Option(
name = "check_fileset_dependencies_recursively",
defaultValue = "true",
@@ -930,6 +942,7 @@ public FragmentOptions getHost() {
host.legacyExternalRunfiles = legacyExternalRunfiles;
host.remotableSourceManifestActions = remotableSourceManifestActions;
host.skipRunfilesManifests = skipRunfilesManifests;
+ host.alwaysIncludeFilesToBuildInData = alwaysIncludeFilesToBuildInData;
// === Filesets ===
host.strictFilesetOutput = strictFilesetOutput;
diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java
index 45720b13462f39..344ebf23861505 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTestBase.java
@@ -89,7 +89,10 @@ public ConfiguredTarget create(RuleContext ruleContext)
.addArtifact(testExecutable)
.addArtifact(getInstrumentationApk(ruleContext))
.addArtifact(getTargetApk(ruleContext))
- .addTargets(runfilesDeps, RunfilesProvider.DEFAULT_RUNFILES)
+ .addTargets(
+ runfilesDeps,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData())
.addTransitiveArtifacts(AndroidCommon.getSupportApks(ruleContext))
.addTransitiveArtifacts(getAdb(ruleContext).getFilesToRun())
.merge(getAapt(ruleContext).getRunfilesSupport())
diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java
index 809fc927736960..33905dd3b0a9bf 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java
@@ -469,7 +469,10 @@ private Runfiles collectDefaultRunfiles(
// runtime jars always in naive link order, incompatible with compile order runfiles.
builder.addArtifacts(getRuntimeJarsForTargets(getAndCheckTestSupport(ruleContext)).toList());
- builder.addTargets(depsForRunfiles, RunfilesProvider.DEFAULT_RUNFILES);
+ builder.addTargets(
+ depsForRunfiles,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
// We assume that the runtime jars will not have conflicting artifacts
// with the same root relative path
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
index dfb04a255166f7..4734c3a1754af8 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
@@ -739,7 +739,10 @@ private void collectDefaultRunfiles(
builder.addSymlinks(runfiles.getSymlinks());
builder.addRootSymlinks(runfiles.getRootSymlinks());
} else {
- builder.addTarget(defaultLauncher, RunfilesProvider.DEFAULT_RUNFILES);
+ builder.addTarget(
+ defaultLauncher,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
}
}
@@ -748,7 +751,10 @@ private void collectDefaultRunfiles(
List<? extends TransitiveInfoCollection> runtimeDeps =
ruleContext.getPrerequisites("runtime_deps");
- builder.addTargets(runtimeDeps, RunfilesProvider.DEFAULT_RUNFILES);
+ builder.addTargets(
+ runtimeDeps,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
builder.addTransitiveArtifactsWrappedInStableOrder(common.getRuntimeClasspath());
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
index b6e2245c82e379..b382b1f39f7a36 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
@@ -886,11 +886,17 @@ public static Runfiles getRunfiles(
depsForRunfiles.addAll(ruleContext.getPrerequisites("exports"));
}
- runfilesBuilder.addTargets(depsForRunfiles, RunfilesProvider.DEFAULT_RUNFILES);
+ runfilesBuilder.addTargets(
+ depsForRunfiles,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
TransitiveInfoCollection launcher = JavaHelper.launcherForTarget(semantics, ruleContext);
if (launcher != null) {
- runfilesBuilder.addTarget(launcher, RunfilesProvider.DATA_RUNFILES);
+ runfilesBuilder.addTarget(
+ launcher,
+ RunfilesProvider.DATA_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData());
}
semantics.addRunfilesForLibrary(ruleContext, runfilesBuilder);
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java
index a4d1d0556d3529..d3ed1d7f97a47f 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaImport.java
@@ -140,7 +140,10 @@ public ConfiguredTarget create(RuleContext ruleContext)
ruleContext.getConfiguration().legacyExternalRunfiles())
// add the jars to the runfiles
.addArtifacts(javaArtifacts.getRuntimeJars())
- .addTargets(targets, RunfilesProvider.DEFAULT_RUNFILES)
+ .addTargets(
+ targets,
+ RunfilesProvider.DEFAULT_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES)
.build();
| diff --git a/src/main/java/com/google/devtools/build/lib/rules/test/TestSuite.java b/src/main/java/com/google/devtools/build/lib/rules/test/TestSuite.java
index 40eeb359852495..07ad56196be619 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/test/TestSuite.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/test/TestSuite.java
@@ -79,10 +79,15 @@ public ConfiguredTarget create(RuleContext ruleContext)
directTestsAndSuitesBuilder.add(dep);
}
- Runfiles runfiles = new Runfiles.Builder(
- ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles())
- .addTargets(directTestsAndSuitesBuilder, RunfilesProvider.DATA_RUNFILES)
- .build();
+ Runfiles runfiles =
+ new Runfiles.Builder(
+ ruleContext.getWorkspaceName(),
+ ruleContext.getConfiguration().legacyExternalRunfiles())
+ .addTargets(
+ directTestsAndSuitesBuilder,
+ RunfilesProvider.DATA_RUNFILES,
+ ruleContext.getConfiguration().alwaysIncludeFilesToBuildInData())
+ .build();
return new RuleConfiguredTargetBuilder(ruleContext)
.add(RunfilesProvider.class,
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
index 8ba84526fd64b9..0fad5fa2d6cb1e 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkIntegrationTest.java
@@ -713,6 +713,134 @@ public void testDefaultInfoWithRunfilesConstructor() throws Exception {
assertThat(getConfiguredTarget("//src:r_tools")).isNotNull();
}
+ @Test
+ public void testDefaultInfoFilesAddedToCcBinaryTargetRunfiles() throws Exception {
+ scratch.file(
+ "test/starlark/extension.bzl",
+ "def custom_rule_impl(ctx):",
+ " out = ctx.actions.declare_file(ctx.attr.name + '.out')",
+ " ctx.actions.write(out, 'foobar')",
+ " return [DefaultInfo(files = depset([out]))]",
+ "",
+ "custom_rule = rule(implementation = custom_rule_impl)");
+
+ scratch.file(
+ "test/starlark/BUILD",
+ "load('//test/starlark:extension.bzl', 'custom_rule')",
+ "",
+ "custom_rule(name = 'cr')",
+ "cc_binary(name = 'binary', data = [':cr'])");
+
+ useConfiguration("--incompatible_always_include_files_in_data");
+ ConfiguredTarget target = getConfiguredTarget("//test/starlark:binary");
+
+ assertThat(target.getLabel().toString()).isEqualTo("//test/starlark:binary");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDataRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ }
+
+ @Test
+ public void testDefaultInfoFilesAddedToJavaBinaryTargetRunfiles() throws Exception {
+ scratch.file(
+ "test/starlark/extension.bzl",
+ "def custom_rule_impl(ctx):",
+ " out = ctx.actions.declare_file(ctx.attr.name + '.out')",
+ " ctx.actions.write(out, 'foobar')",
+ " return [DefaultInfo(files = depset([out]))]",
+ "",
+ "custom_rule = rule(implementation = custom_rule_impl)");
+
+ scratch.file(
+ "test/starlark/BUILD",
+ "load('//test/starlark:extension.bzl', 'custom_rule')",
+ "",
+ "custom_rule(name = 'cr')",
+ "java_binary(name = 'binary', data = [':cr'], srcs = ['Foo.java'], main_class = 'Foo')");
+
+ useConfiguration("--incompatible_always_include_files_in_data");
+ ConfiguredTarget target = getConfiguredTarget("//test/starlark:binary");
+
+ assertThat(target.getLabel().toString()).isEqualTo("//test/starlark:binary");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDataRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ }
+
+ @Test
+ public void testDefaultInfoFilesAddedToPyBinaryTargetRunfiles() throws Exception {
+ scratch.file(
+ "test/starlark/extension.bzl",
+ "def custom_rule_impl(ctx):",
+ " out = ctx.actions.declare_file(ctx.attr.name + '.out')",
+ " ctx.actions.write(out, 'foobar')",
+ " return [DefaultInfo(files = depset([out]))]",
+ "",
+ "custom_rule = rule(implementation = custom_rule_impl)");
+
+ scratch.file(
+ "test/starlark/BUILD",
+ "load('//test/starlark:extension.bzl', 'custom_rule')",
+ "",
+ "custom_rule(name = 'cr')",
+ "py_binary(name = 'binary', data = [':cr'], srcs = ['binary.py'])");
+
+ useConfiguration("--incompatible_always_include_files_in_data");
+ ConfiguredTarget target = getConfiguredTarget("//test/starlark:binary");
+
+ assertThat(target.getLabel().toString()).isEqualTo("//test/starlark:binary");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDataRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ }
+
+ @Test
+ public void testDefaultInfoFilesAddedToShBinaryTargetRunfiles() throws Exception {
+ scratch.file(
+ "test/starlark/extension.bzl",
+ "def custom_rule_impl(ctx):",
+ " out = ctx.actions.declare_file(ctx.attr.name + '.out')",
+ " ctx.actions.write(out, 'foobar')",
+ " return [DefaultInfo(files = depset([out]))]",
+ "",
+ "custom_rule = rule(implementation = custom_rule_impl)");
+
+ scratch.file(
+ "test/starlark/BUILD",
+ "load('//test/starlark:extension.bzl', 'custom_rule')",
+ "",
+ "custom_rule(name = 'cr')",
+ "sh_binary(name = 'binary', data = [':cr'], srcs = ['script.sh'])");
+
+ useConfiguration("--incompatible_always_include_files_in_data");
+ ConfiguredTarget target = getConfiguredTarget("//test/starlark:binary");
+
+ assertThat(target.getLabel().toString()).isEqualTo("//test/starlark:binary");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ assertThat(
+ ActionsTestUtil.baseArtifactNames(
+ target.getProvider(RunfilesProvider.class).getDataRunfiles().getAllArtifacts()))
+ .contains("cr.out");
+ }
+
@Test
public void testInstrumentedFilesProviderWithCodeCoverageDisabled() throws Exception {
setBuildLanguageOptions("--incompatible_disallow_struct_provider_syntax=false");
| train | val | 2022-11-07T20:13:04 | "2022-03-15T02:30:32Z" | linzhp | test |
bazelbuild/bazel/16643_16733 | bazelbuild/bazel | bazelbuild/bazel/16643 | bazelbuild/bazel/16733 | [
"keyword_pr_to_issue"
] | 38c501912fc4efc14abc0741d19f5f8e8763afcb | 5929cb72aa01768e6352898b1a056ef678c81d90 | [
"@Wyverald ",
"My guess (it really is only a guess) is that we have to explicitly add the repo mapping manifest to the input mapping in [`SpawnInputExpander`](https://cs.opensource.google/bazel/bazel/+/bbc221f60bc8c9177470529d85c3e47a5d9aaf21:src/main/java/com/google/devtools/build/lib/exec/SpawnInputExpander.java;l=119;drc=0a23d46976c3fc999d44fbd1e37732ec2442d485) for it to show up in sandboxed and remote execution.",
"@bazel-io flag",
"Fix cherry picked in https://github.com/bazelbuild/bazel/pull/16733, removing the `potential release blocker` label."
] | [] | "2022-11-10T15:45:37Z" | [
"type: bug",
"team-ExternalDeps",
"untriaged",
"area-Bzlmod"
] | Repository mapping manifest does not exist in test sandbox | ### Description of the bug:
The `.repo_mapping` file does not appear in test sandboxes.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
# WORKSPACE
# MODULE.bazel
# pkg/BUILD
sh_test(
name = "test",
srcs = ["test.sh"],
)
# pkg/test.sh
#!/usr/bin/env bash
runfiles_dir="$TEST_SRCDIR/../test.runfiles"
if [[ ! -d "$runfiles_dir" ]]; then
echo "$runfiles_dir does not exist"
exit 1
fi
repo_mapping="$TEST_SRCDIR/../test.repo_mapping"
if [[ ! -f "$repo_mapping" ]]; then
echo "$repo_mapping does not exist"
exit 1
fi
```
`USE_BAZEL_VERSION=last_green bazel test //pkg:test --enable_bzlmod` fails
`USE_BAZEL_VERSION=last_green bazel run //pkg:test --enable_bzlmod` passes
`USE_BAZEL_VERSION=last_green bazel test //pkg:test --enable_bzlmod --spawn_strategy=local` passes
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
HEAD
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java",
"src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java",
"src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java",
"src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java",
"src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java",
"src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java",
"src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java",
"src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java",
"src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java",
"src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java",
"src/test/py/bazel/bzlmod/bazel_module_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
index d9933d60b19561..00a4fe5f6a486f 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
@@ -386,11 +386,14 @@ static Map<PathFragment, Artifact> filterListForObscuringSymlinks(
* normal source tree entries, or runfile conflicts. May be null, in which case obscuring
* symlinks are silently discarded, and conflicts are overwritten.
* @param location Location for eventHandler warnings. Ignored if eventHandler is null.
+ * @param repoMappingManifest repository mapping manifest to add as a root symlink. This manifest
+ * has to be added automatically for every executable and is thus not part of the Runfiles
+ * advertised by a configured target.
* @return Map<PathFragment, Artifact> path fragment to artifact, of normal source tree entries
* and elements that live outside the source tree. Null values represent empty input files.
*/
public Map<PathFragment, Artifact> getRunfilesInputs(
- EventHandler eventHandler, Location location) {
+ EventHandler eventHandler, Location location, @Nullable Artifact repoMappingManifest) {
ConflictChecker checker = new ConflictChecker(conflictPolicy, eventHandler, location);
Map<PathFragment, Artifact> manifest = getSymlinksAsMap(checker);
// Add artifacts (committed to inclusion on construction of runfiles).
@@ -417,6 +420,9 @@ public Map<PathFragment, Artifact> getRunfilesInputs(
checker = new ConflictChecker(ConflictPolicy.WARN, eventHandler, location);
}
builder.add(getRootSymlinksAsMap(checker), checker);
+ if (repoMappingManifest != null) {
+ checker.put(builder.manifest, PathFragment.create("_repo_mapping"), repoMappingManifest);
+ }
return builder.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
index 189cb882fe15d7..3772cf7cb700da 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
@@ -132,18 +132,20 @@ private static RunfilesSupport create(
}
Preconditions.checkState(!runfiles.isEmpty());
+ Artifact repoMappingManifest =
+ createRepoMappingManifestAction(ruleContext, runfiles, owningExecutable);
+
Artifact runfilesInputManifest;
Artifact runfilesManifest;
if (createManifest) {
runfilesInputManifest = createRunfilesInputManifestArtifact(ruleContext, owningExecutable);
runfilesManifest =
- createRunfilesAction(ruleContext, runfiles, buildRunfileLinks, runfilesInputManifest);
+ createRunfilesAction(
+ ruleContext, runfiles, buildRunfileLinks, runfilesInputManifest, repoMappingManifest);
} else {
runfilesInputManifest = null;
runfilesManifest = null;
}
- Artifact repoMappingManifest =
- createRepoMappingManifestAction(ruleContext, runfiles, owningExecutable);
Artifact runfilesMiddleman =
createRunfilesMiddleman(
ruleContext, owningExecutable, runfiles, runfilesManifest, repoMappingManifest);
@@ -387,7 +389,8 @@ private static Artifact createRunfilesAction(
ActionConstructionContext context,
Runfiles runfiles,
boolean createSymlinks,
- Artifact inputManifest) {
+ Artifact inputManifest,
+ @Nullable Artifact repoMappingManifest) {
// Compute the names of the runfiles directory and its MANIFEST file.
context
.getAnalysisEnvironment()
@@ -397,6 +400,7 @@ private static Artifact createRunfilesAction(
context.getActionOwner(),
inputManifest,
runfiles,
+ repoMappingManifest,
context.getConfiguration().remotableSourceManifestActions()));
if (!createSymlinks) {
@@ -423,6 +427,7 @@ private static Artifact createRunfilesAction(
inputManifest,
runfiles,
outputManifest,
+ repoMappingManifest,
/*filesetRoot=*/ null));
return outputManifest;
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java b/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
index 126c0e98548430..379c875b3d2141 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
@@ -34,10 +34,12 @@
/** {@link RunfilesSupplier} implementation wrapping a single {@link Runfiles} directory mapping. */
@AutoCodec
public final class SingleRunfilesSupplier implements RunfilesSupplier {
+
private final PathFragment runfilesDir;
private final Runfiles runfiles;
private final Supplier<Map<PathFragment, Artifact>> runfilesInputs;
@Nullable private final Artifact manifest;
+ @Nullable private final Artifact repoMappingManifest;
private final boolean buildRunfileLinks;
private final boolean runfileLinksEnabled;
@@ -50,14 +52,15 @@ public static SingleRunfilesSupplier create(RunfilesSupport runfilesSupport) {
runfilesSupport.getRunfiles(),
/*runfilesCachingEnabled=*/ false,
/*manifest=*/ null,
+ runfilesSupport.getRepoMappingManifest(),
runfilesSupport.isBuildRunfileLinks(),
runfilesSupport.isRunfilesEnabled());
}
/**
* Same as {@link SingleRunfilesSupplier#SingleRunfilesSupplier(PathFragment, Runfiles, Artifact,
- * boolean, boolean)}, except adds caching for {@linkplain Runfiles#getRunfilesInputs runfiles
- * inputs}.
+ * Artifact, boolean, boolean)}, except adds caching for {@linkplain Runfiles#getRunfilesInputs
+ * runfiles inputs}.
*
* <p>The runfiles inputs are computed lazily and softly cached. Caching is shared across
* instances created via {@link #withOverriddenRunfilesDir}.
@@ -65,6 +68,7 @@ public static SingleRunfilesSupplier create(RunfilesSupport runfilesSupport) {
public static SingleRunfilesSupplier createCaching(
PathFragment runfilesDir,
Runfiles runfiles,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
return new SingleRunfilesSupplier(
@@ -72,6 +76,7 @@ public static SingleRunfilesSupplier createCaching(
runfiles,
/*runfilesCachingEnabled=*/ true,
/*manifest=*/ null,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -92,6 +97,7 @@ public SingleRunfilesSupplier(
PathFragment runfilesDir,
Runfiles runfiles,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
this(
@@ -99,6 +105,7 @@ public SingleRunfilesSupplier(
runfiles,
/*runfilesCachingEnabled=*/ false,
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -108,15 +115,19 @@ private SingleRunfilesSupplier(
Runfiles runfiles,
boolean runfilesCachingEnabled,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
this(
runfilesDir,
runfiles,
runfilesCachingEnabled
- ? new RunfilesCacher(runfiles)
- : () -> runfiles.getRunfilesInputs(/*eventHandler=*/ null, /*location=*/ null),
+ ? new RunfilesCacher(runfiles, repoMappingManifest)
+ : () ->
+ runfiles.getRunfilesInputs(
+ /*eventHandler=*/ null, /*location=*/ null, repoMappingManifest),
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -126,6 +137,7 @@ private SingleRunfilesSupplier(
Runfiles runfiles,
Supplier<Map<PathFragment, Artifact>> runfilesInputs,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
checkArgument(!runfilesDir.isAbsolute());
@@ -133,6 +145,7 @@ private SingleRunfilesSupplier(
this.runfiles = checkNotNull(runfiles);
this.runfilesInputs = checkNotNull(runfilesInputs);
this.manifest = manifest;
+ this.repoMappingManifest = repoMappingManifest;
this.buildRunfileLinks = buildRunfileLinks;
this.runfileLinksEnabled = runfileLinksEnabled;
}
@@ -199,17 +212,21 @@ public SingleRunfilesSupplier withOverriddenRunfilesDir(PathFragment newRunfiles
runfiles,
runfilesInputs,
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
/** Softly caches the result of {@link Runfiles#getRunfilesInputs}. */
private static final class RunfilesCacher implements Supplier<Map<PathFragment, Artifact>> {
+
private final Runfiles runfiles;
+ @Nullable private final Artifact repoMappingManifest;
private volatile SoftReference<Map<PathFragment, Artifact>> ref = new SoftReference<>(null);
- RunfilesCacher(Runfiles runfiles) {
+ RunfilesCacher(Runfiles runfiles, @Nullable Artifact repoMappingManifest) {
this.runfiles = runfiles;
+ this.repoMappingManifest = repoMappingManifest;
}
@Override
@@ -221,7 +238,9 @@ public Map<PathFragment, Artifact> get() {
synchronized (this) {
result = ref.get();
if (result == null) {
- result = runfiles.getRunfilesInputs(/*eventHandler=*/ null, /*location=*/ null);
+ result =
+ runfiles.getRunfilesInputs(
+ /*eventHandler=*/ null, /*location=*/ null, repoMappingManifest);
ref = new SoftReference<>(result);
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java b/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
index 8ca38d37c50658..6feb2b91321df8 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
@@ -61,7 +61,7 @@ public final class SourceManifestAction extends AbstractFileWriteAction {
private static final Comparator<Map.Entry<PathFragment, Artifact>> ENTRY_COMPARATOR =
(path1, path2) -> path1.getKey().getPathString().compareTo(path2.getKey().getPathString());
-
+ private final Artifact repoMappingManifest;
/**
* Interface for defining manifest formatting and reporting specifics. Implementations must be
* immutable.
@@ -118,7 +118,7 @@ void writeEntry(
@VisibleForTesting
SourceManifestAction(
ManifestWriter manifestWriter, ActionOwner owner, Artifact primaryOutput, Runfiles runfiles) {
- this(manifestWriter, owner, primaryOutput, runfiles, /*remotableSourceManifestActions=*/ false);
+ this(manifestWriter, owner, primaryOutput, runfiles, null, false);
}
/**
@@ -129,17 +129,20 @@ void writeEntry(
* @param owner the action owner
* @param primaryOutput the file to which to write the manifest
* @param runfiles runfiles
+ * @param repoMappingManifest the repository mapping manifest for runfiles
*/
public SourceManifestAction(
ManifestWriter manifestWriter,
ActionOwner owner,
Artifact primaryOutput,
Runfiles runfiles,
+ @Nullable Artifact repoMappingManifest,
boolean remotableSourceManifestActions) {
// The real set of inputs is computed in #getInputs().
super(owner, NestedSetBuilder.emptySet(Order.STABLE_ORDER), primaryOutput, false);
this.manifestWriter = manifestWriter;
this.runfiles = runfiles;
+ this.repoMappingManifest = repoMappingManifest;
this.remotableSourceManifestActions = remotableSourceManifestActions;
}
@@ -180,7 +183,9 @@ public synchronized NestedSet<Artifact> getInputs() {
@VisibleForTesting
public void writeOutputFile(OutputStream out, @Nullable EventHandler eventHandler)
throws IOException {
- writeFile(out, runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation()));
+ writeFile(
+ out,
+ runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation(), repoMappingManifest));
}
/**
@@ -202,7 +207,8 @@ public String getStarlarkContent() throws IOException {
@Override
public DeterministicWriter newDeterministicWriter(ActionExecutionContext ctx) {
final Map<PathFragment, Artifact> runfilesInputs =
- runfiles.getRunfilesInputs(ctx.getEventHandler(), getOwner().getLocation());
+ runfiles.getRunfilesInputs(
+ ctx.getEventHandler(), getOwner().getLocation(), repoMappingManifest);
return out -> writeFile(out, runfilesInputs);
}
@@ -247,6 +253,10 @@ protected void computeKey(
fp.addString(GUID);
fp.addBoolean(remotableSourceManifestActions);
runfiles.fingerprint(fp);
+ fp.addBoolean(repoMappingManifest != null);
+ if (repoMappingManifest != null) {
+ fp.addPath(repoMappingManifest.getExecPath());
+ }
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java b/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
index 14a06ca1511f5c..4a819506532e24 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
@@ -49,6 +49,7 @@ public final class SymlinkTreeAction extends AbstractAction {
private final boolean enableRunfiles;
private final boolean inprocessSymlinkCreation;
private final boolean skipRunfilesManifests;
+ private final Artifact repoMappingManifest;
/**
* Creates SymlinkTreeAction instance.
@@ -59,6 +60,7 @@ public final class SymlinkTreeAction extends AbstractAction {
* @param runfiles the input runfiles
* @param outputManifest the generated symlink tree manifest (must have "MANIFEST" base name).
* Symlink tree root will be set to the artifact's parent directory.
+ * @param repoMappingManifest the repository mapping manifest
* @param filesetRoot non-null if this is a fileset symlink tree
*/
public SymlinkTreeAction(
@@ -67,12 +69,14 @@ public SymlinkTreeAction(
Artifact inputManifest,
@Nullable Runfiles runfiles,
Artifact outputManifest,
+ @Nullable Artifact repoMappingManifest,
String filesetRoot) {
this(
owner,
inputManifest,
runfiles,
outputManifest,
+ repoMappingManifest,
filesetRoot,
config.getActionEnvironment(),
config.runfilesEnabled(),
@@ -90,6 +94,7 @@ public SymlinkTreeAction(
* @param runfiles the input runfiles
* @param outputManifest the generated symlink tree manifest (must have "MANIFEST" base name).
* Symlink tree root will be set to the artifact's parent directory.
+ * @param repoMappingManifest the repository mapping manifest
* @param filesetRoot non-null if this is a fileset symlink tree,
*/
public SymlinkTreeAction(
@@ -97,6 +102,7 @@ public SymlinkTreeAction(
Artifact inputManifest,
@Nullable Runfiles runfiles,
Artifact outputManifest,
+ @Nullable Artifact repoMappingManifest,
@Nullable String filesetRoot,
ActionEnvironment env,
boolean enableRunfiles,
@@ -104,7 +110,8 @@ public SymlinkTreeAction(
boolean skipRunfilesManifests) {
super(
owner,
- computeInputs(enableRunfiles, skipRunfilesManifests, runfiles, inputManifest),
+ computeInputs(
+ enableRunfiles, skipRunfilesManifests, runfiles, inputManifest, repoMappingManifest),
ImmutableSet.of(outputManifest),
env);
Preconditions.checkArgument(outputManifest.getPath().getBaseName().equals("MANIFEST"));
@@ -118,13 +125,15 @@ public SymlinkTreeAction(
this.inprocessSymlinkCreation = inprocessSymlinkCreation;
this.skipRunfilesManifests = skipRunfilesManifests && enableRunfiles && (filesetRoot == null);
this.inputManifest = this.skipRunfilesManifests ? null : inputManifest;
+ this.repoMappingManifest = repoMappingManifest;
}
private static NestedSet<Artifact> computeInputs(
boolean enableRunfiles,
boolean skipRunfilesManifests,
Runfiles runfiles,
- Artifact inputManifest) {
+ Artifact inputManifest,
+ @Nullable Artifact repoMappingManifest) {
NestedSetBuilder<Artifact> inputs = NestedSetBuilder.<Artifact>stableOrder();
if (!skipRunfilesManifests || !enableRunfiles || runfiles == null) {
inputs.add(inputManifest);
@@ -134,6 +143,9 @@ private static NestedSet<Artifact> computeInputs(
// existing, so directory or file links can be made as appropriate.
if (enableRunfiles && runfiles != null && OS.getCurrent() == OS.WINDOWS) {
inputs.addTransitive(runfiles.getAllArtifacts());
+ if (repoMappingManifest != null) {
+ inputs.add(repoMappingManifest);
+ }
}
return inputs.build();
}
@@ -151,6 +163,11 @@ public Artifact getOutputManifest() {
return outputManifest;
}
+ @Nullable
+ public Artifact getRepoMappingManifest() {
+ return repoMappingManifest;
+ }
+
public boolean isFilesetTree() {
return filesetRoot != null;
}
@@ -201,6 +218,10 @@ protected void computeKey(
if (runfiles != null) {
runfiles.fingerprint(fp);
}
+ fp.addBoolean(repoMappingManifest != null);
+ if (repoMappingManifest != null) {
+ fp.addPath(repoMappingManifest.getExecPath());
+ }
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java b/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
index fc5dc61676466f..5d2e4371f1e177 100644
--- a/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
+++ b/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
@@ -151,7 +151,8 @@ private static Map<PathFragment, Artifact> runfilesToMap(
.getRunfiles()
.getRunfilesInputs(
action.getInputManifest() == null ? actionExecutionContext.getEventHandler() : null,
- action.getOwner().getLocation());
+ action.getOwner().getLocation(),
+ action.getRepoMappingManifest());
}
private static void createOutput(
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
index 4734c3a1754af8..df8b8aaa0b1225 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
@@ -495,6 +495,7 @@ public ConfiguredTarget create(RuleContext ruleContext)
// This matches the code below in collectDefaultRunfiles.
.addTransitiveArtifactsWrappedInStableOrder(common.getRuntimeClasspath())
.build(),
+ null,
true));
filesBuilder.add(runtimeClasspathArtifact);
| diff --git a/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java b/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
index 726b433670c331..cf908ce46c1651 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
@@ -379,6 +379,7 @@ private TestParams createTestAction(int shards)
SingleRunfilesSupplier.createCaching(
runfilesSupport.getRunfilesDirectoryExecPath(),
runfilesSupport.getRunfiles(),
+ runfilesSupport.getRepoMappingManifest(),
runfilesSupport.isBuildRunfileLinks(),
runfilesSupport.isRunfilesEnabled());
} else {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java b/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
index ee17341d27ce32..fc0a713e1495af 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
@@ -56,6 +56,7 @@ public void testGetArtifactsWithSingleMapping() {
PathFragment.create("notimportant"),
mkRunfiles(artifacts),
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
@@ -69,6 +70,7 @@ public void testGetManifestsWhenNone() {
PathFragment.create("ignored"),
Runfiles.EMPTY,
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(underTest.getManifests()).isEmpty();
@@ -82,6 +84,7 @@ public void testGetManifestsWhenSupplied() {
PathFragment.create("ignored"),
Runfiles.EMPTY,
manifest,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(underTest.getManifests()).containsExactly(manifest);
@@ -94,6 +97,7 @@ public void withOverriddenRunfilesDir() {
PathFragment.create("old"),
Runfiles.EMPTY,
ActionsTestUtil.createArtifact(rootDir, "manifest"),
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
PathFragment newDir = PathFragment.create("new");
@@ -115,6 +119,7 @@ public void withOverriddenRunfilesDir_noChange_sameObject() {
dir,
Runfiles.EMPTY,
ActionsTestUtil.createArtifact(rootDir, "manifest"),
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(original.withOverriddenRunfilesDir(dir)).isSameInstanceAs(original);
@@ -126,12 +131,16 @@ public void cachedMappings() {
Runfiles runfiles = mkRunfiles(mkArtifacts("a", "b", "c"));
SingleRunfilesSupplier underTest =
SingleRunfilesSupplier.createCaching(
- dir, runfiles, /*buildRunfileLinks=*/ false, /*runfileLinksEnabled=*/ false);
+ dir,
+ runfiles,
+ /*repoMappingManifest=*/ null,
+ /*buildRunfileLinks=*/ false,
+ /*runfileLinksEnabled=*/ false);
Map<PathFragment, Map<PathFragment, Artifact>> mappings1 = underTest.getMappings();
Map<PathFragment, Map<PathFragment, Artifact>> mappings2 = underTest.getMappings();
- assertThat(mappings1).containsExactly(dir, runfiles.getRunfilesInputs(null, null));
+ assertThat(mappings1).containsExactly(dir, runfiles.getRunfilesInputs(null, null, null));
assertThat(mappings1).isEqualTo(mappings2);
assertThat(mappings1.get(dir)).isSameInstanceAs(mappings2.get(dir));
}
@@ -143,14 +152,18 @@ public void cachedMappings_sharedAcrossDirOverrides() {
Runfiles runfiles = mkRunfiles(mkArtifacts("a", "b", "c"));
SingleRunfilesSupplier original =
SingleRunfilesSupplier.createCaching(
- oldDir, runfiles, /*buildRunfileLinks=*/ false, /*runfileLinksEnabled=*/ false);
- SingleRunfilesSupplier overriden = original.withOverriddenRunfilesDir(newDir);
+ oldDir,
+ runfiles,
+ /*repoMappingManifest=*/ null,
+ /*buildRunfileLinks=*/ false,
+ /*runfileLinksEnabled=*/ false);
+ SingleRunfilesSupplier overridden = original.withOverriddenRunfilesDir(newDir);
Map<PathFragment, Map<PathFragment, Artifact>> mappingsOld = original.getMappings();
- Map<PathFragment, Map<PathFragment, Artifact>> mappingsNew = overriden.getMappings();
+ Map<PathFragment, Map<PathFragment, Artifact>> mappingsNew = overridden.getMappings();
- assertThat(mappingsOld).containsExactly(oldDir, runfiles.getRunfilesInputs(null, null));
- assertThat(mappingsNew).containsExactly(newDir, runfiles.getRunfilesInputs(null, null));
+ assertThat(mappingsOld).containsExactly(oldDir, runfiles.getRunfilesInputs(null, null, null));
+ assertThat(mappingsNew).containsExactly(newDir, runfiles.getRunfilesInputs(null, null, null));
assertThat(mappingsOld.get(newDir)).isSameInstanceAs(mappingsNew.get(oldDir));
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
index 49e3aba3e4c9e9..31a92732c2fb4a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
@@ -409,6 +409,7 @@ public void testInputManifestsRemovedIfSupplied() throws Exception {
PathFragment.create("destination"),
Runfiles.EMPTY,
manifest,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false))
.addOutput(getBinArtifactWithNoOwner("output"))
@@ -628,6 +629,7 @@ private static RunfilesSupplier runfilesSupplier(Artifact manifest, PathFragment
dir,
Runfiles.EMPTY,
manifest,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false);
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
index b849cf8733acbf..6ce4bcc2771442 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
@@ -70,6 +70,7 @@ public void testComputeKey() throws Exception {
? new Runfiles.Builder("TESTING", false).addArtifact(runfile).build()
: new Runfiles.Builder("TESTING", false).addArtifact(runfile2).build(),
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(
attributesToFlip.contains(RunfilesActionAttributes.FIXED_ENVIRONMENT),
@@ -85,6 +86,7 @@ public void testComputeKey() throws Exception {
inputManifest,
/*runfiles=*/ null,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ "root",
createActionEnvironment(
attributesToFlip.contains(FilesetActionAttributes.FIXED_ENVIRONMENT),
@@ -103,6 +105,7 @@ public void testComputeKey() throws Exception {
? new Runfiles.Builder("TESTING", false).addArtifact(runfile).build()
: new Runfiles.Builder("TESTING", false).addArtifact(runfile2).build(),
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(
attributesToFlip.contains(SkipManifestAttributes.FIXED_ENVIRONMENT),
@@ -131,6 +134,7 @@ public void testNullRunfilesThrows() {
inputManifest,
/*runfiles=*/ null,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(false, false),
/*enableRunfiles=*/ true,
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
index 53b05d891bef9c..12fbcb55ec44f8 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
@@ -562,6 +562,7 @@ public static RunfilesSupplier createRunfilesSupplier(
runfilesDir,
runfiles,
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
}
diff --git a/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java b/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
index 839a4bb64dd615..ad7a7a5e8d2687 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
@@ -92,6 +92,7 @@ public void outputServiceInteraction() throws Exception {
inputManifest,
runfiles,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
ActionEnvironment.EMPTY,
/*enableRunfiles=*/ true,
@@ -138,6 +139,7 @@ public void inprocessSymlinkCreation() throws Exception {
inputManifest,
runfiles,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
ActionEnvironment.EMPTY,
/*enableRunfiles=*/ true,
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
index ed7d6da4fb9d0a..ec40c1f7e85a51 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
@@ -218,6 +218,7 @@ public Action generate(ImmutableSet<KeyAttributes> attributesToFlip) {
PathFragment.create("a"),
Runfiles.EMPTY,
artifactA,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false));
} else {
@@ -226,6 +227,7 @@ public Action generate(ImmutableSet<KeyAttributes> attributesToFlip) {
PathFragment.create("a"),
Runfiles.EMPTY,
artifactB,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false));
}
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
index 3ecf4c1950728e..a04a2dc31a3abb 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
@@ -1033,7 +1033,7 @@ public void testRunfilesSymlinkConflict() throws Exception {
" symlinks = {'sym1': ruleContext.files.srcs[1]})");
Runfiles runfiles = (Runfiles) result;
reporter.removeHandler(failFastHandler); // So it doesn't throw an exception.
- runfiles.getRunfilesInputs(reporter, null);
+ var unused = runfiles.getRunfilesInputs(reporter, null, null);
assertContainsEvent("ERROR <no location>: overwrote runfile");
}
diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 5312a26de2e708..301477560bb224 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -583,27 +583,29 @@ def testRunfilesRepoMappingManifest(self):
self.main_registry.setModuleBasePath('projects')
projects_dir = self.main_registry.projects
- # Set up a "bare_rule" module that contains the "bare_binary" rule which
+ # Set up a "bare_rule" module that contains the "bare_test" rule which
# passes runfiles along
self.main_registry.createLocalPathModule('bare_rule', '1.0', 'bare_rule')
projects_dir.joinpath('bare_rule').mkdir(exist_ok=True)
scratchFile(projects_dir.joinpath('bare_rule', 'WORKSPACE'))
scratchFile(projects_dir.joinpath('bare_rule', 'BUILD'))
+ # The working directory of a test is the subdirectory of the runfiles
+ # directory corresponding to the main repository.
scratchFile(
projects_dir.joinpath('bare_rule', 'defs.bzl'), [
- 'def _bare_binary_impl(ctx):',
+ 'def _bare_test_impl(ctx):',
' exe = ctx.actions.declare_file(ctx.label.name)',
' ctx.actions.write(exe,',
- ' "#/bin/bash\\nif [[ ! -f \\"$0.repo_mapping\\" ]]; then\\necho >&2 \\"ERROR: cannot find repo mapping manifest file\\"\\nexit 1\\nfi",',
+ ' "#/bin/bash\\nif [[ ! -f ../_repo_mapping || ! -s ../_repo_mapping ]]; then\\necho >&2 \\"ERROR: cannot find repo mapping manifest file\\"\\nexit 1\\nfi",',
' True)',
' runfiles = ctx.runfiles(files=ctx.files.data)',
' for data in ctx.attr.data:',
' runfiles = runfiles.merge(data[DefaultInfo].default_runfiles)',
' return DefaultInfo(files=depset(direct=[exe]), executable=exe, runfiles=runfiles)',
- 'bare_binary=rule(',
- ' implementation=_bare_binary_impl,',
+ 'bare_test=rule(',
+ ' implementation=_bare_test_impl,',
' attrs={"data":attr.label_list(allow_files=True)},',
- ' executable=True,',
+ ' test=True,',
')',
])
@@ -617,8 +619,8 @@ def testRunfilesRepoMappingManifest(self):
self.ScratchFile('WORKSPACE')
self.ScratchFile('WORKSPACE.bzlmod', ['workspace(name="me_ws")'])
self.ScratchFile('BUILD', [
- 'load("@bare_rule//:defs.bzl", "bare_binary")',
- 'bare_binary(name="me",data=["@foo"])',
+ 'load("@bare_rule//:defs.bzl", "bare_test")',
+ 'bare_test(name="me",data=["@foo"])',
])
self.main_registry.createLocalPathModule('foo', '1.0', 'foo', {
'quux': '1.0',
@@ -633,16 +635,16 @@ def testRunfilesRepoMappingManifest(self):
self.main_registry.createLocalPathModule('quux', '2.0', 'quux2',
{'bare_rule': '1.0'})
for dir_name, build_file in [
- ('foo', 'bare_binary(name="foo",data=["@quux"])'),
- ('bar', 'bare_binary(name="bar",data=["@quux"])'),
- ('quux1', 'bare_binary(name="quux")'),
- ('quux2', 'bare_binary(name="quux")'),
+ ('foo', 'bare_test(name="foo",data=["@quux"])'),
+ ('bar', 'bare_test(name="bar",data=["@quux"])'),
+ ('quux1', 'bare_test(name="quux")'),
+ ('quux2', 'bare_test(name="quux")'),
]:
projects_dir.joinpath(dir_name).mkdir(exist_ok=True)
scratchFile(projects_dir.joinpath(dir_name, 'WORKSPACE'))
scratchFile(
projects_dir.joinpath(dir_name, 'BUILD'), [
- 'load("@bare_rule//:defs.bzl", "bare_binary")',
+ 'load("@bare_rule//:defs.bzl", "bare_test")',
'package(default_visibility=["//visibility:public"])',
build_file,
])
@@ -650,25 +652,47 @@ def testRunfilesRepoMappingManifest(self):
# We use a shell script to check that the binary itself can see the repo
# mapping manifest. This obviously doesn't work on Windows, so we just build
# the target. TODO(wyv): make this work on Windows by using Batch.
- bazel_command = 'build' if self.IsWindows() else 'run'
+ # On Linux and macOS, the script is executed in the sandbox, so we verify
+ # that the repository mapping is present in it.
+ bazel_command = 'build' if self.IsWindows() else 'test'
# Finally we get to build stuff!
- self.RunBazel([bazel_command, '//:me'], allow_failure=False)
- with open(self.Path('bazel-bin/me.repo_mapping'), 'r') as f:
- self.assertEqual(
- f.read().strip(), """,foo,foo~1.0
+ exit_code, stderr, stdout = self.RunBazel(
+ [bazel_command, '//:me', '--test_output=errors'], allow_failure=True)
+ self.AssertExitCode(0, exit_code, stderr, stdout)
+
+ paths = ['bazel-bin/me.repo_mapping']
+ if not self.IsWindows():
+ paths.append('bazel-bin/me.runfiles/_repo_mapping')
+ for path in paths:
+ with open(self.Path(path), 'r') as f:
+ self.assertEqual(
+ f.read().strip(), """,foo,foo~1.0
,me,_main
,me_ws,_main
foo~1.0,foo,foo~1.0
foo~1.0,quux,quux~2.0
quux~2.0,quux,quux~2.0""")
- self.RunBazel([bazel_command, '@bar//:bar'], allow_failure=False)
- with open(self.Path('bazel-bin/external/bar~2.0/bar.repo_mapping'),
- 'r') as f:
- self.assertEqual(
- f.read().strip(), """bar~2.0,bar,bar~2.0
+ with open(self.Path('bazel-bin/me.runfiles_manifest')) as f:
+ self.assertIn('_repo_mapping ', f.read())
+
+ exit_code, stderr, stdout = self.RunBazel(
+ [bazel_command, '@bar//:bar', '--test_output=errors'],
+ allow_failure=True)
+ self.AssertExitCode(0, exit_code, stderr, stdout)
+
+ paths = ['bazel-bin/external/bar~2.0/bar.repo_mapping']
+ if not self.IsWindows():
+ paths.append('bazel-bin/external/bar~2.0/bar.runfiles/_repo_mapping')
+ for path in paths:
+ with open(self.Path(path), 'r') as f:
+ self.assertEqual(
+ f.read().strip(), """bar~2.0,bar,bar~2.0
bar~2.0,quux,quux~2.0
quux~2.0,quux,quux~2.0""")
+ with open(
+ self.Path('bazel-bin/external/bar~2.0/bar.runfiles_manifest')) as f:
+ self.assertIn('_repo_mapping ', f.read())
if __name__ == '__main__':
unittest.main()
| test | val | 2022-11-10T16:25:41 | "2022-11-02T23:27:44Z" | fmeum | test |
bazelbuild/bazel/16124_16733 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16733 | [
"keyword_pr_to_issue"
] | 38c501912fc4efc14abc0741d19f5f8e8763afcb | 5929cb72aa01768e6352898b1a056ef678c81d90 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-10T15:45:37Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java",
"src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java",
"src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java",
"src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java",
"src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java",
"src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java",
"src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java",
"src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java",
"src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java",
"src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java",
"src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java",
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java",
"src/test/py/bazel/bzlmod/bazel_module_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
index d9933d60b19561..00a4fe5f6a486f 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java
@@ -386,11 +386,14 @@ static Map<PathFragment, Artifact> filterListForObscuringSymlinks(
* normal source tree entries, or runfile conflicts. May be null, in which case obscuring
* symlinks are silently discarded, and conflicts are overwritten.
* @param location Location for eventHandler warnings. Ignored if eventHandler is null.
+ * @param repoMappingManifest repository mapping manifest to add as a root symlink. This manifest
+ * has to be added automatically for every executable and is thus not part of the Runfiles
+ * advertised by a configured target.
* @return Map<PathFragment, Artifact> path fragment to artifact, of normal source tree entries
* and elements that live outside the source tree. Null values represent empty input files.
*/
public Map<PathFragment, Artifact> getRunfilesInputs(
- EventHandler eventHandler, Location location) {
+ EventHandler eventHandler, Location location, @Nullable Artifact repoMappingManifest) {
ConflictChecker checker = new ConflictChecker(conflictPolicy, eventHandler, location);
Map<PathFragment, Artifact> manifest = getSymlinksAsMap(checker);
// Add artifacts (committed to inclusion on construction of runfiles).
@@ -417,6 +420,9 @@ public Map<PathFragment, Artifact> getRunfilesInputs(
checker = new ConflictChecker(ConflictPolicy.WARN, eventHandler, location);
}
builder.add(getRootSymlinksAsMap(checker), checker);
+ if (repoMappingManifest != null) {
+ checker.put(builder.manifest, PathFragment.create("_repo_mapping"), repoMappingManifest);
+ }
return builder.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
index 189cb882fe15d7..3772cf7cb700da 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
@@ -132,18 +132,20 @@ private static RunfilesSupport create(
}
Preconditions.checkState(!runfiles.isEmpty());
+ Artifact repoMappingManifest =
+ createRepoMappingManifestAction(ruleContext, runfiles, owningExecutable);
+
Artifact runfilesInputManifest;
Artifact runfilesManifest;
if (createManifest) {
runfilesInputManifest = createRunfilesInputManifestArtifact(ruleContext, owningExecutable);
runfilesManifest =
- createRunfilesAction(ruleContext, runfiles, buildRunfileLinks, runfilesInputManifest);
+ createRunfilesAction(
+ ruleContext, runfiles, buildRunfileLinks, runfilesInputManifest, repoMappingManifest);
} else {
runfilesInputManifest = null;
runfilesManifest = null;
}
- Artifact repoMappingManifest =
- createRepoMappingManifestAction(ruleContext, runfiles, owningExecutable);
Artifact runfilesMiddleman =
createRunfilesMiddleman(
ruleContext, owningExecutable, runfiles, runfilesManifest, repoMappingManifest);
@@ -387,7 +389,8 @@ private static Artifact createRunfilesAction(
ActionConstructionContext context,
Runfiles runfiles,
boolean createSymlinks,
- Artifact inputManifest) {
+ Artifact inputManifest,
+ @Nullable Artifact repoMappingManifest) {
// Compute the names of the runfiles directory and its MANIFEST file.
context
.getAnalysisEnvironment()
@@ -397,6 +400,7 @@ private static Artifact createRunfilesAction(
context.getActionOwner(),
inputManifest,
runfiles,
+ repoMappingManifest,
context.getConfiguration().remotableSourceManifestActions()));
if (!createSymlinks) {
@@ -423,6 +427,7 @@ private static Artifact createRunfilesAction(
inputManifest,
runfiles,
outputManifest,
+ repoMappingManifest,
/*filesetRoot=*/ null));
return outputManifest;
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java b/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
index 126c0e98548430..379c875b3d2141 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplier.java
@@ -34,10 +34,12 @@
/** {@link RunfilesSupplier} implementation wrapping a single {@link Runfiles} directory mapping. */
@AutoCodec
public final class SingleRunfilesSupplier implements RunfilesSupplier {
+
private final PathFragment runfilesDir;
private final Runfiles runfiles;
private final Supplier<Map<PathFragment, Artifact>> runfilesInputs;
@Nullable private final Artifact manifest;
+ @Nullable private final Artifact repoMappingManifest;
private final boolean buildRunfileLinks;
private final boolean runfileLinksEnabled;
@@ -50,14 +52,15 @@ public static SingleRunfilesSupplier create(RunfilesSupport runfilesSupport) {
runfilesSupport.getRunfiles(),
/*runfilesCachingEnabled=*/ false,
/*manifest=*/ null,
+ runfilesSupport.getRepoMappingManifest(),
runfilesSupport.isBuildRunfileLinks(),
runfilesSupport.isRunfilesEnabled());
}
/**
* Same as {@link SingleRunfilesSupplier#SingleRunfilesSupplier(PathFragment, Runfiles, Artifact,
- * boolean, boolean)}, except adds caching for {@linkplain Runfiles#getRunfilesInputs runfiles
- * inputs}.
+ * Artifact, boolean, boolean)}, except adds caching for {@linkplain Runfiles#getRunfilesInputs
+ * runfiles inputs}.
*
* <p>The runfiles inputs are computed lazily and softly cached. Caching is shared across
* instances created via {@link #withOverriddenRunfilesDir}.
@@ -65,6 +68,7 @@ public static SingleRunfilesSupplier create(RunfilesSupport runfilesSupport) {
public static SingleRunfilesSupplier createCaching(
PathFragment runfilesDir,
Runfiles runfiles,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
return new SingleRunfilesSupplier(
@@ -72,6 +76,7 @@ public static SingleRunfilesSupplier createCaching(
runfiles,
/*runfilesCachingEnabled=*/ true,
/*manifest=*/ null,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -92,6 +97,7 @@ public SingleRunfilesSupplier(
PathFragment runfilesDir,
Runfiles runfiles,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
this(
@@ -99,6 +105,7 @@ public SingleRunfilesSupplier(
runfiles,
/*runfilesCachingEnabled=*/ false,
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -108,15 +115,19 @@ private SingleRunfilesSupplier(
Runfiles runfiles,
boolean runfilesCachingEnabled,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
this(
runfilesDir,
runfiles,
runfilesCachingEnabled
- ? new RunfilesCacher(runfiles)
- : () -> runfiles.getRunfilesInputs(/*eventHandler=*/ null, /*location=*/ null),
+ ? new RunfilesCacher(runfiles, repoMappingManifest)
+ : () ->
+ runfiles.getRunfilesInputs(
+ /*eventHandler=*/ null, /*location=*/ null, repoMappingManifest),
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
@@ -126,6 +137,7 @@ private SingleRunfilesSupplier(
Runfiles runfiles,
Supplier<Map<PathFragment, Artifact>> runfilesInputs,
@Nullable Artifact manifest,
+ @Nullable Artifact repoMappingManifest,
boolean buildRunfileLinks,
boolean runfileLinksEnabled) {
checkArgument(!runfilesDir.isAbsolute());
@@ -133,6 +145,7 @@ private SingleRunfilesSupplier(
this.runfiles = checkNotNull(runfiles);
this.runfilesInputs = checkNotNull(runfilesInputs);
this.manifest = manifest;
+ this.repoMappingManifest = repoMappingManifest;
this.buildRunfileLinks = buildRunfileLinks;
this.runfileLinksEnabled = runfileLinksEnabled;
}
@@ -199,17 +212,21 @@ public SingleRunfilesSupplier withOverriddenRunfilesDir(PathFragment newRunfiles
runfiles,
runfilesInputs,
manifest,
+ repoMappingManifest,
buildRunfileLinks,
runfileLinksEnabled);
}
/** Softly caches the result of {@link Runfiles#getRunfilesInputs}. */
private static final class RunfilesCacher implements Supplier<Map<PathFragment, Artifact>> {
+
private final Runfiles runfiles;
+ @Nullable private final Artifact repoMappingManifest;
private volatile SoftReference<Map<PathFragment, Artifact>> ref = new SoftReference<>(null);
- RunfilesCacher(Runfiles runfiles) {
+ RunfilesCacher(Runfiles runfiles, @Nullable Artifact repoMappingManifest) {
this.runfiles = runfiles;
+ this.repoMappingManifest = repoMappingManifest;
}
@Override
@@ -221,7 +238,9 @@ public Map<PathFragment, Artifact> get() {
synchronized (this) {
result = ref.get();
if (result == null) {
- result = runfiles.getRunfilesInputs(/*eventHandler=*/ null, /*location=*/ null);
+ result =
+ runfiles.getRunfilesInputs(
+ /*eventHandler=*/ null, /*location=*/ null, repoMappingManifest);
ref = new SoftReference<>(result);
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java b/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
index 8ca38d37c50658..6feb2b91321df8 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/SourceManifestAction.java
@@ -61,7 +61,7 @@ public final class SourceManifestAction extends AbstractFileWriteAction {
private static final Comparator<Map.Entry<PathFragment, Artifact>> ENTRY_COMPARATOR =
(path1, path2) -> path1.getKey().getPathString().compareTo(path2.getKey().getPathString());
-
+ private final Artifact repoMappingManifest;
/**
* Interface for defining manifest formatting and reporting specifics. Implementations must be
* immutable.
@@ -118,7 +118,7 @@ void writeEntry(
@VisibleForTesting
SourceManifestAction(
ManifestWriter manifestWriter, ActionOwner owner, Artifact primaryOutput, Runfiles runfiles) {
- this(manifestWriter, owner, primaryOutput, runfiles, /*remotableSourceManifestActions=*/ false);
+ this(manifestWriter, owner, primaryOutput, runfiles, null, false);
}
/**
@@ -129,17 +129,20 @@ void writeEntry(
* @param owner the action owner
* @param primaryOutput the file to which to write the manifest
* @param runfiles runfiles
+ * @param repoMappingManifest the repository mapping manifest for runfiles
*/
public SourceManifestAction(
ManifestWriter manifestWriter,
ActionOwner owner,
Artifact primaryOutput,
Runfiles runfiles,
+ @Nullable Artifact repoMappingManifest,
boolean remotableSourceManifestActions) {
// The real set of inputs is computed in #getInputs().
super(owner, NestedSetBuilder.emptySet(Order.STABLE_ORDER), primaryOutput, false);
this.manifestWriter = manifestWriter;
this.runfiles = runfiles;
+ this.repoMappingManifest = repoMappingManifest;
this.remotableSourceManifestActions = remotableSourceManifestActions;
}
@@ -180,7 +183,9 @@ public synchronized NestedSet<Artifact> getInputs() {
@VisibleForTesting
public void writeOutputFile(OutputStream out, @Nullable EventHandler eventHandler)
throws IOException {
- writeFile(out, runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation()));
+ writeFile(
+ out,
+ runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation(), repoMappingManifest));
}
/**
@@ -202,7 +207,8 @@ public String getStarlarkContent() throws IOException {
@Override
public DeterministicWriter newDeterministicWriter(ActionExecutionContext ctx) {
final Map<PathFragment, Artifact> runfilesInputs =
- runfiles.getRunfilesInputs(ctx.getEventHandler(), getOwner().getLocation());
+ runfiles.getRunfilesInputs(
+ ctx.getEventHandler(), getOwner().getLocation(), repoMappingManifest);
return out -> writeFile(out, runfilesInputs);
}
@@ -247,6 +253,10 @@ protected void computeKey(
fp.addString(GUID);
fp.addBoolean(remotableSourceManifestActions);
runfiles.fingerprint(fp);
+ fp.addBoolean(repoMappingManifest != null);
+ if (repoMappingManifest != null) {
+ fp.addPath(repoMappingManifest.getExecPath());
+ }
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java b/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
index 14a06ca1511f5c..4a819506532e24 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeAction.java
@@ -49,6 +49,7 @@ public final class SymlinkTreeAction extends AbstractAction {
private final boolean enableRunfiles;
private final boolean inprocessSymlinkCreation;
private final boolean skipRunfilesManifests;
+ private final Artifact repoMappingManifest;
/**
* Creates SymlinkTreeAction instance.
@@ -59,6 +60,7 @@ public final class SymlinkTreeAction extends AbstractAction {
* @param runfiles the input runfiles
* @param outputManifest the generated symlink tree manifest (must have "MANIFEST" base name).
* Symlink tree root will be set to the artifact's parent directory.
+ * @param repoMappingManifest the repository mapping manifest
* @param filesetRoot non-null if this is a fileset symlink tree
*/
public SymlinkTreeAction(
@@ -67,12 +69,14 @@ public SymlinkTreeAction(
Artifact inputManifest,
@Nullable Runfiles runfiles,
Artifact outputManifest,
+ @Nullable Artifact repoMappingManifest,
String filesetRoot) {
this(
owner,
inputManifest,
runfiles,
outputManifest,
+ repoMappingManifest,
filesetRoot,
config.getActionEnvironment(),
config.runfilesEnabled(),
@@ -90,6 +94,7 @@ public SymlinkTreeAction(
* @param runfiles the input runfiles
* @param outputManifest the generated symlink tree manifest (must have "MANIFEST" base name).
* Symlink tree root will be set to the artifact's parent directory.
+ * @param repoMappingManifest the repository mapping manifest
* @param filesetRoot non-null if this is a fileset symlink tree,
*/
public SymlinkTreeAction(
@@ -97,6 +102,7 @@ public SymlinkTreeAction(
Artifact inputManifest,
@Nullable Runfiles runfiles,
Artifact outputManifest,
+ @Nullable Artifact repoMappingManifest,
@Nullable String filesetRoot,
ActionEnvironment env,
boolean enableRunfiles,
@@ -104,7 +110,8 @@ public SymlinkTreeAction(
boolean skipRunfilesManifests) {
super(
owner,
- computeInputs(enableRunfiles, skipRunfilesManifests, runfiles, inputManifest),
+ computeInputs(
+ enableRunfiles, skipRunfilesManifests, runfiles, inputManifest, repoMappingManifest),
ImmutableSet.of(outputManifest),
env);
Preconditions.checkArgument(outputManifest.getPath().getBaseName().equals("MANIFEST"));
@@ -118,13 +125,15 @@ public SymlinkTreeAction(
this.inprocessSymlinkCreation = inprocessSymlinkCreation;
this.skipRunfilesManifests = skipRunfilesManifests && enableRunfiles && (filesetRoot == null);
this.inputManifest = this.skipRunfilesManifests ? null : inputManifest;
+ this.repoMappingManifest = repoMappingManifest;
}
private static NestedSet<Artifact> computeInputs(
boolean enableRunfiles,
boolean skipRunfilesManifests,
Runfiles runfiles,
- Artifact inputManifest) {
+ Artifact inputManifest,
+ @Nullable Artifact repoMappingManifest) {
NestedSetBuilder<Artifact> inputs = NestedSetBuilder.<Artifact>stableOrder();
if (!skipRunfilesManifests || !enableRunfiles || runfiles == null) {
inputs.add(inputManifest);
@@ -134,6 +143,9 @@ private static NestedSet<Artifact> computeInputs(
// existing, so directory or file links can be made as appropriate.
if (enableRunfiles && runfiles != null && OS.getCurrent() == OS.WINDOWS) {
inputs.addTransitive(runfiles.getAllArtifacts());
+ if (repoMappingManifest != null) {
+ inputs.add(repoMappingManifest);
+ }
}
return inputs.build();
}
@@ -151,6 +163,11 @@ public Artifact getOutputManifest() {
return outputManifest;
}
+ @Nullable
+ public Artifact getRepoMappingManifest() {
+ return repoMappingManifest;
+ }
+
public boolean isFilesetTree() {
return filesetRoot != null;
}
@@ -201,6 +218,10 @@ protected void computeKey(
if (runfiles != null) {
runfiles.fingerprint(fp);
}
+ fp.addBoolean(repoMappingManifest != null);
+ if (repoMappingManifest != null) {
+ fp.addPath(repoMappingManifest.getExecPath());
+ }
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java b/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
index fc5dc61676466f..5d2e4371f1e177 100644
--- a/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
+++ b/src/main/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategy.java
@@ -151,7 +151,8 @@ private static Map<PathFragment, Artifact> runfilesToMap(
.getRunfiles()
.getRunfilesInputs(
action.getInputManifest() == null ? actionExecutionContext.getEventHandler() : null,
- action.getOwner().getLocation());
+ action.getOwner().getLocation(),
+ action.getRepoMappingManifest());
}
private static void createOutput(
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
index 4734c3a1754af8..df8b8aaa0b1225 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaBinary.java
@@ -495,6 +495,7 @@ public ConfiguredTarget create(RuleContext ruleContext)
// This matches the code below in collectDefaultRunfiles.
.addTransitiveArtifactsWrappedInStableOrder(common.getRuntimeClasspath())
.build(),
+ null,
true));
filesBuilder.add(runtimeClasspathArtifact);
| diff --git a/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java b/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
index 726b433670c331..cf908ce46c1651 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/test/TestActionBuilder.java
@@ -379,6 +379,7 @@ private TestParams createTestAction(int shards)
SingleRunfilesSupplier.createCaching(
runfilesSupport.getRunfilesDirectoryExecPath(),
runfilesSupport.getRunfiles(),
+ runfilesSupport.getRepoMappingManifest(),
runfilesSupport.isBuildRunfileLinks(),
runfilesSupport.isRunfilesEnabled());
} else {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java b/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
index ee17341d27ce32..fc0a713e1495af 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/SingleRunfilesSupplierTest.java
@@ -56,6 +56,7 @@ public void testGetArtifactsWithSingleMapping() {
PathFragment.create("notimportant"),
mkRunfiles(artifacts),
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
@@ -69,6 +70,7 @@ public void testGetManifestsWhenNone() {
PathFragment.create("ignored"),
Runfiles.EMPTY,
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(underTest.getManifests()).isEmpty();
@@ -82,6 +84,7 @@ public void testGetManifestsWhenSupplied() {
PathFragment.create("ignored"),
Runfiles.EMPTY,
manifest,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(underTest.getManifests()).containsExactly(manifest);
@@ -94,6 +97,7 @@ public void withOverriddenRunfilesDir() {
PathFragment.create("old"),
Runfiles.EMPTY,
ActionsTestUtil.createArtifact(rootDir, "manifest"),
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
PathFragment newDir = PathFragment.create("new");
@@ -115,6 +119,7 @@ public void withOverriddenRunfilesDir_noChange_sameObject() {
dir,
Runfiles.EMPTY,
ActionsTestUtil.createArtifact(rootDir, "manifest"),
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
assertThat(original.withOverriddenRunfilesDir(dir)).isSameInstanceAs(original);
@@ -126,12 +131,16 @@ public void cachedMappings() {
Runfiles runfiles = mkRunfiles(mkArtifacts("a", "b", "c"));
SingleRunfilesSupplier underTest =
SingleRunfilesSupplier.createCaching(
- dir, runfiles, /*buildRunfileLinks=*/ false, /*runfileLinksEnabled=*/ false);
+ dir,
+ runfiles,
+ /*repoMappingManifest=*/ null,
+ /*buildRunfileLinks=*/ false,
+ /*runfileLinksEnabled=*/ false);
Map<PathFragment, Map<PathFragment, Artifact>> mappings1 = underTest.getMappings();
Map<PathFragment, Map<PathFragment, Artifact>> mappings2 = underTest.getMappings();
- assertThat(mappings1).containsExactly(dir, runfiles.getRunfilesInputs(null, null));
+ assertThat(mappings1).containsExactly(dir, runfiles.getRunfilesInputs(null, null, null));
assertThat(mappings1).isEqualTo(mappings2);
assertThat(mappings1.get(dir)).isSameInstanceAs(mappings2.get(dir));
}
@@ -143,14 +152,18 @@ public void cachedMappings_sharedAcrossDirOverrides() {
Runfiles runfiles = mkRunfiles(mkArtifacts("a", "b", "c"));
SingleRunfilesSupplier original =
SingleRunfilesSupplier.createCaching(
- oldDir, runfiles, /*buildRunfileLinks=*/ false, /*runfileLinksEnabled=*/ false);
- SingleRunfilesSupplier overriden = original.withOverriddenRunfilesDir(newDir);
+ oldDir,
+ runfiles,
+ /*repoMappingManifest=*/ null,
+ /*buildRunfileLinks=*/ false,
+ /*runfileLinksEnabled=*/ false);
+ SingleRunfilesSupplier overridden = original.withOverriddenRunfilesDir(newDir);
Map<PathFragment, Map<PathFragment, Artifact>> mappingsOld = original.getMappings();
- Map<PathFragment, Map<PathFragment, Artifact>> mappingsNew = overriden.getMappings();
+ Map<PathFragment, Map<PathFragment, Artifact>> mappingsNew = overridden.getMappings();
- assertThat(mappingsOld).containsExactly(oldDir, runfiles.getRunfilesInputs(null, null));
- assertThat(mappingsNew).containsExactly(newDir, runfiles.getRunfilesInputs(null, null));
+ assertThat(mappingsOld).containsExactly(oldDir, runfiles.getRunfilesInputs(null, null, null));
+ assertThat(mappingsNew).containsExactly(newDir, runfiles.getRunfilesInputs(null, null, null));
assertThat(mappingsOld.get(newDir)).isSameInstanceAs(mappingsNew.get(oldDir));
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
index 49e3aba3e4c9e9..31a92732c2fb4a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
@@ -409,6 +409,7 @@ public void testInputManifestsRemovedIfSupplied() throws Exception {
PathFragment.create("destination"),
Runfiles.EMPTY,
manifest,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false))
.addOutput(getBinArtifactWithNoOwner("output"))
@@ -628,6 +629,7 @@ private static RunfilesSupplier runfilesSupplier(Artifact manifest, PathFragment
dir,
Runfiles.EMPTY,
manifest,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false);
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
index b849cf8733acbf..6ce4bcc2771442 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkTreeActionTest.java
@@ -70,6 +70,7 @@ public void testComputeKey() throws Exception {
? new Runfiles.Builder("TESTING", false).addArtifact(runfile).build()
: new Runfiles.Builder("TESTING", false).addArtifact(runfile2).build(),
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(
attributesToFlip.contains(RunfilesActionAttributes.FIXED_ENVIRONMENT),
@@ -85,6 +86,7 @@ public void testComputeKey() throws Exception {
inputManifest,
/*runfiles=*/ null,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ "root",
createActionEnvironment(
attributesToFlip.contains(FilesetActionAttributes.FIXED_ENVIRONMENT),
@@ -103,6 +105,7 @@ public void testComputeKey() throws Exception {
? new Runfiles.Builder("TESTING", false).addArtifact(runfile).build()
: new Runfiles.Builder("TESTING", false).addArtifact(runfile2).build(),
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(
attributesToFlip.contains(SkipManifestAttributes.FIXED_ENVIRONMENT),
@@ -131,6 +134,7 @@ public void testNullRunfilesThrows() {
inputManifest,
/*runfiles=*/ null,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
createActionEnvironment(false, false),
/*enableRunfiles=*/ true,
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
index 53b05d891bef9c..12fbcb55ec44f8 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestUtil.java
@@ -562,6 +562,7 @@ public static RunfilesSupplier createRunfilesSupplier(
runfilesDir,
runfiles,
/*manifest=*/ null,
+ /*repoMappingManifest=*/ null,
/*buildRunfileLinks=*/ false,
/*runfileLinksEnabled=*/ false);
}
diff --git a/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java b/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
index 839a4bb64dd615..ad7a7a5e8d2687 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/SymlinkTreeStrategyTest.java
@@ -92,6 +92,7 @@ public void outputServiceInteraction() throws Exception {
inputManifest,
runfiles,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
ActionEnvironment.EMPTY,
/*enableRunfiles=*/ true,
@@ -138,6 +139,7 @@ public void inprocessSymlinkCreation() throws Exception {
inputManifest,
runfiles,
outputManifest,
+ /*repoMappingManifest=*/ null,
/*filesetRoot=*/ null,
ActionEnvironment.EMPTY,
/*enableRunfiles=*/ true,
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
index ed7d6da4fb9d0a..ec40c1f7e85a51 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/LtoBackendActionTest.java
@@ -218,6 +218,7 @@ public Action generate(ImmutableSet<KeyAttributes> attributesToFlip) {
PathFragment.create("a"),
Runfiles.EMPTY,
artifactA,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false));
} else {
@@ -226,6 +227,7 @@ public Action generate(ImmutableSet<KeyAttributes> attributesToFlip) {
PathFragment.create("a"),
Runfiles.EMPTY,
artifactB,
+ /* repoMappingManifest= */ null,
/* buildRunfileLinks= */ false,
/* runfileLinksEnabled= */ false));
}
diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
index 3ecf4c1950728e..a04a2dc31a3abb 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java
@@ -1033,7 +1033,7 @@ public void testRunfilesSymlinkConflict() throws Exception {
" symlinks = {'sym1': ruleContext.files.srcs[1]})");
Runfiles runfiles = (Runfiles) result;
reporter.removeHandler(failFastHandler); // So it doesn't throw an exception.
- runfiles.getRunfilesInputs(reporter, null);
+ var unused = runfiles.getRunfilesInputs(reporter, null, null);
assertContainsEvent("ERROR <no location>: overwrote runfile");
}
diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 5312a26de2e708..301477560bb224 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -583,27 +583,29 @@ def testRunfilesRepoMappingManifest(self):
self.main_registry.setModuleBasePath('projects')
projects_dir = self.main_registry.projects
- # Set up a "bare_rule" module that contains the "bare_binary" rule which
+ # Set up a "bare_rule" module that contains the "bare_test" rule which
# passes runfiles along
self.main_registry.createLocalPathModule('bare_rule', '1.0', 'bare_rule')
projects_dir.joinpath('bare_rule').mkdir(exist_ok=True)
scratchFile(projects_dir.joinpath('bare_rule', 'WORKSPACE'))
scratchFile(projects_dir.joinpath('bare_rule', 'BUILD'))
+ # The working directory of a test is the subdirectory of the runfiles
+ # directory corresponding to the main repository.
scratchFile(
projects_dir.joinpath('bare_rule', 'defs.bzl'), [
- 'def _bare_binary_impl(ctx):',
+ 'def _bare_test_impl(ctx):',
' exe = ctx.actions.declare_file(ctx.label.name)',
' ctx.actions.write(exe,',
- ' "#/bin/bash\\nif [[ ! -f \\"$0.repo_mapping\\" ]]; then\\necho >&2 \\"ERROR: cannot find repo mapping manifest file\\"\\nexit 1\\nfi",',
+ ' "#/bin/bash\\nif [[ ! -f ../_repo_mapping || ! -s ../_repo_mapping ]]; then\\necho >&2 \\"ERROR: cannot find repo mapping manifest file\\"\\nexit 1\\nfi",',
' True)',
' runfiles = ctx.runfiles(files=ctx.files.data)',
' for data in ctx.attr.data:',
' runfiles = runfiles.merge(data[DefaultInfo].default_runfiles)',
' return DefaultInfo(files=depset(direct=[exe]), executable=exe, runfiles=runfiles)',
- 'bare_binary=rule(',
- ' implementation=_bare_binary_impl,',
+ 'bare_test=rule(',
+ ' implementation=_bare_test_impl,',
' attrs={"data":attr.label_list(allow_files=True)},',
- ' executable=True,',
+ ' test=True,',
')',
])
@@ -617,8 +619,8 @@ def testRunfilesRepoMappingManifest(self):
self.ScratchFile('WORKSPACE')
self.ScratchFile('WORKSPACE.bzlmod', ['workspace(name="me_ws")'])
self.ScratchFile('BUILD', [
- 'load("@bare_rule//:defs.bzl", "bare_binary")',
- 'bare_binary(name="me",data=["@foo"])',
+ 'load("@bare_rule//:defs.bzl", "bare_test")',
+ 'bare_test(name="me",data=["@foo"])',
])
self.main_registry.createLocalPathModule('foo', '1.0', 'foo', {
'quux': '1.0',
@@ -633,16 +635,16 @@ def testRunfilesRepoMappingManifest(self):
self.main_registry.createLocalPathModule('quux', '2.0', 'quux2',
{'bare_rule': '1.0'})
for dir_name, build_file in [
- ('foo', 'bare_binary(name="foo",data=["@quux"])'),
- ('bar', 'bare_binary(name="bar",data=["@quux"])'),
- ('quux1', 'bare_binary(name="quux")'),
- ('quux2', 'bare_binary(name="quux")'),
+ ('foo', 'bare_test(name="foo",data=["@quux"])'),
+ ('bar', 'bare_test(name="bar",data=["@quux"])'),
+ ('quux1', 'bare_test(name="quux")'),
+ ('quux2', 'bare_test(name="quux")'),
]:
projects_dir.joinpath(dir_name).mkdir(exist_ok=True)
scratchFile(projects_dir.joinpath(dir_name, 'WORKSPACE'))
scratchFile(
projects_dir.joinpath(dir_name, 'BUILD'), [
- 'load("@bare_rule//:defs.bzl", "bare_binary")',
+ 'load("@bare_rule//:defs.bzl", "bare_test")',
'package(default_visibility=["//visibility:public"])',
build_file,
])
@@ -650,25 +652,47 @@ def testRunfilesRepoMappingManifest(self):
# We use a shell script to check that the binary itself can see the repo
# mapping manifest. This obviously doesn't work on Windows, so we just build
# the target. TODO(wyv): make this work on Windows by using Batch.
- bazel_command = 'build' if self.IsWindows() else 'run'
+ # On Linux and macOS, the script is executed in the sandbox, so we verify
+ # that the repository mapping is present in it.
+ bazel_command = 'build' if self.IsWindows() else 'test'
# Finally we get to build stuff!
- self.RunBazel([bazel_command, '//:me'], allow_failure=False)
- with open(self.Path('bazel-bin/me.repo_mapping'), 'r') as f:
- self.assertEqual(
- f.read().strip(), """,foo,foo~1.0
+ exit_code, stderr, stdout = self.RunBazel(
+ [bazel_command, '//:me', '--test_output=errors'], allow_failure=True)
+ self.AssertExitCode(0, exit_code, stderr, stdout)
+
+ paths = ['bazel-bin/me.repo_mapping']
+ if not self.IsWindows():
+ paths.append('bazel-bin/me.runfiles/_repo_mapping')
+ for path in paths:
+ with open(self.Path(path), 'r') as f:
+ self.assertEqual(
+ f.read().strip(), """,foo,foo~1.0
,me,_main
,me_ws,_main
foo~1.0,foo,foo~1.0
foo~1.0,quux,quux~2.0
quux~2.0,quux,quux~2.0""")
- self.RunBazel([bazel_command, '@bar//:bar'], allow_failure=False)
- with open(self.Path('bazel-bin/external/bar~2.0/bar.repo_mapping'),
- 'r') as f:
- self.assertEqual(
- f.read().strip(), """bar~2.0,bar,bar~2.0
+ with open(self.Path('bazel-bin/me.runfiles_manifest')) as f:
+ self.assertIn('_repo_mapping ', f.read())
+
+ exit_code, stderr, stdout = self.RunBazel(
+ [bazel_command, '@bar//:bar', '--test_output=errors'],
+ allow_failure=True)
+ self.AssertExitCode(0, exit_code, stderr, stdout)
+
+ paths = ['bazel-bin/external/bar~2.0/bar.repo_mapping']
+ if not self.IsWindows():
+ paths.append('bazel-bin/external/bar~2.0/bar.runfiles/_repo_mapping')
+ for path in paths:
+ with open(self.Path(path), 'r') as f:
+ self.assertEqual(
+ f.read().strip(), """bar~2.0,bar,bar~2.0
bar~2.0,quux,quux~2.0
quux~2.0,quux,quux~2.0""")
+ with open(
+ self.Path('bazel-bin/external/bar~2.0/bar.runfiles_manifest')) as f:
+ self.assertIn('_repo_mapping ', f.read())
if __name__ == '__main__':
unittest.main()
| test | val | 2022-11-10T16:25:41 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16124_16736 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16736 | [
"keyword_pr_to_issue"
] | 5929cb72aa01768e6352898b1a056ef678c81d90 | 0f95c8a8a74d18823c3117d8f3370bc7301081b4 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-10T18:24:46Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java",
"tools/java/runfiles/BUILD",
"tools/java/runfiles/BUILD.tools"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java",
"tools/java/runfiles/AutoBazelRepository.java",
"tools/java/runfiles/AutoBazelRepositoryProcessor.java",
"tools/java/runfiles/BUILD",
"tools/java/runfiles/BUILD.tools"
] | [
"src/test/shell/bazel/bazel_java_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
index b382b1f39f7a36..313d1b07383d88 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java
@@ -371,9 +371,18 @@ public final void initializeJavacOpts() {
/** Computes javacopts for the current rule. */
private ImmutableList<String> computeJavacOpts(Collection<String> extraRuleJavacOpts) {
- return ImmutableList.<String>builder()
- .addAll(javaToolchain.getJavacOptions(ruleContext))
- .addAll(extraRuleJavacOpts)
+ ImmutableList.Builder<String> javacOpts =
+ ImmutableList.<String>builder()
+ .addAll(javaToolchain.getJavacOptions(ruleContext))
+ .addAll(extraRuleJavacOpts);
+ if (activePlugins
+ .plugins()
+ .processorClasses()
+ .toSet()
+ .contains("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor")) {
+ javacOpts.add("-Abazel.repository=" + ruleContext.getRepository().getName());
+ }
+ return javacOpts
.addAll(computePerPackageJavacOpts(ruleContext, javaToolchain))
.addAll(addModuleJavacopts(ruleContext))
.addAll(ruleContext.getExpander().withDataLocations().tokenized("javacopts"))
@@ -538,8 +547,8 @@ public JavaTargetAttributes.Builder initCommon() {
public JavaTargetAttributes.Builder initCommon(
Collection<Artifact> extraSrcs, Iterable<String> extraJavacOpts) {
Preconditions.checkState(javacOpts == null);
- javacOpts = computeJavacOpts(ImmutableList.copyOf(extraJavacOpts));
activePlugins = collectPlugins();
+ javacOpts = computeJavacOpts(ImmutableList.copyOf(extraJavacOpts));
JavaTargetAttributes.Builder javaTargetAttributes = new JavaTargetAttributes.Builder(semantics);
javaCompilationHelper =
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java
index 2a9d98e3b706d0..c732329beb2ce3 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfoBuildHelper.java
@@ -284,6 +284,28 @@ public JavaInfo createJavaCompileAction(
JavaToolchainProvider toolchainProvider = javaToolchain;
+ JavaPluginInfo pluginInfo = mergeExportedJavaPluginInfo(plugins, deps);
+ ImmutableList.Builder<String> allJavacOptsBuilder =
+ ImmutableList.<String>builder()
+ .addAll(toolchainProvider.getJavacOptions(starlarkRuleContext.getRuleContext()))
+ .addAll(
+ javaSemantics.getCompatibleJavacOptions(
+ starlarkRuleContext.getRuleContext(), toolchainProvider));
+ if (pluginInfo
+ .plugins()
+ .processorClasses()
+ .toSet()
+ .contains("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor")) {
+ allJavacOptsBuilder.add(
+ "-Abazel.repository=" + starlarkRuleContext.getRuleContext().getRepository().getName());
+ }
+ allJavacOptsBuilder
+ .addAll(
+ JavaCommon.computePerPackageJavacOpts(
+ starlarkRuleContext.getRuleContext(), toolchainProvider))
+ .addAll(JavaModuleFlagsProvider.toFlags(addExports, addOpens))
+ .addAll(tokenize(javacOpts));
+
JavaLibraryHelper helper =
new JavaLibraryHelper(starlarkRuleContext.getRuleContext())
.setOutput(outputJar)
@@ -295,18 +317,7 @@ public JavaInfo createJavaCompileAction(
.setSourcePathEntries(sourcepathEntries)
.addAdditionalOutputs(annotationProcessorAdditionalOutputs)
.enableJspecify(enableJSpecify)
- .setJavacOpts(
- ImmutableList.<String>builder()
- .addAll(toolchainProvider.getJavacOptions(starlarkRuleContext.getRuleContext()))
- .addAll(
- javaSemantics.getCompatibleJavacOptions(
- starlarkRuleContext.getRuleContext(), toolchainProvider))
- .addAll(
- JavaCommon.computePerPackageJavacOpts(
- starlarkRuleContext.getRuleContext(), toolchainProvider))
- .addAll(JavaModuleFlagsProvider.toFlags(addExports, addOpens))
- .addAll(tokenize(javacOpts))
- .build());
+ .setJavacOpts(allJavacOptsBuilder.build());
if (injectingRuleKind != Starlark.NONE) {
helper.setInjectingRuleKind((String) injectingRuleKind);
@@ -316,7 +327,6 @@ public JavaInfo createJavaCompileAction(
streamProviders(deps, JavaCompilationArgsProvider.class).forEach(helper::addDep);
streamProviders(exports, JavaCompilationArgsProvider.class).forEach(helper::addExport);
helper.setCompilationStrictDepsMode(getStrictDepsMode(Ascii.toUpperCase(strictDepsMode)));
- JavaPluginInfo pluginInfo = mergeExportedJavaPluginInfo(plugins, deps);
// Optimization: skip this if there are no annotation processors, to avoid unnecessarily
// disabling the direct classpath optimization if `enable_annotation_processor = False`
// but there aren't any annotation processors.
diff --git a/tools/java/runfiles/AutoBazelRepository.java b/tools/java/runfiles/AutoBazelRepository.java
new file mode 100644
index 00000000000000..6dc533001c299e
--- /dev/null
+++ b/tools/java/runfiles/AutoBazelRepository.java
@@ -0,0 +1,29 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.runfiles;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotating a class {@code Fooer} with this annotation generates a class {@code
+ * AutoBazelRepository_Fooer} defining a {@link String} constant {@code NAME} containing the
+ * canonical name of the repository containing the Bazel target that compiled the annotated class.
+ */
+@Retention(RetentionPolicy.SOURCE)
+@Target(ElementType.TYPE)
+public @interface AutoBazelRepository {}
diff --git a/tools/java/runfiles/AutoBazelRepositoryProcessor.java b/tools/java/runfiles/AutoBazelRepositoryProcessor.java
new file mode 100644
index 00000000000000..ae356d800f6d03
--- /dev/null
+++ b/tools/java/runfiles/AutoBazelRepositoryProcessor.java
@@ -0,0 +1,127 @@
+// Copyright 2022 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.
+
+package com.google.devtools.build.runfiles;
+
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toList;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Stream;
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.annotation.processing.SupportedOptions;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+import javax.tools.Diagnostic.Kind;
+
+/** Processor for {@link AutoBazelRepository}. */
+@SupportedAnnotationTypes("com.google.devtools.build.runfiles.AutoBazelRepository")
+@SupportedOptions(AutoBazelRepositoryProcessor.BAZEL_REPOSITORY_OPTION)
+public final class AutoBazelRepositoryProcessor extends AbstractProcessor {
+
+ static final String BAZEL_REPOSITORY_OPTION = "bazel.repository";
+
+ @Override
+ public SourceVersion getSupportedSourceVersion() {
+ return SourceVersion.latestSupported();
+ }
+
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+ annotations.stream()
+ .flatMap(element -> roundEnv.getElementsAnnotatedWith(element).stream())
+ .map(element -> (TypeElement) element)
+ .forEach(this::emitClass);
+ return true;
+ }
+
+ private void emitClass(TypeElement annotatedClass) {
+ // This option is always provided by the Java rule implementations.
+ if (!processingEnv.getOptions().containsKey(BAZEL_REPOSITORY_OPTION)) {
+ processingEnv
+ .getMessager()
+ .printMessage(
+ Kind.ERROR,
+ String.format(
+ "The %1$s annotation processor option is not set. To use this annotation"
+ + " processor, provide the canonical repository name of the current target as"
+ + " the value of the -A%1$s flag.",
+ BAZEL_REPOSITORY_OPTION),
+ annotatedClass);
+ return;
+ }
+ String repositoryName = processingEnv.getOptions().get(BAZEL_REPOSITORY_OPTION);
+ if (repositoryName == null) {
+ // javac translates '-Abazel.repository=' into a null value.
+ // https://github.com/openjdk/jdk/blob/7a49c9baa1d4ad7df90e7ca626ec48ba76881822/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java#L651
+ repositoryName = "";
+ }
+
+ // For a nested class Outer.Middle.Inner, generate a class with simple name
+ // AutoBazelRepository_Outer_Middle_Inner.
+ // Note: There can be collisions when local classes are involved, but since the definition of a
+ // class depends only on the containing Bazel target, this does not result in ambiguity.
+ List<String> nestedClassNames =
+ Stream.iterate(
+ annotatedClass,
+ element -> element instanceof TypeElement,
+ Element::getEnclosingElement)
+ .map(Element::getSimpleName)
+ .map(Name::toString)
+ .collect(toList());
+ Collections.reverse(nestedClassNames);
+ String generatedClassSimpleName =
+ Stream.concat(Stream.of("AutoBazelRepository"), nestedClassNames.stream())
+ .collect(joining("_"));
+
+ String generatedClassPackage =
+ processingEnv.getElementUtils().getPackageOf(annotatedClass).getQualifiedName().toString();
+
+ String generatedClassName =
+ generatedClassPackage.isEmpty()
+ ? generatedClassSimpleName
+ : generatedClassPackage + "." + generatedClassSimpleName;
+
+ try (PrintWriter out =
+ new PrintWriter(
+ processingEnv.getFiler().createSourceFile(generatedClassName).openWriter())) {
+ out.printf("package %s;\n", generatedClassPackage);
+ out.printf("\n");
+ out.printf("class %s {\n", generatedClassSimpleName);
+ out.printf(" /**\n");
+ out.printf(" * The canonical name of the repository containing the Bazel target that\n");
+ out.printf(" * compiled {@link %s}.\n", annotatedClass.getQualifiedName().toString());
+ out.printf(" */\n");
+ out.printf(" static final String NAME = \"%s\";\n", repositoryName);
+ out.printf("\n");
+ out.printf(" private %s() {}\n", generatedClassSimpleName);
+ out.printf("}\n");
+ } catch (IOException e) {
+ processingEnv
+ .getMessager()
+ .printMessage(
+ Kind.ERROR,
+ String.format("Failed to generate %s: %s", generatedClassName, e.getMessage()),
+ annotatedClass);
+ }
+ }
+}
diff --git a/tools/java/runfiles/BUILD b/tools/java/runfiles/BUILD
index fdd782d87db9dd..e0487a301761e0 100644
--- a/tools/java/runfiles/BUILD
+++ b/tools/java/runfiles/BUILD
@@ -26,6 +26,8 @@ filegroup(
filegroup(
name = "java-srcs",
srcs = [
+ "AutoBazelRepository.java",
+ "AutoBazelRepositoryProcessor.java",
"Runfiles.java",
"Util.java",
],
@@ -33,6 +35,22 @@ filegroup(
java_library(
name = "runfiles",
- srcs = [":java-srcs"],
+ srcs = [
+ "Runfiles.java",
+ "Util.java",
+ ],
+ exported_plugins = [":auto_bazel_repository_processor"],
visibility = ["//tools/java/runfiles/testing:__pkg__"],
+ exports = [":auto_bazel_repository"],
+)
+
+java_library(
+ name = "auto_bazel_repository",
+ srcs = ["AutoBazelRepository.java"],
+)
+
+java_plugin(
+ name = "auto_bazel_repository_processor",
+ srcs = ["AutoBazelRepositoryProcessor.java"],
+ processor_class = "com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor",
)
diff --git a/tools/java/runfiles/BUILD.tools b/tools/java/runfiles/BUILD.tools
index a2ac4f58cd0677..70cd870d46ff5f 100644
--- a/tools/java/runfiles/BUILD.tools
+++ b/tools/java/runfiles/BUILD.tools
@@ -4,5 +4,18 @@ java_library(
"Runfiles.java",
"Util.java",
],
+ exported_plugins = [":auto_bazel_repository_processor"],
visibility = ["//visibility:public"],
+ exports = [":auto_bazel_repository"],
+)
+
+java_library(
+ name = "auto_bazel_repository",
+ srcs = ["AutoBazelRepository.java"],
+)
+
+java_plugin(
+ name = "auto_bazel_repository_processor",
+ srcs = ["AutoBazelRepositoryProcessor.java"],
+ processor_class = "com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor",
)
| diff --git a/src/test/shell/bazel/bazel_java_test.sh b/src/test/shell/bazel/bazel_java_test.sh
index c11137ffc2f7dd..5e55ff302f6b1b 100755
--- a/src/test/shell/bazel/bazel_java_test.sh
+++ b/src/test/shell/bazel/bazel_java_test.sh
@@ -1763,5 +1763,191 @@ EOF
bazel build //java/main:C2 &>"${TEST_log}" || fail "Expected to build"
}
+function test_auto_bazel_repository() {
+ cat >> WORKSPACE <<'EOF'
+local_repository(
+ name = "other_repo",
+ path = "other_repo",
+)
+EOF
+
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+java_library(
+ name = "library",
+ srcs = ["Library.java"],
+ deps = ["@bazel_tools//tools/java/runfiles"],
+ visibility = ["//visibility:public"],
+)
+
+java_binary(
+ name = "binary",
+ srcs = ["Binary.java"],
+ main_class = "com.example.Binary",
+ deps = [
+ ":library",
+ "@bazel_tools//tools/java/runfiles",
+ ],
+)
+
+java_test(
+ name = "test",
+ srcs = ["Test.java"],
+ main_class = "com.example.Test",
+ use_testrunner = False,
+ deps = [
+ ":library",
+ "@bazel_tools//tools/java/runfiles",
+ ],
+)
+EOF
+
+ cat > pkg/Library.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+
+@AutoBazelRepository
+public class Library {
+ public static void printRepositoryName() {
+ System.out.printf("in pkg/Library.java: '%s'%n", AutoBazelRepository_Library.NAME);
+ }
+}
+EOF
+
+ cat > pkg/Binary.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+
+public class Binary {
+ @AutoBazelRepository
+ private static class Class1 {
+ }
+
+ public static void main(String[] args) {
+ System.out.printf("in pkg/Binary.java: '%s'%n", AutoBazelRepository_Binary_Class1.NAME);
+ Library.printRepositoryName();
+ }
+}
+EOF
+
+ cat > pkg/Test.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+
+public class Test {
+ private static class Class1 {
+ @AutoBazelRepository
+ private static class Class2 {
+ }
+ }
+
+ public static void main(String[] args) {
+ System.out.printf("in pkg/Test.java: '%s'%n", AutoBazelRepository_Test_Class1_Class2.NAME);
+ Library.printRepositoryName();
+ }
+}
+EOF
+
+ mkdir -p other_repo
+ touch other_repo/WORKSPACE
+
+ mkdir -p other_repo/pkg
+ cat > other_repo/pkg/BUILD.bazel <<'EOF'
+java_library(
+ name = "library2",
+ srcs = ["Library2.java"],
+ deps = ["@bazel_tools//tools/java/runfiles"],
+)
+
+java_binary(
+ name = "binary",
+ srcs = ["Binary.java"],
+ main_class = "com.example.Binary",
+ deps = [
+ ":library2",
+ "@//pkg:library",
+ "@bazel_tools//tools/java/runfiles",
+ ],
+)
+java_test(
+ name = "test",
+ srcs = ["Test.java"],
+ main_class = "com.example.Test",
+ use_testrunner = False,
+ deps = [
+ ":library2",
+ "@//pkg:library",
+ "@bazel_tools//tools/java/runfiles",
+ ],
+)
+EOF
+
+ cat > other_repo/pkg/Library2.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+
+@AutoBazelRepository
+public class Library2 {
+ public static void printRepositoryName() {
+ System.out.printf("in external/other_repo/pkg/Library2.java: '%s'%n", AutoBazelRepository_Library2.NAME);
+ }
+}
+EOF
+
+ cat > other_repo/pkg/Binary.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+import static com.example.AutoBazelRepository_Binary.NAME;
+
+@AutoBazelRepository
+public class Binary {
+ public static void main(String[] args) {
+ System.out.printf("in external/other_repo/pkg/Binary.java: '%s'%n", NAME);
+ Library2.printRepositoryName();
+ Library.printRepositoryName();
+ }
+}
+EOF
+
+ cat > other_repo/pkg/Test.java <<'EOF'
+package com.example;
+
+import com.google.devtools.build.runfiles.AutoBazelRepository;
+
+@AutoBazelRepository
+public class Test {
+ public static void main(String[] args) {
+ System.out.printf("in external/other_repo/pkg/Test.java: '%s'%n", AutoBazelRepository_Test.NAME);
+ Library2.printRepositoryName();
+ Library.printRepositoryName();
+ }
+}
+EOF
+
+ bazel run //pkg:binary &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in pkg/Binary.java: ''"
+ expect_log "in pkg/Library.java: ''"
+
+ bazel test --test_output=streamed //pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in pkg/Test.java: ''"
+ expect_log "in pkg/Library.java: ''"
+
+ bazel run @other_repo//pkg:binary &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in external/other_repo/pkg/Binary.java: 'other_repo'"
+ expect_log "in external/other_repo/pkg/Library2.java: 'other_repo'"
+ expect_log "in pkg/Library.java: ''"
+
+ bazel test --test_output=streamed \
+ @other_repo//pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in external/other_repo/pkg/Test.java: 'other_repo'"
+ expect_log "in external/other_repo/pkg/Library2.java: 'other_repo'"
+ expect_log "in pkg/Library.java: ''"
+}
+
run_suite "Java integration tests"
| train | val | 2022-11-10T17:31:35 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16124_16751 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16751 | [
"keyword_pr_to_issue"
] | feed6ce2d15268320dac6bf851223608c4fe5bd4 | a4a6b59a9250a22fc1a92df6a031fbe4be381d53 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-11T23:02:13Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"tools/java/runfiles/Runfiles.java"
] | [
"tools/java/runfiles/Runfiles.java"
] | [
"src/test/py/bazel/bzlmod/bazel_module_test.py",
"tools/java/runfiles/testing/BUILD",
"tools/java/runfiles/testing/RunfilesTest.java"
] | diff --git a/tools/java/runfiles/Runfiles.java b/tools/java/runfiles/Runfiles.java
index 9a3aa26c4517a9..171d1b2078ade4 100644
--- a/tools/java/runfiles/Runfiles.java
+++ b/tools/java/runfiles/Runfiles.java
@@ -17,12 +17,16 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.lang.ref.SoftReference;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
/**
* Runfiles lookup library for Bazel-built Java binaries and tests.
@@ -45,15 +49,58 @@
* import com.google.devtools.build.runfiles.Runfiles;
* </pre>
*
- * <p>3. Create a Runfiles object and use rlocation to look up runfile paths:
+ * <p>3. Create a {@link Preloaded} object:
*
* <pre>
* public void myFunction() {
- * Runfiles runfiles = Runfiles.create();
- * String path = runfiles.rlocation("my_workspace/path/to/my/data.txt");
+ * Runfiles.Preloaded runfiles = Runfiles.preload();
* ...
* </pre>
*
+ * <p>4. To look up a runfile, use either of the following approaches:
+ *
+ * <p>4a. Annotate the class from which runfiles should be looked up with {@link
+ * AutoBazelRepository} and obtain the name of the Bazel repository containing the class from a
+ * constant generated by this annotation:
+ *
+ * <pre>
+ * import com.google.devtools.build.runfiles.AutoBazelRepository;
+ * @AutoBazelRepository
+ * public class MyClass {
+ * public void myFunction() {
+ * Runfiles.Preloaded runfiles = Runfiles.preload();
+ * String path = runfiles.withSourceRepository(AutoBazelRepository_MyClass.NAME)
+ * .rlocation("my_workspace/path/to/my/data.txt");
+ * ...
+ *
+ * </pre>
+ *
+ * <p>4b. Let Bazel compute the path passed to rlocation and pass it into a <code>java_binary</code>
+ * via an argument or an environment variable:
+ *
+ * <pre>
+ * java_binary(
+ * name = "my_binary",
+ * srcs = ["MyClass.java"],
+ * data = ["@my_workspace//path/to/my:data.txt"],
+ * env = {"MY_RUNFILE": "$(rlocationpath @my_workspace//path/to/my:data.txt)"},
+ * )
+ * </pre>
+ *
+ * <pre>
+ * public class MyClass {
+ * public void myFunction() {
+ * Runfiles.Preloaded runfiles = Runfiles.preload();
+ * String path = runfiles.unmapped().rlocation(System.getenv("MY_RUNFILE"));
+ * ...
+ *
+ * </pre>
+ *
+ * For more details on why it is required to pass in the current repository name, see {@see
+ * https://bazel.build/build/bzlmod#repository-names}.
+ *
+ * <h3>Subprocesses</h3>
+ *
* <p>If you want to start subprocesses that also need runfiles, you need to set the right
* environment variables for them:
*
@@ -64,23 +111,135 @@
* ...
* Process p = pb.start();
* </pre>
+ *
+ * <h3>{@link Preloaded} vs. {@link Runfiles}</h3>
+ *
+ * <p>Instances of {@link Preloaded} are meant to be stored and passed around to other components
+ * that need to access runfiles. They are created by calling {@link Runfiles#preload()} {@link
+ * Runfiles#preload(Map)} and immutably encapsulate all data required to look up runfiles with the
+ * repository mapping of any Bazel repository specified at a later time.
+ *
+ * <p>Creating {@link Runfiles} instances can be costly, so applications should try to create as few
+ * instances as possible. {@link Runfiles#preload()}, but not {@link Runfiles#preload(Map)}, returns
+ * a single global, softly cached instance of {@link Preloaded} that is constructed based on the
+ * JVM's environment variables.
+ *
+ * <p>Instance of {@link Runfiles} are only meant to be used by code located in a single Bazel
+ * repository and should not be passed around. They are created by calling {@link
+ * Preloaded#withSourceRepository(String)} or {@link Preloaded#unmapped()} and in addition to the
+ * data in {@link Preloaded} also fix a source repository relative to which apparent repository
+ * names are resolved.
+ *
+ * <p>Creating {@link Preloaded} instances is cheap.
*/
-public abstract class Runfiles {
+public final class Runfiles {
+
+ /**
+ * A class that encapsulates all data required to look up runfiles relative to any Bazel
+ * repository fixed at a later time.
+ *
+ * <p>This class is immutable.
+ */
+ public abstract static class Preloaded {
+
+ /** See {@link com.google.devtools.build.lib.analysis.RepoMappingManifestAction.Entry}. */
+ static class RepoMappingKey {
+
+ public final String sourceRepo;
+ public final String targetRepoApparentName;
+
+ public RepoMappingKey(String sourceRepo, String targetRepoApparentName) {
+ this.sourceRepo = sourceRepo;
+ this.targetRepoApparentName = targetRepoApparentName;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || !(o instanceof RepoMappingKey)) {
+ return false;
+ }
+ RepoMappingKey that = (RepoMappingKey) o;
+ return sourceRepo.equals(that.sourceRepo)
+ && targetRepoApparentName.equals(that.targetRepoApparentName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(sourceRepo, targetRepoApparentName);
+ }
+ }
+
+ /**
+ * Returns a {@link Runfiles} instance that uses the provided source repository's repository
+ * mapping to translate apparent into canonical repository names.
+ *
+ * <p>{@see https://bazel.build/build/bzlmod#repository-names}
+ *
+ * @param sourceRepository the canonical name of the Bazel repository relative to which apparent
+ * repository names should be resolved. Should generally coincide with the Bazel repository
+ * that contains the caller of this method, which can be obtained via {@link
+ * AutoBazelRepository}.
+ * @return a {@link Runfiles} instance that looks up runfiles relative to the provided source
+ * repository and shares all other data with this {@link Preloaded} instance.
+ */
+ public final Runfiles withSourceRepository(String sourceRepository) {
+ Util.checkArgument(sourceRepository != null);
+ return new Runfiles(this, sourceRepository);
+ }
+
+ /**
+ * Returns a {@link Runfiles} instance backed by the preloaded runfiles data that can be used to
+ * look up runfiles paths with canonical repository names only.
+ *
+ * @return a {@link Runfiles} instance that can only look up paths with canonical repository
+ * names and shared all data with this {@link Preloaded} instance.
+ */
+ public final Runfiles unmapped() {
+ return new Runfiles(this, null);
+ }
- // Package-private constructor, so only package-private classes may extend it.
- private Runfiles() {}
+ protected abstract Map<String, String> getEnvVars();
+
+ protected abstract String rlocationChecked(String path);
+
+ protected abstract Map<RepoMappingKey, String> getRepoMapping();
+
+ // Private constructor, so only nested classes may extend it.
+ private Preloaded() {}
+ }
+
+ private static final String MAIN_REPOSITORY = "";
+
+ private static SoftReference<Preloaded> defaultInstance = new SoftReference<>(null);
+
+ private final Preloaded preloadedRunfiles;
+ private final String sourceRepository;
+
+ private Runfiles(Preloaded preloadedRunfiles, String sourceRepository) {
+ this.preloadedRunfiles = preloadedRunfiles;
+ this.sourceRepository = sourceRepository;
+ }
/**
- * Returns a new {@link Runfiles} instance.
+ * Returns the softly cached global {@link Runfiles.Preloaded} instance, creating it if needed.
*
* <p>This method passes the JVM's environment variable map to {@link #create(Map)}.
*/
- public static Runfiles create() throws IOException {
- return create(System.getenv());
+ public static synchronized Preloaded preload() throws IOException {
+ Preloaded instance = defaultInstance.get();
+ if (instance != null) {
+ return instance;
+ }
+ instance = preload(System.getenv());
+ defaultInstance = new SoftReference<>(instance);
+ return instance;
}
/**
- * Returns a new {@link Runfiles} instance.
+ * Returns a new {@link Runfiles.Preloaded} instance.
*
* <p>The returned object is either:
*
@@ -104,7 +263,7 @@ public static Runfiles create() throws IOException {
* "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", or "JAVA_RUNFILES" key in {@code env} or their
* values are empty, or some IO error occurs
*/
- public static Runfiles create(Map<String, String> env) throws IOException {
+ public static Preloaded preload(Map<String, String> env) throws IOException {
if (isManifestOnly(env)) {
// On Windows, Bazel sets RUNFILES_MANIFEST_ONLY=1.
// On every platform, Bazel also sets RUNFILES_MANIFEST_FILE, but on Linux and macOS it's
@@ -115,6 +274,51 @@ public static Runfiles create(Map<String, String> env) throws IOException {
}
}
+ /**
+ * Returns a new {@link Runfiles} instance.
+ *
+ * <p>This method passes the JVM's environment variable map to {@link #create(Map)}.
+ *
+ * @deprecated Use {@link #preload()} instead. With {@code --enable_bzlmod}, this function does
+ * not work correctly.
+ */
+ @Deprecated
+ public static Runfiles create() throws IOException {
+ return preload().withSourceRepository(MAIN_REPOSITORY);
+ }
+
+ /**
+ * Returns a new {@link Runfiles} instance.
+ *
+ * <p>The returned object is either:
+ *
+ * <ul>
+ * <li>manifest-based, meaning it looks up runfile paths from a manifest file, or
+ * <li>directory-based, meaning it looks up runfile paths under a given directory path
+ * </ul>
+ *
+ * <p>If {@code env} contains "RUNFILES_MANIFEST_ONLY" with value "1", this method returns a
+ * manifest-based implementation. The manifest's path is defined by the "RUNFILES_MANIFEST_FILE"
+ * key's value in {@code env}.
+ *
+ * <p>Otherwise this method returns a directory-based implementation. The directory's path is
+ * defined by the value in {@code env} under the "RUNFILES_DIR" key, or if absent, then under the
+ * "JAVA_RUNFILES" key.
+ *
+ * <p>Note about performance: the manifest-based implementation eagerly reads and caches the whole
+ * manifest file upon instantiation.
+ *
+ * @throws IOException if RUNFILES_MANIFEST_ONLY=1 is in {@code env} but there's no
+ * "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", or "JAVA_RUNFILES" key in {@code env} or their
+ * values are empty, or some IO error occurs
+ * @deprecated Use {@link #preload(Map)} instead. With {@code --enable_bzlmod}, this function does
+ * not work correctly.
+ */
+ @Deprecated
+ public static Runfiles create(Map<String, String> env) throws IOException {
+ return preload(env).withSourceRepository(MAIN_REPOSITORY);
+ }
+
/**
* Returns the runtime path of a runfile (a Bazel-built binary's/test's data-dependency).
*
@@ -128,7 +332,7 @@ public static Runfiles create(Map<String, String> env) throws IOException {
* @throws IllegalArgumentException if {@code path} fails validation, for example if it's null or
* empty, or not normalized (contains "./", "../", or "//")
*/
- public final String rlocation(String path) {
+ public String rlocation(String path) {
Util.checkArgument(path != null);
Util.checkArgument(!path.isEmpty());
Util.checkArgument(
@@ -145,7 +349,22 @@ public final String rlocation(String path) {
if (new File(path).isAbsolute()) {
return path;
}
- return rlocationChecked(path);
+
+ if (sourceRepository == null) {
+ return preloadedRunfiles.rlocationChecked(path);
+ }
+ String[] apparentTargetAndRemainder = path.split("/", 2);
+ if (apparentTargetAndRemainder.length < 2) {
+ return preloadedRunfiles.rlocationChecked(path);
+ }
+ String targetCanonical =
+ preloadedRunfiles
+ .getRepoMapping()
+ .getOrDefault(
+ new Preloaded.RepoMappingKey(sourceRepository, apparentTargetAndRemainder[0]),
+ apparentTargetAndRemainder[0]);
+ return preloadedRunfiles.rlocationChecked(
+ targetCanonical + "/" + apparentTargetAndRemainder[1]);
}
/**
@@ -154,7 +373,9 @@ public final String rlocation(String path) {
* <p>The caller should add the returned key-value pairs to the environment of subprocesses in
* case those subprocesses are also Bazel-built binaries that need to use runfiles.
*/
- public abstract Map<String, String> getEnvVars();
+ public Map<String, String> getEnvVars() {
+ return preloadedRunfiles.getEnvVars();
+ }
/** Returns true if the platform supports runfiles only via manifests. */
private static boolean isManifestOnly(Map<String, String> env) {
@@ -183,50 +404,49 @@ private static String getRunfilesDir(Map<String, String> env) throws IOException
return value;
}
- abstract String rlocationChecked(String path);
+ private static Map<Preloaded.RepoMappingKey, String> loadRepositoryMapping(String path)
+ throws IOException {
+ if (path == null || !new File(path).exists()) {
+ return Collections.emptyMap();
+ }
+
+ try (BufferedReader r = new BufferedReader(new FileReader(path, StandardCharsets.UTF_8))) {
+ return Collections.unmodifiableMap(
+ r.lines()
+ .filter(line -> !line.isEmpty())
+ .map(
+ line -> {
+ String[] split = line.split(",");
+ if (split.length != 3) {
+ throw new IllegalArgumentException(
+ "Invalid line in repository mapping: '" + line + "'");
+ }
+ return split;
+ })
+ .collect(
+ Collectors.toMap(
+ split -> new Preloaded.RepoMappingKey(split[0], split[1]),
+ split -> split[2])));
+ }
+ }
/** {@link Runfiles} implementation that parses a runfiles-manifest file to look up runfiles. */
- private static final class ManifestBased extends Runfiles {
+ private static final class ManifestBased extends Runfiles.Preloaded {
+
private final Map<String, String> runfiles;
private final String manifestPath;
+ private final Map<RepoMappingKey, String> repoMapping;
ManifestBased(String manifestPath) throws IOException {
Util.checkArgument(manifestPath != null);
Util.checkArgument(!manifestPath.isEmpty());
this.manifestPath = manifestPath;
this.runfiles = loadRunfiles(manifestPath);
- }
-
- private static Map<String, String> loadRunfiles(String path) throws IOException {
- HashMap<String, String> result = new HashMap<>();
- try (BufferedReader r =
- new BufferedReader(
- new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
- String line = null;
- while ((line = r.readLine()) != null) {
- int index = line.indexOf(' ');
- String runfile = (index == -1) ? line : line.substring(0, index);
- String realPath = (index == -1) ? line : line.substring(index + 1);
- result.put(runfile, realPath);
- }
- }
- return Collections.unmodifiableMap(result);
- }
-
- private static String findRunfilesDir(String manifest) {
- if (manifest.endsWith("/MANIFEST")
- || manifest.endsWith("\\MANIFEST")
- || manifest.endsWith(".runfiles_manifest")) {
- String path = manifest.substring(0, manifest.length() - 9);
- if (new File(path).isDirectory()) {
- return path;
- }
- }
- return "";
+ this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping"));
}
@Override
- public String rlocationChecked(String path) {
+ protected String rlocationChecked(String path) {
String exactMatch = runfiles.get(path);
if (exactMatch != null) {
return exactMatch;
@@ -245,7 +465,7 @@ public String rlocationChecked(String path) {
}
@Override
- public Map<String, String> getEnvVars() {
+ protected Map<String, String> getEnvVars() {
HashMap<String, String> result = new HashMap<>(4);
result.put("RUNFILES_MANIFEST_ONLY", "1");
result.put("RUNFILES_MANIFEST_FILE", manifestPath);
@@ -255,25 +475,66 @@ public Map<String, String> getEnvVars() {
result.put("JAVA_RUNFILES", runfilesDir);
return result;
}
+
+ @Override
+ protected Map<RepoMappingKey, String> getRepoMapping() {
+ return repoMapping;
+ }
+
+ private static Map<String, String> loadRunfiles(String path) throws IOException {
+ HashMap<String, String> result = new HashMap<>();
+ try (BufferedReader r =
+ new BufferedReader(
+ new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
+ String line = null;
+ while ((line = r.readLine()) != null) {
+ int index = line.indexOf(' ');
+ String runfile = (index == -1) ? line : line.substring(0, index);
+ String realPath = (index == -1) ? line : line.substring(index + 1);
+ result.put(runfile, realPath);
+ }
+ }
+ return Collections.unmodifiableMap(result);
+ }
+
+ private static String findRunfilesDir(String manifest) {
+ if (manifest.endsWith("/MANIFEST")
+ || manifest.endsWith("\\MANIFEST")
+ || manifest.endsWith(".runfiles_manifest")) {
+ String path = manifest.substring(0, manifest.length() - 9);
+ if (new File(path).isDirectory()) {
+ return path;
+ }
+ }
+ return "";
+ }
}
/** {@link Runfiles} implementation that appends runfiles paths to the runfiles root. */
- private static final class DirectoryBased extends Runfiles {
+ private static final class DirectoryBased extends Preloaded {
+
private final String runfilesRoot;
+ private final Map<RepoMappingKey, String> repoMapping;
- DirectoryBased(String runfilesDir) {
+ DirectoryBased(String runfilesDir) throws IOException {
Util.checkArgument(!Util.isNullOrEmpty(runfilesDir));
Util.checkArgument(new File(runfilesDir).isDirectory());
this.runfilesRoot = runfilesDir;
+ this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping"));
}
@Override
- String rlocationChecked(String path) {
+ protected String rlocationChecked(String path) {
return runfilesRoot + "/" + path;
}
@Override
- public Map<String, String> getEnvVars() {
+ protected Map<RepoMappingKey, String> getRepoMapping() {
+ return repoMapping;
+ }
+
+ @Override
+ protected Map<String, String> getEnvVars() {
HashMap<String, String> result = new HashMap<>(2);
result.put("RUNFILES_DIR", runfilesRoot);
// TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can pick up RUNFILES_DIR.
@@ -282,11 +543,11 @@ public Map<String, String> getEnvVars() {
}
}
- static Runfiles createManifestBasedForTesting(String manifestPath) throws IOException {
+ static Preloaded createManifestBasedForTesting(String manifestPath) throws IOException {
return new ManifestBased(manifestPath);
}
- static Runfiles createDirectoryBasedForTesting(String runfilesDir) {
+ static Preloaded createDirectoryBasedForTesting(String runfilesDir) throws IOException {
return new DirectoryBased(runfilesDir);
}
}
| diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 301477560bb224..b9fd78688c8d49 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -694,5 +694,73 @@ def testRunfilesRepoMappingManifest(self):
self.Path('bazel-bin/external/bar~2.0/bar.runfiles_manifest')) as f:
self.assertIn('_repo_mapping ', f.read())
+ def testJavaRunfilesLibraryRepoMapping(self):
+ self.main_registry.setModuleBasePath('projects')
+ projects_dir = self.main_registry.projects
+
+ self.main_registry.createLocalPathModule('data', '1.0', 'data')
+ projects_dir.joinpath('data').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('data', 'WORKSPACE'))
+ scratchFile(projects_dir.joinpath('data', 'foo.txt'), ['hello'])
+ scratchFile(
+ projects_dir.joinpath('data', 'BUILD'), ['exports_files(["foo.txt"])'])
+
+ self.main_registry.createLocalPathModule('test', '1.0', 'test',
+ {'data': '1.0'})
+ projects_dir.joinpath('test').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('test', 'WORKSPACE'))
+ scratchFile(
+ projects_dir.joinpath('test', 'BUILD'), [
+ 'java_test(',
+ ' name = "test",',
+ ' srcs = ["Test.java"],',
+ ' main_class = "com.example.Test",',
+ ' use_testrunner = False,',
+ ' data = ["@data//:foo.txt"],',
+ ' args = ["$(rlocationpath @data//:foo.txt)"],',
+ ' deps = ["@bazel_tools//tools/java/runfiles"],',
+ ')',
+ ])
+ scratchFile(
+ projects_dir.joinpath('test', 'Test.java'), [
+ 'package com.example;',
+ '',
+ 'import com.google.devtools.build.runfiles.AutoBazelRepository;',
+ 'import com.google.devtools.build.runfiles.Runfiles;',
+ '',
+ 'import java.io.File;',
+ 'import java.io.IOException;',
+ '',
+ '@AutoBazelRepository',
+ 'public class Test {',
+ ' public static void main(String[] args) throws IOException {',
+ ' Runfiles.Preloaded rp = Runfiles.preload();',
+ ' if (!new File(rp.unmapped().rlocation(args[0])).exists()) {',
+ ' System.exit(1);',
+ ' }',
+ ' if (!new File(rp.withSourceRepository(AutoBazelRepository_Test.NAME).rlocation("data/foo.txt")).exists()) {',
+ ' System.exit(1);',
+ ' }',
+ ' }',
+ '}',
+ ])
+
+ self.ScratchFile('MODULE.bazel', ['bazel_dep(name="test",version="1.0")'])
+ self.ScratchFile('WORKSPACE')
+
+ # Run sandboxed on Linux and macOS.
+ exit_code, stderr, stdout = self.RunBazel([
+ 'test', '@test//:test', '--test_output=errors',
+ '--test_env=RUNFILES_LIB_DEBUG=1'
+ ],
+ allow_failure=True)
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+ # Run unsandboxed on all platforms.
+ exit_code, stderr, stdout = self.RunBazel(
+ ['run', '@test//:test'],
+ allow_failure=True,
+ env_add={'RUNFILES_LIB_DEBUG': '1'})
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tools/java/runfiles/testing/BUILD b/tools/java/runfiles/testing/BUILD
index 82d7836e16cde3..841724b36dc453 100644
--- a/tools/java/runfiles/testing/BUILD
+++ b/tools/java/runfiles/testing/BUILD
@@ -36,7 +36,6 @@ java_library(
name = "test_deps",
testonly = 1,
exports = [
- ":mock-file",
"//third_party:guava",
"//third_party:guava-testlib",
"//third_party:junit4",
@@ -44,11 +43,3 @@ java_library(
"//tools/java/runfiles",
],
)
-
-java_library(
- name = "mock-file",
- testonly = 1,
- srcs = ["MockFile.java"],
- exports = ["//third_party:guava"],
- deps = ["//third_party:guava"],
-)
diff --git a/tools/java/runfiles/testing/MockFile.java b/tools/java/runfiles/testing/MockFile.java
deleted file mode 100644
index 886bfcbcc82a38..00000000000000
--- a/tools/java/runfiles/testing/MockFile.java
+++ /dev/null
@@ -1,45 +0,0 @@
-// 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.
-
-package com.google.devtools.build.runfiles;
-
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-import java.io.Closeable;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-final class MockFile implements Closeable {
-
- public final Path path;
-
- public MockFile(ImmutableList<String> lines) throws IOException {
- String testTmpdir = System.getenv("TEST_TMPDIR");
- if (Strings.isNullOrEmpty(testTmpdir)) {
- throw new IOException("$TEST_TMPDIR is empty or undefined");
- }
- path = Files.createTempFile(new File(testTmpdir).toPath(), null, null);
- Files.write(path, lines, StandardCharsets.UTF_8);
- }
-
- @Override
- public void close() throws IOException {
- if (path != null) {
- Files.delete(path);
- }
- }
-}
diff --git a/tools/java/runfiles/testing/RunfilesTest.java b/tools/java/runfiles/testing/RunfilesTest.java
index e98ca554a8a27d..8b88ce28bd4e3d 100644
--- a/tools/java/runfiles/testing/RunfilesTest.java
+++ b/tools/java/runfiles/testing/RunfilesTest.java
@@ -25,10 +25,11 @@
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -36,6 +37,9 @@
@RunWith(JUnit4.class)
public final class RunfilesTest {
+ @Rule
+ public TemporaryFolder tempDir = new TemporaryFolder(new File(System.getenv("TEST_TMPDIR")));
+
private static boolean isWindows() {
return File.separatorChar == '\\';
}
@@ -44,7 +48,7 @@ private void assertRlocationArg(Runfiles runfiles, String path, @Nullable String
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> runfiles.rlocation(path));
if (error != null) {
- assertThat(e).hasMessageThat().contains(error);
+ assertThat(e).hasMessageThat().contains(error);
}
}
@@ -71,24 +75,23 @@ public void testRlocationArgumentValidation() throws Exception {
@Test
public void testCreatesManifestBasedRunfiles() throws Exception {
- try (MockFile mf = new MockFile(ImmutableList.of("a/b c/d"))) {
- Runfiles r =
- Runfiles.create(
- ImmutableMap.of(
- "RUNFILES_MANIFEST_ONLY", "1",
- "RUNFILES_MANIFEST_FILE", mf.path.toString(),
- "RUNFILES_DIR", "ignored when RUNFILES_MANIFEST_ONLY=1",
- "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value",
- "TEST_SRCDIR", "should always be ignored"));
- assertThat(r.rlocation("a/b")).isEqualTo("c/d");
- assertThat(r.rlocation("foo")).isNull();
-
- if (isWindows()) {
- assertThat(r.rlocation("c:/foo")).isEqualTo("c:/foo");
- assertThat(r.rlocation("c:\\foo")).isEqualTo("c:\\foo");
- } else {
- assertThat(r.rlocation("/foo")).isEqualTo("/foo");
- }
+ Path mf = tempFile("foo.runfiles_manifest", ImmutableList.of("a/b c/d"));
+ Runfiles r =
+ Runfiles.create(
+ ImmutableMap.of(
+ "RUNFILES_MANIFEST_ONLY", "1",
+ "RUNFILES_MANIFEST_FILE", mf.toString(),
+ "RUNFILES_DIR", "ignored when RUNFILES_MANIFEST_ONLY=1",
+ "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value",
+ "TEST_SRCDIR", "should always be ignored"));
+ assertThat(r.rlocation("a/b")).isEqualTo("c/d");
+ assertThat(r.rlocation("foo")).isNull();
+
+ if (isWindows()) {
+ assertThat(r.rlocation("c:/foo")).isEqualTo("c:/foo");
+ assertThat(r.rlocation("c:\\foo")).isEqualTo("c:\\foo");
+ } else {
+ assertThat(r.rlocation("/foo")).isEqualTo("/foo");
}
}
@@ -143,11 +146,14 @@ public void testIgnoresTestSrcdirWhenJavaRunfilesIsUndefinedAndJustFails() throw
() ->
Runfiles.create(
ImmutableMap.of(
- "RUNFILES_DIR", "",
- "JAVA_RUNFILES", "",
+ "RUNFILES_DIR",
+ "",
+ "JAVA_RUNFILES",
+ "",
"RUNFILES_MANIFEST_FILE",
- "ignored when RUNFILES_MANIFEST_ONLY is not set to 1",
- "TEST_SRCDIR", "should always be ignored")));
+ "ignored when RUNFILES_MANIFEST_ONLY is not set to 1",
+ "TEST_SRCDIR",
+ "should always be ignored")));
assertThat(e).hasMessageThat().contains("$RUNFILES_DIR and $JAVA_RUNFILES");
}
@@ -166,12 +172,7 @@ public void testFailsToCreateManifestBasedBecauseManifestDoesNotExist() {
@Test
public void testManifestBasedEnvVars() throws Exception {
- Path dir =
- Files.createTempDirectory(
- FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR")), null);
-
- Path mf = dir.resolve("MANIFEST");
- Files.write(mf, Collections.emptyList(), StandardCharsets.UTF_8);
+ Path mf = tempFile("MANIFEST", ImmutableList.of());
Map<String, String> envvars =
Runfiles.create(
ImmutableMap.of(
@@ -186,13 +187,12 @@ public void testManifestBasedEnvVars() throws Exception {
"RUNFILES_MANIFEST_ONLY", "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", "JAVA_RUNFILES");
assertThat(envvars.get("RUNFILES_MANIFEST_ONLY")).isEqualTo("1");
assertThat(envvars.get("RUNFILES_MANIFEST_FILE")).isEqualTo(mf.toString());
- assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(dir.toString());
- assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(dir.toString());
+ assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(tempDir.getRoot().toString());
+ assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(tempDir.getRoot().toString());
- Path rfDir = dir.resolve("foo.runfiles");
+ Path rfDir = tempDir.getRoot().toPath().resolve("foo.runfiles");
Files.createDirectories(rfDir);
- mf = dir.resolve("foo.runfiles_manifest");
- Files.write(mf, Collections.emptyList(), StandardCharsets.UTF_8);
+ mf = tempFile("foo.runfiles_manifest", ImmutableList.of());
envvars =
Runfiles.create(
ImmutableMap.of(
@@ -210,81 +210,371 @@ public void testManifestBasedEnvVars() throws Exception {
@Test
public void testDirectoryBasedEnvVars() throws Exception {
- Path dir =
- Files.createTempDirectory(
- FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR")), null);
-
Map<String, String> envvars =
Runfiles.create(
ImmutableMap.of(
"RUNFILES_MANIFEST_FILE",
"ignored when RUNFILES_MANIFEST_ONLY is not set to 1",
"RUNFILES_DIR",
- dir.toString(),
+ tempDir.getRoot().toString(),
"JAVA_RUNFILES",
"ignored when RUNFILES_DIR has a value",
"TEST_SRCDIR",
"should always be ignored"))
.getEnvVars();
assertThat(envvars.keySet()).containsExactly("RUNFILES_DIR", "JAVA_RUNFILES");
- assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(dir.toString());
- assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(dir.toString());
+ assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(tempDir.getRoot().toString());
+ assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(tempDir.getRoot().toString());
}
@Test
- public void testDirectoryBasedRlocation() {
+ public void testDirectoryBasedRlocation() throws IOException {
// The DirectoryBased implementation simply joins the runfiles directory and the runfile's path
// on a "/". DirectoryBased does not perform any normalization, nor does it check that the path
// exists.
File dir = new File(System.getenv("TEST_TMPDIR"), "mock/runfiles");
assertThat(dir.mkdirs()).isTrue();
- Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString());
+ Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).withSourceRepository("");
// Escaping for "\": once for string and once for regex.
assertThat(r.rlocation("arg")).matches(".*[/\\\\]mock[/\\\\]runfiles[/\\\\]arg");
}
@Test
public void testManifestBasedRlocation() throws Exception {
- try (MockFile mf =
- new MockFile(
+ Path mf =
+ tempFile(
+ "MANIFEST",
ImmutableList.of(
"Foo/runfile1 C:/Actual Path\\runfile1",
"Foo/Bar/runfile2 D:\\the path\\run file 2.txt",
- "Foo/Bar/Dir E:\\Actual Path\\Directory"))) {
- Runfiles r = Runfiles.createManifestBasedForTesting(mf.path.toString());
- assertThat(r.rlocation("Foo/runfile1")).isEqualTo("C:/Actual Path\\runfile1");
- assertThat(r.rlocation("Foo/Bar/runfile2")).isEqualTo("D:\\the path\\run file 2.txt");
- assertThat(r.rlocation("Foo/Bar/Dir")).isEqualTo("E:\\Actual Path\\Directory");
- assertThat(r.rlocation("Foo/Bar/Dir/File")).isEqualTo("E:\\Actual Path\\Directory/File");
- assertThat(r.rlocation("Foo/Bar/Dir/Deeply/Nested/File"))
- .isEqualTo("E:\\Actual Path\\Directory/Deeply/Nested/File");
- assertThat(r.rlocation("unknown")).isNull();
- }
+ "Foo/Bar/Dir E:\\Actual Path\\Directory"));
+ Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository("");
+ assertThat(r.rlocation("Foo/runfile1")).isEqualTo("C:/Actual Path\\runfile1");
+ assertThat(r.rlocation("Foo/Bar/runfile2")).isEqualTo("D:\\the path\\run file 2.txt");
+ assertThat(r.rlocation("Foo/Bar/Dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("Foo/Bar/Dir/File")).isEqualTo("E:\\Actual Path\\Directory/File");
+ assertThat(r.rlocation("Foo/Bar/Dir/Deeply/Nested/File"))
+ .isEqualTo("E:\\Actual Path\\Directory/Deeply/Nested/File");
+ assertThat(r.rlocation("unknown")).isNull();
+ }
+
+ @Test
+ public void testManifestBasedRlocationWithRepoMapping_fromMain() throws Exception {
+ Path rm =
+ tempFile(
+ "foo.repo_mapping",
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Path mf =
+ tempFile(
+ "foo.runfiles_manifest",
+ ImmutableList.of(
+ "_repo_mapping " + rm,
+ "config.json /etc/config.json",
+ "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
+ "_main/bar/runfile /the/path/./to/other//other runfile.txt",
+ "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"));
+ Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository("");
+
+ assertThat(r.rlocation("my_module/bar/runfile"))
+ .isEqualTo("/the/path/./to/other//other runfile.txt");
+ assertThat(r.rlocation("my_workspace/bar/runfile"))
+ .isEqualTo("/the/path/./to/other//other runfile.txt");
+ assertThat(r.rlocation("my_protobuf/foo/runfile"))
+ .isEqualTo("C:/Actual Path\\protobuf\\runfile");
+ assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("my_protobuf/bar/dir/file"))
+ .isEqualTo("E:\\Actual Path\\Directory/file");
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir/file")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le")).isNull();
+
+ assertThat(r.rlocation("_main/bar/runfile"))
+ .isEqualTo("/the/path/./to/other//other runfile.txt");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo("C:/Actual Path\\protobuf\\runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo("E:\\Actual Path\\Directory/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json");
+ assertThat(r.rlocation("_main")).isNull();
+ assertThat(r.rlocation("my_module")).isNull();
+ assertThat(r.rlocation("protobuf")).isNull();
+ }
+
+ @Test
+ public void testManifestBasedRlocationUnmapped() throws Exception {
+ Path rm =
+ tempFile(
+ "foo.repo_mapping",
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Path mf =
+ tempFile(
+ "foo.runfiles_manifest",
+ ImmutableList.of(
+ "_repo_mapping " + rm,
+ "config.json /etc/config.json",
+ "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
+ "_main/bar/runfile /the/path/./to/other//other runfile.txt",
+ "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"));
+ Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).unmapped();
+
+ assertThat(r.rlocation("my_module/bar/runfile")).isNull();
+ assertThat(r.rlocation("my_workspace/bar/runfile")).isNull();
+ assertThat(r.rlocation("my_protobuf/foo/runfile")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir/file")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le")).isNull();
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir/file")).isNull();
+ assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le")).isNull();
+
+ assertThat(r.rlocation("_main/bar/runfile"))
+ .isEqualTo("/the/path/./to/other//other runfile.txt");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo("C:/Actual Path\\protobuf\\runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo("E:\\Actual Path\\Directory/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json");
+ assertThat(r.rlocation("_main")).isNull();
+ assertThat(r.rlocation("my_module")).isNull();
+ assertThat(r.rlocation("protobuf")).isNull();
+ }
+
+ @Test
+ public void testManifestBasedRlocationWithRepoMapping_fromOtherRepo() throws Exception {
+ Path rm =
+ tempFile(
+ "foo.repo_mapping",
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Path mf =
+ tempFile(
+ "foo.runfiles/MANIFEST",
+ ImmutableList.of(
+ "_repo_mapping " + rm,
+ "config.json /etc/config.json",
+ "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
+ "_main/bar/runfile /the/path/./to/other//other runfile.txt",
+ "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"));
+ Runfiles r =
+ Runfiles.createManifestBasedForTesting(mf.toString())
+ .withSourceRepository("protobuf~3.19.2");
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo("C:/Actual Path\\protobuf\\runfile");
+ assertThat(r.rlocation("protobuf/bar/dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("protobuf/bar/dir/file")).isEqualTo("E:\\Actual Path\\Directory/file");
+ assertThat(r.rlocation("protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("my_module/bar/runfile")).isNull();
+ assertThat(r.rlocation("my_protobuf/foo/runfile")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir/file")).isNull();
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le")).isNull();
+
+ assertThat(r.rlocation("_main/bar/runfile"))
+ .isEqualTo("/the/path/./to/other//other runfile.txt");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo("C:/Actual Path\\protobuf\\runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo("E:\\Actual Path\\Directory/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json");
+ assertThat(r.rlocation("_main")).isNull();
+ assertThat(r.rlocation("my_module")).isNull();
+ assertThat(r.rlocation("protobuf")).isNull();
+ }
+
+ @Test
+ public void testDirectoryBasedRlocationWithRepoMapping_fromMain() throws Exception {
+ Path dir = tempDir.newFolder("foo.runfiles").toPath();
+ Path unused =
+ tempFile(
+ dir.resolve("_repo_mapping").toString(),
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).withSourceRepository("");
+
+ assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile");
+ assertThat(r.rlocation("my_workspace/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile");
+ assertThat(r.rlocation("my_protobuf/foo/runfile"))
+ .isEqualTo(dir + "/protobuf~3.19.2/foo/runfile");
+ assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo(dir + "/protobuf~3.19.2/bar/dir");
+ assertThat(r.rlocation("my_protobuf/bar/dir/file"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/file");
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf/foo/runfile");
+ assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf/bar/dir/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo(dir + "/protobuf~3.19.2/foo/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo(dir + "/protobuf~3.19.2/bar/dir");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json");
+ }
+
+ @Test
+ public void testDirectoryBasedRlocationUnmapped() throws Exception {
+ Path dir = tempDir.newFolder("foo.runfiles").toPath();
+ Path unused =
+ tempFile(
+ dir.resolve("_repo_mapping").toString(),
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).unmapped();
+
+ assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/my_module/bar/runfile");
+ assertThat(r.rlocation("my_workspace/bar/runfile"))
+ .isEqualTo(dir + "/my_workspace/bar/runfile");
+ assertThat(r.rlocation("my_protobuf/foo/runfile")).isEqualTo(dir + "/my_protobuf/foo/runfile");
+ assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo(dir + "/my_protobuf/bar/dir");
+ assertThat(r.rlocation("my_protobuf/bar/dir/file"))
+ .isEqualTo(dir + "/my_protobuf/bar/dir/file");
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/my_protobuf/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf/foo/runfile");
+ assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf/bar/dir/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo(dir + "/protobuf~3.19.2/foo/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo(dir + "/protobuf~3.19.2/bar/dir");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json");
+ }
+
+ @Test
+ public void testDirectoryBasedRlocationWithRepoMapping_fromOtherRepo() throws Exception {
+ Path dir = tempDir.newFolder("foo.runfiles").toPath();
+ Path unused =
+ tempFile(
+ dir.resolve("_repo_mapping").toString(),
+ ImmutableList.of(
+ ",my_module,_main",
+ ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main",
+ "protobuf~3.19.2,protobuf,protobuf~3.19.2"));
+ Runfiles r =
+ Runfiles.createDirectoryBasedForTesting(dir.toString())
+ .withSourceRepository("protobuf~3.19.2");
+
+ assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf~3.19.2/foo/runfile");
+ assertThat(r.rlocation("protobuf/bar/dir")).isEqualTo(dir + "/protobuf~3.19.2/bar/dir");
+ assertThat(r.rlocation("protobuf/bar/dir/file"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/file");
+ assertThat(r.rlocation("protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/my_module/bar/runfile");
+ assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/my_protobuf/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/foo/runfile"))
+ .isEqualTo(dir + "/protobuf~3.19.2/foo/runfile");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir")).isEqualTo(dir + "/protobuf~3.19.2/bar/dir");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/file"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/file");
+ assertThat(r.rlocation("protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"))
+ .isEqualTo(dir + "/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le");
+
+ assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json");
}
@Test
- public void testDirectoryBasedCtorArgumentValidation() {
+ public void testDirectoryBasedCtorArgumentValidation() throws IOException {
assertThrows(
- IllegalArgumentException.class, () -> Runfiles.createDirectoryBasedForTesting(null));
+ IllegalArgumentException.class,
+ () -> Runfiles.createDirectoryBasedForTesting(null).withSourceRepository(""));
- assertThrows(IllegalArgumentException.class, () -> Runfiles.createDirectoryBasedForTesting(""));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> Runfiles.createDirectoryBasedForTesting("").withSourceRepository(""));
assertThrows(
IllegalArgumentException.class,
- () -> Runfiles.createDirectoryBasedForTesting("non-existent directory is bad"));
+ () ->
+ Runfiles.createDirectoryBasedForTesting("non-existent directory is bad")
+ .withSourceRepository(""));
- Runfiles.createDirectoryBasedForTesting(System.getenv("TEST_TMPDIR"));
+ var unused =
+ Runfiles.createDirectoryBasedForTesting(System.getenv("TEST_TMPDIR"))
+ .withSourceRepository("");
}
@Test
public void testManifestBasedCtorArgumentValidation() throws Exception {
assertThrows(
- IllegalArgumentException.class, () -> Runfiles.createManifestBasedForTesting(null));
+ IllegalArgumentException.class,
+ () -> Runfiles.createManifestBasedForTesting(null).withSourceRepository(""));
- assertThrows(IllegalArgumentException.class, () -> Runfiles.createManifestBasedForTesting(""));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> Runfiles.createManifestBasedForTesting("").withSourceRepository(""));
- try (MockFile mf = new MockFile(ImmutableList.of("a b"))) {
- Runfiles.createManifestBasedForTesting(mf.path.toString());
- }
+ Path mf = tempFile("foobar", ImmutableList.of("a b"));
+ var unused = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository("");
+ }
+
+ @Test
+ public void testInvalidRepoMapping() throws Exception {
+ Path rm = tempFile("foo.repo_mapping", ImmutableList.of("a,b,c,d"));
+ Path mf = tempFile("foo.runfiles/MANIFEST", ImmutableList.of("_repo_mapping " + rm));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""));
+ }
+
+ private Path tempFile(String path, ImmutableList<String> lines) throws IOException {
+ Path file = tempDir.getRoot().toPath().resolve(path.replace('/', File.separatorChar));
+ Files.createDirectories(file.getParent());
+ return Files.write(file, lines, StandardCharsets.UTF_8);
}
}
| test | val | 2022-11-11T17:32:25 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16124_16752 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16752 | [
"keyword_pr_to_issue"
] | a4a6b59a9250a22fc1a92df6a031fbe4be381d53 | 148bbb1c025a628643698f65627333d86975c1d7 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-11T23:16:52Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"tools/cpp/runfiles/runfiles_src.cc",
"tools/cpp/runfiles/runfiles_src.h",
"tools/cpp/runfiles/runfiles_test.cc"
] | [
"tools/cpp/runfiles/runfiles_src.cc",
"tools/cpp/runfiles/runfiles_src.h",
"tools/cpp/runfiles/runfiles_test.cc"
] | [
"src/test/py/bazel/bzlmod/bazel_module_test.py"
] | diff --git a/tools/cpp/runfiles/runfiles_src.cc b/tools/cpp/runfiles/runfiles_src.cc
index f35dd969949f4a..d81edb643f9cec 100644
--- a/tools/cpp/runfiles/runfiles_src.cc
+++ b/tools/cpp/runfiles/runfiles_src.cc
@@ -96,15 +96,13 @@ bool IsDirectory(const string& path) {
bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
std::string runfiles_dir, std::string* out_manifest,
- std::string* out_directory, std::string* out_repo_mapping);
+ std::string* out_directory);
bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
std::string runfiles_dir,
std::function<bool(const std::string&)> is_runfiles_manifest,
std::function<bool(const std::string&)> is_runfiles_directory,
- std::function<bool(const std::string&)> is_repo_mapping,
- std::string* out_manifest, std::string* out_directory,
- std::string* out_repo_mapping);
+ std::string* out_manifest, std::string* out_directory);
bool ParseManifest(const string& path, map<string, string>* result,
string* error);
@@ -117,9 +115,9 @@ Runfiles* Runfiles::Create(const string& argv0,
const string& runfiles_manifest_file,
const string& runfiles_dir,
const string& source_repository, string* error) {
- string manifest, directory, repo_mapping;
+ string manifest, directory;
if (!PathsFrom(argv0, runfiles_manifest_file, runfiles_dir, &manifest,
- &directory, &repo_mapping)) {
+ &directory)) {
if (error) {
std::ostringstream err;
err << "ERROR: " << __FILE__ << "(" << __LINE__
@@ -144,10 +142,10 @@ Runfiles* Runfiles::Create(const string& argv0,
}
map<pair<string, string>, string> mapping;
- if (!repo_mapping.empty()) {
- if (!ParseRepoMapping(repo_mapping, &mapping, error)) {
- return nullptr;
- }
+ if (!ParseRepoMapping(
+ RlocationUnchecked("_repo_mapping", runfiles, directory), &mapping,
+ error)) {
+ return nullptr;
}
return new Runfiles(std::move(runfiles), std::move(directory),
@@ -196,28 +194,28 @@ string Runfiles::Rlocation(const string& path,
return path;
}
- if (repo_mapping_.empty()) {
- return RlocationUnchecked(path);
- }
string::size_type first_slash = path.find_first_of('/');
if (first_slash == string::npos) {
- return RlocationUnchecked(path);
+ return RlocationUnchecked(path, runfiles_map_, directory_);
}
string target_apparent = path.substr(0, first_slash);
auto target =
repo_mapping_.find(std::make_pair(source_repo, target_apparent));
if (target == repo_mapping_.cend()) {
- return RlocationUnchecked(path);
+ return RlocationUnchecked(path, runfiles_map_, directory_);
}
- return RlocationUnchecked(target->second + path.substr(first_slash));
+ return RlocationUnchecked(target->second + path.substr(first_slash),
+ runfiles_map_, directory_);
}
-string Runfiles::RlocationUnchecked(const string& path) const {
- const auto exact_match = runfiles_map_.find(path);
- if (exact_match != runfiles_map_.end()) {
+string Runfiles::RlocationUnchecked(const string& path,
+ const map<string, string>& runfiles_map,
+ const string& directory) {
+ const auto exact_match = runfiles_map.find(path);
+ if (exact_match != runfiles_map.end()) {
return exact_match->second;
}
- if (!runfiles_map_.empty()) {
+ if (!runfiles_map.empty()) {
// If path references a runfile that lies under a directory that itself is a
// runfile, then only the directory is listed in the manifest. Look up all
// prefixes of path in the manifest and append the relative path from the
@@ -226,14 +224,14 @@ string Runfiles::RlocationUnchecked(const string& path) const {
while ((prefix_end = path.find_last_of('/', prefix_end - 1)) !=
string::npos) {
const string prefix = path.substr(0, prefix_end);
- const auto prefix_match = runfiles_map_.find(prefix);
- if (prefix_match != runfiles_map_.end()) {
+ const auto prefix_match = runfiles_map.find(prefix);
+ if (prefix_match != runfiles_map.end()) {
return prefix_match->second + "/" + path.substr(prefix_end + 1);
}
}
}
- if (!directory_.empty()) {
- return directory_ + "/" + path;
+ if (!directory.empty()) {
+ return directory + "/" + path;
}
return "";
}
@@ -279,13 +277,7 @@ bool ParseRepoMapping(const string& path,
string* error) {
std::ifstream stm(path);
if (!stm.is_open()) {
- if (error) {
- std::ostringstream err;
- err << "ERROR: " << __FILE__ << "(" << __LINE__
- << "): cannot open repository mapping \"" << path << "\"";
- *error = err.str();
- }
- return false;
+ return true;
}
string line;
std::getline(stm, line);
@@ -333,12 +325,9 @@ namespace testing {
bool TestOnly_PathsFrom(const string& argv0, string mf, string dir,
function<bool(const string&)> is_runfiles_manifest,
function<bool(const string&)> is_runfiles_directory,
- function<bool(const string&)> is_repo_mapping,
- string* out_manifest, string* out_directory,
- string* out_repo_mapping) {
+ string* out_manifest, string* out_directory) {
return PathsFrom(argv0, mf, dir, is_runfiles_manifest, is_runfiles_directory,
- is_repo_mapping, out_manifest, out_directory,
- out_repo_mapping);
+ out_manifest, out_directory);
}
bool TestOnly_IsAbsolute(const string& path) { return IsAbsolute(path); }
@@ -376,23 +365,19 @@ Runfiles* Runfiles::CreateForTest(std::string* error) {
namespace {
bool PathsFrom(const string& argv0, string mf, string dir, string* out_manifest,
- string* out_directory, string* out_repo_mapping) {
+ string* out_directory) {
return PathsFrom(
argv0, mf, dir, [](const string& path) { return IsReadableFile(path); },
- [](const string& path) { return IsDirectory(path); },
- [](const string& path) { return IsReadableFile(path); }, out_manifest,
- out_directory, out_repo_mapping);
+ [](const string& path) { return IsDirectory(path); }, out_manifest,
+ out_directory);
}
bool PathsFrom(const string& argv0, string mf, string dir,
function<bool(const string&)> is_runfiles_manifest,
function<bool(const string&)> is_runfiles_directory,
- function<bool(const string&)> is_repo_mapping,
- string* out_manifest, string* out_directory,
- string* out_repo_mapping) {
+ string* out_manifest, string* out_directory) {
out_manifest->clear();
out_directory->clear();
- out_repo_mapping->clear();
bool mfValid = is_runfiles_manifest(mf);
bool dirValid = is_runfiles_directory(dir);
@@ -428,21 +413,6 @@ bool PathsFrom(const string& argv0, string mf, string dir,
dirValid = is_runfiles_directory(dir);
}
- string rm;
- bool rmValid = false;
-
- if (dirValid && ends_with(dir, ".runfiles")) {
- rm = dir.substr(0, dir.size() - 9) + ".repo_mapping";
- rmValid = is_repo_mapping(rm);
- }
-
- if (!rmValid && mfValid &&
- (ends_with(mf, ".runfiles_manifest") ||
- ends_with(mf, ".runfiles/MANIFEST"))) {
- rm = mf.substr(0, mf.size() - 18) + ".repo_mapping";
- rmValid = is_repo_mapping(rm);
- }
-
if (mfValid) {
*out_manifest = mf;
}
@@ -451,10 +421,6 @@ bool PathsFrom(const string& argv0, string mf, string dir,
*out_directory = dir;
}
- if (rmValid) {
- *out_repo_mapping = rm;
- }
-
return true;
}
diff --git a/tools/cpp/runfiles/runfiles_src.h b/tools/cpp/runfiles/runfiles_src.h
index 6e0a0c2f203556..75103e230bf8ce 100644
--- a/tools/cpp/runfiles/runfiles_src.h
+++ b/tools/cpp/runfiles/runfiles_src.h
@@ -206,14 +206,17 @@ class Runfiles {
Runfiles& operator=(const Runfiles&) = delete;
Runfiles& operator=(Runfiles&&) = delete;
+ static std::string RlocationUnchecked(
+ const std::string& path,
+ const std::map<std::string, std::string>& runfiles_map,
+ const std::string& directory);
+
const std::map<std::string, std::string> runfiles_map_;
const std::string directory_;
const std::map<std::pair<std::string, std::string>, std::string>
repo_mapping_;
const std::vector<std::pair<std::string, std::string> > envvars_;
const std::string source_repository_;
-
- std::string RlocationUnchecked(const std::string& path) const;
};
// The "testing" namespace contains functions that allow unit testing the code.
@@ -243,9 +246,7 @@ bool TestOnly_PathsFrom(
std::string runfiles_dir,
std::function<bool(const std::string&)> is_runfiles_manifest,
std::function<bool(const std::string&)> is_runfiles_directory,
- std::function<bool(const std::string&)> is_repo_mapping,
- std::string* out_manifest, std::string* out_directory,
- std::string* out_repo_mapping);
+ std::string* out_manifest, std::string* out_directory);
// For testing only.
// Returns true if `path` is an absolute Unix or Windows path.
diff --git a/tools/cpp/runfiles/runfiles_test.cc b/tools/cpp/runfiles/runfiles_test.cc
index 771510112ad28d..b859968f33dad1 100644
--- a/tools/cpp/runfiles/runfiles_test.cc
+++ b/tools/cpp/runfiles/runfiles_test.cc
@@ -494,135 +494,106 @@ TEST_F(RunfilesTest, PathsFromEnvVars) {
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
[](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
- [](const string& path) { return path == "mock2.runfiles"; },
- [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
EXPECT_EQ(dir, "mock2.runfiles");
- EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good and there's a
// runfiles manifest in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
[](const string& path) { return path == "mock2.runfiles/MANIFEST"; },
- [](const string& path) { return path == "mock2.runfiles"; },
- [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "mock2.runfiles/MANIFEST");
EXPECT_EQ(dir, "mock2.runfiles");
- EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good, but there's no
// runfiles manifest in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
[](const string& path) { return false; },
- [](const string& path) { return path == "mock2.runfiles"; },
- [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "");
EXPECT_EQ(dir, "mock2.runfiles");
- EXPECT_EQ(rm, "mock2.repo_mapping");
// RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, and it is in
// a valid-looking runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1.runfiles/MANIFEST", "mock2",
[](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
- [](const string& path) { return path == "mock1.runfiles"; },
- [](const string& path) { return path == "mock1.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "mock1.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
EXPECT_EQ(dir, "mock1.runfiles");
- EXPECT_EQ(rm, "mock1.repo_mapping");
// RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, but it is not
// in any valid-looking runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "mock1/MANIFEST"; },
- [](const string& path) { return false; },
- [](const string& path) { return true; }, &mf, &dir, &rm));
+ [](const string& path) { return false; }, &mf, &dir));
EXPECT_EQ(mf, "mock1/MANIFEST");
EXPECT_EQ(dir, "");
- EXPECT_EQ(rm, "");
// Both envvars are invalid, but there's a manifest in a runfiles directory
// next to argv0, however there's no other content in the runfiles directory.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
- [](const string& path) { return false; },
- [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return false; }, &mf, &dir));
EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
EXPECT_EQ(dir, "");
- EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a manifest next to argv0. There's
// no runfiles tree anywhere.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles_manifest"; },
- [](const string& path) { return false; },
- [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return false; }, &mf, &dir));
EXPECT_EQ(mf, "argv0.runfiles_manifest");
EXPECT_EQ(dir, "");
- EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid manifest next to argv0, and a
// valid runfiles directory (without a manifest in it).
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles_manifest"; },
- [](const string& path) { return path == "argv0.runfiles"; },
- [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "argv0.runfiles_manifest");
EXPECT_EQ(dir, "argv0.runfiles");
- EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid runfiles directory next to
// argv0, though no manifest in it.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return false; },
- [](const string& path) { return path == "argv0.runfiles"; },
- [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "");
EXPECT_EQ(dir, "argv0.runfiles");
- EXPECT_EQ(rm, "argv0.repo_mapping");
// Both envvars are invalid, but there's a valid runfiles directory next to
// argv0 with a valid manifest in it.
EXPECT_TRUE(TestOnly_PathsFrom(
"argv0", "mock1/MANIFEST", "mock2",
[](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
- [](const string& path) { return path == "argv0.runfiles"; },
- [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
- &dir, &rm));
+ [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
EXPECT_EQ(dir, "argv0.runfiles");
- EXPECT_EQ(rm, "argv0.repo_mapping");
}
TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromMain) {
string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ ASSERT_TRUE(rm != nullptr);
unique_ptr<MockFile> mf(MockFile::Create(
"foo" + uid + ".runfiles_manifest",
- {"config.json /etc/config.json",
+ {"_repo_mapping " + rm->Path(), "config.json /etc/config.json",
"protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
"_main/bar/runfile /the/path/./to/other//other runfile.txt",
"protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
- EXPECT_TRUE(mf != nullptr);
- unique_ptr<MockFile> rm(MockFile::Create(
- "foo" + uid + ".repo_mapping",
- {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
- ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
- EXPECT_TRUE(rm != nullptr);
+ ASSERT_TRUE(mf != nullptr);
string argv0(mf->Path().substr(
0, mf->Path().size() - string(".runfiles_manifest").size()));
@@ -667,18 +638,18 @@ TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromMain) {
TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromOtherRepo) {
string uid = LINE_AS_STRING();
+ unique_ptr<MockFile> rm(MockFile::Create(
+ "foo" + uid + ".repo_mapping",
+ {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+ ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+ ASSERT_TRUE(rm != nullptr);
unique_ptr<MockFile> mf(MockFile::Create(
"foo" + uid + ".runfiles_manifest",
- {"config.json /etc/config.json",
+ {"_repo_mapping " + rm->Path(), "config.json /etc/config.json",
"protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
"_main/bar/runfile /the/path/./to/other//other runfile.txt",
"protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
- EXPECT_TRUE(mf != nullptr);
- unique_ptr<MockFile> rm(MockFile::Create(
- "foo" + uid + ".repo_mapping",
- {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
- ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
- EXPECT_TRUE(rm != nullptr);
+ ASSERT_TRUE(mf != nullptr);
string argv0(mf->Path().substr(
0, mf->Path().size() - string(".runfiles_manifest").size()));
@@ -721,17 +692,13 @@ TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromOtherRepo) {
TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromMain) {
string uid = LINE_AS_STRING();
- unique_ptr<MockFile> dir_marker(
- MockFile::Create("foo" + uid + ".runfiles/marker"), {});
- EXPECT_TRUE(dir_marker != nullptr);
- string dir = dir_marker->DirName();
unique_ptr<MockFile> rm(MockFile::Create(
- "foo" + uid + ".repo_mapping",
+ "foo" + uid + ".runfiles/_repo_mapping",
{",my_module,_main", ",my_protobuf,protobuf~3.19.2",
",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
- EXPECT_TRUE(rm != nullptr);
- string argv0(
- rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+ ASSERT_TRUE(rm != nullptr);
+ string dir = rm->DirName();
+ string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
string error;
unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
@@ -770,17 +737,13 @@ TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromMain) {
TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromOtherRepo) {
string uid = LINE_AS_STRING();
- unique_ptr<MockFile> dir_marker(
- MockFile::Create("foo" + uid + ".runfiles/marker"), {});
- EXPECT_TRUE(dir_marker != nullptr);
- string dir = dir_marker->DirName();
unique_ptr<MockFile> rm(MockFile::Create(
- "foo" + uid + ".repo_mapping",
+ "foo" + uid + ".runfiles/_repo_mapping",
{",my_module,_main", ",my_protobuf,protobuf~3.19.2",
",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
- EXPECT_TRUE(rm != nullptr);
- string argv0(
- rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+ ASSERT_TRUE(rm != nullptr);
+ string dir = rm->DirName();
+ string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
string error;
unique_ptr<Runfiles> r(
@@ -817,17 +780,13 @@ TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromOtherRepo) {
TEST_F(RunfilesTest,
DirectoryBasedRlocationWithRepoMapping_fromOtherRepo_withSourceRepo) {
string uid = LINE_AS_STRING();
- unique_ptr<MockFile> dir_marker(
- MockFile::Create("foo" + uid + ".runfiles/marker"), {});
- EXPECT_TRUE(dir_marker != nullptr);
- string dir = dir_marker->DirName();
unique_ptr<MockFile> rm(MockFile::Create(
- "foo" + uid + ".repo_mapping",
+ "foo" + uid + ".runfiles/_repo_mapping",
{",my_module,_main", ",my_protobuf,protobuf~3.19.2",
",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
- EXPECT_TRUE(rm != nullptr);
- string argv0(
- rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+ ASSERT_TRUE(rm != nullptr);
+ string dir = rm->DirName();
+ string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
string error;
unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
@@ -863,15 +822,11 @@ TEST_F(RunfilesTest,
TEST_F(RunfilesTest, InvalidRepoMapping) {
string uid = LINE_AS_STRING();
- unique_ptr<MockFile> dir_marker(
- MockFile::Create("foo" + uid + ".runfiles/marker"), {});
- EXPECT_TRUE(dir_marker != nullptr);
- string dir = dir_marker->DirName();
unique_ptr<MockFile> rm(
- MockFile::Create("foo" + uid + ".repo_mapping", {"a,b"}));
- EXPECT_TRUE(rm != nullptr);
- string argv0(
- rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+ MockFile::Create("foo" + uid + ".runfiles/_repo_mapping", {"a,b"}));
+ ASSERT_TRUE(rm != nullptr);
+ string dir = rm->DirName();
+ string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
string error;
unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
| diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index b9fd78688c8d49..5da5f7802962f1 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -762,5 +762,57 @@ def testJavaRunfilesLibraryRepoMapping(self):
env_add={'RUNFILES_LIB_DEBUG': '1'})
self.AssertExitCode(exit_code, 0, stderr, stdout)
+ def testCppRunfilesLibraryRepoMapping(self):
+ self.main_registry.setModuleBasePath('projects')
+ projects_dir = self.main_registry.projects
+
+ self.main_registry.createLocalPathModule('data', '1.0', 'data')
+ projects_dir.joinpath('data').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('data', 'WORKSPACE'))
+ scratchFile(projects_dir.joinpath('data', 'foo.txt'), ['hello'])
+ scratchFile(
+ projects_dir.joinpath('data', 'BUILD'), ['exports_files(["foo.txt"])'])
+
+ self.main_registry.createLocalPathModule('test', '1.0', 'test',
+ {'data': '1.0'})
+ projects_dir.joinpath('test').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('test', 'WORKSPACE'))
+ scratchFile(
+ projects_dir.joinpath('test', 'BUILD'), [
+ 'cc_test(',
+ ' name = "test",',
+ ' srcs = ["test.cpp"],',
+ ' data = ["@data//:foo.txt"],',
+ ' args = ["$(rlocationpath @data//:foo.txt)"],',
+ ' deps = ["@bazel_tools//tools/cpp/runfiles"],',
+ ')',
+ ])
+ scratchFile(
+ projects_dir.joinpath('test', 'test.cpp'), [
+ '#include <cstdlib>',
+ '#include <fstream>',
+ '#include "tools/cpp/runfiles/runfiles.h"',
+ 'using bazel::tools::cpp::runfiles::Runfiles;',
+ 'int main(int argc, char** argv) {',
+ ' Runfiles* runfiles = Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY);',
+ ' std::ifstream f1(runfiles->Rlocation(argv[1]));',
+ ' if (!f1.good()) std::exit(1);',
+ ' std::ifstream f2(runfiles->Rlocation("data/foo.txt"));',
+ ' if (!f2.good()) std::exit(2);',
+ '}',
+ ])
+
+ self.ScratchFile('MODULE.bazel', ['bazel_dep(name="test",version="1.0")'])
+ self.ScratchFile('WORKSPACE')
+
+ # Run sandboxed on Linux and macOS.
+ exit_code, stderr, stdout = self.RunBazel(
+ ['test', '@test//:test', '--test_output=errors'], allow_failure=True)
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+ # Run unsandboxed on all platforms.
+ exit_code, stderr, stdout = self.RunBazel(['run', '@test//:test'],
+ allow_failure=True)
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+
if __name__ == '__main__':
unittest.main()
| train | val | 2022-11-13T06:34:01 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16124_16753 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16753 | [
"keyword_pr_to_issue"
] | c3e2b988c23a7b8d3b03a62b428017f347fb7006 | 0b645254b41edc738c6641fd192fca86203ff2e2 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-11T23:18:21Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"tools/bash/runfiles/runfiles.bash",
"tools/bash/runfiles/runfiles_test.bash"
] | [
"tools/bash/runfiles/runfiles.bash",
"tools/bash/runfiles/runfiles_test.bash"
] | [
"src/test/py/bazel/bzlmod/bazel_module_test.py",
"src/test/shell/bazel/BUILD",
"src/test/shell/bazel/bazel_rules_test.sh"
] | diff --git a/tools/bash/runfiles/runfiles.bash b/tools/bash/runfiles/runfiles.bash
index d0aedd41deca89..6c6ae4661aa4b4 100644
--- a/tools/bash/runfiles/runfiles.bash
+++ b/tools/bash/runfiles/runfiles.bash
@@ -12,9 +12,25 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Runfiles lookup library for Bazel-built Bash binaries and tests, version 2.
+# Runfiles lookup library for Bazel-built Bash binaries and tests, version 3.
#
# VERSION HISTORY:
+# - version 3: Fixes a bug in the init code on macOS and makes the library aware
+# of Bzlmod repository mappings.
+# Features:
+# - With Bzlmod enabled, rlocation now takes the repository mapping of the
+# Bazel repository containing the calling script into account when
+# looking up runfiles. The new, optional second argument to rlocation can
+# be used to specify the canonical name of the Bazel repository to use
+# instead of this default. The new runfiles_current_repository function
+# can be used to obtain the canonical name of the N-th caller's Bazel
+# repository.
+# Fixed:
+# - Sourcing a shell script that contains the init code from a shell script
+# that itself contains the init code no longer fails on macOS.
+# Compatibility:
+# - The init script and the runfiles library are backwards and forwards
+# compatible with version 2.
# - version 2: Shorter init code.
# Features:
# - "set -euo pipefail" only at end of init code.
@@ -53,7 +69,7 @@
#
# # --- begin runfiles.bash initialization v2 ---
# # Copy-pasted from the Bazel Bash runfiles library v2.
-# set -uo pipefail; f=bazel_tools/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 || \
@@ -90,6 +106,10 @@ msys*|mingw*|cygwin*)
esac
# Prints to stdout the runtime location of a data-dependency.
+# The optional second argument can be used to specify the canonical name of the
+# repository whose repository mapping should be used to resolve the repository
+# part of the provided path. If not specified, the repository of the caller is
+# used.
function rlocation() {
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
echo >&2 "INFO[runfiles.bash]: rlocation($1): start"
@@ -111,72 +131,40 @@ function rlocation() {
"drive name"
fi
return 1
- else
- if [[ -e "${RUNFILES_DIR:-/dev/null}/$1" ]]; then
+ fi
+
+ if [[ -f "$RUNFILES_REPO_MAPPING" ]]; then
+ local -r target_repo_apparent_name=$(echo "$1" | cut -d / -f 1)
+ local -r remainder=$(echo "$1" | cut -d / -f 2-)
+ if [[ -n "$remainder" ]]; then
+ if [[ -z "${2+x}" ]]; then
+ local -r source_repo=$(runfiles_current_repository 2)
+ else
+ local -r source_repo=$2
+ fi
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: rlocation($1): found under RUNFILES_DIR ($RUNFILES_DIR), return"
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): looking up canonical name for ($target_repo_apparent_name) from ($source_repo) in ($RUNFILES_REPO_MAPPING)"
fi
- echo "${RUNFILES_DIR}/$1"
- elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ local -r target_repo=$(grep -m1 "^$source_repo,$target_repo_apparent_name," "$RUNFILES_REPO_MAPPING" | cut -d , -f 3)
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: rlocation($1): looking in RUNFILES_MANIFEST_FILE ($RUNFILES_MANIFEST_FILE)"
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): canonical name of target repo is ($target_repo)"
fi
- local -r result=$(grep -m1 "^$1 " "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 2-)
- if [[ -z "$result" ]]; then
- # If path references a runfile that lies under a directory that itself
- # is a runfile, then only the directory is listed in the manifest. Look
- # up all prefixes of path in the manifest and append the relative path
- # from the prefix if there is a match.
- local prefix="$1"
- local prefix_result=
- local new_prefix=
- while true; do
- new_prefix="${prefix%/*}"
- [[ "$new_prefix" == "$prefix" ]] && break
- prefix="$new_prefix"
- prefix_result=$(grep -m1 "^$prefix " "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 2-)
- [[ -z "$prefix_result" ]] && continue
- local -r candidate="${prefix_result}${1#"${prefix}"}"
- if [[ -e "$candidate" ]]; then
- if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($candidate) via prefix ($prefix)"
- fi
- echo "$candidate"
- return 0
- fi
- # At this point, the manifest lookup of prefix has been successful,
- # but the file at the relative path given by the suffix does not
- # exist. We do not continue the lookup with a shorter prefix for two
- # reasons:
- # 1. Manifests generated by Bazel never contain a path that is a
- # prefix of another path.
- # 2. Runfiles libraries for other languages do not check for file
- # existence and would have returned the non-existent path. It seems
- # better to return no path rather than a potentially different,
- # non-empty path.
- break
- done
- if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: rlocation($1): not found in manifest"
- fi
- echo ""
+ if [[ -n "$target_repo" ]]; then
+ local -r rlocation_path="$target_repo/$remainder"
else
- if [[ -e "$result" ]]; then
- if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($result)"
- fi
- echo "$result"
- fi
+ local -r rlocation_path="$1"
fi
else
- if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "ERROR[runfiles.bash]: cannot look up runfile \"$1\" " \
- "(RUNFILES_DIR=\"${RUNFILES_DIR:-}\"," \
- "RUNFILES_MANIFEST_FILE=\"${RUNFILES_MANIFEST_FILE:-}\")"
- fi
- return 1
+ local -r rlocation_path="$1"
fi
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): not using repository mapping ($RUNFILES_REPO_MAPPING) since it does not exist"
+ fi
+ local -r rlocation_path="$1"
fi
+
+ runfiles_rlocation_checked "$rlocation_path"
}
export -f rlocation
@@ -214,3 +202,165 @@ function runfiles_export_envvars() {
fi
}
export -f runfiles_export_envvars
+
+# Returns the canonical name of the Bazel repository containing the script that
+# calls this function.
+# The optional argument N, which defaults to 1, can be used to return the
+# canonical name of the N-th caller instead.
+#
+# Note: This function only works correctly with Bzlmod enabled. Without Bzlmod,
+# its return value is ignored if passed to rlocation.
+function runfiles_current_repository() {
+ local -r idx=${1:-1}
+ local -r caller_path="${BASH_SOURCE[$idx]}"
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): caller's path is ($caller_path)"
+ fi
+
+ local rlocation_path=
+
+ # If the runfiles manifest exists, search for an entry with target the caller's path.
+ if [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ # Escape $caller_path for use in the grep regex below. Also replace \ with / since the manifest
+ # uses / as the path separator even on Windows.
+ local -r normalized_caller_path="$(echo "$caller_path" | sed 's|\\\\*|/|g')"
+ local -r escaped_caller_path="$(echo "$normalized_caller_path" | sed 's/[^-A-Za-z0-9_/]/\\&/g')"
+ rlocation_path=$(grep -m1 "^[^ ]* ${escaped_caller_path}$" "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 1)
+ if [[ -z "$rlocation_path" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is not the target of an entry in the runfiles manifest ($RUNFILES_MANIFEST_FILE)"
+ fi
+ return 1
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is the target of ($rlocation_path) in the runfiles manifest"
+ fi
+ fi
+ fi
+
+ # If the runfiles directory exists, check if the caller's path is of the form
+ # $RUNFILES_DIR/rlocation_path and if so, set $rlocation_path.
+ if [[ -z "$rlocation_path" && -d "${RUNFILES_DIR:-/dev/null}" ]]; then
+ local -r normalized_caller_path="$(echo "$caller_path" | sed 's|\\\\*|/|g')"
+ local -r normalized_dir="$(echo "${RUNFILES_DIR%[\/]}" | sed 's|\\\\*|/|g')"
+ if [[ "$normalized_caller_path" == "$normalized_dir"/* ]]; then
+ rlocation_path=${normalized_caller_path:${#normalized_dir}}
+ rlocation_path=${rlocation_path:1}
+ fi
+ if [[ -z "$rlocation_path" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) does not lie under the runfiles directory ($normalized_dir)"
+ fi
+ # The only shell script that is not executed from the runfiles directory (if it is populated)
+ # is the sh_binary entrypoint. Parse its path under the execroot, using the last match to
+ # allow for nested execroots (e.g. in Bazel integration tests).
+ local -r repository=$(echo "$normalized_caller_path" | grep -E -o '/execroot/[^/]+/bazel-out/[^/]+/bin/external/[^/]+/' | tail -1 | rev | cut -d / -f 2 | rev)
+ if [[ -n "$repository" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in repository ($repository)"
+ fi
+ echo "$repository"
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in the main repository"
+ fi
+ echo ""
+ fi
+ return 0
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($caller_path) has path ($rlocation_path) relative to the runfiles directory ($RUNFILES_DIR)"
+ fi
+ fi
+ fi
+
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($caller_path) corresponds to rlocation path ($rlocation_path)"
+ fi
+ # Normalize the rlocation path to be of the form repo/pkg/file.
+ rlocation_path=${rlocation_path#_main/external/}
+ rlocation_path=${rlocation_path#_main/../}
+ local -r repository=$(echo "$rlocation_path" | cut -d / -f 1)
+ if [[ "$repository" == _main ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($rlocation_path) lies in the main repository"
+ fi
+ echo ""
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($rlocation_path) lies in repository ($repository)"
+ fi
+ echo "$repository"
+ fi
+}
+export -f runfiles_current_repository
+
+function runfiles_rlocation_checked() {
+ if [[ -e "${RUNFILES_DIR:-/dev/null}/$1" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): found under RUNFILES_DIR ($RUNFILES_DIR), return"
+ fi
+ echo "${RUNFILES_DIR}/$1"
+ elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): looking in RUNFILES_MANIFEST_FILE ($RUNFILES_MANIFEST_FILE)"
+ fi
+ local -r result=$(grep -m1 "^$1 " "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 2-)
+ if [[ -z "$result" ]]; then
+ # If path references a runfile that lies under a directory that itself
+ # is a runfile, then only the directory is listed in the manifest. Look
+ # up all prefixes of path in the manifest and append the relative path
+ # from the prefix if there is a match.
+ local prefix="$1"
+ local prefix_result=
+ local new_prefix=
+ while true; do
+ new_prefix="${prefix%/*}"
+ [[ "$new_prefix" == "$prefix" ]] && break
+ prefix="$new_prefix"
+ prefix_result=$(grep -m1 "^$prefix " "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 2-)
+ [[ -z "$prefix_result" ]] && continue
+ local -r candidate="${prefix_result}${1#"${prefix}"}"
+ if [[ -e "$candidate" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($candidate) via prefix ($prefix)"
+ fi
+ echo "$candidate"
+ return 0
+ fi
+ # At this point, the manifest lookup of prefix has been successful,
+ # but the file at the relative path given by the suffix does not
+ # exist. We do not continue the lookup with a shorter prefix for two
+ # reasons:
+ # 1. Manifests generated by Bazel never contain a path that is a
+ # prefix of another path.
+ # 2. Runfiles libraries for other languages do not check for file
+ # existence and would have returned the non-existent path. It seems
+ # better to return no path rather than a potentially different,
+ # non-empty path.
+ break
+ done
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): not found in manifest"
+ fi
+ echo ""
+ else
+ if [[ -e "$result" ]]; then
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($result)"
+ fi
+ echo "$result"
+ fi
+ fi
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "ERROR[runfiles.bash]: cannot look up runfile \"$1\" " \
+ "(RUNFILES_DIR=\"${RUNFILES_DIR:-}\"," \
+ "RUNFILES_MANIFEST_FILE=\"${RUNFILES_MANIFEST_FILE:-}\")"
+ fi
+ return 1
+ fi
+}
+export -f runfiles_rlocation_checked
+
+export RUNFILES_REPO_MAPPING=$(runfiles_rlocation_checked _repo_mapping 2> /dev/null)
diff --git a/tools/bash/runfiles/runfiles_test.bash b/tools/bash/runfiles/runfiles_test.bash
index e532824770fa3c..7105f7fc0bd082 100755
--- a/tools/bash/runfiles/runfiles_test.bash
+++ b/tools/bash/runfiles/runfiles_test.bash
@@ -205,6 +205,182 @@ function test_init_directory_based_runfiles() {
[[ -z "$(rlocation "c d")" ]] || fail
}
+function test_directory_based_runfiles_with_repo_mapping_from_main() {
+ local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+
+ export RUNFILES_DIR=${tmpdir}/mock/runfiles
+ mkdir -p "$RUNFILES_DIR"
+ cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,my_module,_main
+,my_protobuf,protobuf~3.19.2
+,my_workspace,_main
+protobuf~3.19.2,protobuf,protobuf~3.19.2
+EOF
+ export RUNFILES_MANIFEST_FILE=
+ source "$runfiles_lib_path"
+
+ mkdir -p "$RUNFILES_DIR/_main/bar"
+ touch "$RUNFILES_DIR/_main/bar/runfile"
+ mkdir -p "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"
+ mkdir -p "$RUNFILES_DIR/protobuf~3.19.2/foo"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile"
+ touch "$RUNFILES_DIR/config.json"
+
+ [[ "$(rlocation "my_module/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_workspace/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/foo/runfile" "")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/file" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ -z "$(rlocation "protobuf/foo/runfile" "")" ]] || fail
+ [[ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "")" ]] || fail
+
+ [[ "$(rlocation "_main/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ "$(rlocation "config.json" "")" == "$RUNFILES_DIR/config.json" ]] || fail
+}
+
+function test_directory_based_runfiles_with_repo_mapping_from_other_repo() {
+ local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+
+ export RUNFILES_DIR=${tmpdir}/mock/runfiles
+ mkdir -p "$RUNFILES_DIR"
+ cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,my_module,_main
+,my_protobuf,protobuf~3.19.2
+,my_workspace,_main
+protobuf~3.19.2,protobuf,protobuf~3.19.2
+EOF
+ export RUNFILES_MANIFEST_FILE=
+ source "$runfiles_lib_path"
+
+ mkdir -p "$RUNFILES_DIR/_main/bar"
+ touch "$RUNFILES_DIR/_main/bar/runfile"
+ mkdir -p "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"
+ mkdir -p "$RUNFILES_DIR/protobuf~3.19.2/foo"
+ touch "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile"
+ touch "$RUNFILES_DIR/config.json"
+
+ [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ -z "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2")" ]] || fail
+ [[ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" ]] || fail
+
+ [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ "$(rlocation "config.json" "protobuf~3.19.2")" == "$RUNFILES_DIR/config.json" ]] || fail
+}
+
+function test_manifest_based_runfiles_with_repo_mapping_from_main() {
+ local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+
+ cat > "$tmpdir/foo.repo_mapping" <<EOF
+,my_module,_main
+,my_protobuf,protobuf~3.19.2
+,my_workspace,_main
+protobuf~3.19.2,protobuf,protobuf~3.19.2
+EOF
+ export RUNFILES_DIR=
+ export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+ cat > "$RUNFILES_MANIFEST_FILE" << EOF
+_repo_mapping $tmpdir/foo.repo_mapping
+config.json $tmpdir/config.json
+protobuf~3.19.2/foo/runfile $tmpdir/protobuf~3.19.2/foo/runfile
+_main/bar/runfile $tmpdir/_main/bar/runfile
+protobuf~3.19.2/bar/dir $tmpdir/protobuf~3.19.2/bar/dir
+EOF
+ source "$runfiles_lib_path"
+
+ mkdir -p "$tmpdir/_main/bar"
+ touch "$tmpdir/_main/bar/runfile"
+ mkdir -p "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted"
+ touch "$tmpdir/protobuf~3.19.2/bar/dir/file"
+ touch "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"
+ mkdir -p "$tmpdir/protobuf~3.19.2/foo"
+ touch "$tmpdir/protobuf~3.19.2/foo/runfile"
+ touch "$tmpdir/config.json"
+
+ [[ "$(rlocation "my_module/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_workspace/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/foo/runfile" "")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir" "")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/file" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ -z "$(rlocation "protobuf/foo/runfile" "")" ]] || fail
+ [[ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "")" ]] || fail
+
+ [[ "$(rlocation "_main/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ "$(rlocation "config.json" "")" == "$tmpdir/config.json" ]] || fail
+}
+
+function test_manifest_based_runfiles_with_repo_mapping_from_other_repo() {
+ local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+
+ cat > "$tmpdir/foo.repo_mapping" <<EOF
+,my_module,_main
+,my_protobuf,protobuf~3.19.2
+,my_workspace,_main
+protobuf~3.19.2,protobuf,protobuf~3.19.2
+EOF
+ export RUNFILES_DIR=
+ export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+ cat > "$RUNFILES_MANIFEST_FILE" << EOF
+_repo_mapping $tmpdir/foo.repo_mapping
+config.json $tmpdir/config.json
+protobuf~3.19.2/foo/runfile $tmpdir/protobuf~3.19.2/foo/runfile
+_main/bar/runfile $tmpdir/_main/bar/runfile
+protobuf~3.19.2/bar/dir $tmpdir/protobuf~3.19.2/bar/dir
+EOF
+ source "$runfiles_lib_path"
+
+ mkdir -p "$tmpdir/_main/bar"
+ touch "$tmpdir/_main/bar/runfile"
+ mkdir -p "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted"
+ touch "$tmpdir/protobuf~3.19.2/bar/dir/file"
+ touch "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le"
+ mkdir -p "$tmpdir/protobuf~3.19.2/foo"
+ touch "$tmpdir/protobuf~3.19.2/foo/runfile"
+ touch "$tmpdir/config.json"
+
+ [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ -z "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2")" ]] || fail
+ [[ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" ]] || fail
+
+ [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2")" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+
+ [[ "$(rlocation "config.json" "protobuf~3.19.2")" == "$tmpdir/config.json" ]] || fail
+}
+
function test_directory_based_envvars() {
export RUNFILES_DIR=mock/runfiles
export RUNFILES_MANIFEST_FILE=
| diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 5da5f7802962f1..b2e20d4c82e71d 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -814,5 +814,65 @@ def testCppRunfilesLibraryRepoMapping(self):
allow_failure=True)
self.AssertExitCode(exit_code, 0, stderr, stdout)
+ def testBashRunfilesLibraryRepoMapping(self):
+ self.main_registry.setModuleBasePath('projects')
+ projects_dir = self.main_registry.projects
+
+ self.main_registry.createLocalPathModule('data', '1.0', 'data')
+ projects_dir.joinpath('data').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('data', 'WORKSPACE'))
+ scratchFile(projects_dir.joinpath('data', 'foo.txt'), ['hello'])
+ scratchFile(
+ projects_dir.joinpath('data', 'BUILD'), ['exports_files(["foo.txt"])'])
+
+ self.main_registry.createLocalPathModule('test', '1.0', 'test',
+ {'data': '1.0'})
+ projects_dir.joinpath('test').mkdir(exist_ok=True)
+ scratchFile(projects_dir.joinpath('test', 'WORKSPACE'))
+ scratchFile(
+ projects_dir.joinpath('test', 'BUILD'), [
+ 'sh_test(',
+ ' name = "test",',
+ ' srcs = ["test.sh"],',
+ ' data = ["@data//:foo.txt"],',
+ ' args = ["$(rlocationpath @data//:foo.txt)"],',
+ ' deps = ["@bazel_tools//tools/bash/runfiles"],',
+ ')',
+ ])
+ test_script = projects_dir.joinpath('test', 'test.sh')
+ scratchFile(
+ test_script, """#!/usr/bin/env bash
+# --- begin runfiles.bash initialization v2 ---
+# Copy-pasted from the Bazel Bash runfiles library v2.
+set -uo pipefail; 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 ---
+[[ -f "$(rlocation $1)" ]] || exit 1
+[[ -f "$(rlocation data/foo.txt)" ]] || exit 2
+""".splitlines())
+ os.chmod(test_script, 0o755)
+
+ self.ScratchFile('MODULE.bazel', ['bazel_dep(name="test",version="1.0")'])
+ self.ScratchFile('WORKSPACE')
+
+ # Run sandboxed on Linux and macOS.
+ exit_code, stderr, stdout = self.RunBazel([
+ 'test', '@test//:test', '--test_output=errors',
+ '--test_env=RUNFILES_LIB_DEBUG=1'
+ ],
+ allow_failure=True)
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+ # Run unsandboxed on all platforms.
+ exit_code, stderr, stdout = self.RunBazel(
+ ['run', '@test//:test'],
+ allow_failure=True,
+ env_add={'RUNFILES_LIB_DEBUG': '1'})
+ self.AssertExitCode(exit_code, 0, stderr, stdout)
+
if __name__ == '__main__':
unittest.main()
diff --git a/src/test/shell/bazel/BUILD b/src/test/shell/bazel/BUILD
index 7fb9e679008127..ee97c61db6d2d8 100644
--- a/src/test/shell/bazel/BUILD
+++ b/src/test/shell/bazel/BUILD
@@ -357,6 +357,7 @@ sh_test(
"@bazel_tools//tools/bash/runfiles",
],
shard_count = 3,
+ tags = ["requires-network"],
)
sh_test(
diff --git a/src/test/shell/bazel/bazel_rules_test.sh b/src/test/shell/bazel/bazel_rules_test.sh
index f4d69224e261e4..cc49a1fe4728dc 100755
--- a/src/test/shell/bazel/bazel_rules_test.sh
+++ b/src/test/shell/bazel/bazel_rules_test.sh
@@ -743,4 +743,296 @@ EOF
bazel run //pkg:my_executable >$TEST_log 2>&1 || fail "Binary should have exit code 0"
}
+function setup_bash_runfiles_current_repository() {
+ touch MODULE.bazel
+
+ cat >> WORKSPACE <<'EOF'
+local_repository(
+ name = "other_repo",
+ path = "other_repo",
+)
+EOF
+
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+sh_library(
+ name = "library",
+ srcs = ["library.sh"],
+ deps = ["@bazel_tools//tools/bash/runfiles"],
+ visibility = ["//visibility:public"],
+)
+sh_binary(
+ name = "binary",
+ srcs = ["binary.sh"],
+ deps = [
+ ":library",
+ "@other_repo//pkg:library2",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
+)
+sh_test(
+ name = "test",
+ srcs = ["test.sh"],
+ deps = [
+ ":library",
+ "@other_repo//pkg:library2",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
+)
+EOF
+
+ cat > pkg/library.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+function library() {
+ echo "in pkg/library.sh: '$(runfiles_current_repository)'"
+}
+export -f library
+EOF
+ chmod +x pkg/library.sh
+
+ cat > pkg/binary.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+echo "in pkg/binary.sh: '$(runfiles_current_repository)'"
+source $(rlocation _main/pkg/library.sh)
+library
+source $(rlocation other_repo/pkg/library2.sh)
+library2
+EOF
+ chmod +x pkg/binary.sh
+
+ cat > pkg/test.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+echo "in pkg/test.sh: '$(runfiles_current_repository)'"
+source $(rlocation _main/pkg/library.sh)
+library
+source $(rlocation other_repo/pkg/library2.sh)
+library2
+EOF
+ chmod +x pkg/test.sh
+
+ mkdir -p other_repo
+ touch other_repo/WORKSPACE
+
+ mkdir -p other_repo/pkg
+ cat > other_repo/pkg/BUILD.bazel <<'EOF'
+sh_library(
+ name = "library2",
+ srcs = ["library2.sh"],
+ deps = ["@bazel_tools//tools/bash/runfiles"],
+ visibility = ["//visibility:public"],
+)
+sh_binary(
+ name = "binary",
+ srcs = ["binary.sh"],
+ deps = [
+ "//pkg:library2",
+ "@//pkg:library",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
+)
+sh_test(
+ name = "test",
+ srcs = ["test.sh"],
+ deps = [
+ "//pkg:library2",
+ "@//pkg:library",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
+)
+EOF
+
+ cat > other_repo/pkg/library2.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+function library2() {
+ echo "in external/other_repo/pkg/library2.sh: '$(runfiles_current_repository)'"
+}
+export -f library2
+EOF
+ chmod +x pkg/library.sh
+
+ cat > other_repo/pkg/binary.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+echo "in external/other_repo/pkg/binary.sh: '$(runfiles_current_repository)'"
+source $(rlocation _main/pkg/library.sh)
+library
+source $(rlocation other_repo/pkg/library2.sh)
+library2
+EOF
+ chmod +x other_repo/pkg/binary.sh
+
+ cat > other_repo/pkg/test.sh <<'EOF'
+#!/usr/bin/env bash
+# --- 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 ---
+
+echo "in external/other_repo/pkg/test.sh: '$(runfiles_current_repository)'"
+source $(rlocation _main/pkg/library.sh)
+library
+source $(rlocation other_repo/pkg/library2.sh)
+library2
+EOF
+ chmod +x other_repo/pkg/test.sh
+}
+
+function test_bash_runfiles_current_repository_binary_enable_runfiles() {
+ setup_bash_runfiles_current_repository
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --enable_runfiles //pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in pkg/binary.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --enable_runfiles @other_repo//pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in external/other_repo/pkg/binary.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
+function test_bash_runfiles_current_repository_test_enable_runfiles() {
+ setup_bash_runfiles_current_repository
+
+ bazel test --enable_bzlmod --enable_runfiles --test_env=RUNFILES_LIB_DEBUG=1 \
+ --test_output=all //pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in pkg/test.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ bazel test --enable_bzlmod --enable_runfiles --test_env=RUNFILES_LIB_DEBUG=1 \
+ --test_output=all @other_repo//pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in external/other_repo/pkg/test.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
+function test_bash_runfiles_current_repository_binary_noenable_runfiles() {
+ setup_bash_runfiles_current_repository
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --noenable_runfiles //pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in pkg/binary.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --noenable_runfiles @other_repo//pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in external/other_repo/pkg/binary.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
+function test_bash_runfiles_current_repository_test_noenable_runfiles() {
+ setup_bash_runfiles_current_repository
+
+ bazel test --enable_bzlmod --noenable_runfiles --test_env=RUNFILES_LIB_DEBUG=1 \
+ --test_output=all //pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in pkg/test.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ bazel test --enable_bzlmod --noenable_runfiles --test_env=RUNFILES_LIB_DEBUG=1 \
+ --test_output=all @other_repo//pkg:test &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in external/other_repo/pkg/test.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
+function test_bash_runfiles_current_repository_binary_nobuild_runfile_links() {
+ setup_bash_runfiles_current_repository
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --nobuild_runfile_links //pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in pkg/binary.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ RUNFILES_LIB_DEBUG=1 bazel run --enable_bzlmod --nobuild_runfile_links @other_repo//pkg:binary \
+ &>"$TEST_log" || fail "Run should succeed"
+ expect_log "in external/other_repo/pkg/binary.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
+function test_bash_runfiles_current_repository_test_nobuild_runfile_links() {
+ setup_bash_runfiles_current_repository
+
+ bazel test --enable_bzlmod --noenable_runfiles --nobuild_runfile_links \
+ --test_env=RUNFILES_LIB_DEBUG=1 --test_output=all //pkg:test \
+ &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in pkg/test.sh: ''"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+
+ bazel test --enable_bzlmod --noenable_runfiles --nobuild_runfile_links \
+ --test_env=RUNFILES_LIB_DEBUG=1 --test_output=all @other_repo//pkg:test \
+ &>"$TEST_log" || fail "Test should succeed"
+ expect_log "in external/other_repo/pkg/test.sh: 'other_repo'"
+ expect_log "in pkg/library.sh: ''"
+ expect_log "in external/other_repo/pkg/library2.sh: 'other_repo'"
+}
+
run_suite "rules test"
| train | val | 2022-11-14T20:04:33 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16705_16787 | bazelbuild/bazel | bazelbuild/bazel/16705 | bazelbuild/bazel/16787 | [
"keyword_pr_to_issue"
] | 0caf488a7492740425af88b32c622fdc33bc1593 | 81e368f0aa1f66f8626bb2423322a4d8a0a152c1 | [
"Dupe of https://github.com/bazelbuild/bazel/issues/15831"
] | [] | "2022-11-18T04:24:42Z" | [
"more data needed",
"type: support / not a bug (process)",
"team-OSS"
] | Archlinux: "bazel crashed due to an internal error" when building media pipe | ### Description of the bug:
When attempting to build [mediapipe](https://github.com/google/mediapipe) on Archlinux, Bazel experiences an internal error.
Archlinux
bazel v5.3.2
java openjdk 19.0.1 2022-10-18
mediapipe v0.8.11
`
[user@system mediapipe]$ bazel --version | sed 's/bazel //' >.bazelversion # requires Bazel 5.2.0 by default
[user@system mediapipe]$ bazel build -c opt --define MEDIAPIPE_DISABLE_GPU=1 mediapipe/examples/desktop/hand_tracking:hand_tracking_cpu
Starting local Bazel server and connecting to it...
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_google_absl' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_google_benchmark' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'flatbuffers' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'pybind11_bazel' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_googlesource_code_re2' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_google_protobuf' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_google_googletest' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'com_github_gflags_gflags' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'zlib' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'build_bazel_rules_apple' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'build_bazel_rules_swift' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'build_bazel_apple_support' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'xctestrunner' because it already exists.
DEBUG: /home/user/.cache/bazel/_bazel_user/76aa75a67bc63428e516562f91dd6704/external/org_tensorflow/third_party/repo.bzl:132:14:
Warning: skipping import of repository 'pybind11' because it already exists.
WARNING: /home/user/Git/mediapipe/mediapipe/framework/BUILD:54:24: in cc_library rule //mediapipe/framework:calculator_cc_proto: target '//mediapipe/framework:calculator_cc_proto' depends on deprecated target '@com_google_protobuf//:cc_wkt_protos': Only for backward compatibility. Do not use.
WARNING: /home/user/Git/mediapipe/mediapipe/framework/tool/BUILD:185:24: in cc_library rule //mediapipe/framework/tool:field_data_cc_proto: target '//mediapipe/framework/tool:field_data_cc_proto' depends on deprecated target '@com_google_protobuf//:cc_wkt_protos': Only for backward compatibility. Do not use.
INFO: Analyzed target //mediapipe/examples/desktop/hand_tracking:hand_tracking_cpu (140 packages loaded, 5537 targets configured).
INFO: Found 1 target...
[0 / 8] 3 actions, 0 running
[Prepa] BazelWorkspaceStatusAction stable-status.txt
[Prepa] Writing file mediapipe/examples/desktop/hand_tracking/hand_tracking_cpu-2.params
[Prepa] Creating source manifest for //mediapipe/examples/desktop/hand_tracking:hand_tracking_cpu
FATAL: bazel crashed due to an internal error. Printing stack trace:
java.lang.ExceptionInInitializerError
at com.google.devtools.build.lib.actions.ParameterFile.writeContent(ParameterFile.java:118)
at com.google.devtools.build.lib.actions.ParameterFile.writeParameterFile(ParameterFile.java:111)
at com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction$ParamFileWriter.writeOutputFile(ParameterFileWriteAction.java:170)
at com.google.devtools.build.lib.exec.FileWriteStrategy.beginWriteOutputToFile(FileWriteStrategy.java:58)
at com.google.devtools.build.lib.analysis.actions.FileWriteActionContext.beginWriteOutputToFile(FileWriteActionContext.java:49)
at com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction.beginExecution(AbstractFileWriteAction.java:66)
at com.google.devtools.build.lib.actions.Action.execute(Action.java:133)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$5.execute(SkyframeActionExecutor.java:907)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.continueAction(SkyframeActionExecutor.java:1076)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.run(SkyframeActionExecutor.java:1031)
at com.google.devtools.build.lib.skyframe.ActionExecutionState.runStateMachine(ActionExecutionState.java:152)
at com.google.devtools.build.lib.skyframe.ActionExecutionState.getResultOrDependOnFuture(ActionExecutionState.java:91)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:492)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:856)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:349)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:169)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:590)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
at java.base/java.lang.Thread.run(Thread.java:1589)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not "opens java.lang" to unnamed module @7ed7259e
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:387)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:363)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:311)
at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:192)
at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:185)
at com.google.devtools.build.lib.unsafe.StringUnsafe.<init>(StringUnsafe.java:75)
at com.google.devtools.build.lib.unsafe.StringUnsafe.initInstance(StringUnsafe.java:56)
at com.google.devtools.build.lib.unsafe.StringUnsafe.<clinit>(StringUnsafe.java:37)
... 21 more
`
Thanks!
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
[user@system mediapipe]$ git clone https://github.com/google/mediapipe.git
[user@system mediapipe]$ cd mediapipe
[user@system mediapipe]$ bazel --version | sed 's/bazel //' >.bazelversion
[user@system mediapipe]$ bazel build -c opt --define MEDIAPIPE_DISABLE_GPU=1 mediapipe/examples/desktop
### Which operating system are you running Bazel on?
Archlinux
### What is the output of `bazel info release`?
release 5.3.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
No.
### Any other information, logs, or outputs that you want to share?
See description. | [
"src/main/cpp/blaze.cc"
] | [
"src/main/cpp/blaze.cc"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 5907865fb70b7f..ee0b32268bf47d 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -359,13 +359,10 @@ static vector<string> GetServerExeArgs(const blaze_util::Path &jvm_path,
startup_options.AddJVMArgumentPrefix(jvm_path.GetParent().GetParent(),
&result);
- // TODO(b/109998449): only assume JDK >= 9 for embedded JDKs
- if (!startup_options.GetEmbeddedJavabase().IsEmpty()) {
- // quiet warnings from com.google.protobuf.UnsafeUtil,
- // see: https://github.com/google/protobuf/issues/3781
- result.push_back("--add-opens=java.base/java.nio=ALL-UNNAMED");
- result.push_back("--add-opens=java.base/java.lang=ALL-UNNAMED");
- }
+ // com.google.devtools.build.lib.unsafe.StringUnsafe uses reflection to access
+ // private fields in java.lang.String. The Bazel server requires Java 11, so
+ // this option is known to be supported.
+ result.push_back("--add-opens=java.base/java.lang=ALL-UNNAMED");
result.push_back("-Xverify:none");
| null | val | val | 2022-11-17T18:16:28 | "2022-11-09T07:46:00Z" | siquus | test |
bazelbuild/bazel/15831_16787 | bazelbuild/bazel | bazelbuild/bazel/15831 | bazelbuild/bazel/16787 | [
"keyword_pr_to_issue"
] | 0caf488a7492740425af88b32c622fdc33bc1593 | 81e368f0aa1f66f8626bb2423322a4d8a0a152c1 | [
"Duplicate of https://github.com/bazelbuild/bazel/issues/14548",
"Hello @dmivankov, Can you try the above with the latest release[ 5.2.0](https://github.com/bazelbuild/bazel/releases/tag/5.2.0). Thanks! ",
"I'm not dmivankov, but I tried compling v 5.2.0 with openjdk17 and am getting the same crash. Here's a full build log:\r\n\r\n```sh\r\n\r\nBuilding Bazel from scratch../opt/openjdk-bin-17.0.3_p7/bin/javac -classpath derived/jars/zstd-jni/libzstd-jni.jar:derived/jars/com_google_protobuf/java/core/liblite.jar:derived/jars/com_google_protobuf/java/core/libcore.jar:derived/jars/com_google_protobuf/java/util/libutil.jar:third_party/checker_framework_annotations/checker-qual-3.2.0-sources.jar:third_party/checker_framework_annotations/checker-qual-3.2.0.jar:third_party/javax_annotations/javax.annotation-api-1.3.2-sources.jar:third_party/javax_annotations/javax.annotation-api-1.3.2.jar:third_party/truth/truth-1.0.1.jar:third_party/bazel_bootstrap/libserialization-constant-annotation.jar:third_party/bazel_bootstrap/libserialization-constant-processor.jar:third_party/bazel_bootstrap/libserialization.jar:third_party/bazel_bootstrap/libautocodec-processor.jar:third_party/bazel_bootstrap/libunsafe-provider.jar:third_party/bazel_bootstrap/libautocodec-annotation.jar:third_party/bazel_bootstrap/libserialization-processor-util.jar:third_party/bazel_bootstrap/libregistered-singleton.jar:third_party/turbine/turbine_direct.jar:third_party/jcip_annotations/jcip-annotations-1.0-1.jar:third_party/apache_commons_pool2/commons-pool2-2.8.0.jar:third_party/apache_commons_compress/apache-commons-compress-1.19.jar:third_party/animal_sniffer/animal-sniffer-annotations-1.14.jar:third_party/flogger/flogger-system-backend-0.5.1.jar:third_party/flogger/flogger-0.5.1.jar:third_party/flogger/google-extensions-0.5.1.jar:third_party/jetbrains_annotations/annotations-13.0.jar:third_party/truth8/truth-java8-extension-1.0.1.jar:third_party/objenesis/objenesis-1_3.jar:third_party/api_client/google-api-client-1.22.0.jar:third_party/api_client/google-api-client-gson-1.22.0.jar:third_party/api_client/google-http-client-1.22.0-SNAPSHOT.jar:third_party/api_client/google-http-client-gson-1.22.0.jar:third_party/tomcat_annotations_api/tomcat-annotations-api-8.0.5.jar:third_party/jimfs/jimfs-1.1.jar:third_party/hamcrest/hamcrest-core-1.3.jar:third_party/diffutils/diffutils-1.3.0.jar:third_party/caffeine/caffeine-2.9.2.jar:third_party/checker_framework_javacutil/javacutil-3.2.0-sources.jar:third_party/checker_framework_javacutil/javacutil-3.2.0.jar:third_party/jsr330_inject/javax.inject.jar:third_party/java/jdk/langtools/jdk_compiler-src.jar:third_party/java/jdk/langtools/jdk_compiler.jar:third_party/java/jdk/langtools/java_compiler.jar:third_party/java/jdk/langtools/java_compiler-src.jar:third_party/java/jdk/langtools/javac-9+181-r4173-1.jar:third_party/java/proguard/proguard6.2.2/lib/proguard.jar:third_party/java/proguard/proguard6.2.2/lib/proguardgui.jar:third_party/java/proguard/proguard6.2.2/lib/retrace.jar:third_party/java/javapoet/javapoet-1.8.0.jar:third_party/java/android_databinding/v3_4_0/base.jar:third_party/java/android_databinding/v3_4_0/exec.jar:third_party/java/android_databinding/v3_4_0/x_common.jar:third_party/java/android_databinding/v3_4_0/compiler.jar:third_party/java/android_databinding/v3_4_0/compiler_common.jar:third_party/java/jacoco/org.jacoco.ant-0.8.7-sources.jar:third_party/java/jacoco/org.jacoco.agent-0.8.7.jar:third_party/java/jacoco/org.jacoco.ant-0.8.7-nodeps.jar:third_party/java/jacoco/org.jacoco.agent-0.8.7-sources.jar:third_party/java/jacoco/org.jacoco.core-0.8.7.jar:third_party/java/jacoco/jacocoagent-0.8.7.jar:third_party/java/jacoco/org.jacoco.report-0.8.7-sources.jar:third_party/java/jacoco/org.jacoco.ant-0.8.7.jar:third_party/java/jacoco/org.jacoco.report-0.8.7.jar:third_party/java/jacoco/org.jacoco.core-0.8.7-sources.jar:third_party/java/j2objc-annotations/j2objc-annotations-1.1.jar:third_party/java/jcommander/jcommander-1.48.jar:third_party/juniversalchardet/juniversalchardet-1.0.3.jar:third_party/guava/failureaccess-1.0.1.jar:third_party/checker_framework_dataflow/dataflow-errorprone-3.15.0.jar:third_party/checker_framework_dataflow/dataflow-shaded-3.11.0.jar:third_party/checker_framework_dataflow/dataflow-errorprone-3.15.0-sources.jar:third_party/checker_framework_dataflow/dataflow-shaded-3.11.0-sources.jar:third_party/jsr305/jsr-305.jar:third_party/asm/asm-util-9.2.jar:third_party/asm/asm-util-9.2-sources.jar:third_party/asm/asm-commons-9.2-sources.jar:third_party/asm/asm-tree-9.2.jar:third_party/asm/asm-analysis-9.2-sources.jar:third_party/asm/asm-commons-9.2.jar:third_party/asm/asm-analysis-9.2.jar:third_party/asm/asm-9.2-sources.jar:third_party/asm/asm-tree-9.2-sources.jar:third_party/asm/asm-9.2.jar:third_party/apache_velocity/velocity-1.7.jar:third_party/mockito/mockito-core-3.12.4.jar:third_party/allocation_instrumenter/java-allocation-instrumenter-3.3.0.jar:third_party/antlr/antlr4-4.5.3.jar:third_party/perfmark/perfmark-api-0.19.0.jar:third_party/error_prone/error_prone_core-2.9.0.jar:third_party/error_prone/threeten-extra-1.5.0.jar:third_party/error_prone/error_prone_type_annotations-2.9.0.jar:third_party/error_prone/error_prone_annotation-2.9.0.jar:third_party/error_prone/error_prone_annotations-2.9.0.jar:third_party/error_prone/error_prone_check_api-2.9.0.jar:third_party/ijar/test/libwrongcentraldir.jar:third_party/ijar/test/jar-without-manifest.jar:third_party/ijar/test/sealed/sealed.jar:third_party/ijar/test/nestmates/nestmates.jar:third_party/ijar/test/records/records.jar:third_party/ijar/test/jar-with-manifest.jar:third_party/ijar/test/jar-with-manifest-and-target-label.jar:third_party/javax_activation/javax.activation-api-1.2.0-sources.jar:third_party/javax_activation/javax.activation-api-1.2.0.jar:third_party/apache_commons_collections/commons-collections-3.2.2.jar:third_party/xz/xz-1.9.jar:third_party/apache_commons_lang/commons-lang-2.6.jar:third_party/junit/junit-4.13.jar:third_party/java-diff-utils/java-diff-utils-4.0.jar:third_party/rxjava3/rxjava-3.1.2.jar:third_party/apache_commons_logging/commons-logging-1.1.1.jar:third_party/jaxb/2.3.0/jaxb-core-2.3.0-sources.jar:third_party/jaxb/2.3.0/jaxb-core-2.3.0.jar:third_party/jaxb/2.3.0/jaxb-api-2.3.0-sources.jar:third_party/jaxb/2.3.0/jaxb-impl-2.3.0.jar:third_party/jaxb/2.3.0/jaxb-api-2.3.0.jar:third_party/jaxb/2.3.0/jaxb-impl-2.3.0-sources.jar:third_party/jaxb/jaxb-api-2.3.1.jar:third_party/jaxb/jaxb-api-2.3.1-patched.jar:third_party/jaxb/jaxb-api-2.3.1-sources.jar:third_party/hungarian_algorithm/software-and-algorithms-1.0.jar:third_party/hungarian_algorithm/software-and-algorithms-1.0-src.jar:third_party/kotlin_stdlib/kotlin-stdlib-jdk8-1.3.21.jar:third_party/kotlin_stdlib/kotlin-stdlib-1.3.21.jar:third_party/kotlin_stdlib/kotlin-stdlib-jdk7-1.3.21.jar:third_party/kotlin_stdlib/kotlin-stdlib-common-1.3.21.jar:third_party/apache_commons_io/commons-io-2.4.jar:third_party/reactive_streams/reactive-streams-1.0.3.jar:third_party/netty/netty-transport-native-unix-common-4.1.69.Final-linux-aarch_64.jar:third_party/netty/netty-handler-proxy-4.1.69.Final.jar:third_party/netty/netty-codec-http2-4.1.69.Final.jar:third_party/netty/netty-buffer-4.1.69.Final.jar:third_party/netty/netty-handler-4.1.69.Final.jar:third_party/netty/netty-transport-native-unix-common-4.1.69.Final-osx-x86_64.jar:third_party/netty/netty-transport-native-epoll-4.1.69.Final-linux-x86_64.jar:third_party/netty/netty-transport-native-unix-common-4.1.69.Final-osx-aarch_64.jar:third_party/netty/netty-transport-native-unix-common-4.1.69.Final.jar:third_party/netty/netty-transport-sctp-4.1.69.Final.jar:third_party/netty/netty-transport-native-kqueue-4.1.69.Final.jar:third_party/netty/netty-transport-native-unix-common-4.1.69.Final-linux-x86_64.jar:third_party/netty/netty-common-4.1.69.Final.jar:third_party/netty/netty-resolver-4.1.69.Final.jar:third_party/netty/netty-transport-native-epoll-4.1.69.Final.jar:third_party/netty/netty-resolver-dns-4.1.69.Final.jar:third_party/netty/netty-transport-4.1.69.Final.jar:third_party/netty/netty-codec-http-4.1.69.Final.jar:third_party/netty/netty-transport-native-epoll-4.1.69.Final-linux-aarch_64.jar:third_party/netty/netty-transport-native-kqueue-4.1.69.Final-osx-aarch_64.jar:third_party/netty/netty-transport-native-kqueue-4.1.69.Final-osx-x86_64.jar:third_party/netty/netty-codec-4.1.69.Final.jar:third_party/auto/auto-service-annotations-1.0-rc7.jar:third_party/auto/auto-value-1.8.2.jar:third_party/auto/auto-service-1.0-rc7.jar:third_party/auto/auto-value-annotations-1.8.2.jar:third_party/auto/auto-common-1.1.2.jar:third_party/truth_proto/truth-proto-extension-1.0.1.jar:third_party/truth_proto/truth-liteproto-extension-1.0.1.jar:third_party/pcollections/pcollections-2.1.2.jar:third_party/jetifier/jetifier-core-1.0.0-beta04.jar:third_party/compile_testing/compile-testing-0.18.jar:third_party/auth/google-auth-library-oauth2-http-1.6.0.jar:third_party/auth/google-auth-library-credentials-1.6.0.jar:third_party/android_common/com.android_annotations_25.0.0.jar:third_party/android_common/com.android.tools.build_builder-test-api_2.0.0.jar:third_party/android_common/com.android.tools_sdk-common_25.0.0-patched-stripped.jar:third_party/android_common/com.android.tools.lint_lint-checks_25.0.0.jar:third_party/android_common/com.android.tools_dvlib_25.0.0.jar:third_party/android_common/com.android.tools.build_builder-model_2.0.0.jar:third_party/android_common/com.android.tools_sdklib_25.0.0.jar:third_party/android_common/com.android.tools.build_manifest-merger_25.0.0-patched.jar:third_party/android_common/com.android.tools_common_25.0.0.jar:third_party/android_common/com.android.tools.layoutlib_layoutlib_26.1.2-stripped.jar:third_party/android_common/com.android.tools_sdk-common_25.0.0-patched.jar:third_party/android_common/com.android.tools.layoutlib_layoutlib_26.1.2.jar:third_party/android_common/com.android.tools.build_builder_2.0.0.jar:third_party/android_common/com.android.tools.external.lombok_lombok-ast_0.2.3.jar:third_party/android_common/com.android.tools.lint_lint-api_25.0.0.jar:third_party/android_common/com.android.tools_repository_25.0.0.jar:third_party/opencensus/opencensus-api-0.24.0.jar:third_party/opencensus/opencensus-contrib-grpc-metrics-0.24.0.jar:third_party/gson/gson-2.8.0.jar:third_party/apache_commons_codec/commons-codec-1.10.jar:third_party/bytebuddy/byte-buddy-agent-1.9.7.jar:third_party/bytebuddy/byte-buddy-1.9.7.jar::third_party/grpc/grpc-core-1.41.0.jar:third_party/grpc/grpc-stub-1.41.0.jar:third_party/grpc/grpc-context-1.41.0.jar:third_party/grpc/grpc-protobuf-lite-1.41.0.jar:third_party/grpc/grpc-protobuf-1.41.0.jar:third_party/grpc/grpc-api-1.41.0.jar:third_party/grpc/grpc-netty-1.41.0.jar:third_party/grpc/grpc-auth-1.41.0.jar::third_party/guava/guava-30.1.1-jre.jar:third_party/guava/guava-testlib-30.1.1-jre.jar::/var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61 -sourcepath src/java_tools/singlejar/java/com/google/devtools/build/zip:src/main/java:tools/java/runfiles:/var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/src -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes -source 1.8 -target 1.8 -encoding UTF-8 @/var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_owYrdOr7/param\r\nwarning: [options] bootstrap class path not set in conjunction with -source 8\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:17: warning: Signal is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Signal;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:18: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\nimport sun.misc.SignalHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/DynamicCodec.java:30: warning: ReflectionFactory is internal proprietary API and may be removed in a future release\r\nimport sun.reflect.ReflectionFactory;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/EnumMapCodec.java:23: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:18: warning: [removal] AccessController in java.security has been deprecated and marked for removal\r\nimport java.security.AccessController;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:17: warning: Signal is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Signal;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:18: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\nimport sun.misc.SignalHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/DynamicCodec.java:30: warning: ReflectionFactory is internal proprietary API and may be removed in a future release\r\nimport sun.reflect.ReflectionFactory;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/EnumMapCodec.java:23: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:18: warning: [removal] AccessController in java.security has been deprecated and marked for removal\r\nimport java.security.AccessController;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:17: warning: Signal is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Signal;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:18: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\nimport sun.misc.SignalHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/DynamicCodec.java:30: warning: ReflectionFactory is internal proprietary API and may be removed in a future release\r\nimport sun.reflect.ReflectionFactory;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/EnumMapCodec.java:23: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:18: warning: [removal] AccessController in java.security has been deprecated and marked for removal\r\nimport java.security.AccessController;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:17: warning: Signal is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Signal;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:18: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\nimport sun.misc.SignalHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/DynamicCodec.java:30: warning: ReflectionFactory is internal proprietary API and may be removed in a future release\r\nimport sun.reflect.ReflectionFactory;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/EnumMapCodec.java:23: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:18: warning: [removal] AccessController in java.security has been deprecated and marked for removal\r\nimport java.security.AccessController;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:21: warning: Unsafe is internal proprietary API and may be removed in a future release\r\nimport sun.misc.Unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:29: warning: Signal is internal proprietary API and may be removed in a future release\r\n private static final Signal SIGINT = new Signal(\"INT\");\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:29: warning: Signal is internal proprietary API and may be removed in a future release\r\n private static final Signal SIGINT = new Signal(\"INT\");\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:29: warning: Signal is internal proprietary API and may be removed in a future release\r\n private static final Signal SIGINT = new Signal(\"INT\");\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:29: warning: Signal is internal proprietary API and may be removed in a future release\r\n private static final Signal SIGINT = new Signal(\"INT\");\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:29: warning: Signal is internal proprietary API and may be removed in a future release\r\n private static final Signal SIGINT = new Signal(\"INT\");\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:31: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\n private SignalHandler oldHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:31: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\n private SignalHandler oldHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:31: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\n private SignalHandler oldHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:31: warning: SignalHandler is internal proprietary API and may be removed in a future release\r\n private SignalHandler oldHandler;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:39: warning: Signal is internal proprietary API and may be removed in a future release\r\n this.oldHandler = Signal.handle(SIGINT, signal -> run());\r\n ^\r\nwarning: Signal is internal proprietary API and may be removed in a future release\r\nsrc/main/java/com/google/devtools/build/lib/server/signal/InterruptSignalHandler.java:45: warning: Signal is internal proprietary API and may be removed in a future release\r\n Signal.handle(SIGINT, oldHandler);\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/DynamicCodec.java:276: warning: ReflectionFactory is internal proprietary API and may be removed in a future release\r\n ReflectionFactory.getReflectionFactory()\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/skyframe/serialization/EnumMapCodec.java:59: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n Unsafe unsafe = UnsafeProvider.getInstance();\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:38: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private final Unsafe unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:38: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private final Unsafe unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:38: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private final Unsafe unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java:38: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private final Unsafe unsafe;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:31: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static final Unsafe UNSAFE = getUnsafe();\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:31: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static final Unsafe UNSAFE = getUnsafe();\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:31: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static final Unsafe UNSAFE = getUnsafe();\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:31: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static final Unsafe UNSAFE = getUnsafe();\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:33: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n public static Unsafe getInstance() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:33: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n public static Unsafe getInstance() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:33: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n public static Unsafe getInstance() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:33: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n public static Unsafe getInstance() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:43: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static Unsafe getUnsafe() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:43: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static Unsafe getUnsafe() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:43: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static Unsafe getUnsafe() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:43: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n private static Unsafe getUnsafe() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:48: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n new PrivilegedExceptionAction<Unsafe>() {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:50: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n public Unsafe run() throws Exception {\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:51: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n Class<Unsafe> unsafeClass = Unsafe.class;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:51: warning: Unsafe is internal proprietary API and may be removed in a future release\r\n Class<Unsafe> unsafeClass = Unsafe.class;\r\n ^\r\nsrc/main/java/com/google/devtools/build/lib/unsafe/UnsafeProvider.java:47: warning: [removal] AccessController in java.security has been deprecated and marked for removal\r\n return AccessController.doPrivileged(\r\n ^\r\nwarning: Implicitly compiled files were not subject to annotation processing.\r\n Use -proc:none to disable annotation processing or -implicit to specify a policy for implicit compilation.\r\nNote: Some input files use or override a deprecated API.\r\nNote: Recompile with -Xlint:deprecation for details.\r\nNote: Some input files use unchecked or unsafe operations.\r\nNote: Recompile with -Xlint:unchecked for details.\r\n65 warnings\r\n.unzip -qn derived/jars/zstd-jni/libzstd-jni.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn derived/jars/com_google_protobuf/java/core/liblite.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn derived/jars/com_google_protobuf/java/core/libcore.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn derived/jars/com_google_protobuf/java/util/libutil.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_annotations/checker-qual-3.2.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_annotations/checker-qual-3.2.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/javax_annotations/javax.annotation-api-1.3.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/javax_annotations/javax.annotation-api-1.3.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/truth/truth-1.0.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libserialization-constant-annotation.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libserialization-constant-processor.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libserialization.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libautocodec-processor.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libunsafe-provider.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libautocodec-annotation.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libserialization-processor-util.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bazel_bootstrap/libregistered-singleton.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/turbine/turbine_direct.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jcip_annotations/jcip-annotations-1.0-1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_pool2/commons-pool2-2.8.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_compress/apache-commons-compress-1.19.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/animal_sniffer/animal-sniffer-annotations-1.14.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/flogger/flogger-system-backend-0.5.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/flogger/flogger-0.5.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/flogger/google-extensions-0.5.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jetbrains_annotations/annotations-13.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/truth8/truth-java8-extension-1.0.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/objenesis/objenesis-1_3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/api_client/google-api-client-1.22.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/api_client/google-api-client-gson-1.22.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/api_client/google-http-client-1.22.0-SNAPSHOT.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/api_client/google-http-client-gson-1.22.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/tomcat_annotations_api/tomcat-annotations-api-8.0.5.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jimfs/jimfs-1.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/hamcrest/hamcrest-core-1.3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/diffutils/diffutils-1.3.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/caffeine/caffeine-2.9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_javacutil/javacutil-3.2.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_javacutil/javacutil-3.2.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jsr330_inject/javax.inject.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jdk/langtools/jdk_compiler-src.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jdk/langtools/jdk_compiler.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jdk/langtools/java_compiler.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jdk/langtools/java_compiler-src.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jdk/langtools/javac-9+181-r4173-1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/proguard/proguard6.2.2/lib/proguard.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/proguard/proguard6.2.2/lib/proguardgui.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/proguard/proguard6.2.2/lib/retrace.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/javapoet/javapoet-1.8.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/android_databinding/v3_4_0/base.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/android_databinding/v3_4_0/exec.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/android_databinding/v3_4_0/x_common.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/android_databinding/v3_4_0/compiler.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/android_databinding/v3_4_0/compiler_common.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.ant-0.8.7-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.agent-0.8.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.ant-0.8.7-nodeps.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.agent-0.8.7-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.core-0.8.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/jacocoagent-0.8.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.report-0.8.7-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.ant-0.8.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.report-0.8.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jacoco/org.jacoco.core-0.8.7-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/j2objc-annotations/j2objc-annotations-1.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java/jcommander/jcommander-1.48.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/juniversalchardet/juniversalchardet-1.0.3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/guava/failureaccess-1.0.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_dataflow/dataflow-errorprone-3.15.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_dataflow/dataflow-shaded-3.11.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_dataflow/dataflow-errorprone-3.15.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/checker_framework_dataflow/dataflow-shaded-3.11.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jsr305/jsr-305.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-util-9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-util-9.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-commons-9.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-tree-9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-analysis-9.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-commons-9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-analysis-9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-9.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-tree-9.2-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/asm/asm-9.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_velocity/velocity-1.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/mockito/mockito-core-3.12.4.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/allocation_instrumenter/java-allocation-instrumenter-3.3.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/antlr/antlr4-4.5.3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/perfmark/perfmark-api-0.19.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/error_prone_core-2.9.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/threeten-extra-1.5.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/error_prone_type_annotations-2.9.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/error_prone_annotation-2.9.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/error_prone_annotations-2.9.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/error_prone/error_prone_check_api-2.9.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/libwrongcentraldir.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/jar-without-manifest.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/sealed/sealed.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/nestmates/nestmates.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/records/records.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/jar-with-manifest.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/ijar/test/jar-with-manifest-and-target-label.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/javax_activation/javax.activation-api-1.2.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/javax_activation/javax.activation-api-1.2.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_collections/commons-collections-3.2.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/xz/xz-1.9.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_lang/commons-lang-2.6.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/junit/junit-4.13.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/java-diff-utils/java-diff-utils-4.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/rxjava3/rxjava-3.1.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_logging/commons-logging-1.1.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-core-2.3.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-core-2.3.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-api-2.3.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-impl-2.3.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-api-2.3.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/2.3.0/jaxb-impl-2.3.0-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/jaxb-api-2.3.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/jaxb-api-2.3.1-patched.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jaxb/jaxb-api-2.3.1-sources.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/hungarian_algorithm/software-and-algorithms-1.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/hungarian_algorithm/software-and-algorithms-1.0-src.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/kotlin_stdlib/kotlin-stdlib-jdk8-1.3.21.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/kotlin_stdlib/kotlin-stdlib-1.3.21.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/kotlin_stdlib/kotlin-stdlib-jdk7-1.3.21.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/kotlin_stdlib/kotlin-stdlib-common-1.3.21.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_io/commons-io-2.4.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/reactive_streams/reactive-streams-1.0.3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-unix-common-4.1.69.Final-linux-aarch_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-handler-proxy-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-codec-http2-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-buffer-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-handler-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-unix-common-4.1.69.Final-osx-x86_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-epoll-4.1.69.Final-linux-x86_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-unix-common-4.1.69.Final-osx-aarch_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-unix-common-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-sctp-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-kqueue-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-unix-common-4.1.69.Final-linux-x86_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-common-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-resolver-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-epoll-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-resolver-dns-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-codec-http-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-epoll-4.1.69.Final-linux-aarch_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-kqueue-4.1.69.Final-osx-aarch_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-transport-native-kqueue-4.1.69.Final-osx-x86_64.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/netty/netty-codec-4.1.69.Final.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auto/auto-service-annotations-1.0-rc7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auto/auto-value-1.8.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auto/auto-service-1.0-rc7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auto/auto-value-annotations-1.8.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auto/auto-common-1.1.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/truth_proto/truth-proto-extension-1.0.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/truth_proto/truth-liteproto-extension-1.0.1.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/pcollections/pcollections-2.1.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/jetifier/jetifier-core-1.0.0-beta04.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/compile_testing/compile-testing-0.18.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auth/google-auth-library-oauth2-http-1.6.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/auth/google-auth-library-credentials-1.6.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android_annotations_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.build_builder-test-api_2.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_sdk-common_25.0.0-patched-stripped.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.lint_lint-checks_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_dvlib_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.build_builder-model_2.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_sdklib_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.build_manifest-merger_25.0.0-patched.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_common_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.layoutlib_layoutlib_26.1.2-stripped.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_sdk-common_25.0.0-patched.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.layoutlib_layoutlib_26.1.2.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.build_builder_2.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.external.lombok_lombok-ast_0.2.3.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools.lint_lint-api_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/android_common/com.android.tools_repository_25.0.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/opencensus/opencensus-api-0.24.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/opencensus/opencensus-contrib-grpc-metrics-0.24.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/gson/gson-2.8.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/apache_commons_codec/commons-codec-1.10.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bytebuddy/byte-buddy-agent-1.9.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/bytebuddy/byte-buddy-1.9.7.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-core-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-stub-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-context-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-protobuf-lite-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-protobuf-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-api-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-netty-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/grpc/grpc-auth-1.41.0.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/guava/guava-30.1.1-jre.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\nunzip -qn third_party/guava/guava-testlib-30.1.1-jre.jar -d /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes\r\n./opt/openjdk-bin-17.0.3_p7/bin/jar cmf /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/MANIFEST.MF /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/libblaze.jar -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes A.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes AUTHORS -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes AnnotatedClass.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes Annotations$ParametersOnlyAnnotation.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes Annotations$RuntimeInvisible.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes Annotations$RuntimeVisible.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes Annotations.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes B.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes LICENSE -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes LICENSE-junit.txt -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes LICENSE.txt -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes MANIFEST.MF -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes NOTICE -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes NOTICE.txt -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes NestTest$P.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes NestTest.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes RecordTest.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes SealedTest$Bar.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes SealedTest$Foo.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes SealedTest.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes about.html -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes android -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes androidx -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes api-versions.xml -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes api_diff.proto -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes autovalue -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes blogspot -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes build -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes com -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes data_binding_version_info.properties -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes default.config -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes default.generated.config -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes deps.proto -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes difflib -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes io -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes jacocoagent.jar -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes javax -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes jdk -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes junit -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes kotlin -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes libzstd-jni.so -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes lombok -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes manifest.proto -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes module-info.class -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes module-info.java -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes net -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes org -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes pom.xml -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes proguard -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes sun -C /var/tmp/portage/dev-util/bazel-5.2.0/temp/bazel_bf8keP61/classes textfile.txt\r\n..\r\nBuilding Bazel with Bazel.\r\n.OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.\r\nINFO: Analyzed target //src:bazel_nojdk (367 packages loaded, 10170 targets configured).\r\nINFO: Found 1 target...\r\n[0 / 653] [Prepa] BazelWorkspaceStatusAction stable-status.txt\r\nFATAL: bazel crashed due to an internal error. Printing stack trace:\r\njava.lang.ExceptionInInitializerError\r\n at com.google.devtools.build.lib.actions.ParameterFile.writeContent(ParameterFile.java:118)\r\n at com.google.devtools.build.lib.actions.ParameterFile.writeParameterFile(ParameterFile.java:111)\r\n at com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction$ParamFileWriter.writeOutputFile(ParameterFileWriteAction.java:170)\r\n at com.google.devtools.build.lib.exec.FileWriteStrategy.beginWriteOutputToFile(FileWriteStrategy.java:58)\r\n at com.google.devtools.build.lib.analysis.actions.FileWriteActionContext.beginWriteOutputToFile(FileWriteActionContext.java:49)\r\n at com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction.beginExecution(AbstractFileWriteAction.java:66)\r\n at com.google.devtools.build.lib.actions.Action.execute(Action.java:133)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$5.execute(SkyframeActionExecutor.java:907)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.continueAction(SkyframeActionExecutor.java:1076)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.run(SkyframeActionExecutor.java:1031)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.runStateMachine(ActionExecutionState.java:152)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.getResultOrDependOnFuture(ActionExecutionState.java:91)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:492)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:856)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:349)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:169)\r\n at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:590)\r\n at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n at java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not \"opens java.lang\" to unnamed module @3e07d849\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)\r\n at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:188)\r\n at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:181)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.<init>(StringUnsafe.java:75)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.initInstance(StringUnsafe.java:56)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.<clinit>(StringUnsafe.java:37)\r\n ... 21 more\r\n```",
"The same issue happens for me with Bazel 5.3 and OpenJDK 17, `StringUnsafe`'s constructor fails with an `java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not \"opens java.lang\" to unnamed module` error:\r\n\r\n```\r\nFATAL: bazel crashed due to an internal error. Printing stack trace:\r\njava.lang.ExceptionInInitializerError\r\n at com.google.devtools.build.lib.actions.ParameterFile.writeContent(ParameterFile.java:118)\r\n at com.google.devtools.build.lib.actions.ParameterFile.writeParameterFile(ParameterFile.java:111)\r\n at com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction$ParamFileWriter.writeOutputFile(ParameterFileWriteAction.java:170)\r\n at com.google.devtools.build.lib.exec.FileWriteStrategy.beginWriteOutputToFile(FileWriteStrategy.java:58)\r\n at com.google.devtools.build.lib.analysis.actions.FileWriteActionContext.beginWriteOutputToFile(FileWriteActionContext.java:49)\r\n at com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction.beginExecution(AbstractFileWriteAction.java:66)\r\n at com.google.devtools.build.lib.actions.Action.execute(Action.java:133)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$5.execute(SkyframeActionExecutor.java:907)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.continueAction(SkyframeActionExecutor.java:1076)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.run(SkyframeActionExecutor.java:1031)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.runStateMachine(ActionExecutionState.java:152)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.getResultOrDependOnFuture(ActionExecutionState.java:91)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:492)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:856)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:349)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:169)\r\n at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:590)\r\n at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\r\n at java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not \"opens java.lang\" to unnamed module @3e07d849\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)\r\n at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:188)\r\n at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:181)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.<init>(StringUnsafe.java:75)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.initInstance(StringUnsafe.java:56)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.<clinit>(StringUnsafe.java:37)\r\n ... 21 more\r\n```",
"/cc @cushon ",
"```\r\nCaused by: java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not \"opens java.lang\" to unnamed module @3e07d849\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)\r\n at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)\r\n at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:188)\r\n at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:181)\r\n at com.google.devtools.build.lib.unsafe.StringUnsafe.<init>(StringUnsafe.java:75)\r\n```\r\n\r\nThis is https://openjdk.org/jeps/403\r\n\r\nThe workaround is to pass `--add-opens=java.base/java.nio=ALL-UNNAMED` as a server JVM flag. The bazel launcher already passes that flag, but only for embedded JDKs:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/03ad0cd1203b7b54ec02ea3f5788d1d673a9d6d6/src/main/cpp/blaze.cc#L362-L367",
"> The workaround is to pass `--add-opens=java.base/java.nio=ALL-UNNAMED` as a server JVM flag\r\n\r\n@cushon \r\nHow to do that? I've tried `--jvmopt=--add-opens=java.base/java.nio=ALL-UNNAMED` unsuccessfully.",
"I think you want `bazel --host_jvm_args=--add-opens=java.base/java.nio=ALL-UNNAMED build ...`, see https://bazel.build/docs/user-manual#host-jvm-args\r\n\r\nThis needs to be passed to the JVM running Bazel itself, `bazel build --jvmopt=...` is configuring JVM flags for the JVM in the target configuration (e.g. for a `java_binary` or `java_test`)",
"The command executed successfully but it didn't fix my issue. Still seeing `Unable to make java.lang.String(byte[],byte) accessible: module java.base does not \"opens java.lang\" to unnamed module`.\r\n\r\nAnyway, as a workaround, I'm using `asdf` to use the `openjdk-11` in my project for now.\r\n\r\nThank you for your help.",
"> java.base does not \"opens java.lang\"\r\n\r\nThat one requires `--add-opens=java.base/java.lang=ALL-UNNAMED`, not `--add-opens=java.base/java.nio=ALL-UNNAMED`, you might need to pass multiple `--add-opens=` flags",
"Thank you @cushon. The command below worked:\r\n```\r\nbazel \\\r\n--host_jvm_args=\"--add-opens=java.base/java.nio=ALL-UNNAMED\" \\\r\n--host_jvm_args=\"--add-opens=java.base/java.lang=ALL-UNNAMED\" \\\r\nbuild ...\r\n```"
] | [] | "2022-11-18T04:24:42Z" | [
"P4",
"type: support / not a bug (process)",
"team-Rules-Java"
] | Bazel 5.1.1 with openjdk17 server | ### Description of the bug:
If using openjdk17 as bazel server runtime some actions may fail
```
java.lang.ExceptionInInitializerError
at com.google.devtools.build.lib.actions.ParameterFile.writeContent(ParameterFile.java:118)
at com.google.devtools.build.lib.actions.ParameterFile.writeParameterFile(ParameterFile.java:111)
at com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction$ParamFileWriter.writeOutputFile(ParameterFileWriteAction.java:170)
at com.google.devtools.build.lib.exec.FileWriteStrategy.beginWriteOutputToFile(FileWriteStrategy.java:58)
at com.google.devtools.build.lib.analysis.actions.FileWriteActionContext.beginWriteOutputToFile(FileWriteActionContext.java:49)
at com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction.beginExecution(AbstractFileWriteAction.java:66)
at com.google.devtools.build.lib.actions.Action.execute(Action.java:133)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$5.execute(SkyframeActionExecutor.java:907)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.continueAction(SkyframeActionExecutor.java:1076)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.run(SkyframeActionExecutor.java:1031)
at com.google.devtools.build.lib.skyframe.ActionExecutionState.runStateMachine(ActionExecutionState.java:152)
at com.google.devtools.build.lib.skyframe.ActionExecutionState.getResultOrDependOnFuture(ActionExecutionState.java:91)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:492)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:856)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:349)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:169)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:590)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make java.lang.String(byte[],byte) accessible: module java.base does not "opens java.lang" to unnamed module @5e3c3cb
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:188)
at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:181)
at com.google.devtools.build.lib.unsafe.StringUnsafe.<init>(StringUnsafe.java:75)
at com.google.devtools.build.lib.unsafe.StringUnsafe.initInstance(StringUnsafe.java:56)
at com.google.devtools.build.lib.unsafe.StringUnsafe.<clinit>(StringUnsafe.java:37)
... 21 more
```
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Haven't minimized this yet, also not yet tested with newer bazel releases
### Which operating system are you running Bazel on?
NixOS
### What is the output of `bazel info release`?
release 5.1.1- (@non-git)
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
NixOS nixpkgs
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
https://openjdk.org/jeps/403
since java16 default is
> -illegal-access=deny disables all illegal-access operations except for those enabled by other command-line options, e.g., --add-opens.
Something like `--add-opens=java.base/java.lang=ALL-UNNAMED` for server jvm flags could be a workaround
somewhat related https://github.com/bazelbuild/bazel/issues/5599
reflection is still present in latest bazel source code https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/unsafe/StringUnsafe.java | [
"src/main/cpp/blaze.cc"
] | [
"src/main/cpp/blaze.cc"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 5907865fb70b7f..ee0b32268bf47d 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -359,13 +359,10 @@ static vector<string> GetServerExeArgs(const blaze_util::Path &jvm_path,
startup_options.AddJVMArgumentPrefix(jvm_path.GetParent().GetParent(),
&result);
- // TODO(b/109998449): only assume JDK >= 9 for embedded JDKs
- if (!startup_options.GetEmbeddedJavabase().IsEmpty()) {
- // quiet warnings from com.google.protobuf.UnsafeUtil,
- // see: https://github.com/google/protobuf/issues/3781
- result.push_back("--add-opens=java.base/java.nio=ALL-UNNAMED");
- result.push_back("--add-opens=java.base/java.lang=ALL-UNNAMED");
- }
+ // com.google.devtools.build.lib.unsafe.StringUnsafe uses reflection to access
+ // private fields in java.lang.String. The Bazel server requires Java 11, so
+ // this option is known to be supported.
+ result.push_back("--add-opens=java.base/java.lang=ALL-UNNAMED");
result.push_back("-Xverify:none");
| null | train | val | 2022-11-17T18:16:28 | "2022-07-07T13:39:54Z" | dmivankov | test |
bazelbuild/bazel/15340_16830 | bazelbuild/bazel | bazelbuild/bazel/15340 | bazelbuild/bazel/16830 | [
"keyword_pr_to_issue"
] | 06f9202e813d649b4ea48aa48cb0668fecb9cefa | d0b78055480ecdc57848dfe9289568bc6f9e6980 | [
"Looping in @frazze-jobb who wrote the hermetic sandbox code.",
"Leaving out `--experimental_use_sandboxfs` doesn't change this but reduces the problem space.",
"@frazze-jobb is on another project now. I worked with him on this sandbox and answer instead.\r\n\r\nThanks for reporting this issue.\r\n\r\nI will try to find time to investigate this and planning to create test cases for a few related special cases.\r\n",
"FYI, I'm encountering the same problem in the context of a hermtic cc_toolchain using a symlink.\r\nMinimal reproducible example:\r\n```\r\n#!/bin/bash\r\nset -exuo pipefail\r\n\r\n# Create files for bazel\r\ntouch src.cc\r\nmkdir a\r\nln -s a b\r\n\r\ntouch WORKSPACE\r\ncat > BUILD << EOF\r\nload(\"toolchain.bzl\", \"gcc_toolchain\")\r\n\r\ncc_binary(\r\n name = \"test\",\r\n srcs = [\"src.cc\"],\r\n)\r\n\r\ncc_toolchain_suite(\r\n name = \"my_toolchain\",\r\n toolchains = {\"k8\": \"dummy_toolchain\"},\r\n)\r\n\r\nfilegroup(\r\n name = \"compiler_files\",\r\n srcs = [\"b\"],\r\n)\r\n\r\ngcc_toolchain(\"dummy_toolchain\")\r\nEOF\r\n\r\ncat > toolchain.bzl << EOF\r\ndef _impl(ctx):\r\n crosstool_proto = cc_common.create_cc_toolchain_config_info(\r\n ctx = ctx,\r\n toolchain_identifier = \"cc-compiler-\" + ctx.label.name,\r\n host_system_name = \"x86_64-linux-gnu\",\r\n target_system_name = \"linux\",\r\n target_cpu = \"k8\",\r\n target_libc = \"unknown-glibc\",\r\n compiler = \"gcc\",\r\n )\r\n return [crosstool_proto]\r\n\r\ngcc_toolchain_configuration = rule(\r\n attrs = {},\r\n provides = [CcToolchainConfigInfo],\r\n implementation = _impl,\r\n)\r\n\r\ndef gcc_toolchain(name):\r\n gcc_toolchain_configuration(name = name + \"_configuration\")\r\n\r\n native.cc_toolchain(\r\n name = name,\r\n toolchain_config = name + \"_configuration\",\r\n all_files = \"//:compiler_files\",\r\n compiler_files = \"//:compiler_files\",\r\n dwp_files = \"//:compiler_files\",\r\n linker_files = \"//:compiler_files\",\r\n objcopy_files = \"//:compiler_files\",\r\n strip_files = \"//:compiler_files\",\r\n supports_param_files = True,\r\n supports_header_parsing = True,\r\n )\r\nEOF\r\n```\r\n\r\nTrying to build the binary via\r\n```\r\nbazel build //:test --crosstool_top=//:my_toolchain --experimental_use_hermetic_linux_sandbox\r\n```\r\n\r\nresults in\r\n```\r\nERROR: .../BUILD:3:10: Compiling src.cc failed: I/O exception during sandboxed execution: input dependency /home/.../de7a35bfd5cefbaf6a88e91201c016c4/execroot/__main__/b could not be checked for modifications during execution.\r\n```",
"So the command-line output is not that useful, but looking into the server log I see this stack trace which shows a UnsupportedOperationException at FileArtifactValue.java:352 - it's trying to get a ContentsProxy of a directory, which isn't supported. Despite what FileArtifactValue may think, it's not always an actual file. So the modification check should take appropriate action on things that are not files.\r\n\r\n```\r\ncom.google.devtools.build.lib.skyframe.ActionExecutionFunction$ActionExecutionFunctionException: com.google.devtools.build.lib.actions.AlreadyReportedActionEx\r\necutionException: I/O exception during sandboxed execution: input dependency /usr/local/google/home/larsrc/.cache/bazel/_bazel_larsrc/b91bdcc9c8a35d79096b4ba9\r\nb5794356/execroot/__main__/b could not be checked for modifications during execution.\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:368)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:169)\r\n at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:590)\r\n at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)\r\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)\r\n at java.base/java.lang.Thread.run(Unknown Source)\r\nCaused by: com.google.devtools.build.lib.actions.AlreadyReportedActionExecutionException: I/O exception during sandboxed execution: input dependency /usr/loca\r\nl/google/home/larsrc/.cache/bazel/_bazel_larsrc/b91bdcc9c8a35d79096b4ba9b5794356/execroot/__main__/b could not be checked for modifications during execution.\r\n ... 7 more\r\nCaused by: com.google.devtools.build.lib.actions.UserExecException: I/O exception during sandboxed execution: input dependency /usr/local/google/home/larsrc/.\r\ncache/bazel/_bazel_larsrc/b91bdcc9c8a35d79096b4ba9b5794356/execroot/__main__/b could not be checked for modifications during execution.\r\n at com.google.devtools.build.lib.sandbox.AbstractSandboxSpawnRunner.exec(AbstractSandboxSpawnRunner.java:97)\r\n at com.google.devtools.build.lib.sandbox.SandboxModule$SandboxFallbackSpawnRunner.exec(SandboxModule.java:494)\r\n at com.google.devtools.build.lib.exec.SpawnRunner.execAsync(SpawnRunner.java:245)\r\n at com.google.devtools.build.lib.exec.AbstractSpawnStrategy.exec(AbstractSpawnStrategy.java:146)\r\n at com.google.devtools.build.lib.exec.AbstractSpawnStrategy.exec(AbstractSpawnStrategy.java:108)\r\n at com.google.devtools.build.lib.actions.SpawnStrategy.beginExecution(SpawnStrategy.java:47)\r\n at com.google.devtools.build.lib.exec.SpawnStrategyResolver.beginExecution(SpawnStrategyResolver.java:68)\r\n at com.google.devtools.build.lib.rules.cpp.CppCompileAction.beginExecution(CppCompileAction.java:1454)\r\n at com.google.devtools.build.lib.actions.Action.execute(Action.java:133)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$5.execute(SkyframeActionExecutor.java:907)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.continueAction(SkyframeActionExecutor.java:1076)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionR\r\nunner.run(SkyframeActionExecutor.java:1031)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.runStateMachine(ActionExecutionState.java:152)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionState.getResultOrDependOnFuture(ActionExecutionState.java:91)\r\n at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:492)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:856)\r\n at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.computeInternal(ActionExecutionFunction.java:349)\r\n ... 6 more\r\nCaused by: java.io.IOException: input dependency /usr/local/google/home/larsrc/.cache/bazel/_bazel_larsrc/b91bdcc9c8a35d79096b4ba9b5794356/execroot/__main__/b could not be checked for modifications during execution.\r\n at com.google.devtools.build.lib.sandbox.LinuxSandboxedSpawnRunner.checkForConcurrentModifications(LinuxSandboxedSpawnRunner.java:399)\r\n at com.google.devtools.build.lib.sandbox.LinuxSandboxedSpawnRunner.verifyPostCondition(LinuxSandboxedSpawnRunner.java:380)\r\n at com.google.devtools.build.lib.sandbox.AbstractSandboxSpawnRunner.runSpawn(AbstractSandboxSpawnRunner.java:136)\r\n at com.google.devtools.build.lib.sandbox.AbstractSandboxSpawnRunner.exec(AbstractSandboxSpawnRunner.java:92)\r\n ... 22 more\r\nCaused by: java.lang.UnsupportedOperationException\r\n at com.google.devtools.build.lib.actions.FileArtifactValue$DirectoryArtifactValue.getContentsProxy(FileArtifactValue.java:352)\r\n at com.google.devtools.build.lib.sandbox.LinuxSandboxedSpawnRunner.checkForConcurrentModifications(LinuxSandboxedSpawnRunner.java:395)\r\n ... 25 more\r\n```",
"Looking at the possible subclasses of FileArtifactValue, they mostly don't support the operations needed for the modification check. @frazze-jobb we'll have to figure out which kinds of inputs to ignore and which to handle properly. Here are the direct subclasses:\r\n\r\n```\r\ngoogle3/third_party/bazel/src/main/java/com/google/devtools/build/lib/actions/ActionCacheChecker.java\r\n851: private static final class ConstantMetadataValue extends FileArtifactValue\r\ngoogle3/third_party/bazel/src/main/java/com/google/devtools/build/lib/actions/FileArtifactValue.java\r\n332: private static final class DirectoryArtifactValue extends FileArtifactValue {\r\n399: private static final class HashedDirectoryArtifactValue extends FileArtifactValue {\r\n462: private static final class RegularFileArtifactValue extends FileArtifactValue {\r\n549: public static class RemoteFileArtifactValue extends FileArtifactValue {\r\n718: public static final class UnresolvedSymlinkArtifactValue extends FileArtifactValue {\r\n758: public static final class InlineFileArtifactValue extends FileArtifactValue {\r\n832: public static final class SourceFileArtifactValue extends FileArtifactValue {\r\n895: private static final class SingletonMarkerValue extends FileArtifactValue implements Singleton {\r\n940: private static final class OmittedFileValue extends FileArtifactValue implements Singleton {\r\ngoogle3/third_party/bazel/src/main/java/com/google/devtools/build/lib/skyframe/TreeArtifactValue.java\r\n210: private static final class TreeArtifactCompositeFileArtifactValue extends FileArtifactValue {\r\n```",
"Thanks for looking into this. Not that it would help much, but leaving this smaller minimal example here for sake of simplicity\r\n```\r\n#!/bin/bash\r\ntouch WORKSPACE\r\nmkdir a\r\nln -s a b\r\n\r\ncat > BUILD << EOF\r\ngenrule(\r\n name = \"target\",\r\n srcs = [\":b\"],\r\n outs = [\"dummy\"],\r\n cmd = \"ls $< > \\$@\",\r\n)\r\nEOF\r\n```\r\n\r\n```\r\nbazel build //:target --experimental_use_hermetic_linux_sandbox\r\n```",
"That's a nice small repro. It can also be done with just a directory as an input, so both directory and symlink handling needs to be fixed.",
"The purpose of `checkForConcurrentModifications` is to check that an action has not changed the content of hardlinked files outside of the sandbox. `HardlinkedSandboxedSpawn.hardLinkRecursive` is resolving symbolic links and are only creating hardlinks for files, not directories. Therefor it should be safe to skip the concurrent modification check when `metadata.getType().isFile()` is false. That should address the use cases in this ticket reliably.\r\n\r\nHowever, then the following subclasses of FileArtifactValue, mentioned by @larsrc-google, remains:\r\n\r\n- ConstantMetadataValue\r\n- InlineFileArtifactValue\r\n- RemoteFileArtifactValue\r\n- SourceFileArtifactValue\r\n\r\nI don't see any good way to handle them. Are they rare? As workaround, should we catch UnsupportedOperationException and log a warning each time it occurs? (That could be up to one warning per action.)",
"Thanks for the fix!\r\n\r\nI don't know anything about Bazel release policies - is this fix likely to make it to a 6.x release?",
"@lunch-glide-pepper You can use the `@bazel-io flag` command in a GitHub comment to mark it for cherry-picking and then create a PR with the commit cherry-picked on `release-6.0.0`."
] | [] | "2022-11-23T16:12:39Z" | [
"type: bug",
"P2",
"team-Local-Exec"
] | I/O exception during sandboxed execution: input dependency could not be checked for modifications during execution | ### Description of the bug:
My build fails with `I/O exception during sandboxed execution: input dependency <path> could not be checked for modifications during execution`. The error seems to be about a symlink inside a tree artifact, with the symlink pointing to a directory inside the same tree artifact, and only happens when using `--experimental_use_hermetic_linux_sandbox`.
Using bazel 5.1.1 (official binaries), and also reproduced with recent master at 4e6153e, on Ubuntu 20.04.
Simplified reproduction below.
I'm sure that I'm doing a number of questionable things that can be achieved in better ways, but the error looks more like a bug than a deliberate error message, so I figured I'd open an issue.
```
#!/bin/bash
cat << 'EOF' > .bazelrc
build --experimental_use_hermetic_linux_sandbox
build --experimental_use_sandboxfs
build --spawn_strategy=linux-sandbox
EOF
cat << 'EOF' > BUILD
load(":defs.bzl", "custom_python_binary", "generate_sum", "python_virtualenv")
python_virtualenv(
name = "virtualenv",
output = "env",
)
custom_python_binary(
name = "add_numbers",
main = "add_numbers.py",
venv = "virtualenv",
)
generate_sum(
name = "two_plus_two",
a = 2,
b = 2,
output = "result.txt",
)
EOF
cat << 'EOF' > defs.bzl
# buildifier: disable=module-docstring
def _python_virtualenv_impl(ctx):
test_directory = ctx.actions.declare_directory(ctx.attr.output)
ctx.actions.run_shell(
command = " && ".join([
'mkdir -p "$DIR_PATH/lib/python3.8/site-packages"',
'echo "add = lambda a, b: a + b" > "$DIR_PATH/lib/python3.8/site-packages/addition.py"',
'ln -s lib "$DIR_PATH/lib64"',
'echo "Change this to trigger rebuild: 1" > /dev/null',
]),
outputs = [test_directory],
env = {"DIR_PATH": test_directory.path},
)
return [DefaultInfo(files = depset([test_directory]))]
python_virtualenv = rule(
implementation = _python_virtualenv_impl,
attrs = {
"output": attr.string(mandatory = True),
},
)
def _custom_python_binary_impl(ctx):
output_file = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(output_file, """#!/bin/bash
set -Eeuo pipefail
BASE_PATH="$(dirname "${BASH_SOURCE[0]}")"
export PYTHONPATH="$BASE_PATH/env/lib/python3.8/site-packages"
exec python3 -B -s -S "%MAIN_FILE_PATH%" "$@"
""".replace("%MAIN_FILE_PATH%", ctx.file.main.path), is_executable = True)
return [
DefaultInfo(
files = depset(direct = [output_file, ctx.file.main] + ctx.files.venv),
runfiles = ctx.runfiles(files = [ctx.file.main] + ctx.files.venv),
executable = output_file,
),
]
custom_python_binary = rule(
implementation = _custom_python_binary_impl,
attrs = {
"main": attr.label(allow_single_file = [".py"], mandatory = True),
"venv": attr.label(allow_files = True, mandatory = True),
},
executable = True,
)
def _generate_sum_impl(ctx):
output_file = ctx.actions.declare_file(ctx.attr.output)
ctx.actions.run_shell(
inputs = ctx.files.tool,
command = " && ".join([
'"$TOOL_PATH" $A $B > "$OUTPUT_PATH"',
]),
outputs = [output_file],
env = {
"A": str(ctx.attr.a),
"B": str(ctx.attr.b),
"TOOL_PATH": ctx.executable.tool.path,
"OUTPUT_PATH": output_file.path,
},
)
return [DefaultInfo(files = depset(direct = [output_file]))]
generate_sum = rule(
implementation = _generate_sum_impl,
attrs = {
"a": attr.int(mandatory = True),
"b": attr.int(mandatory = True),
"output": attr.string(mandatory = True),
"tool": attr.label(executable = True, cfg = "target", default = Label("//:add_numbers")),
},
)
EOF
cat << 'EOF' > add_numbers.py
import sys
from addition import add
a = int(sys.argv[1])
b = int(sys.argv[2])
sum = add(a, b)
print(sum)
EOF
cat << 'EOF' > WORKSPACE
EOF
bazel clean --expunge
bazel build :two_plus_two
```
Output:
```
user@localhost:~/path$ ./bug_report.sh
INFO: Starting clean (this may take a while). Consider using --async if the clean takes more than several minutes.
Starting local Bazel server and connecting to it...
INFO: Analyzed target //:two_plus_two (4 packages loaded, 9 targets configured).
INFO: Found 1 target...
ERROR: /home/user/path/BUILD:14:13: Action result.txt failed: I/O exception during sandboxed execution: input dependency /home/user/.cache/bazel/_bazel_user/c45d20c83f728d794469b8036365b9b4/execroot/__main__/bazel-out/k8-fastbuild/bin/env/lib64 could not be checked for modifications during execution.
Target //:two_plus_two failed to build
INFO: Elapsed time: 2.627s, Critical Path: 0.07s
INFO: 4 processes: 3 internal, 1 linux-sandbox.
FAILED: Build did NOT complete successfully
```
Workaround that makes the build work (and also works in the real codebase that this example is derived from), but I have no idea what this actually does (based on 4e6153e):
```
diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
index ffb7a5f3b7..eb075319e1 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
@@ -24,6 +24,7 @@ import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionRequirements;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.FileContentsProxy;
+import com.google.devtools.build.lib.actions.FileStateType;
import com.google.devtools.build.lib.actions.ForbiddenActionInputException;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.Spawns;
@@ -391,6 +392,11 @@ final class LinuxSandboxedSpawnRunner extends AbstractSandboxSpawnRunner {
}
FileArtifactValue metadata = context.getMetadataProvider().getMetadata(input);
+
+ if (metadata.getType() == FileStateType.DIRECTORY) {
+ continue;
+ }
+
Path path = execRoot.getRelative(input.getExecPath());
try {
```
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
_No response_
### Which operating system are you running Bazel on?
_No response_
### What is the output of `bazel info release`?
_No response_
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [
"src/test/shell/bazel/bazel_hermetic_sandboxing_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
index 1da4ee5b2dfa6b..89eb4a70f0668f 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
@@ -66,6 +66,8 @@ final class LinuxSandboxedSpawnRunner extends AbstractSandboxSpawnRunner {
private static final Map<Path, Boolean> isSupportedMap = new HashMap<>();
private static final AtomicBoolean warnedAboutNonHermeticTmp = new AtomicBoolean();
+ private static final AtomicBoolean warnedAboutUnsupportedModificationCheck = new AtomicBoolean();
+
/**
* Returns whether the linux sandbox is supported on the local machine by running a small command
* in it.
@@ -216,9 +218,7 @@ protected SandboxedSpawn prepareSpawn(Spawn spawn, SpawnExecutionContext context
ImmutableSet<Path> writableDirs = getWritableDirs(sandboxExecRoot, environment);
SandboxInputs inputs =
- helpers.processInputFiles(
- context.getInputMapping(PathFragment.EMPTY_FRAGMENT),
- execRoot);
+ helpers.processInputFiles(context.getInputMapping(PathFragment.EMPTY_FRAGMENT), execRoot);
SandboxOutputs outputs = helpers.getOutputs(spawn);
Duration timeout = context.getTimeout();
@@ -439,22 +439,39 @@ private void checkForConcurrentModifications(SpawnExecutionContext context)
throws IOException, ForbiddenActionInputException {
for (ActionInput input : context.getInputMapping(PathFragment.EMPTY_FRAGMENT).values()) {
if (input instanceof VirtualActionInput) {
+ // Virtual inputs are not existing in file system and can't be tampered with via sandbox. No
+ // need to check them.
continue;
}
FileArtifactValue metadata = context.getMetadataProvider().getMetadata(input);
- Path path = execRoot.getRelative(input.getExecPath());
+ if (!metadata.getType().isFile()) {
+ // The hermetic sandbox creates hardlinks from files inside sandbox to files outside
+ // sandbox. The content of the files outside the sandbox could have been tampered with via
+ // the hardlinks. Therefore files are checked for modifications. But directories and
+ // unresolved symlinks are not represented as hardlinks in sandbox and don't need to be
+ // checked. By continue and not checking them, we avoid UnsupportedOperationException and
+ // IllegalStateException.
+ continue;
+ }
+ Path path = execRoot.getRelative(input.getExecPath());
try {
if (wasModifiedSinceDigest(metadata.getContentsProxy(), path)) {
throw new IOException("input dependency " + path + " was modified during execution.");
}
} catch (UnsupportedOperationException e) {
- throw new IOException(
- "input dependency "
- + path
- + " could not be checked for modifications during execution.",
- e);
+ // Some FileArtifactValue implementations are ignored safely and silently already by the
+ // isFile check above. The remaining ones should probably be checked, but some are not
+ // supporting necessary operations.
+ if (warnedAboutUnsupportedModificationCheck.compareAndSet(false, true)) {
+ reporter.handle(
+ Event.warn(
+ String.format(
+ "Input dependency %s of type %s could not be checked for modifications during"
+ + " execution. Suppressing similar warnings.",
+ path, metadata.getClass().getSimpleName())));
+ }
}
}
}
| diff --git a/src/test/shell/bazel/bazel_hermetic_sandboxing_test.sh b/src/test/shell/bazel/bazel_hermetic_sandboxing_test.sh
index a67f4be7421ebb..51fdf239f25ce7 100755
--- a/src/test/shell/bazel/bazel_hermetic_sandboxing_test.sh
+++ b/src/test/shell/bazel/bazel_hermetic_sandboxing_test.sh
@@ -95,6 +95,37 @@ import import_module
EOF
cat << 'EOF' > examples/hermetic/BUILD
+
+load(
+ "test.bzl",
+ "overwrite_via_symlink",
+ "overwrite_file_from_declared_directory",
+ "subdirectories_in_declared_directory",
+ "other_artifacts",
+)
+
+overwrite_via_symlink(
+ name = "overwrite_via_resolved_symlink",
+ resolve_symlink = True
+)
+
+overwrite_via_symlink(
+ name = "overwrite_via_unresolved_symlink",
+ resolve_symlink = False
+)
+
+overwrite_file_from_declared_directory(
+ name = "overwrite_file_from_declared_directory"
+)
+
+subdirectories_in_declared_directory(
+ name = "subdirectories_in_declared_directory"
+)
+
+other_artifacts(
+ name = "other_artifacts"
+)
+
genrule(
name = "absolute_path",
srcs = ["script_absolute_path.sh"], # unknown_file.txt not referenced.
@@ -129,6 +160,141 @@ genrule(
(echo overwrite text > $(location :input_file)) && \
(echo success > $@)) || (echo fail > $@)",
)
+EOF
+
+ cat << 'EOF' > examples/hermetic/test.bzl
+
+def _overwrite_via_symlink_impl(ctx):
+ file = ctx.actions.declare_file(ctx.attr.name + ".file")
+ if ctx.attr.resolve_symlink:
+ symlink = ctx.actions.declare_file(ctx.attr.name + ".symlink")
+ else:
+ symlink = ctx.actions.declare_symlink(ctx.attr.name + ".symlink")
+
+ ctx.actions.write(file, "")
+
+ if ctx.attr.resolve_symlink:
+ ctx.actions.symlink(
+ output = symlink,
+ target_file = file
+ )
+ # Symlink become resolved to RegularFileArtifactValue.
+ needed_inputs = [symlink]
+ else:
+ ctx.actions.symlink(
+ output = symlink,
+ target_path = file.basename
+ )
+ # Symlink become UnresolvedSymlinkArtifactValue and would be
+ # dangling unless also providing the actual file as input to sandbox.
+ needed_inputs = [symlink, file]
+
+ result_file = ctx.actions.declare_file(ctx.attr.name + ".result")
+
+ # Try invalid write to the input file via the symlink
+ ctx.actions.run_shell(
+ command = "chmod u+w $1 && echo hello >> $1 && ls -lR > $2",
+ arguments = [symlink.path, result_file.path],
+ inputs = needed_inputs,
+ outputs = [result_file],
+ )
+
+ return [DefaultInfo(files = depset([result_file]))]
+
+overwrite_via_symlink = rule(
+ attrs = {
+ "resolve_symlink" : attr.bool(),
+ },
+ implementation = _overwrite_via_symlink_impl,
+)
+
+
+def _overwrite_file_from_declared_directory_impl(ctx):
+ dir = ctx.actions.declare_directory(ctx.attr.name + ".dir")
+
+ ctx.actions.run_shell(
+ command = "mkdir -p $1/subdir && touch $1/subdir/file",
+ arguments = [dir.path],
+ outputs = [dir],
+ )
+
+ # Try invalid write to input file, with file as implicit input
+ # from declared directory.
+ result_file = ctx.actions.declare_file(ctx.attr.name + ".result")
+ ctx.actions.run_shell(
+ command = "chmod -R u+w $1 && echo hello >> $1/subdir/file && touch $2",
+ arguments = [dir.path, result_file.path],
+ inputs = [dir],
+ outputs = [result_file],
+ )
+
+ return [DefaultInfo(files = depset([result_file]))]
+
+overwrite_file_from_declared_directory = rule(
+ implementation = _overwrite_file_from_declared_directory_impl,
+)
+
+
+def _subdirectories_in_declared_directory_impl(ctx):
+ dir = ctx.actions.declare_directory(ctx.attr.name + ".dir")
+
+ ctx.actions.run_shell(
+ command = "mkdir -p %s/subdir1/subdir2" % dir.path,
+ outputs = [dir],
+ )
+
+ result_file = ctx.actions.declare_file(ctx.attr.name + ".result")
+ ctx.actions.run_shell(
+ command = "ls -lRH %s > %s" % (dir.path, result_file.path),
+ inputs = [dir],
+ outputs = [result_file],
+ )
+
+ return [DefaultInfo(files = depset([result_file]))]
+
+subdirectories_in_declared_directory = rule(
+ implementation = _subdirectories_in_declared_directory_impl,
+)
+
+
+def _other_artifacts_impl(ctx):
+
+ # Produce artifacts of other types
+
+ regular_file_artifact = ctx.actions.declare_file(ctx.attr.name + ".regular_file_artifact")
+ directory_artifact = ctx.actions.declare_file(ctx.attr.name + ".directory_artifact")
+ tree_artifact = ctx.actions.declare_directory(ctx.attr.name + ".tree_artifact")
+ unresolved_symlink_artifact = ctx.actions.declare_symlink(ctx.attr.name + ".unresolved_symlink_artifact")
+
+ ctx.actions.run_shell(
+ command = "touch %s && mkdir %s" % (regular_file_artifact.path, directory_artifact.path),
+ outputs = [regular_file_artifact, tree_artifact, directory_artifact],
+ )
+
+ ctx.actions.symlink(
+ output = unresolved_symlink_artifact,
+ target_path="dangling"
+ )
+
+ # Test other artifact types as input to hermetic sandbox.
+
+ all_artifacts = [regular_file_artifact,
+ directory_artifact,
+ tree_artifact,
+ unresolved_symlink_artifact]
+ input_paths_string = " ".join([a.path for a in all_artifacts])
+ result_file = ctx.actions.declare_file(ctx.attr.name + ".result")
+ ctx.actions.run_shell(
+ command = "ls -lR %s > %s" % (input_paths_string, result_file.path),
+ inputs = all_artifacts,
+ outputs = [result_file],
+ )
+
+ return [DefaultInfo(files = depset([result_file]))]
+
+other_artifacts = rule(
+ implementation = _other_artifacts_impl,
+)
EOF
}
@@ -141,8 +307,6 @@ function test_absolute_path() {
# Test that the build can't escape the sandbox by resolving symbolic link.
function test_symbolic_link() {
- [ "$PLATFORM" != "darwin" ] || return 0
-
bazel build examples/hermetic:symbolic_link &> $TEST_log \
&& fail "Fail due to non hermetic sandbox: examples/hermetic:symbolic_link" || true
expect_log "cat: \/execroot\/main\/examples\/hermetic\/unknown_file.txt: No such file or directory"
@@ -150,8 +314,6 @@ function test_symbolic_link() {
# Test that the sandbox discover if the bazel python rule miss dependencies.
function test_missing_python_deps() {
- [ "$PLATFORM" != "darwin" ] || return 0
-
bazel test examples/hermetic:py_module_test --test_output=all &> $TEST_TMPDIR/log \
&& fail "Fail due to non hermetic sandbox: examples/hermetic:py_module_test" || true
@@ -160,7 +322,6 @@ function test_missing_python_deps() {
# Test that the intermediate corrupt input file gets re:evaluated
function test_writing_input_file() {
- [ "$PLATFORM" != "darwin" ] || return 0
# Write an input file, this should cause the hermetic sandbox to fail with an exception
bazel build examples/hermetic:write_input_test &> $TEST_log \
&& fail "Fail due to non hermetic sandbox: examples/hermetic:write_input_test" || true
@@ -177,7 +338,48 @@ function test_writing_input_file() {
expect_log "original text input"
}
+# Test that invalid write of input file is detected, when file is accessed via resolved symlink.
+function test_overwrite_via_resolved_symlink() {
+ bazel build examples/hermetic:overwrite_via_resolved_symlink &> $TEST_log \
+ && fail "Hermetic sandbox did not detect invalid write to input file"
+ expect_log "input dependency .* was modified during execution."
+}
+
+# Test that invalid write of input file is detected, when file is accessed via unresolved symlink.
+function test_overwrite_via_unresolved_symlink() {
+ bazel build examples/hermetic:overwrite_via_unresolved_symlink &> $TEST_log \
+ && fail "Hermetic sandbox did not detect invalid write to input file"
+ expect_log "input dependency .* was modified during execution."
+}
+
+# Test that invalid write of input file is detected, when file is found implicit via declared directory.
+function test_overwrite_file_from_declared_directory() {
+ bazel build examples/hermetic:overwrite_file_from_declared_directory &> $TEST_log \
+ && fail "Hermetic sandbox did not detect invalid write to input file"
+ expect_log "input dependency .* was modified during execution."
+}
+
+# Test that the sandbox can handle deep directory trees from declared directory.
+function test_subdirectories_in_declared_directory() {
+ bazel build examples/hermetic:subdirectories_in_declared_directory &> $TEST_log
+ cat bazel-bin/examples/hermetic/subdirectories_in_declared_directory.result
+ assert_contains "dir/subdir1/subdir2" "bazel-bin/examples/hermetic/subdirectories_in_declared_directory.result"
+}
+
+# Test that the sandbox is not crashing and not producing warnings for various types of artifacts.
+# Regression test for Issue #15340
+function test_other_artifacts() {
+ bazel shutdown # Clear memory about duplicated warnings
+ bazel build examples/hermetic:other_artifacts &> $TEST_log
+ expect_not_log "WARNING"
+ assert_contains "regular_file_artifact" "bazel-bin/examples/hermetic/other_artifacts.result"
+ assert_contains "unresolved_symlink_artifact" "bazel-bin/examples/hermetic/other_artifacts.result"
+ assert_contains "directory_artifact" "bazel-bin/examples/hermetic/other_artifacts.result"
+ assert_contains "tree_artifact" "bazel-bin/examples/hermetic/other_artifacts.result"
+}
+
# The test shouldn't fail if the environment doesn't support running it.
check_sandbox_allowed || exit 0
+[ "$PLATFORM" != "darwin" ] || exit 0
run_suite "hermetic_sandbox"
| train | val | 2022-11-30T13:24:06 | "2022-04-25T22:03:49Z" | lunch-glide-pepper | test |
bazelbuild/bazel/16849_16862 | bazelbuild/bazel | bazelbuild/bazel/16849 | bazelbuild/bazel/16862 | [
"keyword_pr_to_issue"
] | 21b0992eb26e91ad3e6d3046fa90f1f7ad8b9f08 | 29669e605c74b1572335d1cabf52737cde8caa21 | [
"@bazel-io flag",
"Submitted a fix in https://github.com/bazelbuild/bazel/pull/16851",
"@bazel-io fork 6.0.0"
] | [] | "2022-11-28T12:56:02Z" | [
"type: bug",
"team-Rules-Java",
"untriaged"
] | Java runfiles library no longer compiles with Java 8 | ### Description of the bug:
In Bazel 6.0.0rc2, the Java runfiles library no longer builds with Java 8:
```
ERROR: /home/runner/.cache/bazel/_bazel_runner/6bc610921f14939de4c55cf170d55a62/external/bazel_tools/tools/java/runfiles/BUILD:1:13: Building external/bazel_tools/tools/java/runfiles/librunfiles.jar (2 source files) failed: (Exit 1): java failed: error executing command (from target @bazel_tools//tools/java/runfiles:runfiles) external/remotejdk11_linux/bin/java -XX:-CompactStrings '--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED' '--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED' ... (remaining 16 arguments skipped)
external/bazel_tools/tools/java/runfiles/Runfiles.java:413: error: no suitable constructor found for FileReader(String,Charset)
try (BufferedReader r = new BufferedReader(new FileReader(path, StandardCharsets.UTF_8))) {
^
constructor FileReader.FileReader(String) is not applicable
(actual and formal argument lists differ in length)
constructor FileReader.FileReader(File) is not applicable
(actual and formal argument lists differ in length)
constructor FileReader.FileReader(FileDescriptor) is not applicable
(actual and formal argument lists differ in length)
```
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Point `JAVA_HOME` to a Java 8 JDK
2. In any Bazel project, run `bazel build @bazel_tools//tools/java/runfiles --java_runtime_version=local_jdk_8`.
### Which operating system are you running Bazel on?
Any
### What is the output of `bazel info release`?
6.0.0rc2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"tools/java/runfiles/Runfiles.java"
] | [
"tools/java/runfiles/Runfiles.java"
] | [] | diff --git a/tools/java/runfiles/Runfiles.java b/tools/java/runfiles/Runfiles.java
index 171d1b2078ade4..c705e1db48bd94 100644
--- a/tools/java/runfiles/Runfiles.java
+++ b/tools/java/runfiles/Runfiles.java
@@ -17,7 +17,6 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
@@ -410,7 +409,9 @@ private static Map<Preloaded.RepoMappingKey, String> loadRepositoryMapping(Strin
return Collections.emptyMap();
}
- try (BufferedReader r = new BufferedReader(new FileReader(path, StandardCharsets.UTF_8))) {
+ try (BufferedReader r =
+ new BufferedReader(
+ new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
return Collections.unmodifiableMap(
r.lines()
.filter(line -> !line.isEmpty())
| null | test | val | 2022-11-28T09:29:30 | "2022-11-25T09:10:49Z" | fmeum | test |
bazelbuild/bazel/16124_16862 | bazelbuild/bazel | bazelbuild/bazel/16124 | bazelbuild/bazel/16862 | [
"keyword_pr_to_issue"
] | 21b0992eb26e91ad3e6d3046fa90f1f7ad8b9f08 | 29669e605c74b1572335d1cabf52737cde8caa21 | [
"@Wyverald Could you assign me and add the appropriate labels?",
"~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.",
"@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.",
"It's the \"To fix #NNN\" line... GitHub trying to be clever here",
"The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.\r\n\r\nIt's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of \"repository\" is specific to Bazel.\r\n\r\nPut differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.\r\n\r\n/cc @rickeylev ",
"@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?",
"Would users have to write that line or is it part of a file that is automatically generated?\r\n\r\nI don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.",
"> Would users have to write that line or is it part of a file that is automatically generated?\r\n> \r\n> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.\r\n\r\n@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.\r\n\r\nWhat I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.",
"Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?",
"> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?\r\n\r\nWe can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.",
"If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.\r\n\r\nI guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?\r\n\r\n> But of course having to replace all runfiles::create() calls with something else won't be too bad.\r\n\r\nHow do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.",
"I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).\r\n\r\nWhat I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.",
"Update: All changes relevant for Bazel 6.0.0 are now in review.",
"This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.",
"@Wyverald You can remove this from the \"6.0.0 nice to have\" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).",
"Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino."
] | [] | "2022-11-28T12:56:02Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Locating runfiles with Bzlmod" proposal | The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:
* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
* [x] Bash (#16693)
* [x] C++ (#16216)
* [x] Java (#16534)
* [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
* [x] Bash (#16693)
* [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
* [x] Java (#16549)
* [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)
Status of runfiles libraries in third-party rulesets:
* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???) | [
"tools/java/runfiles/Runfiles.java"
] | [
"tools/java/runfiles/Runfiles.java"
] | [] | diff --git a/tools/java/runfiles/Runfiles.java b/tools/java/runfiles/Runfiles.java
index 171d1b2078ade4..c705e1db48bd94 100644
--- a/tools/java/runfiles/Runfiles.java
+++ b/tools/java/runfiles/Runfiles.java
@@ -17,7 +17,6 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
@@ -410,7 +409,9 @@ private static Map<Preloaded.RepoMappingKey, String> loadRepositoryMapping(Strin
return Collections.emptyMap();
}
- try (BufferedReader r = new BufferedReader(new FileReader(path, StandardCharsets.UTF_8))) {
+ try (BufferedReader r =
+ new BufferedReader(
+ new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
return Collections.unmodifiableMap(
r.lines()
.filter(line -> !line.isEmpty())
| null | val | val | 2022-11-28T09:29:30 | "2022-08-18T12:57:30Z" | fmeum | test |
bazelbuild/bazel/16796_16869 | bazelbuild/bazel | bazelbuild/bazel/16796 | bazelbuild/bazel/16869 | [
"keyword_pr_to_issue"
] | fe169654a29d8ad33105d5d0034a7857834fed5d | fcf2522739db2165b8da0d883f7af3d5b53d0802 | [
"@bazel-io flag",
"@jwnimmer-tri Thanks for the report. Does #16801 look reasonable to you?",
"@bazel-io fork 6.0.0"
] | [] | "2022-11-28T17:09:51Z" | [
"type: bug",
"team-Rules-CPP",
"untriaged"
] | Compilation failure in C++ runfiles.h under Werror=shadow | ### Description of the bug:
This commit at 8f28513893969b6346d965cab12aac69cb246ced introduces a typo in the `Runfiles` constructor:
https://github.com/bazelbuild/bazel/blob/44918c540250a9e87eba8088e5676e3346695f29/tools/cpp/runfiles/runfiles_src.h#L193-L203
Note that the argument name on L198 is `std::string source_repository_` with an underscore; only member fields should end with an underscore.
When compiled using `-Werror=shadow`, GCC fails:
```
external/bazel_tools/tools/cpp/runfiles/runfiles.h: In constructor 'bazel::tools::cpp::runfiles::Runfiles::Runfiles(std::map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, std::string, std::map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > >, std::string)':
external/bazel_tools/tools/cpp/runfiles/runfiles.h:199:7: error: declaration of 'source_repository_' shadows a member of 'bazel::tools::cpp::runfiles::Runfiles' [-Werror=shadow]
199 | : runfiles_map_(std::move(runfiles_map)),
| ^
external/bazel_tools/tools/cpp/runfiles/runfiles.h:219:21: note: shadowed declaration is here
219 | const std::string source_repository_;
| ^~~~~~~~~~~~~~~~~~
```
This is from GCC 9.4.0 on Ubuntu 20.04, but I suspect most all versions would likewise fail.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Any C++ code that does `#include "tools/cpp/runfiles/runfiles.h"` built with `bazel build --copt=-Werror=shadow` should demonstrate this. I can provide a full repro if needed, but it doesn't seem necessary in this case.
### Which operating system are you running Bazel on?
Ubuntu 20.04
### What is the output of `bazel info release`?
6.0.0rc2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
This is a regression in the 6.0.0 release candidate. | [
"tools/cpp/runfiles/runfiles_src.h"
] | [
"tools/cpp/runfiles/runfiles_src.h"
] | [] | diff --git a/tools/cpp/runfiles/runfiles_src.h b/tools/cpp/runfiles/runfiles_src.h
index 75103e230bf8ce..242b834856553f 100644
--- a/tools/cpp/runfiles/runfiles_src.h
+++ b/tools/cpp/runfiles/runfiles_src.h
@@ -195,12 +195,12 @@ class Runfiles {
std::map<std::string, std::string> runfiles_map, std::string directory,
std::map<std::pair<std::string, std::string>, std::string> repo_mapping,
std::vector<std::pair<std::string, std::string> > envvars,
- std::string source_repository_)
+ std::string source_repository)
: runfiles_map_(std::move(runfiles_map)),
directory_(std::move(directory)),
repo_mapping_(std::move(repo_mapping)),
envvars_(std::move(envvars)),
- source_repository_(std::move(source_repository_)) {}
+ source_repository_(std::move(source_repository)) {}
Runfiles(const Runfiles&) = delete;
Runfiles(Runfiles&&) = delete;
Runfiles& operator=(const Runfiles&) = delete;
| null | train | val | 2022-11-28T16:35:03 | "2022-11-18T15:03:18Z" | jwnimmer-tri | test |
bazelbuild/bazel/16878_16886 | bazelbuild/bazel | bazelbuild/bazel/16878 | bazelbuild/bazel/16886 | [
"keyword_issue_to_pr"
] | 018f38c4b8eb9d65e9fa150cda0c7d85c40f5e3a | 06f9202e813d649b4ea48aa48cb0668fecb9cefa | [
"@kshyanashree Please cherry pick https://github.com/bazelbuild/bazel/commit/cd40666001e8d599bb61735898c195c6d2fae55b to close this one, thanks! ",
"After cherry pick this one, we can create rc3 ;)",
"> @kshyanashree Please cherry pick [cd40666](https://github.com/bazelbuild/bazel/commit/cd40666001e8d599bb61735898c195c6d2fae55b) to close this one, thanks!\r\n\r\nHi @meteorcloudy ! I have already cherry-picked this one here , but check is failing due to missing CLA #16886 . Wanted to check with you. Thanks!",
"For some reason the original commit was showing up as being authored by \"[email protected]\", which can't pass the CLA check. I think we can just force merge that PR.",
"Merged in #16886\r\n\r\nLet's create an rc3!",
"Sure, Thanks @Wyverald!"
] | [] | "2022-11-29T22:14:49Z" | [] | [6.0.0] Missing linkopts when building a cc_test | Forked from #16877 | [
"src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl"
] | [
"src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl"
] | [] | diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
index 48a4f684d641fd..23982806a59d4d 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
@@ -366,12 +366,6 @@ def _get_preloaded_deps_from_dynamic_deps(ctx):
return cc_common.merge_cc_infos(direct_cc_infos = cc_infos, cc_infos = cc_infos).linking_context.linker_inputs.to_list()
-def _get_canonical_form(label):
- repository = label.workspace_name
- if repository == "@":
- repository = ""
- return repository + "//" + label.package + ":" + label.name
-
def _filter_libraries_that_are_linked_dynamically(ctx, cc_linking_context, cpp_config):
merged_cc_shared_library_infos = merge_cc_shared_library_infos(ctx)
preloaded_deps = _get_preloaded_deps_from_dynamic_deps(ctx)
@@ -399,7 +393,7 @@ def _filter_libraries_that_are_linked_dynamically(ctx, cc_linking_context, cpp_c
continue
linker_inputs_seen[stringified_linker_input] = True
owner = str(linker_input.owner)
- if owner not in link_dynamically_labels and (owner in link_statically_labels or _get_canonical_form(ctx.label) == owner):
+ if owner not in link_dynamically_labels and (owner in link_statically_labels or str(ctx.label) == owner):
if owner in link_once_static_libs_map:
linked_statically_but_not_exported.setdefault(link_once_static_libs_map[owner], []).append(owner)
else:
| null | test | val | 2022-11-29T22:25:00 | "2022-11-29T15:12:09Z" | bazel-io | test |
bazelbuild/bazel/16933_16963 | bazelbuild/bazel | bazelbuild/bazel/16933 | bazelbuild/bazel/16963 | [
"keyword_pr_to_issue"
] | e63b8a3c34d2d8384f4fbd47eb3a0d76421a32c5 | b95f85f466856453b9900c4db0fdab9701d5d9a8 | [
"This issue also happens with Bazel@HEAD: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2766#0184e535-8df3-4114-9f65-8777f5bc7fe4, but the Bazel Auto Sheriff points to a [commit](https://github.com/bazelbuild/bazel/commit/fb2324620a4adee19bb4e8a030b6fba58f672dc0) that's not in Bazel 6.0.0rc4: https://buildkite.com/bazel/bazel-auto-sheriff-face-with-cowboy-hat/builds/1118\r\n\r\n**Update**: culprit finder failed due to not being able to download the Bazel binary.\r\n```\r\n:bazel: Test with Bazel built at fb2324620a4adee19bb4e8a030b6fba58f672dc0\r\n:googlecloud: Downloading Bazel built at fb2324620a4adee19bb4e8a030b6fba58f672dc0\r\n \r\ngsutil cp gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel /tmp/tmp09usce0c/bazel\r\nCommandException: No URLs matched: gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel\r\nFailed to download Bazel binary at fb2324620a4adee19bb4e8a030b6fba58f672dc0, error message:\r\nCommand '['gsutil', 'cp', 'gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel', '/tmp/tmp09usce0c/bazel']' returned non-zero exit status 1.\r\n\r\n```\r\n\r\nWe should fix culprit finder\r\n",
"/cc @coeuvre Since this only happens with RBE enabled. https://github.com/bazelbuild/bazel/blob/2a88c8da7783490ef6192336b091910cd662cc67/.bazelci/postsubmit.yml#L266",
"@coeuvre <del>Is https://github.com/bazelbuild/bazel/pull/16749 the possible culprit?</del> probably not since the original change was submitted in Oct, we have only been seen the failure with Bazel@HEAD in Nov.",
"Last green: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2729\r\nFirst fail: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2730\r\n\r\nCulprit should fall into (6e945e8ab422ca0a195d09899cce61ba6c0cfa59, 1500195986dc5095a21f32633cb4e3aabe037f1e]",
"Bisecting the rc4 branch at https://buildkite.com/bazel/culprit-finder/builds/3876 and it points to https://github.com/bazelbuild/bazel/commit/0b645254b41edc738c6641fd192fca86203ff2e2",
"Bisecting again on master branch after fixing the CI issue: https://buildkite.com/bazel/culprit-finder/builds/3877",
"While waiting for the bisect result, I can also reproduce at https://github.com/bazelbuild/bazel/commit/839ce7f5c40240d8b6f49c416c3769e226f43fee (original commit of the 6.0.0 cherrypick https://github.com/bazelbuild/bazel/commit/0b645254b41edc738c6641fd192fca86203ff2e2)\r\n```\r\nUSE_BAZEL_VERSION=839ce7f5c40240d8b6f49c416c3769e226f43fee bazel test //src/test/shell/bazel:bazel_example_test --config=ubuntu1804_java11 --remote_executor=grpcs://remotebuildexecution.googleapis.com\r\n```\r\nBut not at it's parent commit.\r\n\r\n/cc @fmeum @Wyverald ",
"@meteorcloudy Could you run these tests with `--test_env=RUNFILES_LIB_DEBUG=1`? That should provide us with very helpful information.",
"@fmeum Here is the test log:\r\n```\r\nexec ${PAGER:-/usr/bin/less} \"$0\" || exit 1\r\nExecuting tests from //src/test/shell/bazel:bazel_example_test\r\n-----------------------------------------------------------------------------\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nWARNING: Passing test names in arguments (--test_arg) is deprecated, please use --test_filter='/usr/lib/jvm/java-11-openjdk-amd64' instead.\r\nWARNING: Arguments do not specify tests!\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[bazel_example_test 2022-12-07 09:02:51 (+0000)] bazel binary is at /b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles/io_bazel/src/test/shell/bin\r\nINFO[bazel_example_test 2022-12-07 09:02:51 (+0000)] setting up client in /b/f/w/_tmp/bfbf694ed20a8c587876e28f8f9820b1/workspace\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): start\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): absolute path, return\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): not using repository mapping () since it does not exist\r\nERROR[runfiles.bash]: cannot look up runfile \"/usr/lib/jvm/java-11-openjdk-amd64/bin/java\" (RUNFILES_DIR=\"/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles\", RUNFILES_MANIFEST_FILE=\"\")\r\n```",
"@coeuvre I suspected a different issue, so I would like to confirm that isn't a problem either: The Bash runfiles library currently relies on absolute (!) paths of generated files containing an `execroot` segment. Is that guaranteed to be the case with remote execution, just like it is with local execution?",
"The logic for absolute paths passed to `rlocation` broke. I am investigating why the existing test didn't catch that.",
"> @coeuvre I suspected a different issue, so I would like to confirm that isn't a problem either: The Bash runfiles library currently relies on absolute (!) paths of generated files containing an `execroot` segment. Is that guaranteed to be the case with remote execution, just like it is with local execution?\r\n\r\nMy gut feeling is that `execroot` is not included in the path when actions inspect the path inside remote worker but I may be wrong. We use `execroot` as input root when uploading inputs for actions. Remote worker is free to move the input root to any local directories so a file `/.../execroot/bazel-out/a` in bazel host is probably become `/..../bazel-out/a` in remote worker.",
"@coeuvre Thanks, I will remove that assumption in a second PR.\r\n\r\n@meteorcloudy The Bash runfiles test didn't cover the exit codes of `rlocation`, only whatever it printed, and thus missed some corner cases. I have reworked the tests to check the exit codes and am now fixing these cases.",
"@fmeum @coeuvre Thanks!!",
"I submitted two PRs with fixes, #16945 and #16946.",
"I think I know how to fix the RBE test failures, but now that I studied this more closely, there is some underlying inconsistent behavior that makes the library difficult to test and potentially also hard to use: `$(rlocation does/not/exist)` has exit code 0 if and only if the runfiles manifest exists. This means that the behavior differs between local and remote execution on Windows, which is probably why we only noticed this in downstream tests.\r\n\r\n@laszlocsomor Sorry for the sideline mention, but can you recall how you intended the exit code of Bash `$(rlocation ...)` to behave?",
"> `$(rlocationpath does/not/exist)` has exit code 0 if and only if the runfiles manifest exists.\r\n\r\nDid you mean `$(rlocation does/not/exist)`?",
"@Wyverald Yes, sorry, fixed.",
"Fixing this inconsistency isn't required to get the tests to pass, but if we want to do it, 6.0.0 is probably the right time. Since `$(failing_command)` doesn't usually fail the outer shell script, having `$(rlocation does/not/exist)` exit with exit code 1 in all cases doesn't seem to be *that* breaking.\r\n\r\n@Wyverald @meteorcloudy What do you think?"
] | [] | "2022-12-08T16:14:24Z" | [
"type: bug",
"P1"
] | Bazel 6.0.0rc4 breaks Bazel RBE tests | This was first detected in the downstream test for Bazel 6.0.0rc4: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2761#0184d3b5-3cf0-410a-984d-2fdfdf78a49b
And verified in https://buildkite.com/bazel/bazel-bazel/builds/21471#0184e876-6406-4909-9a81-e8dc957b471f
[Integration tests with test args](https://cs.opensource.google/search?q=%22args%20%3D%20%5B%22$(JAVABASE)%22%5D%22&sq=&ss=bazel) are failing remotely with test logs look like:
```
exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //src/test/shell/bazel:bazel_example_test
-----------------------------------------------------------------------------
WARNING: Passing test names in arguments (--test_arg) is deprecated, please use --test_filter='/usr/lib/jvm/java-11-openjdk-amd64' instead.
WARNING: Arguments do not specify tests!
INFO[bazel_example_test 2022-12-06 17:28:07 (+0000)] bazel binary is at /b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles/io_bazel/src/test/shell/bin
INFO[bazel_example_test 2022-12-06 17:28:07 (+0000)] setting up client in /b/f/w/_tmp/55e5a95f98bdfb926d4a13d2054933c5/workspace
```
| [
"tools/bash/runfiles/runfiles.bash"
] | [
"tools/bash/runfiles/runfiles.bash"
] | [] | diff --git a/tools/bash/runfiles/runfiles.bash b/tools/bash/runfiles/runfiles.bash
index 72f85d92563a00..29706dfce6a704 100644
--- a/tools/bash/runfiles/runfiles.bash
+++ b/tools/bash/runfiles/runfiles.bash
@@ -260,7 +260,7 @@ function runfiles_current_repository() {
# The only shell script that is not executed from the runfiles directory (if it is populated)
# is the sh_binary entrypoint. Parse its path under the execroot, using the last match to
# allow for nested execroots (e.g. in Bazel integration tests).
- local -r repository=$(echo "$normalized_caller_path" | __runfiles_maybe_grep -E -o '/execroot/[^/]+/bazel-out/[^/]+/bin/external/[^/]+/' | tail -1 | rev | cut -d / -f 2 | rev)
+ local -r repository=$(echo "$normalized_caller_path" | __runfiles_maybe_grep -E -o '/bazel-out/[^/]+/bin/external/[^/]+/' | tail -1 | rev | cut -d / -f 2 | rev)
if [[ -n "$repository" ]]; then
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in repository ($repository)"
| null | val | val | 2022-12-08T19:11:16 | "2022-12-06T17:34:27Z" | meteorcloudy | test |
bazelbuild/bazel/16933_16988 | bazelbuild/bazel | bazelbuild/bazel/16933 | bazelbuild/bazel/16988 | [
"keyword_pr_to_issue"
] | b95f85f466856453b9900c4db0fdab9701d5d9a8 | 229372a37cfd9a1fa456b6b45f72014cb197dd71 | [
"This issue also happens with Bazel@HEAD: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2766#0184e535-8df3-4114-9f65-8777f5bc7fe4, but the Bazel Auto Sheriff points to a [commit](https://github.com/bazelbuild/bazel/commit/fb2324620a4adee19bb4e8a030b6fba58f672dc0) that's not in Bazel 6.0.0rc4: https://buildkite.com/bazel/bazel-auto-sheriff-face-with-cowboy-hat/builds/1118\r\n\r\n**Update**: culprit finder failed due to not being able to download the Bazel binary.\r\n```\r\n:bazel: Test with Bazel built at fb2324620a4adee19bb4e8a030b6fba58f672dc0\r\n:googlecloud: Downloading Bazel built at fb2324620a4adee19bb4e8a030b6fba58f672dc0\r\n \r\ngsutil cp gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel /tmp/tmp09usce0c/bazel\r\nCommandException: No URLs matched: gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel\r\nFailed to download Bazel binary at fb2324620a4adee19bb4e8a030b6fba58f672dc0, error message:\r\nCommand '['gsutil', 'cp', 'gs://bazel-builds/artifacts/centos7/fb2324620a4adee19bb4e8a030b6fba58f672dc0/bazel', '/tmp/tmp09usce0c/bazel']' returned non-zero exit status 1.\r\n\r\n```\r\n\r\nWe should fix culprit finder\r\n",
"/cc @coeuvre Since this only happens with RBE enabled. https://github.com/bazelbuild/bazel/blob/2a88c8da7783490ef6192336b091910cd662cc67/.bazelci/postsubmit.yml#L266",
"@coeuvre <del>Is https://github.com/bazelbuild/bazel/pull/16749 the possible culprit?</del> probably not since the original change was submitted in Oct, we have only been seen the failure with Bazel@HEAD in Nov.",
"Last green: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2729\r\nFirst fail: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2730\r\n\r\nCulprit should fall into (6e945e8ab422ca0a195d09899cce61ba6c0cfa59, 1500195986dc5095a21f32633cb4e3aabe037f1e]",
"Bisecting the rc4 branch at https://buildkite.com/bazel/culprit-finder/builds/3876 and it points to https://github.com/bazelbuild/bazel/commit/0b645254b41edc738c6641fd192fca86203ff2e2",
"Bisecting again on master branch after fixing the CI issue: https://buildkite.com/bazel/culprit-finder/builds/3877",
"While waiting for the bisect result, I can also reproduce at https://github.com/bazelbuild/bazel/commit/839ce7f5c40240d8b6f49c416c3769e226f43fee (original commit of the 6.0.0 cherrypick https://github.com/bazelbuild/bazel/commit/0b645254b41edc738c6641fd192fca86203ff2e2)\r\n```\r\nUSE_BAZEL_VERSION=839ce7f5c40240d8b6f49c416c3769e226f43fee bazel test //src/test/shell/bazel:bazel_example_test --config=ubuntu1804_java11 --remote_executor=grpcs://remotebuildexecution.googleapis.com\r\n```\r\nBut not at it's parent commit.\r\n\r\n/cc @fmeum @Wyverald ",
"@meteorcloudy Could you run these tests with `--test_env=RUNFILES_LIB_DEBUG=1`? That should provide us with very helpful information.",
"@fmeum Here is the test log:\r\n```\r\nexec ${PAGER:-/usr/bin/less} \"$0\" || exit 1\r\nExecuting tests from //src/test/shell/bazel:bazel_example_test\r\n-----------------------------------------------------------------------------\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/integration_test_setup.sh): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/unittest.bash): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nWARNING: Passing test names in arguments (--test_arg) is deprecated, please use --test_filter='/usr/lib/jvm/java-11-openjdk-amd64' instead.\r\nWARNING: Arguments do not specify tests!\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/testenv.sh): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/bazel): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bin/bazel): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/tools/BUILD): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): start\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): not using repository mapping () since it does not exist\r\nINFO[runfiles.bash]: rlocation(io_bazel/src/test/shell/bazel/testing_server.py): found under RUNFILES_DIR (/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles), return\r\nINFO[bazel_example_test 2022-12-07 09:02:51 (+0000)] bazel binary is at /b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles/io_bazel/src/test/shell/bin\r\nINFO[bazel_example_test 2022-12-07 09:02:51 (+0000)] setting up client in /b/f/w/_tmp/bfbf694ed20a8c587876e28f8f9820b1/workspace\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): start\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): absolute path, return\r\nINFO[runfiles.bash]: rlocation(/usr/lib/jvm/java-11-openjdk-amd64/bin/java): not using repository mapping () since it does not exist\r\nERROR[runfiles.bash]: cannot look up runfile \"/usr/lib/jvm/java-11-openjdk-amd64/bin/java\" (RUNFILES_DIR=\"/b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles\", RUNFILES_MANIFEST_FILE=\"\")\r\n```",
"@coeuvre I suspected a different issue, so I would like to confirm that isn't a problem either: The Bash runfiles library currently relies on absolute (!) paths of generated files containing an `execroot` segment. Is that guaranteed to be the case with remote execution, just like it is with local execution?",
"The logic for absolute paths passed to `rlocation` broke. I am investigating why the existing test didn't catch that.",
"> @coeuvre I suspected a different issue, so I would like to confirm that isn't a problem either: The Bash runfiles library currently relies on absolute (!) paths of generated files containing an `execroot` segment. Is that guaranteed to be the case with remote execution, just like it is with local execution?\r\n\r\nMy gut feeling is that `execroot` is not included in the path when actions inspect the path inside remote worker but I may be wrong. We use `execroot` as input root when uploading inputs for actions. Remote worker is free to move the input root to any local directories so a file `/.../execroot/bazel-out/a` in bazel host is probably become `/..../bazel-out/a` in remote worker.",
"@coeuvre Thanks, I will remove that assumption in a second PR.\r\n\r\n@meteorcloudy The Bash runfiles test didn't cover the exit codes of `rlocation`, only whatever it printed, and thus missed some corner cases. I have reworked the tests to check the exit codes and am now fixing these cases.",
"@fmeum @coeuvre Thanks!!",
"I submitted two PRs with fixes, #16945 and #16946.",
"I think I know how to fix the RBE test failures, but now that I studied this more closely, there is some underlying inconsistent behavior that makes the library difficult to test and potentially also hard to use: `$(rlocation does/not/exist)` has exit code 0 if and only if the runfiles manifest exists. This means that the behavior differs between local and remote execution on Windows, which is probably why we only noticed this in downstream tests.\r\n\r\n@laszlocsomor Sorry for the sideline mention, but can you recall how you intended the exit code of Bash `$(rlocation ...)` to behave?",
"> `$(rlocationpath does/not/exist)` has exit code 0 if and only if the runfiles manifest exists.\r\n\r\nDid you mean `$(rlocation does/not/exist)`?",
"@Wyverald Yes, sorry, fixed.",
"Fixing this inconsistency isn't required to get the tests to pass, but if we want to do it, 6.0.0 is probably the right time. Since `$(failing_command)` doesn't usually fail the outer shell script, having `$(rlocation does/not/exist)` exit with exit code 1 in all cases doesn't seem to be *that* breaking.\r\n\r\n@Wyverald @meteorcloudy What do you think?"
] | [] | "2022-12-12T08:26:05Z" | [
"type: bug",
"P1"
] | Bazel 6.0.0rc4 breaks Bazel RBE tests | This was first detected in the downstream test for Bazel 6.0.0rc4: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2761#0184d3b5-3cf0-410a-984d-2fdfdf78a49b
And verified in https://buildkite.com/bazel/bazel-bazel/builds/21471#0184e876-6406-4909-9a81-e8dc957b471f
[Integration tests with test args](https://cs.opensource.google/search?q=%22args%20%3D%20%5B%22$(JAVABASE)%22%5D%22&sq=&ss=bazel) are failing remotely with test logs look like:
```
exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //src/test/shell/bazel:bazel_example_test
-----------------------------------------------------------------------------
WARNING: Passing test names in arguments (--test_arg) is deprecated, please use --test_filter='/usr/lib/jvm/java-11-openjdk-amd64' instead.
WARNING: Arguments do not specify tests!
INFO[bazel_example_test 2022-12-06 17:28:07 (+0000)] bazel binary is at /b/f/w/bazel-out/k8-fastbuild/bin/src/test/shell/bazel/bazel_example_test.runfiles/io_bazel/src/test/shell/bin
INFO[bazel_example_test 2022-12-06 17:28:07 (+0000)] setting up client in /b/f/w/_tmp/55e5a95f98bdfb926d4a13d2054933c5/workspace
```
| [
"tools/bash/runfiles/runfiles.bash",
"tools/bash/runfiles/runfiles_test.bash"
] | [
"tools/bash/runfiles/runfiles.bash",
"tools/bash/runfiles/runfiles_test.bash"
] | [] | diff --git a/tools/bash/runfiles/runfiles.bash b/tools/bash/runfiles/runfiles.bash
index 29706dfce6a704..9788fa49a28a16 100644
--- a/tools/bash/runfiles/runfiles.bash
+++ b/tools/bash/runfiles/runfiles.bash
@@ -126,6 +126,7 @@ function rlocation() {
fi
# If the path is absolute, print it as-is.
echo "$1"
+ return 0
elif [[ "$1" == ../* || "$1" == */.. || "$1" == ./* || "$1" == */./* || "$1" == "*/." || "$1" == *//* ]]; then
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
echo >&2 "ERROR[runfiles.bash]: rlocation($1): path is not normalized"
@@ -234,7 +235,7 @@ function runfiles_current_repository() {
rlocation_path=$(__runfiles_maybe_grep -m1 "^[^ ]* ${escaped_caller_path}$" "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 1)
if [[ -z "$rlocation_path" ]]; then
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
- echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is not the target of an entry in the runfiles manifest ($RUNFILES_MANIFEST_FILE)"
+ echo >&2 "ERROR[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is not the target of an entry in the runfiles manifest ($RUNFILES_MANIFEST_FILE)"
fi
return 1
else
@@ -302,6 +303,9 @@ function runfiles_current_repository() {
export -f runfiles_current_repository
function runfiles_rlocation_checked() {
+ # FIXME: If the runfiles lookup fails, the exit code of this function is 0 if
+ # and only if the runfiles manifest exists. In particular, the exit code
+ # behavior is not consistent across platforms.
if [[ -e "${RUNFILES_DIR:-/dev/null}/$1" ]]; then
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
echo >&2 "INFO[runfiles.bash]: rlocation($1): found under RUNFILES_DIR ($RUNFILES_DIR), return"
@@ -344,6 +348,9 @@ function runfiles_rlocation_checked() {
# existence and would have returned the non-existent path. It seems
# better to return no path rather than a potentially different,
# non-empty path.
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($candidate) via prefix ($prefix), but file does not exist"
+ fi
break
done
if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
@@ -356,6 +363,11 @@ function runfiles_rlocation_checked() {
echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($result)"
fi
echo "$result"
+ else
+ if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
+ echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest as ($result), but file does not exist"
+ fi
+ echo ""
fi
fi
else
diff --git a/tools/bash/runfiles/runfiles_test.bash b/tools/bash/runfiles/runfiles_test.bash
index 7105f7fc0bd082..1e1c096b29e9cd 100755
--- a/tools/bash/runfiles/runfiles_test.bash
+++ b/tools/bash/runfiles/runfiles_test.bash
@@ -126,10 +126,10 @@ function test_rlocation_abs_path() {
source "$runfiles_lib_path"
if is_windows; then
- [[ "$(rlocation "c:/Foo")" == "c:/Foo" ]] || fail
- [[ "$(rlocation "c:\\Foo")" == "c:\\Foo" ]] || fail
+ [[ "$(rlocation "c:/Foo" || echo failed)" == "c:/Foo" ]] || fail
+ [[ "$(rlocation "c:\\Foo" || echo failed)" == "c:\\Foo" ]] || fail
else
- [[ "$(rlocation "/Foo")" == "/Foo" ]] || fail
+ [[ "$(rlocation "/Foo" || echo failed)" == "/Foo" ]] || fail
fi
}
@@ -140,35 +140,40 @@ a/b $tmpdir/c/d
e/f $tmpdir/g h
y $tmpdir/y
c/dir $tmpdir/dir
+unresolved $tmpdir/unresolved
EOF
mkdir "${tmpdir}/c"
mkdir "${tmpdir}/y"
mkdir -p "${tmpdir}/dir/deeply/nested"
touch "${tmpdir}/c/d" "${tmpdir}/g h"
touch "${tmpdir}/dir/file"
+ ln -s /does/not/exist "${tmpdir}/dir/unresolved"
touch "${tmpdir}/dir/deeply/nested/file"
+ ln -s /does/not/exist "${tmpdir}/unresolved"
export RUNFILES_DIR=
export RUNFILES_MANIFEST_FILE=$tmpdir/foo.runfiles_manifest
source "$runfiles_lib_path"
- [[ -z "$(rlocation a)" ]] || fail
- [[ -z "$(rlocation c/d)" ]] || fail
- [[ "$(rlocation a/b)" == "$tmpdir/c/d" ]] || fail
- [[ "$(rlocation e/f)" == "$tmpdir/g h" ]] || fail
- [[ "$(rlocation y)" == "$tmpdir/y" ]] || fail
- [[ "$(rlocation c)" == "" ]] || fail
- [[ "$(rlocation c/di)" == "" ]] || fail
- [[ "$(rlocation c/dir)" == "$tmpdir/dir" ]] || fail
- [[ "$(rlocation c/dir/file)" == "$tmpdir/dir/file" ]] || fail
- [[ "$(rlocation c/dir/deeply/nested/file)" == "$tmpdir/dir/deeply/nested/file" ]] || fail
- rm -r "$tmpdir/c/d" "$tmpdir/g h" "$tmpdir/y" "$tmpdir/dir"
- [[ -z "$(rlocation a/b)" ]] || fail
- [[ -z "$(rlocation e/f)" ]] || fail
- [[ -z "$(rlocation y)" ]] || fail
- [[ -z "$(rlocation c/dir)" ]] || fail
- [[ -z "$(rlocation c/dir/file)" ]] || fail
- [[ -z "$(rlocation c/dir/deeply/nested/file)" ]] || fail
+ [[ -z "$(rlocation a || echo failed)" ]] || fail
+ [[ -z "$(rlocation c/d || echo failed)" ]] || fail
+ [[ "$(rlocation a/b || echo failed)" == "$tmpdir/c/d" ]] || fail
+ [[ "$(rlocation e/f || echo failed)" == "$tmpdir/g h" ]] || fail
+ [[ "$(rlocation y || echo failed)" == "$tmpdir/y" ]] || fail
+ [[ -z "$(rlocation c || echo failed)" ]] || fail
+ [[ -z "$(rlocation c/di || echo failed)" ]] || fail
+ [[ "$(rlocation c/dir || echo failed)" == "$tmpdir/dir" ]] || fail
+ [[ "$(rlocation c/dir/file || echo failed)" == "$tmpdir/dir/file" ]] || fail
+ [[ -z "$(rlocation c/dir/unresolved || echo failed)" ]] || fail
+ [[ "$(rlocation c/dir/deeply/nested/file || echo failed)" == "$tmpdir/dir/deeply/nested/file" ]] || fail
+ [[ -z "$(rlocation unresolved || echo failed)" ]] || fail
+ rm -r "$tmpdir/c/d" "$tmpdir/g h" "$tmpdir/y" "$tmpdir/dir" "$tmpdir/unresolved"
+ [[ -z "$(rlocation a/b || echo failed)" ]] || fail
+ [[ -z "$(rlocation e/f || echo failed)" ]] || fail
+ [[ -z "$(rlocation y || echo failed)" ]] || fail
+ [[ -z "$(rlocation c/dir || echo failed)" ]] || fail
+ [[ -z "$(rlocation c/dir/file || echo failed)" ]] || fail
+ [[ -z "$(rlocation c/dir/deeply/nested/file || echo failed)" ]] || fail
}
function test_manifest_based_envvars() {
@@ -194,15 +199,15 @@ function test_init_directory_based_runfiles() {
mkdir -p "$RUNFILES_DIR/a"
touch "$RUNFILES_DIR/a/b" "$RUNFILES_DIR/c d"
- [[ "$(rlocation a)" == "$RUNFILES_DIR/a" ]] || fail
- [[ -z "$(rlocation c/d)" ]] || fail
- [[ "$(rlocation a/b)" == "$RUNFILES_DIR/a/b" ]] || fail
- [[ "$(rlocation "c d")" == "$RUNFILES_DIR/c d" ]] || fail
- [[ -z "$(rlocation "c")" ]] || fail
+ [[ "$(rlocation a || echo failed)" == "$RUNFILES_DIR/a" ]] || fail
+ [[ "$(rlocation c/d || echo failed)" == failed ]] || fail
+ [[ "$(rlocation a/b || echo failed)" == "$RUNFILES_DIR/a/b" ]] || fail
+ [[ "$(rlocation "c d" || echo failed)" == "$RUNFILES_DIR/c d" ]] || fail
+ [[ "$(rlocation "c" || echo failed)" == failed ]] || fail
rm -r "$RUNFILES_DIR/a" "$RUNFILES_DIR/c d"
- [[ -z "$(rlocation a)" ]] || fail
- [[ -z "$(rlocation a/b)" ]] || fail
- [[ -z "$(rlocation "c d")" ]] || fail
+ [[ "$(rlocation a || echo failed)" == failed ]] || fail
+ [[ "$(rlocation a/b || echo failed)" == failed ]] || fail
+ [[ "$(rlocation "c d" || echo failed)" == failed ]] || fail
}
function test_directory_based_runfiles_with_repo_mapping_from_main() {
@@ -228,23 +233,23 @@ EOF
touch "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile"
touch "$RUNFILES_DIR/config.json"
- [[ "$(rlocation "my_module/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "my_workspace/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "my_protobuf/foo/runfile" "")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir/file" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "my_module/bar/runfile" "" || echo failed)" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_workspace/bar/runfile" "" || echo failed)" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/foo/runfile" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/file" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ -z "$(rlocation "protobuf/foo/runfile" "")" ]] || fail
- [[ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "")" ]] || fail
+ [[ "$(rlocation "protobuf/foo/runfile" "" || echo failed)" == failed ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "" || echo failed)" == failed ]] || fail
- [[ "$(rlocation "_main/bar/runfile" "")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "_main/bar/runfile" "" || echo failed)" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ "$(rlocation "config.json" "")" == "$RUNFILES_DIR/config.json" ]] || fail
+ [[ "$(rlocation "config.json" "" || echo failed)" == "$RUNFILES_DIR/config.json" ]] || fail
}
function test_directory_based_runfiles_with_repo_mapping_from_other_repo() {
@@ -270,21 +275,21 @@ EOF
touch "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile"
touch "$RUNFILES_DIR/config.json"
- [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ -z "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2")" ]] || fail
- [[ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" ]] || fail
+ [[ "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2" || echo failed)" == failed ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" == failed ]] || fail
- [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ "$(rlocation "config.json" "protobuf~3.19.2")" == "$RUNFILES_DIR/config.json" ]] || fail
+ [[ "$(rlocation "config.json" "protobuf~3.19.2" || echo failed)" == "$RUNFILES_DIR/config.json" ]] || fail
}
function test_manifest_based_runfiles_with_repo_mapping_from_main() {
@@ -316,23 +321,23 @@ EOF
touch "$tmpdir/protobuf~3.19.2/foo/runfile"
touch "$tmpdir/config.json"
- [[ "$(rlocation "my_module/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "my_workspace/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "my_protobuf/foo/runfile" "")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir" "")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir/file" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "my_module/bar/runfile" "" || echo failed)" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_workspace/bar/runfile" "" || echo failed)" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/foo/runfile" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/file" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ -z "$(rlocation "protobuf/foo/runfile" "")" ]] || fail
- [[ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "")" ]] || fail
+ [[ -z "$(rlocation "protobuf/foo/runfile" "" || echo failed)" ]] || fail
+ [[ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi~le" "" || echo failed)" ]] || fail
- [[ "$(rlocation "_main/bar/runfile" "")" == "$tmpdir/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir" "")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "_main/bar/runfile" "" || echo failed)" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ "$(rlocation "config.json" "")" == "$tmpdir/config.json" ]] || fail
+ [[ "$(rlocation "config.json" "" || echo failed)" == "$tmpdir/config.json" ]] || fail
}
function test_manifest_based_runfiles_with_repo_mapping_from_other_repo() {
@@ -364,21 +369,21 @@ EOF
touch "$tmpdir/protobuf~3.19.2/foo/runfile"
touch "$tmpdir/config.json"
- [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "protobuf/foo/runfile" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/file" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ -z "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2")" ]] || fail
- [[ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" ]] || fail
+ [[ -z "$(rlocation "my_module/bar/runfile" "protobuf~3.19.2" || echo failed)" ]] || fail
+ [[ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" ]] || fail
- [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2")" == "$tmpdir/_main/bar/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
- [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2")" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
+ [[ "$(rlocation "_main/bar/runfile" "protobuf~3.19.2" || echo failed)" == "$tmpdir/_main/bar/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/foo/runfile" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/foo/runfile" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/file" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/file" ]] || fail
+ [[ "$(rlocation "protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" "protobuf~3.19.2" || echo failed)" == "$tmpdir/protobuf~3.19.2/bar/dir/de eply/nes ted/fi~le" ]] || fail
- [[ "$(rlocation "config.json" "protobuf~3.19.2")" == "$tmpdir/config.json" ]] || fail
+ [[ "$(rlocation "config.json" "protobuf~3.19.2" || echo failed)" == "$tmpdir/config.json" ]] || fail
}
function test_directory_based_envvars() {
| null | train | val | 2022-12-08T20:17:06 | "2022-12-06T17:34:27Z" | meteorcloudy | test |
bazelbuild/bazel/16992_17004 | bazelbuild/bazel | bazelbuild/bazel/16992 | bazelbuild/bazel/17004 | [
"keyword_pr_to_issue"
] | 7e80d0257fa24ff187f472a525f016989f7dc113 | 3a13af41034e1f80cc0fbc1634cf8f724a85b78f | [
"Fix has been cherry-picked at https://github.com/bazelbuild/bazel/pull/17004"
] | [] | "2022-12-13T08:33:18Z" | [] | [6.0.0] Unable to build x86 based unit tests with bazel 6.0.0rc4 because there is no x86 based remote java toolchain | Forked from #16961 | [
"src/main/starlark/builtins_bzl/common/cc/cc_test.bzl",
"src/main/starlark/builtins_bzl/common/cc/semantics.bzl"
] | [
"src/main/starlark/builtins_bzl/common/cc/cc_test.bzl",
"src/main/starlark/builtins_bzl/common/cc/semantics.bzl"
] | [
"src/test/shell/bazel/cc_integration_test.sh"
] | diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl
index 6540a4ff5643c9..c83582aa78f7b6 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl
@@ -137,7 +137,7 @@ def make_cc_test(with_linkstatic = False, with_aspects = False):
"stripped_binary": "%{name}.stripped",
"dwp_file": "%{name}.dwp",
},
- fragments = ["google_cpp", "cpp"],
+ fragments = ["google_cpp", "cpp", "coverage"],
exec_groups = {
"cpp_link": exec_group(copy_from_rule = True),
},
diff --git a/src/main/starlark/builtins_bzl/common/cc/semantics.bzl b/src/main/starlark/builtins_bzl/common/cc/semantics.bzl
index aaed989b5e01c9..cedeed5b282b5c 100644
--- a/src/main/starlark/builtins_bzl/common/cc/semantics.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/semantics.bzl
@@ -80,14 +80,14 @@ def _get_test_malloc_attr():
def _get_coverage_attrs():
return {
"_lcov_merger": attr.label(
- default = "@bazel_tools//tools/test:lcov_merger",
+ default = configuration_field(fragment = "coverage", name = "output_generator"),
executable = True,
- cfg = "target",
+ cfg = "exec",
),
"_collect_cc_coverage": attr.label(
default = "@bazel_tools//tools/test:collect_cc_coverage",
executable = True,
- cfg = "target",
+ cfg = "exec",
),
}
| diff --git a/src/test/shell/bazel/cc_integration_test.sh b/src/test/shell/bazel/cc_integration_test.sh
index 038fe3ce939151..6964d20eb4e83b 100755
--- a/src/test/shell/bazel/cc_integration_test.sh
+++ b/src/test/shell/bazel/cc_integration_test.sh
@@ -1752,4 +1752,46 @@ EOF
bazel build //:main --repo_env=CC=clang || fail "Expected compiler flag to have value 'clang'"
}
+function test_cc_test_no_target_coverage_dep() {
+ # Regression test for https://github.com/bazelbuild/bazel/issues/16961
+ local package="${FUNCNAME[0]}"
+ mkdir -p "${package}"
+
+ cat > "${package}"/BUILD.bazel <<'EOF'
+cc_test(
+ name = "test",
+ srcs = ["test.cc"],
+)
+EOF
+ touch "${package}"/test.cc
+
+ out=$(bazel cquery --collect_code_coverage \
+ "deps(//${package}:test) intersect config(@remote_coverage_tools//:all, target)")
+ if [[ -n "$out" ]]; then
+ fail "Expected no dependency on lcov_merger in the target configuration, but got: $out"
+ fi
+}
+
+function test_cc_test_no_lcov_merger_dep_without_coverage() {
+ # Regression test for https://github.com/bazelbuild/bazel/issues/16961
+ local package="${FUNCNAME[0]}"
+ mkdir -p "${package}"
+
+ cat > "${package}"/BUILD.bazel <<'EOF'
+cc_test(
+ name = "test",
+ srcs = ["test.cc"],
+)
+EOF
+ touch "${package}"/test.cc
+
+ # FIXME: cc_test still unconditionally depends on the LCOV merger binary through
+ # @remote_coverage_tools//:coverage_output_generator, which is also unnecessary:
+ # https://github.com/bazelbuild/bazel/issues/15088
+ out=$(bazel cquery "somepath(//${package}:test,@remote_coverage_tools//:lcov_merger)")
+ if [[ -n "$out" ]]; then
+ fail "Expected no dependency on lcov_merger, but got: $out"
+ fi
+}
+
run_suite "cc_integration_test"
| test | val | 2022-12-12T16:26:29 | "2022-12-12T13:42:42Z" | bazel-io | test |
bazelbuild/bazel/16333_17013 | bazelbuild/bazel | bazelbuild/bazel/16333 | bazelbuild/bazel/17013 | [
"keyword_pr_to_issue"
] | 3a13af41034e1f80cc0fbc1634cf8f724a85b78f | 86883db929bebcd1e6d0507ed4b8799e6e7591da | [
"In addition, it's possible for an action to consume only one of the files in a tree artifact (see `SpawnActionTemplate`), in which case the prefetcher will try to fetch the entire tree artifact; this currently fails because the metadata for the entire tree artifact isn't present (see https://github.com/bazelbuild/bazel/issues/16987).",
"Reopening because https://github.com/bazelbuild/bazel/commit/25ba76c1b8d420ebae43c1f59890ae46153c2240 was just a workaround, and we have yet to fix it properly.",
"@tjgq Should this be cherry-picked?",
"Yes, but I'm not sure 6.1.0 is still accepting cherry-picks. If we decide to do an rc3, I'll cherry-pick it there. Otherwise, it will have to go into 6.2.0.",
"@bazel-io fork 6.2.0"
] | [] | "2022-12-13T18:00:54Z" | [
"type: bug",
"P2",
"team-Remote-Exec"
] | Input prefetcher handles partial tree artifacts and nested artifacts incorrectly | It's possible for artifacts to nest (i.e., to have a declare_file or declare_directory that descends from another declare_directory). If two nested inputs are presented to the input prefetcher, the common files will be downloaded twice and race against each other, potentially corrupting the input tree.
https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java;l=289;drc=05b97393ff7604f237d9d31bd63714f27fbe83f2
https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java;l=230;drc=05b97393ff7604f237d9d31bd63714f27fbe83f2 | [
"src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java",
"src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java"
] | [
"src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java",
"src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java"
] | [
"src/test/java/com/google/devtools/build/lib/skyframe/SequencedSkyframeExecutorTest.java",
"src/test/shell/bazel/remote/build_without_the_bytes_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java b/src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java
index 0435d17eb3c35b..fb2b07c9ae4cde 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java
+++ b/src/main/java/com/google/devtools/build/lib/actions/ActionInputPrefetcher.java
@@ -28,6 +28,11 @@ public ListenableFuture<Void> prefetchFiles(
// Do nothing.
return immediateVoidFuture();
}
+
+ @Override
+ public boolean supportsPartialTreeArtifactInputs() {
+ return true;
+ }
};
/**
@@ -39,4 +44,10 @@ public ListenableFuture<Void> prefetchFiles(
*/
ListenableFuture<Void> prefetchFiles(
Iterable<? extends ActionInput> inputs, MetadataProvider metadataProvider);
+
+ /**
+ * Whether the prefetcher is able to fetch individual files in a tree artifact without fetching
+ * the entire tree artifact.
+ */
+ boolean supportsPartialTreeArtifactInputs();
}
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java
index 5ae39e9172d9f1..d128e83a6f6bad 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteActionInputFetcher.java
@@ -61,6 +61,12 @@ class RemoteActionInputFetcher extends AbstractActionInputPrefetcher {
this.remoteCache = Preconditions.checkNotNull(remoteCache);
}
+ @Override
+ public boolean supportsPartialTreeArtifactInputs() {
+ // This prefetcher is unable to fetch only individual files inside a tree artifact.
+ return false;
+ }
+
@Override
protected void prefetchVirtualActionInput(VirtualActionInput input) throws IOException {
if (!(input instanceof EmptyActionInput)) {
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java
index 952e2dd573c641..4a116c0fc2b482 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ActionExecutionFunction.java
@@ -1253,7 +1253,8 @@ private <S extends ActionInputMapSink, R> R accumulateInputs(
topLevelFilesets,
input,
value,
- env);
+ env,
+ skyframeActionExecutor.supportsPartialTreeArtifactInputs());
}
if (actionExecutionFunctionExceptionHandler != null) {
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java b/src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java
index f024131f12f511..412659253f3ea4 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ActionInputMapHelper.java
@@ -25,6 +25,7 @@
import com.google.devtools.build.lib.actions.Artifact.ArchivedTreeArtifact;
import com.google.devtools.build.lib.actions.Artifact.DerivedArtifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
+import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.FilesetOutputSymlink;
import com.google.devtools.build.lib.analysis.actions.SymlinkAction;
@@ -47,7 +48,8 @@ static void addToMap(
Map<Artifact, ImmutableList<FilesetOutputSymlink>> topLevelFilesets,
Artifact key,
SkyValue value,
- Environment env)
+ Environment env,
+ boolean prefetcherSupportsPartialTreeArtifacts)
throws InterruptedException {
addToMap(
inputMap,
@@ -58,7 +60,8 @@ static void addToMap(
key,
value,
env,
- MetadataConsumerForMetrics.NO_OP);
+ MetadataConsumerForMetrics.NO_OP,
+ prefetcherSupportsPartialTreeArtifacts);
}
/**
@@ -74,7 +77,8 @@ static void addToMap(
Artifact key,
SkyValue value,
Environment env,
- MetadataConsumerForMetrics consumer)
+ MetadataConsumerForMetrics consumer,
+ boolean prefetcherSupportsPartialTreeArtifacts)
throws InterruptedException {
if (value instanceof RunfilesArtifactValue) {
// Note: we don't expand the .runfiles/MANIFEST file into the inputs. The reason for that
@@ -120,16 +124,35 @@ static void addToMap(
/*depOwner=*/ key);
consumer.accumulate(treeArtifactValue);
} else if (value instanceof ActionExecutionValue) {
- FileArtifactValue metadata = ((ActionExecutionValue) value).getExistingFileArtifactValue(key);
- inputMap.put(key, metadata, key);
- if (key.isFileset()) {
- ImmutableList<FilesetOutputSymlink> filesets = getFilesets(env, (SpecialArtifact) key);
- if (filesets != null) {
- topLevelFilesets.put(key, filesets);
- consumer.accumulate(filesets);
- }
+ if (!prefetcherSupportsPartialTreeArtifacts && key instanceof TreeFileArtifact) {
+ // If we're unable to prefetch individual files in a tree artifact, include the full tree
+ // artifact in the action inputs. This makes actions that consume partial tree artifacts
+ // (such as the ones generated by SpawnActionTemplate or CppCompileActionTemplate) less
+ // efficient, but is needed until https://github.com/bazelbuild/bazel/issues/16333 is fixed.
+ SpecialArtifact treeArtifact = key.getParent();
+ TreeArtifactValue treeArtifactValue =
+ ((ActionExecutionValue) value).getTreeArtifactValue(treeArtifact);
+ expandTreeArtifactAndPopulateArtifactData(
+ treeArtifact,
+ treeArtifactValue,
+ expandedArtifacts,
+ archivedTreeArtifacts,
+ inputMap,
+ /* depOwner= */ treeArtifact);
+ consumer.accumulate(treeArtifactValue);
} else {
- consumer.accumulate(metadata);
+ FileArtifactValue metadata =
+ ((ActionExecutionValue) value).getExistingFileArtifactValue(key);
+ inputMap.put(key, metadata, key);
+ if (key.isFileset()) {
+ ImmutableList<FilesetOutputSymlink> filesets = getFilesets(env, (SpecialArtifact) key);
+ if (filesets != null) {
+ topLevelFilesets.put(key, filesets);
+ consumer.accumulate(filesets);
+ }
+ } else {
+ consumer.accumulate(metadata);
+ }
}
} else {
Preconditions.checkArgument(value instanceof FileArtifactValue, "Unexpected value %s", value);
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java
index df7cb7534d80ce..1dfec25289ade8 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/CompletionFunction.java
@@ -218,7 +218,8 @@ public SkyValue compute(SkyKey skyKey, Environment env)
input,
artifactValue,
env,
- currentConsumer);
+ currentConsumer,
+ skyframeActionExecutor.supportsPartialTreeArtifactInputs());
if (!allArtifactsAreImportant && importantArtifactSet.contains(input)) {
// Calling #addToMap a second time with `input` and `artifactValue` will perform no-op
// updates to the secondary collections passed in (eg. expandedArtifacts,
@@ -233,7 +234,8 @@ public SkyValue compute(SkyKey skyKey, Environment env)
input,
artifactValue,
env,
- MetadataConsumerForMetrics.NO_OP);
+ MetadataConsumerForMetrics.NO_OP,
+ skyframeActionExecutor.supportsPartialTreeArtifactInputs());
}
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java b/src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java
index 6329c467285eb3..342d97715e8944 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/SkyframeActionExecutor.java
@@ -320,6 +320,10 @@ boolean useArchivedTreeArtifacts(ActionAnalysisMetadata action) {
.test(action.getMnemonic());
}
+ boolean supportsPartialTreeArtifactInputs() {
+ return actionInputPrefetcher.supportsPartialTreeArtifactInputs();
+ }
+
boolean publishTargetSummaries() {
return options.getOptions(BuildEventProtocolOptions.class).publishTargetSummary;
}
| diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/SequencedSkyframeExecutorTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/SequencedSkyframeExecutorTest.java
index c806bc3b5861a2..5f4bedca32fb94 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/SequencedSkyframeExecutorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/SequencedSkyframeExecutorTest.java
@@ -879,6 +879,7 @@ public void testSharedActionsRacing() throws Exception {
// is running. This way, both actions will check the action cache beforehand and try to update
// the action cache post-build.
final CountDownLatch inputsRequested = new CountDownLatch(2);
+ skyframeExecutor.configureActionExecutor(/* fileCache= */ null, ActionInputPrefetcher.NONE);
skyframeExecutor
.getEvaluator()
.injectGraphTransformerForTesting(
@@ -1231,6 +1232,7 @@ public void sharedActionTemplate() throws Exception {
ActionTemplate<DummyAction> template2 =
new DummyActionTemplate(baseOutput, sharedOutput2, ActionOwner.SYSTEM_ACTION_OWNER);
ActionLookupValue shared2Ct = createActionLookupValue(template2, shared2);
+ skyframeExecutor.configureActionExecutor(/* fileCache= */ null, ActionInputPrefetcher.NONE);
// Inject the "configured targets" into the graph.
skyframeExecutor
.getDifferencerForTesting()
@@ -1645,6 +1647,7 @@ public void analysisEventsNotStoredInExecution() throws Exception {
createActionLookupValue(action2, lc2),
null,
NestedSetBuilder.create(Order.STABLE_ORDER, Event.warn("analysis warning 2")));
+ skyframeExecutor.configureActionExecutor(/* fileCache= */ null, ActionInputPrefetcher.NONE);
skyframeExecutor
.getDifferencerForTesting()
.inject(ImmutableMap.of(lc1, ctValue1, lc2, ctValue2));
diff --git a/src/test/shell/bazel/remote/build_without_the_bytes_test.sh b/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
index 477a2f0bd8335f..3680f845c1846f 100755
--- a/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
+++ b/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
@@ -70,14 +70,7 @@ else
declare -r EXE_EXT=""
fi
-function test_cc_tree() {
- if [[ "$PLATFORM" == "darwin" ]]; then
- # TODO(b/37355380): This test is disabled due to RemoteWorker not supporting
- # setting SDKROOT and DEVELOPER_DIR appropriately, as is required of
- # action executors in order to select the appropriate Xcode toolchain.
- return 0
- fi
-
+function setup_cc_tree() {
mkdir -p a
cat > a/BUILD <<EOF
load(":tree.bzl", "mytree")
@@ -93,11 +86,40 @@ def _tree_impl(ctx):
mytree = rule(implementation = _tree_impl)
EOF
+}
+
+function test_cc_tree_remote_executor() {
+ if [[ "$PLATFORM" == "darwin" ]]; then
+ # TODO(b/37355380): This test is disabled due to RemoteWorker not supporting
+ # setting SDKROOT and DEVELOPER_DIR appropriately, as is required of
+ # action executors in order to select the appropriate Xcode toolchain.
+ return 0
+ fi
+
+ setup_cc_tree
+
bazel build \
--remote_executor=grpc://localhost:${worker_port} \
--remote_download_minimal \
//a:tree_cc >& "$TEST_log" \
- || fail "Failed to build //a:tree_cc with minimal downloads"
+ || fail "Failed to build //a:tree_cc with remote executor and minimal downloads"
+}
+
+function test_cc_tree_remote_cache() {
+ if [[ "$PLATFORM" == "darwin" ]]; then
+ # TODO(b/37355380): This test is disabled due to RemoteWorker not supporting
+ # setting SDKROOT and DEVELOPER_DIR appropriately, as is required of
+ # action executors in order to select the appropriate Xcode toolchain.
+ return 0
+ fi
+
+ setup_cc_tree
+
+ bazel build \
+ --remote_cache=grpc://localhost:${worker_port} \
+ --remote_download_minimal \
+ //a:tree_cc >& "$TEST_log" \
+ || fail "Failed to build //a:tree_cc with remote cache and minimal downloads"
}
function test_cc_include_scanning_and_minimal_downloads() {
| test | val | 2022-12-13T10:23:10 | "2022-09-23T08:43:16Z" | tjgq | test |
bazelbuild/bazel/12852_17274 | bazelbuild/bazel | bazelbuild/bazel/12852 | bazelbuild/bazel/17274 | [
"keyword_pr_to_issue"
] | b041dd3b9189df98fff9ea70d64ad27fd349ed34 | 3ab8a0a5d628a0d958fb2eb1c0d5bb76b442e2f2 | [
"As an add-on: Seems like all these variables are missing from aquery output, too.",
"It seems like maybe there's something much more general broken with environment variable reporting for actions.\r\n\r\nI ran back into an equivalent problem on Windows and with aquery, and it really does complicate and embrittle tooling.\r\n\r\nI've updated the original report to reflect that.\r\n\r\n@gregestren @oquenchil, might this merit different labels/priorities if its a more general, non-apple-specific, non-extra-action-specific bug?\r\n\r\n",
"I don't have expertise on this part of the code base (aquery, extra actions, environment variable consumption). I'm going to defer to @oquenchil .",
"This is blocking us too. Is there any meaningful progress here?",
"(Sadly not that I know of.) But I'm curious what you're building on top of aquery/extra_actions, @sualehasif!",
"I think this may be an _even_ more general bug where toolchain environment variables are missing from aquery output.\r\n\r\n(I've been trying to help a user over at https://github.com/hedronvision/bazel-compile-commands-extractor/issues/83#issuecomment-1312067222 and noticing that EM_BIN_PATH and the other emscripten environment variables are missing from aquery output, despite being set in [the toolchain](https://github.com/emscripten-core/emsdk/blob/005063304bb4e575f97b7c5f50368f937c06cb54/bazel/emscripten_toolchain/toolchain.bzl))\r\n\r\n@oquenchil, any chance of a higher prioritization, given it's now clear it's a more general issue (not platform-specific), present across the action querying mechanisms (not just extra action), and causing problems for others, too?",
"Is this just for C++ rules and it works for others like Java?",
"I'm pretty sure it also affects Objective-C, at least, but I'm not sure whether it affects other language toolchains/Java.\r\n[It's been a problem everywhere I've looked, but I haven't needed to dive into the Bazel toolchains for other languages just yet.] ",
"This is complicating tooling for me as well. I've implemented a toolchain to use the EWDK to build windows drivers, and it is a real bummer to not be able to query the INCLUDE environment variable for this.",
"@meisterT is this something that aquery could get to?",
"Regarding `DEVELOPER_DIR` and `SDKROOT`: I suspect that these are missing from `aquery` output as the real values for these variable are only determined at execution time by running `xcode-locator` and are then injected into spawns that need them (see https://cs.opensource.google/bazel/bazel/+/abe26b84df03eac149f731f1e71fd9a5f0138f0a:src/main/java/com/google/devtools/build/lib/exec/local/XcodeLocalEnvProvider.java;l=68). Ultimately that seems to be necessary as the values have to be host-dependent absolute paths and thus shouldn't be part of the action key.",
"Regarding the missing toolchain variables on all OSes: Based on a cursory glance, it looks to me as if `aquery` only emits environment variables for `SpawnAction`s: https://cs.opensource.google/bazel/bazel/+/abe26b84df03eac149f731f1e71fd9a5f0138f0a:src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java;l=177. But the C++ compilation and linking actions aren't `SpawnAction`s. Maybe that `if` could just check for `AbstractAction` instead?",
"Thanks so much for diving in, guys.",
"Can confirm that @fmeum's good work in https://github.com/bazelbuild/bazel/pull/17108 surfaced the emscripten environment variables--but the Apple (and I presume the Windows) variables from the original issue are still missing.\r\n\r\nStill think this might be worth fixing (at least by starlarkificiation time). "
] | [
"@kshyanashree This test made it in by mistake, only the one after it is part of the original PR.",
"Hi @fmeum! I removed this test and ran the presubmits, but still checks are failing. Could you please look into it?"
] | "2023-01-19T22:58:06Z" | [
"type: bug",
"P4",
"platform: apple",
"team-Rules-CPP",
"team-Rules-ObjC"
] | SDKROOT, DEVELOPER_DIR, INCLUDE, LIB missing from Environment Variables in Aquery and Extra Actions | ### Description of the problem:
When listening to CppCompile and ObjcCompile (mnemonic) actions on macOS and Windows, the key environment variables DEVELOPER_DIR and SDKROOT (Apple Platforms) and INCLUDE and LIB and [other essentials](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line) (Windows) are missing from the environment variables in aquery and extra actions output, despite being needed to run the action successfully.
For Apple platforms, the [bazel-supplied, wrapped Xcode compiler](https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/wrapped_clang.cc) is dependent on these environment variables, and crashes if they aren't provided. For Windows, MSVC is dependent on these variables for system headers and libraries. Those environment variables provide key information about the compilation command.
On Apple platforms, some other, less-standard variables are supplied: XCODE_VERSION_OVERRIDE, APPLE_SDK_VERSION_OVERRIDE, and APPLE_SDK_PLATFORM. On Windows...not so much.
### What underlying problem are you trying to solve?
The lack of these variables significantly complicates building C++ developer tooling around Bazel.
In my case, I'm [integrating Bazel with clangd autocomplete in a wide variety of editors](https://github.com/hedronvision/bazel-compile-commands-extractor), to make development using Bazel more fun. We're linked to from the bazel docs :)
But I'd imagine this would also be useful for Kythe--the complication databases it generates would be incomplete without this, and they use action_listeners/extra_action, while we use aquery. As above, the problem exists in both.
The workaround I'm currently using on macOS using is to go direct to the system, re-inferring SDKROOT and DEVELOPER_DIR from the system Xcode commands. On Windows, I inspect the top level cc_toolchain. While these generally work, they'll miss any configuration the user does in the build graph.
More generally, it seems odd that those key variables are missing for the core cc rules. It feels like they'd be the primary purpose of being able to query the environment of C++ actions. It feels like there might be something even more general broken here.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Just run `bazel aquery "mnemonic('(Objc|Cpp)Compile',//...)"` on a cc_library on macOS or Windows and look at the (lack of) those environment variables.
Reproing the extra action issue is more involved, and probably is just another manifestation of the same underlying problem. But I think the fastest way to do that would be to grab Kythe's implementation of an extractor (https://github.com/kythe/kythe/blob/master/kythe/cxx/extractor/README.md) and examine the extra_actions_base_proto.
| [
"src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java"
] | [
"src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java"
] | [
"src/test/shell/integration/aquery_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java b/src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java
index 5264c1fd7aea04..12d50a5732d9c1 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/actiongraph/v2/ActionGraphDump.java
@@ -18,6 +18,7 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
+import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionKeyContext;
@@ -32,7 +33,6 @@
import com.google.devtools.build.lib.analysis.SourceManifestAction;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
-import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.Substitution;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionException;
@@ -174,11 +174,15 @@ private void dumpSingleAction(ConfiguredTarget configuredTarget, ActionAnalysisM
}
// store environment
- if (action instanceof SpawnAction) {
- SpawnAction spawnAction = (SpawnAction) action;
+ if (action instanceof AbstractAction && action instanceof CommandAction) {
+ AbstractAction spawnAction = (AbstractAction) action;
+ // Some actions (e.g. CppCompileAction) don't override getEnvironment, but only
+ // getEffectiveEnvironment. Since calling the latter with an empty client env returns the
+ // fixed part of the full ActionEnvironment with the default implementations provided by
+ // AbstractAction, we can call getEffectiveEnvironment here to handle these actions as well.
// TODO(twerth): This handles the fixed environment. We probably want to output the inherited
- // environment as well.
- ImmutableMap<String, String> fixedEnvironment = spawnAction.getEnvironment().getFixedEnv();
+ // environment as well.
+ ImmutableMap<String, String> fixedEnvironment = spawnAction.getEffectiveEnvironment(Map.of());
for (Map.Entry<String, String> environmentVariable : fixedEnvironment.entrySet()) {
actionBuilder.addEnvironmentVariables(
AnalysisProtosV2.KeyValuePair.newBuilder()
| diff --git a/src/test/shell/integration/aquery_test.sh b/src/test/shell/integration/aquery_test.sh
index 9493d3e34b8ec7..83adfcc4f70e28 100755
--- a/src/test/shell/integration/aquery_test.sh
+++ b/src/test/shell/integration/aquery_test.sh
@@ -30,9 +30,15 @@ source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
case "$(uname -s | tr [:upper:] [:lower:])" in
msys*|mingw*|cygwin*)
+ declare -r is_macos=false
declare -r is_windows=true
;;
+darwin)
+ declare -r is_macos=true
+ declare -r is_windows=false
+ ;;
*)
+ declare -r is_macos=false
declare -r is_windows=false
;;
esac
@@ -1659,6 +1665,30 @@ EOF
fi
}
+function test_cpp_compile_action_env() {
+ local pkg="${FUNCNAME[0]}"
+ mkdir -p "$pkg"
+
+ touch "$pkg/main.cpp"
+ cat > "$pkg/BUILD" <<'EOF'
+cc_binary(
+ name = "main",
+ srcs = ["main.cpp"],
+)
+EOF
+ bazel aquery --output=textproto \
+ "mnemonic(CppCompile,//$pkg:main)" >output 2> "$TEST_log" || fail "Expected success"
+ cat output >> "$TEST_log"
+
+ if "$is_macos"; then
+ assert_contains ' key: "XCODE_VERSION_OVERRIDE"' output
+ elif "$is_windows"; then
+ assert_contains ' key: "INCLUDE"' output
+ else
+ assert_contains ' key: "PWD"' output
+ fi
+}
+
# TODO(bazel-team): The non-text aquery output formats don't correctly handle
# non-ASCII fields (input/output paths, environment variables, etc).
function DISABLED_test_unicode_textproto() {
| train | val | 2023-02-20T18:48:14 | "2021-01-19T08:03:34Z" | cpsauer | test |
bazelbuild/bazel/17130_17278 | bazelbuild/bazel | bazelbuild/bazel/17130 | bazelbuild/bazel/17278 | [
"keyword_pr_to_issue"
] | 71c3daee532e19fd7607ee9aee33d32482421085 | 4e35c02c7c400bfbbfa69164a1ec3bd51966ca79 | [
"I have a PR that should fix this: https://github.com/bazelbuild/bazel/pull/17045\r\n"
] | [] | "2023-01-20T06:25:21Z" | [
"type: bug",
"team-ExternalDeps",
"untriaged",
"area-Bzlmod"
] | Cleanup progress when using bzlmod | Currently when using bzlmod your action's progress can look something like `@_main~bzlmod_tool_dependencies~Yams//:Yams`, in the past this would have been displayed as `@Yams//:Yams` and generally IMO this adds a lot of visual noise if you have many dependencies like this. | [
"src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java",
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java",
"src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java",
"src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java",
"src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java",
"src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java",
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java",
"src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java",
"src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java",
"src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java",
"src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java"
] | [
"src/test/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTrackerTest.java",
"src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java b/src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java
index 262754415cf3cb..e76a72dcfedf13 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java
+++ b/src/main/java/com/google/devtools/build/lib/actions/AbstractAction.java
@@ -27,6 +27,7 @@
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
@@ -363,14 +364,47 @@ public boolean showsOutputUnconditionally() {
@Nullable
@Override
public final String getProgressMessage() {
+ return getProgressMessageChecked(null);
+ }
+
+ @Nullable
+ @Override
+ public final String getProgressMessage(RepositoryMapping mainRepositoryMapping) {
+ Preconditions.checkNotNull(mainRepositoryMapping);
+ return getProgressMessageChecked(mainRepositoryMapping);
+ }
+
+ private String getProgressMessageChecked(@Nullable RepositoryMapping mainRepositoryMapping) {
String message = getRawProgressMessage();
if (message == null) {
return null;
}
+ message = replaceProgressMessagePlaceholders(message, mainRepositoryMapping);
String additionalInfo = getOwner().getAdditionalProgressInfo();
return additionalInfo == null ? message : message + " [" + additionalInfo + "]";
}
+ private String replaceProgressMessagePlaceholders(
+ String progressMessage, @Nullable RepositoryMapping mainRepositoryMapping) {
+ if (progressMessage.contains("%{label}") && getOwner().getLabel() != null) {
+ String labelString;
+ if (mainRepositoryMapping != null) {
+ labelString = getOwner().getLabel().getDisplayForm(mainRepositoryMapping);
+ } else {
+ labelString = getOwner().getLabel().toString();
+ }
+ progressMessage = progressMessage.replace("%{label}", labelString);
+ }
+ if (progressMessage.contains("%{output}") && getPrimaryOutput() != null) {
+ progressMessage =
+ progressMessage.replace("%{output}", getPrimaryOutput().getExecPathString());
+ }
+ if (progressMessage.contains("%{input}") && getPrimaryInput() != null) {
+ progressMessage = progressMessage.replace("%{input}", getPrimaryInput().getExecPathString());
+ }
+ return progressMessage;
+ }
+
/**
* Returns a progress message string that is specific for this action. This is then annotated with
* additional information, currently the string '[for tool]' for actions in the tool
diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java
index 338fb06993fdbc..4d21092df79b82 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java
+++ b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionMetadata.java
@@ -13,6 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import javax.annotation.Nullable;
@@ -33,6 +34,19 @@ public interface ActionExecutionMetadata extends ActionAnalysisMetadata {
@Nullable
String getProgressMessage();
+ /**
+ * A variant of {@link #getProgressMessage} that additionally takes the {@link RepositoryMapping}
+ * of the main repository, which can be used by the implementation to emit labels with apparent
+ * instead of canonical repository names. A return value of {@code null} indicates no message
+ * should be reported.
+ *
+ * <p>The default implementation simply returns the result of {@link #getProgressMessage}.
+ */
+ @Nullable
+ default String getProgressMessage(RepositoryMapping mainRepositoryMapping) {
+ return getProgressMessage();
+ }
+
/**
* Returns a human-readable description of the inputs to {@link #getKey(ActionKeyContext)}. Used
* in the output from '--explain', and in error messages for '--check_up_to_date' and
diff --git a/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java b/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java
index aad9f721f1ba05..f40f7a2ceb5aae 100644
--- a/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java
+++ b/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java
@@ -16,6 +16,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
/**
@@ -24,6 +25,7 @@
public final class LoadingPhaseCompleteEvent implements ExtendedEventHandler.Postable {
private final ImmutableSet<Label> labels;
private final ImmutableSet<Label> filteredLabels;
+ private final RepositoryMapping mainRepositoryMapping;
/**
* Construct the event.
@@ -33,9 +35,11 @@ public final class LoadingPhaseCompleteEvent implements ExtendedEventHandler.Pos
*/
public LoadingPhaseCompleteEvent(
ImmutableSet<Label> labels,
- ImmutableSet<Label> filteredLabels) {
+ ImmutableSet<Label> filteredLabels,
+ RepositoryMapping mainRepositoryMapping) {
this.labels = Preconditions.checkNotNull(labels);
this.filteredLabels = Preconditions.checkNotNull(filteredLabels);
+ this.mainRepositoryMapping = Preconditions.checkNotNull(mainRepositoryMapping);
}
/**
@@ -53,6 +57,13 @@ public ImmutableSet<Label> getFilteredLabels() {
return filteredLabels;
}
+ /**
+ * @return The repository mapping of the main repository.
+ */
+ public RepositoryMapping getMainRepositoryMapping() {
+ return mainRepositoryMapping;
+ }
+
@Override
public boolean storeForReplay() {
return true;
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java b/src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java
index a61db61a2cb033..6ce72a6cd894cc 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTracker.java
@@ -171,6 +171,7 @@ void loadingComplete(LoadingPhaseCompleteEvent event) {
} else {
additionalMessage = labelsCount + " targets";
}
+ mainRepositoryMapping = event.getMainRepositoryMapping();
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
index f270dd87e11680..14183b40c01d6b 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/UiStateTracker.java
@@ -42,6 +42,8 @@
import com.google.devtools.build.lib.buildtool.buildevent.TestFilteringCompleteEvent;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
+import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler.FetchProgress;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseCompleteEvent;
import com.google.devtools.build.lib.skyframe.ConfigurationPhaseStartedEvent;
@@ -69,7 +71,7 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/** Tracks state for the UI. */
@@ -89,6 +91,8 @@ class UiStateTracker {
private String status;
protected String additionalMessage;
+ // Not null after the loading phase has completed.
+ protected RepositoryMapping mainRepositoryMapping;
protected final Clock clock;
@@ -427,6 +431,7 @@ void loadingComplete(LoadingPhaseCompleteEvent event) {
} else {
additionalMessage = count + " targets";
}
+ mainRepositoryMapping = event.getMainRepositoryMapping();
}
/**
@@ -641,11 +646,11 @@ static String suffix(String s, int len) {
* If possible come up with a human-readable description of the label that fits within the given
* width; a non-positive width indicates not no restriction at all.
*/
- private static String shortenedLabelString(Label label, int width) {
+ private String shortenedLabelString(Label label, int width) {
if (width <= 0) {
- return label.toString();
+ return label.getDisplayForm(mainRepositoryMapping);
}
- String name = label.toString();
+ String name = label.getDisplayForm(mainRepositoryMapping);
if (name.length() <= width) {
return name;
}
@@ -787,7 +792,7 @@ protected String describeAction(
postfix += " " + strategy;
}
- String message = action.getProgressMessage();
+ String message = action.getProgressMessage(mainRepositoryMapping);
if (message == null) {
message = action.prettyPrint();
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java
index 4b2153e62a5407..18d1e8e7ac158a 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternPhaseFunction.java
@@ -238,7 +238,11 @@ public TargetPatternPhaseValue compute(SkyKey key, Environment env) throws Inter
mapOriginalPatternsToLabels(expandedPatterns, targets.getTargets()),
testSuiteExpansions.buildOrThrow()));
env.getListener()
- .post(new LoadingPhaseCompleteEvent(result.getTargetLabels(), removedTargetLabels));
+ .post(
+ new LoadingPhaseCompleteEvent(
+ result.getTargetLabels(),
+ removedTargetLabels,
+ repositoryMappingValue.getRepositoryMapping()));
return result;
}
| diff --git a/src/test/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTrackerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTrackerTest.java
index f91c05854143a3..c26dffb4e6c5f7 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTrackerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/SkymeldUiStateTrackerTest.java
@@ -24,6 +24,7 @@
import com.google.devtools.build.lib.buildtool.ExecutionProgressReceiver;
import com.google.devtools.build.lib.buildtool.buildevent.BuildCompleteEvent;
import com.google.devtools.build.lib.buildtool.buildevent.ExecutionProgressReceiverAvailableEvent;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseCompleteEvent;
import com.google.devtools.build.lib.runtime.SkymeldUiStateTracker.BuildStatus;
import com.google.devtools.build.lib.skyframe.ConfigurationPhaseStartedEvent;
@@ -74,7 +75,8 @@ public void loadingComplete_stateChanges() {
uiStateTracker.buildStatus = BuildStatus.TARGET_PATTERN_PARSING;
uiStateTracker.loadingComplete(
- new LoadingPhaseCompleteEvent(ImmutableSet.of(), ImmutableSet.of()));
+ new LoadingPhaseCompleteEvent(
+ ImmutableSet.of(), ImmutableSet.of(), RepositoryMapping.ALWAYS_FALLBACK));
assertThat(uiStateTracker.buildStatus).isEqualTo(BuildStatus.LOADING_COMPLETE);
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
index 497b391c26a836..fdd89a87513adf 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/UiStateTrackerTest.java
@@ -18,7 +18,10 @@
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
@@ -54,6 +57,8 @@
import com.google.devtools.build.lib.buildtool.buildevent.TestFilteringCompleteEvent;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
+import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.events.ExtendedEventHandler.FetchProgress;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseCompleteEvent;
import com.google.devtools.build.lib.runtime.SkymeldUiStateTracker.BuildStatus;
@@ -83,12 +88,15 @@
import net.starlark.java.syntax.Location;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.AdditionalMatchers;
/** Tests {@link UiStateTracker}. */
@RunWith(TestParameterInjector.class)
public class UiStateTrackerTest extends FoundationTestCase {
@TestParameter boolean isSkymeld;
+ static final RepositoryMapping MOCK_REPO_MAPPING =
+ RepositoryMapping.createAllowingFallback(ImmutableMap.of("main", RepositoryName.MAIN));
private UiStateTracker getUiStateTracker(ManualClock clock) {
if (isSkymeld) {
@@ -186,8 +194,11 @@ private Action mockAction(String progressMessage, String primaryOutput) {
ActionsTestUtil.createArtifact(ArtifactRoot.asSourceRoot(Root.fromPath(outputBase)), path);
Action action = mock(Action.class);
- when(action.getProgressMessage()).thenReturn(progressMessage);
+ when(action.getProgressMessage(eq(MOCK_REPO_MAPPING))).thenReturn(progressMessage);
when(action.getPrimaryOutput()).thenReturn(artifact);
+
+ verify(action, never()).getProgressMessage(AdditionalMatchers.not(eq(MOCK_REPO_MAPPING)));
+ verify(action, never()).getProgressMessage();
return action;
}
@@ -208,9 +219,13 @@ private ActionOwner dummyActionOwner() throws LabelSyntaxException {
}
private void simulateExecutionPhase(UiStateTracker uiStateTracker) {
+ uiStateTracker.loadingComplete(
+ new LoadingPhaseCompleteEvent(ImmutableSet.of(), ImmutableSet.of(), MOCK_REPO_MAPPING));
if (this.isSkymeld) {
// SkymeldUiStateTracker needs to be in the configuration phase before the execution phase.
((SkymeldUiStateTracker) uiStateTracker).buildStatus = BuildStatus.ANALYSIS_COMPLETE;
+ } else {
+ String unused = uiStateTracker.analysisComplete();
}
uiStateTracker.progressReceiverAvailable(
new ExecutionProgressReceiverAvailableEvent(dummyExecutionProgressReceiver()));
@@ -254,7 +269,7 @@ public void testLoadingActivity() throws IOException {
// When it is configuring targets.
stateTracker.loadingComplete(
- new LoadingPhaseCompleteEvent(ImmutableSet.of(), ImmutableSet.of()));
+ new LoadingPhaseCompleteEvent(ImmutableSet.of(), ImmutableSet.of(), MOCK_REPO_MAPPING));
String additionalMessage = "5 targets";
stateTracker.additionalMessage = additionalMessage;
String configuredTargetProgressString = "5 targets configured";
| train | val | 2023-02-10T17:05:02 | "2023-01-04T01:05:13Z" | keith | test |
bazelbuild/bazel/16911_17284 | bazelbuild/bazel | bazelbuild/bazel/16911 | bazelbuild/bazel/17284 | [
"keyword_pr_to_issue"
] | 950e7554e664f3604f5abcfda970aa6918b9fea2 | 467164208d3b91b37b7b785b41edace9c557805c | [] | [] | "2023-01-20T17:16:47Z" | [
"type: bug",
"team-Configurability",
"untriaged"
] | experimental_action_listener config variable is set to "null" instead of "[]" in exec configuration | ### Description of the bug:
In the configuration associated with `CoreOptions` there is a configuration value `experimental_action_listener: []` associated with the (deprecated) command-line flag `--experimental_action_listener`. We do not use this functionality, and have no desire to do so.
Unfortunately, after any transition to `exec` configuration, this value appears to change from `[]` to `null`, and there is no way to transition it _back_ from Starlark code.
The reason this is a problem is related to our desire to perform "unifying transitions" as discussed in #14023 and #14236. All of the other config set by "exec" can be controlled manually from a Starlark transition, but because this particular flag is "experimental" we can't reset it to `[]`, so we end up with two different configuration hashes for the same configuration, and Bazel ends up building those targets and everything they depend on twice without reason.
This should be a small one-line fix, and is a blocker for many of the benefits of `--experimental_output_directory_naming_scheme=diff_against_baseline`, and possibly for moving to Bazel 6.x entirely, so it would be nice to get this fix backported as well.
I believe the simplest fix is a one-line change here to construct an empty list, although more complicated solutions are possible: https://github.com/bazelbuild/bazel/blob/release-6.0.0rc4/src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java#L131-L132
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
genrule(
name = "rule1",
srcs = [],
outs = ["file1.bin"],
cmd = "echo 'echo hi' > $@",
executable = True,
)
genrule(
name = "rule2",
srcs = [],
outs = ["file2.txt"],
cmd = 'echo "file2" > $@',
exec_tools = [":rule1"],
)
```
`bazel cquery "filter(rule1, deps(:all))"`
This returns two different config hashes, use `diff` on `bazel config` to show the issue
```diff
< experimental_action_listener: []
---
> experimental_action_listener: null
```
Note that we're _not_ concerned with any of the other changes in this list since they are all controllable by Starlark
### Which operating system are you running Bazel on?
Ubuntu 18.04
### What is the output of `bazel info release`?
release 6.0.0rc4
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
Tagging @gregestren @sdtwigg and the Configurability team | [
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java",
"src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
index 19597cc44c23d8..a39d84f01f27f1 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationValue.java
@@ -17,7 +17,6 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableCollection;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
@@ -732,7 +731,7 @@ public int analysisTestingDepsLimit() {
}
public List<Label> getActionListeners() {
- return options.actionListeners == null ? ImmutableList.of() : options.actionListeners;
+ return options.actionListeners;
}
/**
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java b/src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java
index 0ff96d0a655b1f..a4559c333d53c0 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/ExecutionTransitionFactory.java
@@ -129,7 +129,7 @@ private static BuildOptions transitionImpl(BuildOptionsView options, Label execu
coreOptions.isHost = false;
coreOptions.isExec = true;
// Disable extra actions
- coreOptions.actionListeners = null;
+ coreOptions.actionListeners = ImmutableList.of();
// Then set the target to the saved execution platform if there is one.
PlatformOptions platformOptions = execOptions.get(PlatformOptions.class);
| null | train | val | 2023-01-24T19:28:29 | "2022-12-02T23:27:46Z" | eric-skydio | test |
bazelbuild/bazel/15088_17287 | bazelbuild/bazel | bazelbuild/bazel/15088 | bazelbuild/bazel/17287 | [
"keyword_pr_to_issue"
] | 1a438b41b74d94fd8b6ff4dcf20b4526530e3c6e | ee1daaf9852d568dcf38357eadd77b9de953db36 | [
"cc @comius @c-mita ",
"It's seems the issue is that cc_tests unconditionally pulls those coverage tools dependencies.\r\nhttps://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java;l=255-270"
] | [] | "2023-01-20T20:24:34Z" | [
"type: bug",
"P2",
"team-Rules-CPP"
] | `cc_test` rules trigger remote JDK download (~200 MB) | ### Description of the problem / feature request:
`cc_test` rules trigger remote JDK download (~200 MB), which is undesirable when operating under constraints on storage capacity and/or network capacity. https://en.wikipedia.org/wiki/Principle_of_least_astonishment also applies.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
$ rm -rf $HOME/.cache/bazel
$ git clone https://github.com/google/re2.git
$ cd re2
$ bazel build //:all --experimental_repository_resolved_file=resolved.bzl
$ grep openjdk resolved.bzl
$ bazel query 'somepath(//:all, @remote_coverage_tools//:all)'
```
### What operating system are you running Bazel on?
Linux
### What's the output of `bazel info release`?
```
release 5.0.0
```
| [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/rules/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/rules/BUILD"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BUILD b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
index 350541aee2ad63..8076305da098c7 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
@@ -2541,7 +2541,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test",
"//src/main/java/com/google/devtools/common/options",
- "//third_party:jsr305",
+ "//third_party:jsr305_checked_in",
],
)
diff --git a/src/main/java/com/google/devtools/build/lib/rules/BUILD b/src/main/java/com/google/devtools/build/lib/rules/BUILD
index 2a256ca6b2e02a..0b555ff8067976 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/rules/BUILD
@@ -59,6 +59,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:artifacts",
"//src/main/java/com/google/devtools/build/lib/analysis:analysis_cluster",
+ "//src/main/java/com/google/devtools/build/lib/analysis:configured_target",
"//src/main/java/com/google/devtools/build/lib/analysis:test/coverage_configuration",
"//src/main/java/com/google/devtools/build/lib/analysis:test/test_configuration",
"//src/main/java/com/google/devtools/build/lib/analysis:test/test_trimming_transition_factory",
| null | train | val | 2023-02-19T03:56:16 | "2022-03-21T14:42:42Z" | junyer | test |
bazelbuild/bazel/17080_17309 | bazelbuild/bazel | bazelbuild/bazel/17080 | bazelbuild/bazel/17309 | [
"keyword_pr_to_issue"
] | 49e8ed110e6d02117748af4f15128621c5df8e49 | 97f64817472737960841c255baf00bc18df7c6e6 | [
"Forgot to add the place in code that seems to be the writing the broken entry to the disk\r\nhttps://github.com/bazelbuild/bazel/blob/3748bcc8bf0c45e34295583fafaf1f52449114b8/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java#L202",
"@coeuvre @tjgq ",
"@bazel-io flag",
"Thanks for the report!\r\n\r\nThe issue is tricky. When building without the bytes with disk cache alone, we want to check ac entry integrity for disk cache. Otherwise the build could fail if the any blob is missing when we are reading it later.\r\n\r\nHowever, when combined with remote cache, if we hit remote cache, we only download ac and skip downloading of blobs. Hence the AC in the disk cache is always incomplete until all the referenced blobs are downloaded later. The current code didn't check the integrity before deciding using the disk part of a combined cache.\r\nhttps://github.com/bazelbuild/bazel/blob/3748bcc8bf0c45e34295583fafaf1f52449114b8/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java#L190\r\n\r\nWe could fix that by checking the integrity when deciding which part to use of a combined cache. The problem is we will never hit the disk cache until all the referenced blobs are downloaded. The fix could reduce the cache-hit rate for disk cache. Considering 2 consecutive builds:\r\n\r\n```\r\nbazel build --config=remote_exec_with_disk --remote_download_minimal ...\r\nbazel build --config=remote_exec_with_disk --remote_download_minimal ...\r\n```\r\n\r\nThe second build will miss the disk cache because blobs referenced by AC are not downloaded (but can still hit the remote cache). On the other hand, this should the correct behaviour. Since remote cache could evict blobs. We shouldn't accept AC from disk cache if any referenced blob is missing, hoping we could get it from remote cache -- it could also be missing there.\r\n\r\nAnother fix is drop the integrity check for AC from disk cache when using combined cache. This will increase the disk-cache hit rate, but the chance to trigger \"missing blobs\" error is higher if the TTL of blobs on remote cache is low.\r\n\r\nI will go with the second fix for now (for performance reason) and see how can we improve it with lease service.",
">Another fix is drop the integrity check for AC from disk cache when using combined cache. This will increase the disk-cache hit rate, but the chance to trigger \"missing blobs\" error is higher if the TTL of blobs on remote cache is low.\r\n\r\nCan I vote that we _don't_ do this? At least until the lease service is up and running. The change to have the AC check if it's entries are valid is a very good one, in particular with remote caching. If you need to disable the check, and you do it only when disk cache + remote exec, but not disk cache + remote cache?",
"I agree AC check is a good one. But if we enable it for a combined cache (either disk cache + remote exec, or disk cache + remote cache), we will probably never hit the disk cache when building without the bytes.\r\n\r\nTaking the repro as an example, since we are using minimal mode, the outputs of `//:main` will nerve be downloaded which means we will never hit the disk cache if we check the integrity.\r\n\r\nIn real world builds, I believe there are actions whose outputs will never be downloaded. If we do AC check, these actions will never hit the disk cache.",
"I'm fine with the AC result being used in the combined cache, as long as Bazel calls FindMissingBlobs on the remote cache to verify that the result is valid. I think it would be cheaper if Bazel instead just asked for the AC result from the remote cache in that case.\r\n\r\nThe main benefit of the combined disk cache is the storing of the CAS items. There might be some local-only actions that do end up storing themselves, even with BwtB. I feel that BwtB + disk cache only is going to be very rare. The most common case will be the combined cache. And if we want the BwtB experience to be as nice as possible, the combined cache shouldn't degrade the experience. By that, I mean that if one was using just the remote cache, and `bazel clean --expunge` was run (until the lease service lands), Bazel wouldn't run into missing blobs errors because the remote cache wouldn't return AC results if they had missing CAS blobs. This change would degrade that because the disk cache could incorrectly return an invalid AC result.",
"I get you. From this perspective, not throwing an error is definitely a better experience than slowing the build. And yes, just check remote AC is probably not slower. Reusing CAS is the main benefit."
] | [] | "2023-01-24T20:18:17Z" | [
"type: bug",
"P1",
"team-Remote-Exec"
] | Broken AC entries are written to disk cache with --remote_download_minimal | ### Description of the bug:
Building something with build without bytes using remote exec, running bazel clean and then rebuilding fails due to missing digests at least for some targets. Seems that the ac entry gets written to the disk cache while, in general, the cas entries referenced are not written due to build without bytes. This seems to have been the case for some time now but it wasn't a problem until check for the ac entry integrity was added in https://github.com/bazelbuild/bazel/pull/16731.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Setup the workspace:
```
touch WORKSPACE
echo 'int main() { return 0; }' > main.cc
echo 'cc_binary(name = "main", srcs = ["main.cc"])' > BUILD
```
Also setup a config called remote_exec_with_disk which will enable remote execution and disk cache when building this project.
Repro issue
```
bazel build --config=remote_exec_with_disk --remote_download_minimal //:main && bazel clean && bazel build --config=remote_exec_with_disk --remote_download_minimal //:main
```
The second build command should give you an error like
```
ERROR: /repro_project/BUILD:1:10: Linking main failed: (Exit 34): Missing digest: 377e9d2c78fac1172750ae43806f3d3e1ec7dff71c15cdadfbbad10019929b8c/7936
```
### Which operating system are you running Bazel on?
linux
### What is the output of `bazel info release`?
release 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
-
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
-
```
### Have you found anything relevant by searching the web?
-
### Any other information, logs, or outputs that you want to share?
- | [
"src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java",
"src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java",
"src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java"
] | [
"src/test/java/com/google/devtools/build/lib/remote/BUILD",
"src/test/java/com/google/devtools/build/lib/remote/DiskCacheIntegrationTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java b/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java
index 1fc6200cd9e9d7..37ccd2cd4b456a 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/disk/DiskAndRemoteCacheClient.java
@@ -183,31 +183,53 @@ public ListenableFuture<Void> downloadBlob(
}
}
+ private ListenableFuture<CachedActionResult> downloadActionResultFromRemote(
+ RemoteActionExecutionContext context, ActionKey actionKey, boolean inlineOutErr) {
+ return Futures.transformAsync(
+ remoteCache.downloadActionResult(context, actionKey, inlineOutErr),
+ (cachedActionResult) -> {
+ if (cachedActionResult == null) {
+ return immediateFuture(null);
+ } else {
+ return Futures.transform(
+ diskCache.uploadActionResult(context, actionKey, cachedActionResult.actionResult()),
+ v -> cachedActionResult,
+ directExecutor());
+ }
+ },
+ directExecutor());
+ }
+
@Override
public ListenableFuture<CachedActionResult> downloadActionResult(
RemoteActionExecutionContext context, ActionKey actionKey, boolean inlineOutErr) {
- if (context.getReadCachePolicy().allowDiskCache()
- && diskCache.containsActionResult(actionKey)) {
- return diskCache.downloadActionResult(context, actionKey, inlineOutErr);
+ ListenableFuture<CachedActionResult> future = immediateFuture(null);
+
+ if (context.getReadCachePolicy().allowDiskCache()) {
+ // If Build without the Bytes is enabled, the future will likely return null
+ // and fallback to remote cache because AC integrity check is enabled and referenced blobs are
+ // probably missing from disk cache due to BwoB.
+ //
+ // TODO(chiwang): With lease service, instead of doing the integrity check against local
+ // filesystem, we can check whether referenced blobs are alive in the lease service to
+ // increase the cache-hit rate for disk cache.
+ future = diskCache.downloadActionResult(context, actionKey, inlineOutErr);
}
if (context.getReadCachePolicy().allowRemoteCache()) {
- return Futures.transformAsync(
- remoteCache.downloadActionResult(context, actionKey, inlineOutErr),
- (cachedActionResult) -> {
- if (cachedActionResult == null) {
- return immediateFuture(null);
- } else {
- return Futures.transform(
- diskCache.uploadActionResult(
- context, actionKey, cachedActionResult.actionResult()),
- v -> cachedActionResult,
- directExecutor());
- }
- },
- directExecutor());
- } else {
- return immediateFuture(null);
+ future =
+ Futures.transformAsync(
+ future,
+ (result) -> {
+ if (result == null) {
+ return downloadActionResultFromRemote(context, actionKey, inlineOutErr);
+ } else {
+ return immediateFuture(result);
+ }
+ },
+ directExecutor());
}
+
+ return future;
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java b/src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java
index d0d6bd406d7e9c..55d6b43581f8dd 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/disk/DiskCacheClient.java
@@ -68,11 +68,6 @@ public boolean contains(Digest digest) {
return toPath(digest.getHash(), /* actionResult= */ false).exists();
}
- /** Returns {@code true} if the provided {@code key} is stored in the Action Cache. */
- public boolean containsActionResult(ActionKey actionKey) {
- return toPath(actionKey.getDigest().getHash(), /* actionResult= */ true).exists();
- }
-
public void captureFile(Path src, Digest digest, boolean isActionCache) throws IOException {
Path target = toPath(digest.getHash(), isActionCache);
target.getParentDirectory().createDirectoryAndParents();
@@ -161,7 +156,11 @@ public ListenableFuture<CachedActionResult> downloadActionResult(
}
if (checkActionResult) {
- checkActionResult(actionResult);
+ try {
+ checkActionResult(actionResult);
+ } catch (CacheNotFoundException e) {
+ return Futures.immediateFuture(null);
+ }
}
return Futures.immediateFuture(CachedActionResult.disk(actionResult));
| diff --git a/src/test/java/com/google/devtools/build/lib/remote/BUILD b/src/test/java/com/google/devtools/build/lib/remote/BUILD
index 7cef85b3320396..f438d4dce01bc2 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/remote/BUILD
@@ -171,6 +171,9 @@ java_test(
java_test(
name = "DiskCacheIntegrationTest",
srcs = ["DiskCacheIntegrationTest.java"],
+ runtime_deps = [
+ "//third_party/grpc-java:grpc-jar",
+ ],
deps = [
"//src/main/java/com/google/devtools/build/lib:runtime",
"//src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper:credential_module",
@@ -178,8 +181,10 @@ java_test(
"//src/main/java/com/google/devtools/build/lib/standalone",
"//src/main/java/com/google/devtools/build/lib/vfs:pathfragment",
"//src/test/java/com/google/devtools/build/lib/buildtool/util",
+ "//src/test/java/com/google/devtools/build/lib/remote/util:integration_test_utils",
"//src/test/java/com/google/devtools/build/lib/testutil:TestUtils",
"//third_party:guava",
"//third_party:junit4",
+ "//third_party:truth",
],
)
diff --git a/src/test/java/com/google/devtools/build/lib/remote/DiskCacheIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/remote/DiskCacheIntegrationTest.java
index ee64e175c495dd..5c6bf046b48529 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/DiskCacheIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/DiskCacheIntegrationTest.java
@@ -13,11 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.remote;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.TestUtils.tmpDirFile;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialModule;
import com.google.devtools.build.lib.buildtool.util.BuildIntegrationTestCase;
+import com.google.devtools.build.lib.remote.util.IntegrationTestUtils;
+import com.google.devtools.build.lib.remote.util.IntegrationTestUtils.WorkerInstance;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.BlazeRuntime;
import com.google.devtools.build.lib.runtime.BlockWaitingModule;
@@ -32,6 +35,25 @@
@RunWith(JUnit4.class)
public class DiskCacheIntegrationTest extends BuildIntegrationTestCase {
+ private WorkerInstance worker;
+
+ private void startWorker() throws Exception {
+ if (worker == null) {
+ worker = IntegrationTestUtils.startWorker();
+ }
+ }
+
+ private void enableRemoteExec(String... additionalOptions) {
+ assertThat(worker).isNotNull();
+ addOptions("--remote_executor=grpc://localhost:" + worker.getPort());
+ addOptions(additionalOptions);
+ }
+
+ private void enableRemoteCache(String... additionalOptions) {
+ assertThat(worker).isNotNull();
+ addOptions("--remote_cache=grpc://localhost:" + worker.getPort());
+ addOptions(additionalOptions);
+ }
private static PathFragment getDiskCacheDir() {
PathFragment testTmpDir = PathFragment.create(tmpDirFile().getAbsolutePath());
@@ -48,6 +70,10 @@ protected void setupOptions() throws Exception {
@After
public void tearDown() throws IOException {
getWorkspace().getFileSystem().getPath(getDiskCacheDir()).deleteTree();
+
+ if (worker != null) {
+ worker.stop();
+ }
}
@Override
@@ -93,7 +119,7 @@ public void hitDiskCache() throws Exception {
events.assertContainsInfo("2 disk cache hit");
}
- private void blobsReferencedInAAreMissingCasIgnoresAc(String... additionalOptions)
+ private void doBlobsReferencedInAcAreMissingFromCasIgnoresAc(String... additionalOptions)
throws Exception {
// Arrange: Prepare the workspace and populate disk cache
write(
@@ -126,13 +152,72 @@ private void blobsReferencedInAAreMissingCasIgnoresAc(String... additionalOption
}
@Test
- public void blobsReferencedInAcAreMissingCas_ignoresAc() throws Exception {
- blobsReferencedInAAreMissingCasIgnoresAc();
+ public void blobsReferencedInAcAreMissingFromCas_ignoresAc() throws Exception {
+ doBlobsReferencedInAcAreMissingFromCasIgnoresAc();
+ }
+
+ @Test
+ public void bwob_blobsReferencedInAcAreMissingFromCas_ignoresAc() throws Exception {
+ doBlobsReferencedInAcAreMissingFromCasIgnoresAc("--remote_download_minimal");
}
@Test
- public void bwob_blobsReferencedInAcAreMissingCas_ignoresAc() throws Exception {
- blobsReferencedInAAreMissingCasIgnoresAc("--remote_download_minimal");
+ public void bwobAndRemoteExec_blobsReferencedInAcAreMissingFromCas_ignoresAc() throws Exception {
+ startWorker();
+ enableRemoteExec("--remote_download_minimal");
+ doBlobsReferencedInAcAreMissingFromCasIgnoresAc();
+ }
+
+ @Test
+ public void bwobAndRemoteCache_blobsReferencedInAcAreMissingFromCas_ignoresAc() throws Exception {
+ startWorker();
+ enableRemoteCache("--remote_download_minimal");
+ doBlobsReferencedInAcAreMissingFromCasIgnoresAc();
+ }
+
+ private void doRemoteExecWithDiskCache(String... additionalOptions) throws Exception {
+ // Arrange: Prepare the workspace and populate disk cache
+ startWorker();
+ enableRemoteExec(additionalOptions);
+ write(
+ "BUILD",
+ "genrule(",
+ " name = 'foo',",
+ " srcs = ['foo.in'],",
+ " outs = ['foo.out'],",
+ " cmd = 'cat $(SRCS) > $@',",
+ ")",
+ "genrule(",
+ " name = 'foobar',",
+ " srcs = [':foo.out', 'bar.in'],",
+ " outs = ['foobar.out'],",
+ " cmd = 'cat $(SRCS) > $@',",
+ ")");
+ write("foo.in", "foo");
+ write("bar.in", "bar");
+ buildTarget("//:foobar");
+ cleanAndRestartServer();
+
+ // Act: Do a clean build
+ enableRemoteExec("--remote_download_minimal");
+ buildTarget("//:foobar");
+ }
+
+ @Test
+ public void remoteExecWithDiskCache_hitDiskCache() throws Exception {
+ doRemoteExecWithDiskCache();
+
+ // Assert: Should hit the disk cache
+ events.assertContainsInfo("2 disk cache hit");
+ }
+
+ @Test
+ public void bwob_remoteExecWithDiskCache_hitRemoteCache() throws Exception {
+ doRemoteExecWithDiskCache("--remote_download_minimal");
+
+ // Assert: Should hit the remote cache because blobs referenced by the AC are missing from disk
+ // cache due to BwoB.
+ events.assertContainsInfo("2 remote cache hit");
}
private void cleanAndRestartServer() throws Exception {
| val | val | 2023-01-25T16:58:23 | "2022-12-27T10:13:03Z" | exoson | test |
bazelbuild/bazel/16966_17331 | bazelbuild/bazel | bazelbuild/bazel/16966 | bazelbuild/bazel/17331 | [
"keyword_pr_to_issue"
] | c10e7247c5078e2765d5dbe7b0e98d69012bce08 | ac47e1085c59654f29b82b0ca3be224447895774 | [
"CC @katre @illicitonion ",
"I prototyped a PR that realizes the desired behavior (but isn't polished): https://github.com/bazelbuild/bazel/pull/16968\r\n\r\n@katre Given that 5.4.0 hasn't been released yet, do you see a way to add no-op parameters to `find_cpp_toolchain` and/or targets to `@bazel_tools//tools/cpp` that would allow rulesets to make use of optional toolchains sooner? \r\n\r\nFor example, if we added an alias of `current_cc_toolchain` called `optional_current_cc_toolchain` to Bazel 5.4.0, it could become the needed \"optional\" form in Bazel 6.X and rulesets could refer to it once their minimum supported Bazel version is 5.",
"Notes, no particular order:\r\n\r\n1. Please note that this is specifically for CC toolchains. Can you update the issue name and description to clarify that?\r\n2. I see in your example that you get the error text \"Unable to find a CC toolchain using toolchain resolution. Did you properly set --platforms\". Are you actually using your modified version of `find_cpp_toolchain`?\r\n\r\nI can see backporting a small fix to `find_cpp_toolchain` to make it more clear, but looking at your proposed #16968, it looks overly complicated to backport to an LTS release, and not needed at HEAD (because in HEAD optional toolchains exist).\r\n\r\nWhat specific versions do you want to support, and which flags with each version? Part of the appeal of the LTS model for the Bazel team was, honestly, not doing this sort of backporting and incremental rollout of features, because it gets very complicated (and risky) to support the older versions. The optional toolchains API was added a version before the actual implementation in order to allow projects to use the new API, and then get the new features when users upgrade to a Bazel that contained them. Was this the wrong approach? What would have been a better approach, so that we can handle this next time?",
"> 1. Please note that this is specifically for CC toolchains. Can you update the issue name and description to clarify that?\r\n\r\nGood point, done.\r\n\r\n> 2. I see in your example that you get the error text \"Unable to find a CC toolchain using toolchain resolution. Did you properly set --platforms\". Are you actually using your modified version of `find_cpp_toolchain`?\r\n\r\nYes, this text exists in two places:\r\n1. In `@bazel_tools//tools/cpp:toolchain_utils.bzl%find_cpp_toolchain`, which I thus had to inline and modify slightly (simply replaced `fail` with `return None`) here in order to make it work with optional toolchains.\r\n2. In `com.google.devtools.build.lib.rules.cpp.CppHelper#getToolchainFromPlatformConstraints`, which is used by `cc_toolchain_alias` to get the toolchain. This is the root cause of this issue: Compatibility with `--noincompatible_enable_cc_toolchain_resolution` means that the dependency on `cc_toolchain_alias` is needed, but if it is there, this method is always called and always throws this error, even if the toolchain dependency is marked optional.\r\n\r\nThe error you see in my example comes from 2., not 1.\r\n\r\n> I can see backporting a small fix to `find_cpp_toolchain` to make it more clear, but looking at your proposed #16968, it looks overly complicated to backport to an LTS release, and not needed at HEAD (because in HEAD optional toolchains exist).\r\n\r\nI am not proposing to backport #16968 - the change we could backport could be as simple as adding `alias(name = \"optional_current_cc_toolchain\", actual = \"current_cc_toolchain\")` to `@bazel_tools//tools/cpp`. The backport is not meant to add any functionality or make optional toolchains available, it just makes it so that rulesets can expect this target to exist earlier (that is, already when Bazel 5 is their minimum supported version).\r\n\r\nWhile optional toolchains exist at HEAD, I don't see a way for a ruleset to use them for C++ even at HEAD while remaining compatible with scenarios in which `--incompatible_enable_cc_toolchain_resolution` is disabled - this is why I created this issue. It is not about preserving compatibility with an earlier version of Bazel, it is just about compatibility with both values of the flag for any recent Bazel version, including HEAD. #16968 is a draft of a change that would make this possible at HEAD.\r\n\r\n> What specific versions do you want to support, and which flags with each version?\r\n\r\nSummarizing the above, I want to allow a Bazel ruleset to declare an optional C++ toolchain dependency and simultaneously:\r\n* make use of the toolchain actually being optional with Bazel@HEAD and `--incompatible_enable_cc_toolchain_resolution=true`\r\n* do not break with Bazel@HEAD and `--incompatible_enable_cc_toolchain_resolution=false`\r\n\r\nThe example I gave is meant to demonstrate that this doesn't seem to be possible today, so even if we do not care about backwards compatibility, there is something that needs to be fixed.\r\n\r\nIf we do care about allowing a ruleset to do this and remain compatible with a previous version of Bazel (e.g. 5 or 6), I think that this would require a backport even if https://github.com/bazelbuild/rules_go/pull/3390#discussion_r1043539582 is used to only request an optional toolchain dependency if the Bazel version supports it. That is because I don't see a way to fix the example without introducing a new `cc_toolchain_alias`, as is done in #16968.\r\n\r\n> Part of the appeal of the LTS model for the Bazel team was, honestly, not doing this sort of backporting and incremental rollout of features, because it gets very complicated (and risky) to support the older versions. The optional toolchains API was added a version before the actual implementation in order to allow projects to use the new API, and then get the new features when users upgrade to a Bazel that contained them. Was this the wrong approach? What would have been a better approach, so that we can handle this next time?\r\n\r\nI think that the approach was correct and adding the API a version before the feature is makes it so that rulesets can use it earlier, gracefully falling back to the old behavior but not breaking with versions of Bazel that don't have the feature. In fact, the proposal for a new `cc_toolchain_alias` target above is exactly of this type: It would add API to Bazel 5 and/or 6, with the actual \"feature\"/bug fix coming in (likely) Bazel 6.1.\r\n\r\nThe only thing that seems to have been missed is compatibility with `--incompatible_enable_cc_toolchain_resolution=false`. Given that this flag is toggleable even at HEAD makes it even more important for rulesets to remain compatible with both values and, as I intend to demonstrate with this issue, that doesn't seem to be possible at all with any version of Bazel.\r\n",
"If I understand correctly this is about the old mechanism for toolchain resolution used by C++ rules and the new mechanism not being compatible? If the old one is deprecated, we should focus on removing it instead, no need to support the flag --noincompatible_enable_cc_toolchain_resolution. Every incompatible flag is temporary and not meant for long term support.\r\n\r\nIf the problem is that without fixing the issue described here it becomes impossible to migrate, then that'd be a different story.\r\n",
"@oquenchil The problem is that `--noincompatible_enable_cc_toolchain_resolution` is still the default. Even if it is flipped in Bazel 7 (not even sure that is planned), rulesets will only be able to assume it is flipped when they stop supporting Bazel 6, which will happen when Bazel 8 is released at the earliest. As a result, rulesets may not be able to use optional toolchains until the release of Bazel 8, which is probably a year away.\r\n\r\nAdding a single alias to `@bazel_tools` now (that is, for Bazel 6.1), could speed this up by at least half a year.",
"Understood. Thanks for the clarification.",
"@katre For the reasons given by Fabian I think we should backport to 6.1 the simple change adding an alias to a BUILD file (not necessary for 5.4, although doing it for 5.4 wouldn't hurt either). https://github.com/bazelbuild/bazel/pull/16968 can be checked in at HEAD and that's it, no need to backport that PR. It's only the alias that would be needed to speed up progress by a lot as explained by Fabian.\r\n\r\nI know that this falls in the domain of C++ rules but you have a lot of expertise in this area. With those clarifications, would you be ok with backporting the alias?",
"This looks very reasonable. I took a quick look at the change and it makes sense, but you should do the detailed review."
] | [] | "2023-01-25T23:46:20Z" | [
"type: feature request",
"P2",
"team-Rules-CPP"
] | Using optional C++ toolchains while maintaining compatibility with non-platform builds | ### Description of the feature request:
It doesn't seem to be possible for a rule to simultaneously:
* declare an optional C++ toolchain dependency and gracefully handle situations in which it isn't available
* support builds with `--noincompatible_enable_cc_toolchain_resolution`
(ignoring potential hacks such as selecting between two rule implementations based on a `config_setting` backed by `incompatible_enable_cc_toolchain_resolution` or some other signal)
Concretely, consider the following example that tries to achieve both:
```starlark
# BUILD.bazel
load(":rules.bzl", "my_rule")
my_rule(
name = "my_rule",
)
platform(
name = "exotic_platform",
constraint_values = [
"@platforms//cpu:wasm64",
"@platforms//os:windows",
],
)
# rules.bzl
CPP_TOOLCHAIN_TYPE = "@bazel_tools//tools/cpp:toolchain_type"
# Inlined from //tools/cpp:toolchain_utils.bzl, modified to not fail if the toolchain isn't available.
def find_cpp_toolchain(ctx):
# Check the incompatible flag for toolchain resolution.
if hasattr(cc_common, "is_cc_toolchain_resolution_enabled_do_not_use") and cc_common.is_cc_toolchain_resolution_enabled_do_not_use(ctx = ctx):
if not CPP_TOOLCHAIN_TYPE in ctx.toolchains:
fail("In order to use find_cpp_toolchain, you must include the '%s' in the toolchains argument to your rule." % CPP_TOOLCHAIN_TYPE)
toolchain_info = ctx.toolchains[CPP_TOOLCHAIN_TYPE]
if toolchain_info == None:
# No cpp toolchain found, do not report an error.
return None
if hasattr(toolchain_info, "cc_provider_in_toolchain") and hasattr(toolchain_info, "cc"):
return toolchain_info.cc
return toolchain_info
# Fall back to the legacy implicit attribute lookup.
if hasattr(ctx.attr, "_cc_toolchain"):
return ctx.attr._cc_toolchain[cc_common.CcToolchainInfo]
# We didn't find anything.
fail("In order to use find_cpp_toolchain, you must define the '_cc_toolchain' attribute on your rule or aspect.")
# Inlined from //tools/cpp:toolchain_utils.bzl
def use_cpp_toolchain(mandatory = False):
return [config_common.toolchain_type(CPP_TOOLCHAIN_TYPE, mandatory = mandatory)]
def _my_rule_impl(ctx):
toolchain = find_cpp_toolchain(ctx)
if toolchain:
print("Optional toolchain available for", ctx.fragments.platform.platform, toolchain)
else:
print("Optional toolchain not available for", ctx.fragments.platform.platform)
my_rule = rule(
implementation = _my_rule_impl,
attrs = {"_cc_toolchain": attr.label(default = "@bazel_tools//tools/cpp:current_cc_toolchain")},
toolchains = use_cpp_toolchain(mandatory = False),
)
```
With `attrs = {"_cc_toolchain": attr.label(default = "@bazel_tools//tools/cpp:current_cc_toolchain")}`, we get:
```shell
$ USE_BAZEL_VERSION=last_green bazel build //:my_rule --incompatible_enable_cc_toolchain_resolution --platforms=//:exotic_platform
2022/12/09 11:03:39 Using unreleased version at commit 0ca78579ffc00ddc28517ad817bf29153ccd926d
INFO: Invocation ID: 26ed0a35-10e4-4f3d-b3f0-0154b2d7345d
ERROR: /home/fhenneke/.cache/bazel/_bazel_fhenneke/ec81a4d757466008837f55d1b135a58a/external/bazel_tools/tools/cpp/BUILD:58:19: in cc_toolchain_alias rule @bazel_tools//tools/cpp:current_cc_toolchain: Unable to find a CC toolchain using toolchain resolution. Did you properly set --platforms?
ERROR: /home/fhenneke/.cache/bazel/_bazel_fhenneke/ec81a4d757466008837f55d1b135a58a/external/bazel_tools/tools/cpp/BUILD:58:19: Analysis of target '@bazel_tools//tools/cpp:current_cc_toolchain' failed
ERROR: Analysis of target '//:my_rule' failed; build aborted:
INFO: Elapsed time: 2.684s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (34 packages loaded, 147 targets configured)
```
Without the line, we get:
```shell
❯ USE_BAZEL_VERSION=last_green bazel build //:my_rule
2022/12/09 11:05:04 Using unreleased version at commit 0ca78579ffc00ddc28517ad817bf29153ccd926d
INFO: Invocation ID: 8714bb4d-85b4-4469-95f7-5e324f72c759
ERROR: /home/fhenneke/tmp/bazel-optional-cc-toolchain/BUILD.bazel:3:8: in my_rule rule //:my_rule:
Traceback (most recent call last):
File "/home/fhenneke/tmp/bazel-optional-cc-toolchain/rules.bzl", line 29, column 35, in _my_rule_impl
toolchain = find_cpp_toolchain(ctx)
File "/home/fhenneke/tmp/bazel-optional-cc-toolchain/rules.bzl", line 22, column 9, in find_cpp_toolchain
fail("In order to use find_cpp_toolchain, you must define the '_cc_toolchain' attribute on your rule or aspect.")
Error in fail: In order to use find_cpp_toolchain, you must define the '_cc_toolchain' attribute on your rule or aspect.
ERROR: /home/fhenneke/tmp/bazel-optional-cc-toolchain/BUILD.bazel:3:8: Analysis of target '//:my_rule' failed
ERROR: Analysis of target '//:my_rule' failed; build aborted:
INFO: Elapsed time: 0.373s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (1 packages loaded, 0 targets configured)
```
### What underlying problem are you trying to solve with this feature?
Allow rules_go to have an optional C++ toolchain dependency (https://github.com/bazelbuild/rules_go/pull/3390).
### Which operating system are you running Bazel on?
any
### What is the output of `bazel info release`?
0ca78579ffc00ddc28517ad817bf29153ccd926d
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"tools/cpp/BUILD.tools",
"tools/cpp/toolchain_utils.bzl"
] | [
"tools/cpp/BUILD.tools",
"tools/cpp/toolchain_utils.bzl"
] | [] | diff --git a/tools/cpp/BUILD.tools b/tools/cpp/BUILD.tools
index 32ef01e5542dcd..4cf25d9ba99898 100644
--- a/tools/cpp/BUILD.tools
+++ b/tools/cpp/BUILD.tools
@@ -57,6 +57,14 @@ constraint_value(
cc_toolchain_alias(name = "current_cc_toolchain")
+# In future versions of Bazel, this target will not fail if no C++ toolchain is
+# available. Instead, it will not advertise the cc_common.CcToolchainInfo
+# provider.
+alias(
+ name = "optional_current_cc_toolchain",
+ actual = ":current_cc_toolchain",
+)
+
cc_host_toolchain_alias(name = "current_cc_host_toolchain")
cc_libc_top_alias(name = "current_libc_top")
diff --git a/tools/cpp/toolchain_utils.bzl b/tools/cpp/toolchain_utils.bzl
index 23d461d4dd8e57..1583aedcc1873f 100644
--- a/tools/cpp/toolchain_utils.bzl
+++ b/tools/cpp/toolchain_utils.bzl
@@ -19,7 +19,7 @@ Utilities to help work with c++ toolchains.
CPP_TOOLCHAIN_TYPE = "@bazel_tools//tools/cpp:toolchain_type"
-def find_cpp_toolchain(ctx):
+def find_cpp_toolchain(ctx, *, mandatory = True):
"""
Finds the c++ toolchain.
@@ -29,6 +29,9 @@ def find_cpp_toolchain(ctx):
Args:
ctx: The rule context for which to find a toolchain.
+ mandatory: This is currently a no-op. In future releases of Bazel, if this
+ is set to False, this function will return None rather than fail if no
+ toolchain is found.
Returns:
A CcToolchainProvider.
| null | train | val | 2023-01-26T00:34:44 | "2022-12-09T10:06:33Z" | fmeum | test |
bazelbuild/bazel/17359_17360 | bazelbuild/bazel | bazelbuild/bazel/17359 | bazelbuild/bazel/17360 | [
"keyword_pr_to_issue"
] | a951b942dce040cb2baa62758dba433becf8f606 | 40d83a754572c1aea94d0fce8a1bdd074c374584 | [
"Cherry-picked in #17360 "
] | [] | "2023-01-30T17:33:51Z" | [] | [6.1.0] No coverage data if testing code from external repositories | Forked from #16208 | [
"src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java",
"src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java"
] | [
"src/test/shell/bazel/bazel_coverage_java_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java b/src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java
index e3462bab2c8093..d37dde8014438c 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/actions/LazyWritePathsFileAction.java
@@ -29,10 +29,14 @@
import com.google.devtools.build.lib.util.Fingerprint;
import java.io.IOException;
import java.io.OutputStream;
+import java.util.function.Function;
import javax.annotation.Nullable;
/**
- * Lazily writes the exec path of the given files separated by newline into a specified output file.
+ * Lazily writes the path of the given files separated by newline into a specified output file.
+ *
+ * <p>By default the exec path is written but this behaviour can be customized by providing an
+ * alternative converter function.
*/
public final class LazyWritePathsFileAction extends AbstractFileWriteAction {
private static final String GUID = "6be94d90-96f3-4bec-8104-1fb08abc2546";
@@ -40,6 +44,7 @@ public final class LazyWritePathsFileAction extends AbstractFileWriteAction {
private final NestedSet<Artifact> files;
private final ImmutableSet<Artifact> filesToIgnore;
private final boolean includeDerivedArtifacts;
+ private final Function<Artifact, String> converter;
public LazyWritePathsFileAction(
ActionOwner owner,
@@ -47,23 +52,23 @@ public LazyWritePathsFileAction(
NestedSet<Artifact> files,
ImmutableSet<Artifact> filesToIgnore,
boolean includeDerivedArtifacts) {
- // TODO(ulfjack): It's a bad idea to have these two constructors do slightly different things.
- super(owner, files, output, false);
- this.files = files;
- this.includeDerivedArtifacts = includeDerivedArtifacts;
- this.filesToIgnore = filesToIgnore;
+ this(owner, output, files, filesToIgnore, includeDerivedArtifacts, Artifact::getExecPathString);
}
public LazyWritePathsFileAction(
ActionOwner owner,
Artifact output,
- ImmutableSet<Artifact> files,
+ NestedSet<Artifact> files,
ImmutableSet<Artifact> filesToIgnore,
- boolean includeDerivedArtifacts) {
+ boolean includeDerivedArtifacts,
+ Function<Artifact, String> converter) {
+ // We don't need to pass the given files as explicit inputs to this action; we don't care about
+ // them, we only need their names, which we already know.
super(owner, NestedSetBuilder.emptySet(Order.STABLE_ORDER), output, false);
- this.files = NestedSetBuilder.<Artifact>stableOrder().addAll(files).build();
+ this.files = files;
this.includeDerivedArtifacts = includeDerivedArtifacts;
this.filesToIgnore = filesToIgnore;
+ this.converter = converter;
}
@Override
@@ -94,10 +99,14 @@ private String getContents() {
continue;
}
if (file.isSourceArtifact() || includeDerivedArtifacts) {
- stringBuilder.append(file.getRootRelativePathString());
+ stringBuilder.append(converter.apply(file));
stringBuilder.append("\n");
}
}
return stringBuilder.toString();
}
+
+ public NestedSet<Artifact> getFiles() {
+ return files;
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java
index 8ae3fad9cf94f2..efca3d34269412 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java
@@ -365,7 +365,7 @@ && getJavaConfiguration().experimentalEnableJspecify()
new LazyWritePathsFileAction(
ruleContext.getActionOwner(),
coverageArtifact,
- sourceFiles,
+ NestedSetBuilder.<Artifact>stableOrder().addAll(sourceFiles).build(),
/* filesToIgnore= */ ImmutableSet.of(),
false));
}
| diff --git a/src/test/shell/bazel/bazel_coverage_java_test.sh b/src/test/shell/bazel/bazel_coverage_java_test.sh
index 27f86db018b32c..a7b0e31619be8f 100755
--- a/src/test/shell/bazel/bazel_coverage_java_test.sh
+++ b/src/test/shell/bazel/bazel_coverage_java_test.sh
@@ -1143,4 +1143,176 @@ end_of_record"
assert_coverage_result "$coverage_result_num_lib_header" "$coverage_file_path"
}
+function setup_external_java_target() {
+ cat >> WORKSPACE <<'EOF'
+local_repository(
+ name = "other_repo",
+ path = "other_repo",
+)
+EOF
+
+ cat > BUILD <<'EOF'
+java_library(
+ name = "math",
+ srcs = ["src/main/com/example/Math.java"],
+ visibility = ["//visibility:public"],
+)
+EOF
+
+ mkdir -p src/main/com/example
+ cat > src/main/com/example/Math.java <<'EOF'
+package com.example;
+
+public class Math {
+
+ public static boolean isEven(int n) {
+ return n % 2 == 0;
+ }
+}
+EOF
+
+ mkdir -p other_repo
+ touch other_repo/WORKSPACE
+
+ cat > other_repo/BUILD <<'EOF'
+java_library(
+ name = "collatz",
+ srcs = ["src/main/com/example/Collatz.java"],
+ deps = ["@//:math"],
+)
+
+java_test(
+ name = "test",
+ srcs = ["src/test/com/example/TestCollatz.java"],
+ test_class = "com.example.TestCollatz",
+ deps = [":collatz"],
+)
+EOF
+
+ mkdir -p other_repo/src/main/com/example
+ cat > other_repo/src/main/com/example/Collatz.java <<'EOF'
+package com.example;
+
+public class Collatz {
+
+ public static int getCollatzFinal(int n) {
+ if (n == 1) {
+ return 1;
+ }
+ if (Math.isEven(n)) {
+ return getCollatzFinal(n / 2);
+ } else {
+ return getCollatzFinal(n * 3 + 1);
+ }
+ }
+
+}
+EOF
+
+ mkdir -p other_repo/src/test/com/example
+ cat > other_repo/src/test/com/example/TestCollatz.java <<'EOF'
+package com.example;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+public class TestCollatz {
+
+ @Test
+ public void testGetCollatzFinal() {
+ assertEquals(Collatz.getCollatzFinal(1), 1);
+ assertEquals(Collatz.getCollatzFinal(5), 1);
+ assertEquals(Collatz.getCollatzFinal(10), 1);
+ assertEquals(Collatz.getCollatzFinal(21), 1);
+ }
+
+}
+EOF
+}
+
+function test_external_java_target_can_collect_coverage() {
+ setup_external_java_target
+
+ bazel coverage --test_output=all @other_repo//:test --combined_report=lcov \
+ --instrumentation_filter=// &>$TEST_log \
+ || echo "Coverage for //:test failed"
+
+ local coverage_file_path="$(get_coverage_file_path_from_test_log)"
+ local expected_result_math='SF:src/main/com/example/Math.java
+FN:3,com/example/Math::<init> ()V
+FN:6,com/example/Math::isEven (I)Z
+FNDA:0,com/example/Math::<init> ()V
+FNDA:1,com/example/Math::isEven (I)Z
+FNF:2
+FNH:1
+BRDA:6,0,0,1
+BRDA:6,0,1,1
+BRF:2
+BRH:2
+DA:3,0
+DA:6,1
+LH:1
+LF:2
+end_of_record'
+ local expected_result_collatz="SF:external/other_repo/src/main/com/example/Collatz.java
+FN:3,com/example/Collatz::<init> ()V
+FN:6,com/example/Collatz::getCollatzFinal (I)I
+FNDA:0,com/example/Collatz::<init> ()V
+FNDA:1,com/example/Collatz::getCollatzFinal (I)I
+FNF:2
+FNH:1
+BRDA:6,0,0,1
+BRDA:6,0,1,1
+BRDA:9,0,0,1
+BRDA:9,0,1,1
+BRF:4
+BRH:4
+DA:3,0
+DA:6,1
+DA:7,1
+DA:9,1
+DA:10,1
+DA:12,1
+LH:5
+LF:6
+end_of_record"
+
+ assert_coverage_result "$expected_result_math" "$coverage_file_path"
+ assert_coverage_result "$expected_result_collatz" "$coverage_file_path"
+
+ assert_coverage_result "$expected_result_math" bazel-out/_coverage/_coverage_report.dat
+ assert_coverage_result "$expected_result_collatz" bazel-out/_coverage/_coverage_report.dat
+}
+
+function test_external_java_target_coverage_not_collected_by_default() {
+ setup_external_java_target
+
+ bazel coverage --test_output=all @other_repo//:test --combined_report=lcov &>$TEST_log \
+ || echo "Coverage for //:test failed"
+
+ local coverage_file_path="$(get_coverage_file_path_from_test_log)"
+ local expected_result_math='SF:src/main/com/example/Math.java
+FN:3,com/example/Math::<init> ()V
+FN:6,com/example/Math::isEven (I)Z
+FNDA:0,com/example/Math::<init> ()V
+FNDA:1,com/example/Math::isEven (I)Z
+FNF:2
+FNH:1
+BRDA:6,0,0,1
+BRDA:6,0,1,1
+BRF:2
+BRH:2
+DA:3,0
+DA:6,1
+LH:1
+LF:2
+end_of_record'
+
+ assert_coverage_result "$expected_result_math" "$coverage_file_path"
+ assert_not_contains "SF:external/other_repo/" "$coverage_file_path"
+
+ assert_coverage_result "$expected_result_math" bazel-out/_coverage/_coverage_report.dat
+ assert_not_contains "SF:external/other_repo/" bazel-out/_coverage/_coverage_report.dat
+}
+
run_suite "test tests"
| train | test | 2023-01-30T17:21:32 | "2023-01-30T16:42:56Z" | bazel-io | test |
bazelbuild/bazel/17444_17445 | bazelbuild/bazel | bazelbuild/bazel/17444 | bazelbuild/bazel/17445 | [
"keyword_pr_to_issue"
] | 27bc896f36f0e0ea5dbeaaa16f3a124e38a7284a | 544b8164ca352cf06dda0849a589b825631428af | [
"I guess this is done?"
] | [] | "2023-02-08T11:53:46Z" | [
"P1",
"type: process",
"team-Rules-CPP",
"potential 5.x cherry-picks"
] | Cherrypick cc_shared_library fixes into 6.1 | All of these are either bug fixes or compatible changes that will allow users to start migrating their builds earlier before the experimental flag for cc_shared_library is removed:
https://github.com/bazelbuild/bazel/commit/5ba2d25fb581075eed8977815b17087ec5f632bb
https://github.com/bazelbuild/bazel/commit/9815b76121d4e36bdaae110de7e68131916478ca
https://github.com/bazelbuild/bazel/commit/68aad18cfc01400bf6c3f447b6cd7d21dcc8f01f
https://github.com/bazelbuild/bazel/commit/4ed6327523e1698e14dec1900ad71579c7f38b4a | [
"src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl",
"src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl"
] | [
"src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl",
"src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl"
] | [
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets/BUILD.builtin_test",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/foo.cc",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/starlark_tests.bzl",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/BUILD.builtin_test",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.cc",
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h"
] | diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
index 23982806a59d4d..baaaaf9e6a4f1c 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl
@@ -526,7 +526,7 @@ def _create_transitive_linking_actions(
win_def_file = win_def_file,
)
cc_launcher_info = cc_internal.create_cc_launcher_info(cc_info = cc_info_without_extra_link_time_libraries, compilation_outputs = cc_compilation_outputs_with_only_objects)
- return (cc_linking_outputs, cc_launcher_info, rule_impl_debug_files)
+ return (cc_linking_outputs, cc_launcher_info, rule_impl_debug_files, cc_linking_context)
def _use_pic(ctx, cc_toolchain, cpp_config, feature_configuration):
if _is_link_shared(ctx):
@@ -735,7 +735,7 @@ def cc_binary_impl(ctx, additional_linkopts):
if extra_link_time_libraries != None:
linker_inputs_extra, runtime_libraries_extra = extra_link_time_libraries.build_libraries(ctx = ctx, static_mode = linking_mode != _LINKING_DYNAMIC, for_dynamic_library = _is_link_shared(ctx))
- cc_linking_outputs_binary, cc_launcher_info, rule_impl_debug_files = _create_transitive_linking_actions(
+ cc_linking_outputs_binary, cc_launcher_info, rule_impl_debug_files, deps_cc_linking_context = _create_transitive_linking_actions(
ctx,
cc_toolchain,
feature_configuration,
diff --git a/src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl b/src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl
index 32483582fbfb09..5972527b79876e 100644
--- a/src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/experimental_cc_shared_library.bzl
@@ -33,6 +33,15 @@ cc_common = _builtins.toplevel.cc_common
# used sparingly after making sure it's safe to use.
LINKABLE_MORE_THAN_ONCE = "LINKABLE_MORE_THAN_ONCE"
+# Add this as a tag to any static lib target that doesn't export any symbols,
+# thus can be statically linked more than once. This is useful in some cases,
+# for example, a static lib has a constructor that needs to be run during
+# loading time of the shared lib that has it linked into, which is how the
+# code gets called by the OS. This static lib might need to be linked as a
+# whole archive dep for multiple shared libs, otherwise this static lib will
+# be dropped by the linker since there are no incoming symbol references.
+NO_EXPORTING = "NO_EXPORTING"
+
CcSharedLibraryPermissionsInfo = provider(
"Permissions for a cc shared library.",
fields = {
@@ -45,6 +54,7 @@ GraphNodeInfo = provider(
"children": "Other GraphNodeInfo from dependencies of this target",
"label": "Label of the target visited",
"linkable_more_than_once": "Linkable into more than a single cc_shared_library",
+ "no_exporting": "The static lib doesn't export any symbols so don't export it",
},
)
CcSharedLibraryInfo = provider(
@@ -63,14 +73,16 @@ CcSharedLibraryInfo = provider(
},
)
+# For each target, find out whether it should be linked statically or
+# dynamically.
def _separate_static_and_dynamic_link_libraries(
direct_children,
can_be_linked_dynamically,
preloaded_deps_direct_labels):
node = None
all_children = list(direct_children)
- link_statically_labels = {}
- link_dynamically_labels = {}
+ targets_to_be_linked_statically_map = {}
+ targets_to_be_linked_dynamically_set = {}
seen_labels = {}
@@ -87,12 +99,12 @@ def _separate_static_and_dynamic_link_libraries(
seen_labels[node_label] = True
if node_label in can_be_linked_dynamically:
- link_dynamically_labels[node_label] = True
+ targets_to_be_linked_dynamically_set[node_label] = True
elif node_label not in preloaded_deps_direct_labels:
- link_statically_labels[node_label] = node.linkable_more_than_once
+ targets_to_be_linked_statically_map[node_label] = node.linkable_more_than_once
all_children.extend(node.children)
- return (link_statically_labels, link_dynamically_labels)
+ return (targets_to_be_linked_statically_map, targets_to_be_linked_dynamically_set)
def _create_linker_context(ctx, linker_inputs):
return cc_common.create_linking_context(
@@ -132,6 +144,8 @@ def _build_exports_map_from_only_dynamic_deps(merged_shared_library_infos):
exports_map[export] = linker_input
return exports_map
+# The map points from the target that can only be linked once to the
+# cc_shared_library target that already links it.
def _build_link_once_static_libs_map(merged_shared_library_infos):
link_once_static_libs_map = {}
for entry in merged_shared_library_infos.to_list():
@@ -237,16 +251,17 @@ def _filter_inputs(
ctx,
feature_configuration,
cc_toolchain,
+ deps,
transitive_exports,
preloaded_deps_direct_labels,
link_once_static_libs_map):
linker_inputs = []
- curr_link_once_static_libs_map = {}
+ curr_link_once_static_libs_set = {}
graph_structure_aspect_nodes = []
dependency_linker_inputs = []
direct_exports = {}
- for export in ctx.attr.roots:
+ for export in deps:
direct_exports[str(export.label)] = True
dependency_linker_inputs.extend(export[CcInfo].linking_context.linker_inputs.to_list())
graph_structure_aspect_nodes.append(export[GraphNodeInfo])
@@ -257,16 +272,25 @@ def _filter_inputs(
if owner in transitive_exports:
can_be_linked_dynamically[owner] = True
- (link_statically_labels, link_dynamically_labels) = _separate_static_and_dynamic_link_libraries(
+ # The targets_to_be_linked_statically_map points to whether the target to
+ # be linked statically can be linked more than once.
+ (targets_to_be_linked_statically_map, targets_to_be_linked_dynamically_set) = _separate_static_and_dynamic_link_libraries(
graph_structure_aspect_nodes,
can_be_linked_dynamically,
preloaded_deps_direct_labels,
)
+ # We keep track of precompiled_only_dynamic_libraries, so that we can add
+ # them to runfiles.
precompiled_only_dynamic_libraries = []
- unaccounted_for_libs = []
exports = {}
linker_inputs_seen = {}
+
+ # We use this dictionary to give an error if a target containing only
+ # precompiled dynamic libraries is placed directly in roots. If such a
+ # precompiled dynamic library is needed it would be because a target in the
+ # parallel cc_library graph actually needs it. Therefore the precompiled
+ # dynamic library should be made a dependency of that cc_library instead.
dynamic_only_roots = {}
linked_statically_but_not_exported = {}
for linker_input in dependency_linker_inputs:
@@ -275,11 +299,21 @@ def _filter_inputs(
continue
linker_inputs_seen[stringified_linker_input] = True
owner = str(linker_input.owner)
- if owner in link_dynamically_labels:
- dynamic_linker_input = transitive_exports[owner]
- linker_inputs.append(dynamic_linker_input)
- elif owner in link_statically_labels:
+ if owner in targets_to_be_linked_dynamically_set:
+ # Link the library in this iteration dynamically,
+ # transitive_exports contains the artifacts produced by a
+ # cc_shared_library
+ linker_inputs.append(transitive_exports[owner])
+ elif owner in targets_to_be_linked_statically_map:
if owner in link_once_static_libs_map:
+ # We are building a dictionary that will allow us to give
+ # proper errors for libraries that have been linked multiple
+ # times elsewhere but haven't been exported. The values in the
+ # link_once_static_libs_map dictionary are the
+ # cc_shared_library targets. In this iteration we know of at
+ # least one target (i.e. owner) which is being linked
+ # statically by the cc_shared_library
+ # link_once_static_libs_map[owner] but is not being exported
linked_statically_but_not_exported.setdefault(link_once_static_libs_map[owner], []).append(owner)
is_direct_export = owner in direct_exports
@@ -301,41 +335,26 @@ def _filter_inputs(
if len(static_libraries) and owner in dynamic_only_roots:
dynamic_only_roots.pop(owner)
+ linker_input_to_be_linked_statically = linker_input
if is_direct_export:
- wrapped_library = _wrap_static_library_with_alwayslink(
+ linker_input_to_be_linked_statically = _wrap_static_library_with_alwayslink(
ctx,
feature_configuration,
cc_toolchain,
linker_input,
)
+ elif _check_if_target_should_be_exported_with_filter(
+ linker_input.owner,
+ ctx.label,
+ ctx.attr.exports_filter,
+ _get_permissions(ctx),
+ ):
+ exports[owner] = True
- if not link_statically_labels[owner]:
- curr_link_once_static_libs_map[owner] = True
- linker_inputs.append(wrapped_library)
- else:
- can_be_linked_statically = False
-
- for static_dep_path in ctx.attr.static_deps:
- static_dep_path_label = ctx.label.relative(static_dep_path)
- if _check_if_target_under_path(linker_input.owner, static_dep_path_label):
- can_be_linked_statically = True
- break
-
- if _check_if_target_should_be_exported_with_filter(
- linker_input.owner,
- ctx.label,
- ctx.attr.exports_filter,
- _get_permissions(ctx),
- ):
- exports[owner] = True
- can_be_linked_statically = True
-
- if can_be_linked_statically:
- if not link_statically_labels[owner]:
- curr_link_once_static_libs_map[owner] = True
- linker_inputs.append(linker_input)
- else:
- unaccounted_for_libs.append(linker_input.owner)
+ linker_inputs.append(linker_input_to_be_linked_statically)
+
+ if not targets_to_be_linked_statically_map[owner]:
+ curr_link_once_static_libs_set[owner] = True
if dynamic_only_roots:
message = ("Do not place libraries which only contain a " +
@@ -346,8 +365,7 @@ def _filter_inputs(
fail(message)
_throw_linked_but_not_exported_errors(linked_statically_but_not_exported)
- _throw_error_if_unaccounted_libs(unaccounted_for_libs)
- return (exports, linker_inputs, curr_link_once_static_libs_map.keys(), precompiled_only_dynamic_libraries)
+ return (exports, linker_inputs, curr_link_once_static_libs_set.keys(), precompiled_only_dynamic_libraries)
def _throw_linked_but_not_exported_errors(error_libs_dict):
if not error_libs_dict:
@@ -366,28 +384,6 @@ def _throw_linked_but_not_exported_errors(error_libs_dict):
fail("".join(error_builder))
-def _throw_error_if_unaccounted_libs(unaccounted_for_libs):
- if not unaccounted_for_libs:
- return
- libs_message = []
- different_repos = {}
- for unaccounted_lib in unaccounted_for_libs:
- different_repos[unaccounted_lib.workspace_name] = True
- if len(libs_message) < 10:
- libs_message.append(str(unaccounted_lib))
-
- if len(unaccounted_for_libs) > 10:
- libs_message.append("(and " + str(len(unaccounted_for_libs) - 10) + " others)\n")
-
- static_deps_message = []
- for repo in different_repos:
- static_deps_message.append(" \"@" + repo + "//:__subpackages__\",")
-
- fail("The following libraries cannot be linked either statically or dynamically:\n" +
- "\n".join(libs_message) + "\nTo ignore which libraries get linked" +
- " statically for now, add the following to 'static_deps':\n" +
- "\n".join(static_deps_message))
-
def _same_package_or_above(label_a, label_b):
if label_a.workspace_name != label_b.workspace_name:
return False
@@ -408,9 +404,41 @@ def _get_permissions(ctx):
return ctx.attr.permissions
return None
+def _get_deps(ctx):
+ if len(ctx.attr.deps) and len(ctx.attr.roots):
+ fail(
+ "You are using the attribute 'roots' and 'deps'. 'deps' is the " +
+ "new name for the attribute 'roots'. The attribute 'roots' will be" +
+ "removed in the future",
+ attr = "roots",
+ )
+
+ deps = ctx.attr.deps
+ if not len(deps):
+ deps = ctx.attr.roots
+
+ return deps
+
def _cc_shared_library_impl(ctx):
semantics.check_experimental_cc_shared_library(ctx)
+ if not cc_common.check_experimental_cc_shared_library():
+ if len(ctx.attr.static_deps):
+ fail(
+ "This attribute is a no-op and its usage" +
+ " is forbidden after cc_shared_library is no longer experimental. " +
+ "Remove it from every cc_shared_library target",
+ attr = "static_deps",
+ )
+ if len(ctx.attr.roots):
+ fail(
+ "This attribute has been renamed to 'deps'. Simply rename the" +
+ " attribute on the target.",
+ attr = "roots",
+ )
+
+ deps = _get_deps(ctx)
+
cc_toolchain = cc_helper.find_cpp_toolchain(ctx)
feature_configuration = cc_common.configure_features(
ctx = ctx,
@@ -421,7 +449,7 @@ def _cc_shared_library_impl(ctx):
merged_cc_shared_library_info = _merge_cc_shared_library_infos(ctx)
exports_map = _build_exports_map_from_only_dynamic_deps(merged_cc_shared_library_info)
- for export in ctx.attr.roots:
+ for export in deps:
# Do not check for overlap between targets matched by the current
# rule's exports_filter and what is in exports_map. A library in roots
# will have to be linked in statically into the current rule with 100%
@@ -450,10 +478,11 @@ def _cc_shared_library_impl(ctx):
link_once_static_libs_map = _build_link_once_static_libs_map(merged_cc_shared_library_info)
- (exports, linker_inputs, link_once_static_libs, precompiled_only_dynamic_libraries) = _filter_inputs(
+ (exports, linker_inputs, curr_link_once_static_libs_set, precompiled_only_dynamic_libraries) = _filter_inputs(
ctx,
feature_configuration,
cc_toolchain,
+ deps,
exports_map,
preloaded_deps_direct_labels,
link_once_static_libs_map,
@@ -531,21 +560,26 @@ def _cc_shared_library_impl(ctx):
runfiles = runfiles.merge(ctx.runfiles(files = precompiled_only_dynamic_libraries_runfiles))
- for export in ctx.attr.roots:
- exports[str(export.label)] = True
+ for export in deps:
+ export_label = str(export.label)
+ if GraphNodeInfo in export and export[GraphNodeInfo].no_exporting:
+ if export_label in curr_link_once_static_libs_set:
+ curr_link_once_static_libs_set.remove(export_label)
+ continue
+ exports[export_label] = True
debug_files = []
exports_debug_file = ctx.actions.declare_file(ctx.label.name + "_exports.txt")
ctx.actions.write(content = "\n".join(["Owner:" + str(ctx.label)] + exports.keys()), output = exports_debug_file)
link_once_static_libs_debug_file = ctx.actions.declare_file(ctx.label.name + "_link_once_static_libs.txt")
- ctx.actions.write(content = "\n".join(["Owner:" + str(ctx.label)] + link_once_static_libs), output = link_once_static_libs_debug_file)
+ ctx.actions.write(content = "\n".join(["Owner:" + str(ctx.label)] + curr_link_once_static_libs_set), output = link_once_static_libs_debug_file)
debug_files.append(exports_debug_file)
debug_files.append(link_once_static_libs_debug_file)
if not ctx.fragments.cpp.experimental_link_static_libraries_once():
- link_once_static_libs = []
+ curr_link_once_static_libs_set = {}
library = []
if linking_outputs.library_to_link.resolved_symlink_dynamic_library != None:
@@ -574,7 +608,7 @@ def _cc_shared_library_impl(ctx):
CcSharedLibraryInfo(
dynamic_deps = merged_cc_shared_library_info,
exports = exports.keys(),
- link_once_static_libs = link_once_static_libs,
+ link_once_static_libs = curr_link_once_static_libs_set,
linker_input = cc_common.create_linker_input(
owner = ctx.label,
libraries = depset([linking_outputs.library_to_link] + precompiled_only_dynamic_libraries),
@@ -595,15 +629,19 @@ def _graph_structure_aspect_impl(target, ctx):
# TODO(bazel-team): Add flag to Bazel that can toggle the initialization of
# linkable_more_than_once.
linkable_more_than_once = False
+ no_exporting = False
if hasattr(ctx.rule.attr, "tags"):
for tag in ctx.rule.attr.tags:
if tag == LINKABLE_MORE_THAN_ONCE:
linkable_more_than_once = True
+ elif tag == NO_EXPORTING:
+ no_exporting = True
return [GraphNodeInfo(
label = ctx.label,
children = children,
linkable_more_than_once = linkable_more_than_once,
+ no_exporting = no_exporting,
)]
def _cc_shared_library_permissions_impl(ctx):
@@ -642,6 +680,7 @@ cc_shared_library = rule(
"preloaded_deps": attr.label_list(providers = [CcInfo]),
"win_def_file": attr.label(allow_single_file = [".def"]),
"roots": attr.label_list(providers = [CcInfo], aspects = [graph_structure_aspect]),
+ "deps": attr.label_list(providers = [CcInfo], aspects = [graph_structure_aspect]),
"static_deps": attr.string_list(),
"user_link_flags": attr.string_list(),
"_def_parser": semantics.get_def_parser(),
| diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
index 3789ab4ae39aef..de112ad08e23f4 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
@@ -1,4 +1,14 @@
-load(":starlark_tests.bzl", "additional_inputs_test", "build_failure_test", "debug_files_test", "interface_library_output_group_test", "linking_suffix_test", "paths_test", "runfiles_test")
+load(
+ ":starlark_tests.bzl",
+ "additional_inputs_test",
+ "build_failure_test",
+ "debug_files_test",
+ "interface_library_output_group_test",
+ "linking_suffix_test",
+ "paths_test",
+ "runfiles_test",
+ "no_exporting_static_lib_test",
+)
LINKABLE_MORE_THAN_ONCE = "LINKABLE_MORE_THAN_ONCE"
@@ -42,28 +52,28 @@ cc_binary(
cc_shared_library(
name = "python_module",
features = ["windows_export_all_symbols"],
- roots = [":a_suffix"],
+ deps = [":a_suffix"],
shared_lib_name = "python_module.pyd",
)
cc_shared_library(
name = "a_so",
features = ["windows_export_all_symbols"],
- roots = [":a_suffix"],
+ deps = [":a_suffix"],
)
cc_shared_library(
name = "diamond_so",
dynamic_deps = [":a_so"],
features = ["windows_export_all_symbols"],
- roots = [":qux"],
+ deps = [":qux"],
)
cc_shared_library(
name = "diamond2_so",
dynamic_deps = [":a_so"],
features = ["windows_export_all_symbols"],
- roots = [":qux2"],
+ deps = [":qux2"],
)
cc_binary(
@@ -88,19 +98,17 @@ cc_shared_library(
],
"//conditions:default": [],
}),
- dynamic_deps = ["bar_so"],
+ dynamic_deps = [
+ "bar_so",
+ "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3:diff_pkg_so"
+ ],
features = ["windows_export_all_symbols"],
preloaded_deps = ["preloaded_dep"],
- roots = [
+ deps = [
"baz",
"foo",
"a_suffix",
],
- static_deps = [
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:qux",
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:qux2",
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:prebuilt",
- ],
user_link_flags = select({
"//src/conditions:linux": [
"-Wl,-rpath,kittens",
@@ -139,6 +147,7 @@ cc_library(
"qux",
"qux2",
"prebuilt",
+ "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3:diff_pkg"
],
)
@@ -190,18 +199,13 @@ cc_shared_library(
permissions = [
"//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3:permissions",
],
- roots = [
+ deps = [
"bar",
"bar2",
] + select({
":is_bazel": ["@test_repo//:bar"],
"//conditions:default": [],
}),
- static_deps = [
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:barX",
- "@test_repo//:bar",
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:qux2",
- ],
user_link_flags = select({
"//src/conditions:linux": [
"-Wl,--version-script=$(location :bar.lds)",
@@ -346,7 +350,7 @@ filegroup(
cc_shared_library(
name = "direct_so_file",
features = ["windows_export_all_symbols"],
- roots = [
+ deps = [
":direct_so_file_cc_lib",
],
)
@@ -367,7 +371,7 @@ filegroup(
cc_shared_library(
name = "renamed_so_file",
features = ["windows_export_all_symbols"],
- roots = [
+ deps = [
":direct_so_file_cc_lib2",
],
shared_lib_name = "renamed_so_file.so",
@@ -398,6 +402,51 @@ cc_shared_library_permissions(
],
)
+cc_library(
+ name = "static_lib_no_exporting",
+ srcs = [
+ "bar.cc",
+ "bar.h",
+ ],
+ tags = ["NO_EXPORTING"],
+)
+
+cc_library(
+ name = "static_lib_exporting",
+ srcs = [
+ "bar2.cc",
+ "bar2.h",
+ ],
+)
+
+cc_shared_library(
+ name = "lib_with_no_exporting_roots_1",
+ deps = [":static_lib_no_exporting"],
+)
+
+cc_shared_library(
+ name = "lib_with_no_exporting_roots_2",
+ deps = [":static_lib_no_exporting"],
+ dynamic_deps = [":lib_with_no_exporting_roots_3"],
+)
+
+cc_shared_library(
+ name = "lib_with_no_exporting_roots_3",
+ deps = [":static_lib_no_exporting"],
+)
+
+cc_shared_library(
+ name = "lib_with_no_exporting_roots",
+ deps = [
+ ":static_lib_no_exporting",
+ ":static_lib_exporting",
+ ],
+ dynamic_deps = [
+ ":lib_with_no_exporting_roots_1",
+ ":lib_with_no_exporting_roots_2",
+ ],
+)
+
build_failure_test(
name = "two_dynamic_deps_same_export_in_so_test",
message = "Two shared libraries in dependencies export the same symbols",
@@ -433,16 +482,7 @@ runfiles_test(
target_under_test = ":python_test",
)
-build_failure_test(
- name = "static_deps_error_test",
- messages = select({
- ":is_bazel": [
- "@//:__subpackages__",
- "@test_repo//:__subpackages__",
- ],
- "//conditions:default": [
- "@//:__subpackages__",
- ],
- }),
- target_under_test = "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets:unaccounted_for_libs_so",
+no_exporting_static_lib_test(
+ name = "no_exporting_static_lib_test",
+ target_under_test = ":lib_with_no_exporting_roots",
)
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets/BUILD.builtin_test b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets/BUILD.builtin_test
index 82d01bd38879ec..6ab7018d6e2f0b 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets/BUILD.builtin_test
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/failing_targets/BUILD.builtin_test
@@ -19,12 +19,9 @@ cc_binary(
cc_shared_library(
name = "should_fail_shared_lib",
dynamic_deps = ["//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:bar_so"],
- roots = [
+ deps = [
":intermediate",
],
- static_deps = [
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:barX",
- ],
tags = TAGS,
)
@@ -37,7 +34,7 @@ cc_library(
cc_shared_library(
name = "permissions_fail_so",
- roots = [
+ deps = [
"//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3:bar",
],
tags = TAGS,
@@ -72,7 +69,7 @@ cc_shared_library(
":b_so",
":b2_so",
],
- roots = [
+ deps = [
":a",
],
tags = TAGS,
@@ -90,7 +87,7 @@ cc_binary(
cc_shared_library(
name = "b_so",
- roots = [
+ deps = [
":b",
],
tags = TAGS,
@@ -98,38 +95,8 @@ cc_shared_library(
cc_shared_library(
name = "b2_so",
- roots = [
+ deps = [
":b",
],
tags = TAGS,
)
-
-cc_shared_library(
- name = "unaccounted_for_libs_so",
- roots = [
- ":d1",
- ],
- tags = TAGS,
-)
-
-cc_library(
- name = "d1",
- srcs = ["empty.cc"],
- deps = ["d2"],
-)
-
-cc_library(
- name = "d2",
- srcs = ["empty.cc"],
- deps = [
- "d3",
- ] + select({
- "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:is_bazel": ["@test_repo//:bar"],
- "//conditions:default": [],
- }),
-)
-
-cc_library(
- name = "d3",
- srcs = ["empty.cc"],
-)
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/foo.cc b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/foo.cc
index cc9c8da410e740..0559c0a3b9da9c 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/foo.cc
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/foo.cc
@@ -17,8 +17,10 @@
#include "src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/direct_so_file_cc_lib2.h"
#include "src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/preloaded_dep.h"
#include "src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/qux.h"
+#include "src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h"
int foo() {
+ diff_pkg();
bar();
baz();
qux();
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/starlark_tests.bzl b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/starlark_tests.bzl
index 121bb1d41ad6fd..c5de4978aab962 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/starlark_tests.bzl
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/starlark_tests.bzl
@@ -150,7 +150,16 @@ def _debug_files_test_impl(ctx):
actual_files = []
for debug_file in target_under_test[OutputGroupInfo].rule_impl_debug_files.to_list():
actual_files.append(debug_file.basename)
- expected_files = ["bar_so_exports.txt", "bar_so_link_once_static_libs.txt", "foo_so_exports.txt", "foo_so_link_once_static_libs.txt", "binary_link_once_static_libs.txt"]
+
+ expected_files = [
+ "bar_so_exports.txt",
+ "bar_so_link_once_static_libs.txt",
+ "diff_pkg_so_exports.txt",
+ "diff_pkg_so_link_once_static_libs.txt",
+ "foo_so_exports.txt",
+ "foo_so_link_once_static_libs.txt",
+ "binary_link_once_static_libs.txt",
+ ]
asserts.equals(env, expected_files, actual_files)
return analysistest.end(env)
@@ -166,8 +175,10 @@ def _runfiles_test_impl(ctx):
expected_suffixes = [
"libfoo_so.so",
"libbar_so.so",
+ "libdiff_pkg_so.so",
"Smain_Sstarlark_Stests_Sbuiltins_Ubzl_Scc_Scc_Ushared_Ulibrary_Stest_Ucc_Ushared_Ulibrary_Slibfoo_Uso.so",
"Smain_Sstarlark_Stests_Sbuiltins_Ubzl_Scc_Scc_Ushared_Ulibrary_Stest_Ucc_Ushared_Ulibrary_Slibbar_Uso.so",
+ "Smain_Sstarlark_Stests_Sbuiltins_Ubzl_Scc_Scc_Ushared_Ulibrary_Stest_Ucc_Ushared_Ulibrary3_Slibdiff_Upkg_Uso.so",
"Smain_Sstarlark_Stests_Sbuiltins_Ubzl_Scc_Scc_Ushared_Ulibrary_Stest_Ucc_Ushared_Ulibrary/renamed_so_file_copy.so",
"Smain_Sstarlark_Stests_Sbuiltins_Ubzl_Scc_Scc_Ushared_Ulibrary_Stest_Ucc_Ushared_Ulibrary/libdirect_so_file.so",
]
@@ -211,3 +222,21 @@ interface_library_output_group_test = analysistest.make(
"is_windows": attr.bool(),
},
)
+
+def _no_exporting_static_lib_test_impl(ctx):
+ env = analysistest.begin(ctx)
+
+ target_under_test = analysistest.target_under_test(env)
+
+ # There should be only one exported file
+ actual_file = target_under_test[CcSharedLibraryInfo].exports[0]
+
+ # Sometimes "@" is prefixed in some test environments
+ expected = "//src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library:static_lib_exporting"
+ asserts.true(env, actual_file.endswith(expected))
+
+ return analysistest.end(env)
+
+no_exporting_static_lib_test = analysistest.make(
+ _no_exporting_static_lib_test_impl,
+)
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/BUILD.builtin_test b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/BUILD.builtin_test
index 6a5b93da89d103..364e7f84367aa6 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/BUILD.builtin_test
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/BUILD.builtin_test
@@ -8,6 +8,20 @@ cc_library(
hdrs = ["bar.h"],
)
+cc_library(
+ name = "diff_pkg",
+ srcs = ["diff_pkg.cc"],
+ hdrs = ["diff_pkg.h"],
+)
+
+cc_shared_library(
+ name = "diff_pkg_so",
+ features = ["windows_export_all_symbols"],
+ deps = [
+ ":diff_pkg",
+ ],
+)
+
cc_shared_library_permissions(
name = "permissions",
targets = [
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.cc b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.cc
new file mode 100644
index 00000000000000..70e9e53e73ef83
--- /dev/null
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.cc
@@ -0,0 +1,16 @@
+// Copyright 2023 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.
+#include "src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h"
+
+int diff_pkg() { return 42; }
diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h
new file mode 100644
index 00000000000000..8c39aa01d0a4f5
--- /dev/null
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library3/diff_pkg.h
@@ -0,0 +1,19 @@
+// Copyright 2023 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.
+#ifndef EXAMPLES_TEST_CC_SHARED_LIBRARY_DIFF_PKG_H_
+#define EXAMPLES_TEST_CC_SHARED_LIBRARY_DIFF_PKG_H_
+
+int diff_pkg();
+
+#endif // EXAMPLES_TEST_CC_SHARED_LIBRARY_DIFF_PKG_H_
| train | test | 2023-02-08T00:50:56 | "2023-02-08T11:08:26Z" | oquenchil | test |
bazelbuild/bazel/10292_17465 | bazelbuild/bazel | bazelbuild/bazel/10292 | bazelbuild/bazel/17465 | [
"keyword_pr_to_issue"
] | 0c62801773ca2906bf446c8be6ef688eed16d5f4 | dfd19f6aa0f3e406586a7c6a0d6b768889038b92 | [
"We got the same issue on macOS, but it seems to be a problem with git (tried with `git clone --shallow-since`).",
"Yeah, seems like it. Though I'd say Bazel is still responsible for avoiding recommending `shallow_since` unless/until this is fixed (a version check on git might make sense). Otherwise it's really confusing for the user to be recommended an option that's broken.",
"@aehlig Do you know what causes it? ",
"I did some digging here, and reported [an upstream bug to `git`](https://public-inbox.org/git/CAPSG9dZV2EPpVKkOMcjv5z+NF7rUu=V-ZkZNx47rCv122HsiKg@mail.gmail.com/T/#u)\r\n\r\nThe upshot is that `--shallow-since` is subtly incorrect when the provided timestamp would cause us to include _some_ parents of a merge, but not others. In the case provided here, nelhage/rules_boost@df90835 has a commit timestamp of 1569511515. That commit is the second part of a merge, nelhage/rules_boost@76f3064; that merge's first parent is nelhage/rules_boost@a83197e, with an older commit timestamp of 1569487118\r\n\r\nThe bug I reported results in `git` discarding _all_ parents of the merge (nelhage/rules_boost@76f3064), including the desired commit.\r\n\r\nFor now, the workaround for bazel _users_ -- where available -- is to switch your `commit=` line to point to a commit on the first-parent spine, e.g. nelhage/rules_boost@76f3064. If you add the suggested `shallow_since` line for that commit, things work fine.\r\n\r\nFor Bazel itself, it might be nice to recognize this situation and adjust the `shallow_since` recommendation, at least until the upstream bug can be sorted out. I'm not certain offhand what the right/easiest heuristic to detect it is, though.",
"It turns out that the workaround proposed here doesn't work either.\r\n\r\nThe shallow_since bug is even worse than I expected. It stops at the first commit which has any parents before the cutoff time. This means we have the following horrible scenario:\r\n\r\n1. Latest commit on main branch is aaaa, with parents baaa and bbbb. aaaa is at 8am, baaa is at 6am and bbbb is at 4am\r\n2. I create a git_repository rule with commit = \"aaaa\", shallow_since = \"4am\"\r\n3. This works fine when I build it\r\n4. Somebody adds a new commit caaa to main branch, with parents aaaa and cbbb. caaa is at 9am, cbbb is at 2am\r\n5. git clone --shallow_since=4am will now fetch only caaa because it has a parent before 4am, and aaaa will not be fetched\r\n\r\nThis is completely unusable and I don't see a workaround.",
"Yeah, I agree with @asuffield's analysis -- I ran into that situation since posting https://github.com/bazelbuild/bazel/issues/10292#issuecomment-680205748. In light of this and of #12857 it really seems like the right path forward is to stop suggesting `--shallow-since`. It might be appropriate in cases where the developers know neither of these problems will apply -- or are able to debug their way out if necessary -- but it's clearly too broken to suggest as a default.",
"I'm piecing together an alternative solution - for cases where a tag or commit hash is given, we can use point fetch with --depth=1 as long as we verify the results and correctly fallback to deep fetch if we don't get what we needed. It doesn't work on all git versions, but I don't believe there is a solution other than deep fetch for older git.",
"If you auto-detect GitHub URLs you can instead just suggest HTTPS cloning. It's probably a good suggestion in any case; we switched to that as it's faster too.",
"> If you auto-detect GitHub URLs you can instead just suggest HTTPS cloning. It's probably a good suggestion in any case; we switched to that as it's faster too.\r\n\r\nThis is an interesting idea which would likely be best implemented in git itself - the protocol's rich enough to pull it off.",
"`git archive` already exists in git. GitHub has refused to support it.",
"I would like to get some progress on this issue. Would it be fine if I create a PR to remove the debug log saying:\r\n\r\n> indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = \r\n\r\nThe issue with this log is that one a user see it the first thing will do is to set up the shallow_since, but because of this bug it is something that should consider twice.\r\n"
] | [] | "2023-02-10T19:22:50Z" | [
"type: bug",
"P2",
"team-ExternalDeps"
] | shallow_since appears to be broken | ### Description of the problem / feature request:
`shallow_since` appears to be broken.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Try to build `//:BUILD.boost` from https://github.com/nelhage/rules_boost/commit/df908358c605a7d5b8bbacde07afbaede5ac12cf. You'll receive a recommendation for `shallow_since`. Insert that recommendation, and suddenly Bazel fails to find that commit at all.
### What operating system are you running Bazel on?
Windows
### What's the output of `bazel info release`?
release 1.1.0
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
N/A
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
Create an empty `BUILD.bazel` alongside the following `WORKSPACE`:
```
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(name="rules_boost", commit="df908358c605a7d5b8bbacde07afbaede5ac12cf", remote="https://github.com/nelhage/rules_boost")
```
Now run `bazel --ignore_all_rc_files query "deps(@rules_boost//:BUILD.boost)"`:
```
bazel --ignore_all_rc_files query "deps(@rules_boost//:BUILD.boost)"
@bazel --ignore_all_rc_files clean --expunge
```
It outputs something like the following (after formatting/redactions):
```
INFO: Writing tracer profile to 'command.profile.gz'
DEBUG: Rule 'rules_boost' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1569511515 +0200"
DEBUG: Call stack for the definition of repository 'rules_boost' which is a git_repository (rule definition at external/bazel_tools/tools/build_defs/repo/git.bzl:195:18):
- WORKSPACE:2:1
ERROR: no such target '@rules_boost//:BUILD.boost': target 'BUILD.boost' not declared in package ''; however, a source file of this name exists. (Perhaps add 'exports_files(["BUILD.boost"])' to /BUILD?) defined by external/rules_boost/BUILD
Loading: 1 packages loaded
```
Now add `shallow_since="1569511515 +0200"` as recommended and re-run the query:
```
INFO: Writing tracer profile to 'command.profile.gz'
INFO: Call stack for the definition of repository 'rules_boost' which is a git_repository (rule definition at external/bazel_tools/tools/build_defs/repo/git.bzl:195:18):
- WORKSPACE:2:1
ERROR: An error occurred during the fetch of repository 'rules_boost':
error running 'git reset --hard df908358c605a7d5b8bbacde07afbaede5ac12cf' while working with @rules_boost:
fatal: Could not parse object 'df908358c605a7d5b8bbacde07afbaede5ac12cf'.
ERROR: no such package '@rules_boost//'
Loading: 0 packages loaded
```
Suddenly Bazel seems to be unable to find the commit altogether.
| [
"tools/build_defs/repo/git.bzl",
"tools/build_defs/repo/git_worker.bzl"
] | [
"tools/build_defs/repo/git.bzl",
"tools/build_defs/repo/git_worker.bzl"
] | [] | diff --git a/tools/build_defs/repo/git.bzl b/tools/build_defs/repo/git.bzl
index 88678daae163b2..6f21bcd7dcaf9c 100644
--- a/tools/build_defs/repo/git.bzl
+++ b/tools/build_defs/repo/git.bzl
@@ -42,7 +42,10 @@ def _clone_or_update_repo(ctx):
for item in ctx.path(dest_link).readdir():
ctx.symlink(item, root.get_child(item.basename))
- return {"commit": git_.commit, "shallow_since": git_.shallow_since}
+ if ctx.attr.shallow_since:
+ return {"commit": git_.commit, "shallow_since": git_.shallow_since}
+ else:
+ return {"commit": git_.commit}
def _update_git_attrs(orig, keys, override):
result = update_attrs(orig, keys, override)
@@ -68,12 +71,14 @@ _common_attrs = {
"shallow_since": attr.string(
default = "",
doc =
- "an optional date, not after the specified commit; the " +
- "argument is not allowed if a tag is specified (which allows " +
- "cloning with depth 1). Setting such a date close to the " +
- "specified commit allows for a more shallow clone of the " +
- "repository, saving bandwidth " +
- "and wall-clock time.",
+ "an optional date, not after the specified commit; the argument " +
+ "is not allowed if a tag or branch is specified (which can " +
+ "always be cloned with --depth=1). Setting such a date close to " +
+ "the specified commit may allow for a shallow clone of the " +
+ "repository even if the server does not support shallow fetches " +
+ "of arbitary commits. Due to bugs in git's --shallow-since " +
+ "implementation, using this attribute is not recommended as it " +
+ "may result in fetch failures.",
),
"tag": attr.string(
default = "",
@@ -183,6 +188,10 @@ makes its targets available for binding. Also determine the id of the
commit actually checked out and its date, and return a dict with parameters
that provide a reproducible version of this rule (which a tag not necessarily
is).
+
+Bazel will first try to perform a shallow fetch of only the specified commit.
+If that fails (usually due to missing server support), it will fall back to a
+full fetch of the repository.
""",
)
diff --git a/tools/build_defs/repo/git_worker.bzl b/tools/build_defs/repo/git_worker.bzl
index c663cdaabf8032..3e9ba3a10e40bf 100644
--- a/tools/build_defs/repo/git_worker.bzl
+++ b/tools/build_defs/repo/git_worker.bzl
@@ -79,8 +79,8 @@ def git_repo(ctx, directory):
recursive_init_submodules = ctx.attr.recursive_init_submodules,
)
- ctx.report_progress("Cloning %s of %s" % (reset_ref, ctx.attr.remote))
- if (ctx.attr.verbose):
+ _report_progress(ctx, git_repo)
+ if ctx.attr.verbose:
print("git.bzl: Cloning or updating %s repository %s using strip_prefix of [%s]" %
(
" (%s)" % shallow if shallow else "",
@@ -95,6 +95,12 @@ def git_repo(ctx, directory):
return struct(commit = actual_commit, shallow_since = shallow_date)
+def _report_progress(ctx, git_repo, *, shallow_failed = False):
+ warning = ""
+ if shallow_failed:
+ warning = " (shallow fetch failed, fetching full history)"
+ ctx.report_progress("Cloning %s of %s%s" % (git_repo.reset_ref, git_repo.remote, warning))
+
def _update(ctx, git_repo):
ctx.delete(git_repo.directory)
@@ -133,6 +139,7 @@ def fetch(ctx, git_repo):
# "ignore what is specified and fetch all tags".
# The arguments below work correctly for both before 1.9 and after 1.9,
# as we directly specify the list of references to fetch.
+ _report_progress(ctx, git_repo, shallow_failed = True)
_git(
ctx,
git_repo,
| null | test | test | 2023-02-16T18:01:13 | "2019-11-22T08:01:26Z" | mehrdadn | test |
bazelbuild/bazel/12857_17465 | bazelbuild/bazel | bazelbuild/bazel/12857 | bazelbuild/bazel/17465 | [
"keyword_pr_to_issue"
] | 0c62801773ca2906bf446c8be6ef688eed16d5f4 | dfd19f6aa0f3e406586a7c6a0d6b768889038b92 | [
"+1\r\n\r\nAlso git's `--shallow-since` has a bug that can sometimes make git impossible to fetch the desired commit using its suggested timestamp: https://github.com/bazelbuild/bazel/issues/10292.",
"There is no way to persuade git to fetch a specific commit with --depth=1. If you try fetching a commit hash, most servers will just give you \"server does not allow request for unadvertised object\", and if you fetch a ref name then it can return anything and is not reproducible.\r\n\r\nshallow_since is the only feature git offers to do this. Unfortunately, it's completely broken.",
"Correction: --depth=1 on a single commit only works with protocol v2, see https://github.com/bazelbuild/bazel/pull/12199 ",
"@asuffield I don't think we're on protocol v2 (although I'm not completely sure how to verify that) and we've been using the commit only since I posted the issue without any apparent problems or non-reproducibility. As far as I can tell, the actions bazel is taking are equivalent to the following commands, which appear to work for me.\r\n\r\n```\r\nmkdir ruby ; cd ruby\r\ngit init\r\ngit remote add origin [email protected]:ruby/ruby.git\r\n# A random old commit\r\ngit fetch origin 5de38c41ae7bf17ae599fdfa9f8face87f16d8bb --depth 1\r\ngit checkout 5de38c41ae7bf17ae599fdfa9f8face87f16d8bb\r\n```\r\n\r\n Do you mean that it doesn't work reliably with all git servers, so maybe it works on github but not elsewhere?\r\n\r\n```\r\n$ git --version\r\ngit version 2.25.1\r\n$ echo $GIT_PROTOCOL\r\n\r\n```",
"It looks like maybe the server config option `uploadpack.allowReachableSHA1InWant` needs to be set to enable this, but the repository rules already seem to handle falling back when the server doesn't support this option anyway. `shallow_since` is perhaps better than the fallback option, but it's probably worse than fetching the commit directly when supported, so it shouldn't be recommended when fetching by commit is supported.\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/8346ea4cfdd9fbd170d51a528fee26f912dad2d5/tools/build_defs/repo/git_worker.bzl#L129",
"It definitely fails with git 2.18 (ugh, upgrading that right now) against gitlab, I haven't tested exhaustively. But the main problem in the PR linked above is that one of bazel's target platforms has an old git version, and that's going to sabotage us here.",
"Are there ways to improve this situation, even given bazel's support for ubuntu 18.04 and its associated git version?\r\n\r\nOne option is simply to drop the warning from this rule (by making the rule output a canonical version that omits `shallow_since` if the caller did not specify it).\r\n\r\nAnother is to add something like an explicit `depth` arg to the `git_repository` rules: I don't like that from an API perspective, but it could allow callers to explicitly use a depth-based canonical form (rather than a `shallow_since`-based form) if that works for their environments.\r\n\r\nI think that any change to the canonical form of this rule would involve changing what's returned from the [`git_repo` function](https://github.com/bazelbuild/bazel/blob/master/tools/build_defs/repo/git_worker.bzl#L94-L96).\r\n\r\nAre there other ideas that could remove warnings from a correct repository setup that's relying on `depth=1` rather than a `shallow_since` date?"
] | [] | "2023-02-10T19:22:50Z" | [
"type: bug",
"P2",
"team-OSS"
] | shallow_since appears to be a trap when used with commit, debug line should be removed | ### Description of the problem / feature request:
The `shallow_since` option to `new_git_repository` appears to be a trap, at least when used with the `commit` option. When shallow_since is provided, instead of using `depth 1` to check out only the relevant commit, the entire repo state since some timestamp is cloned. On one of our repos, this causes a *25x* difference in clone time (7s -> 175s) and presumably a large size disparity as well.
Now that we have removed shallow_since, bazel emits a debug line encouraging us to add it back.
```
DEBUG: Rule 'foo' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1611092265 -0800"
```
This seems wrong -- as far as I understand, the repo at a specific commit hash _is_ a canonical reproducible form, so it seems like bazel should not be suggesting this change.
### Feature requests: what underlying problem are you trying to solve with this feature?
Bazel should not recommend adding shallow_since since it is dramatically slower in some cases, and seems generally unnecessary to obtain a snapshot of the repository.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Create a `new_git_repository` rule for a large git repository at a commit that is not close to HEAD. Providing shallow_since will slow down the clone substantially.
### What operating system are you running Bazel on?
Linux, Ubuntu 20.04
### What's the output of `bazel info release`?
```
INFO: Invocation ID: 6c8f5dce-cf89-4b6f-a335-93ff77612968
release 3.7.1
```
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
n/a
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
n/a (private repo)
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
n/a | [
"tools/build_defs/repo/git.bzl",
"tools/build_defs/repo/git_worker.bzl"
] | [
"tools/build_defs/repo/git.bzl",
"tools/build_defs/repo/git_worker.bzl"
] | [] | diff --git a/tools/build_defs/repo/git.bzl b/tools/build_defs/repo/git.bzl
index 88678daae163b2..6f21bcd7dcaf9c 100644
--- a/tools/build_defs/repo/git.bzl
+++ b/tools/build_defs/repo/git.bzl
@@ -42,7 +42,10 @@ def _clone_or_update_repo(ctx):
for item in ctx.path(dest_link).readdir():
ctx.symlink(item, root.get_child(item.basename))
- return {"commit": git_.commit, "shallow_since": git_.shallow_since}
+ if ctx.attr.shallow_since:
+ return {"commit": git_.commit, "shallow_since": git_.shallow_since}
+ else:
+ return {"commit": git_.commit}
def _update_git_attrs(orig, keys, override):
result = update_attrs(orig, keys, override)
@@ -68,12 +71,14 @@ _common_attrs = {
"shallow_since": attr.string(
default = "",
doc =
- "an optional date, not after the specified commit; the " +
- "argument is not allowed if a tag is specified (which allows " +
- "cloning with depth 1). Setting such a date close to the " +
- "specified commit allows for a more shallow clone of the " +
- "repository, saving bandwidth " +
- "and wall-clock time.",
+ "an optional date, not after the specified commit; the argument " +
+ "is not allowed if a tag or branch is specified (which can " +
+ "always be cloned with --depth=1). Setting such a date close to " +
+ "the specified commit may allow for a shallow clone of the " +
+ "repository even if the server does not support shallow fetches " +
+ "of arbitary commits. Due to bugs in git's --shallow-since " +
+ "implementation, using this attribute is not recommended as it " +
+ "may result in fetch failures.",
),
"tag": attr.string(
default = "",
@@ -183,6 +188,10 @@ makes its targets available for binding. Also determine the id of the
commit actually checked out and its date, and return a dict with parameters
that provide a reproducible version of this rule (which a tag not necessarily
is).
+
+Bazel will first try to perform a shallow fetch of only the specified commit.
+If that fails (usually due to missing server support), it will fall back to a
+full fetch of the repository.
""",
)
diff --git a/tools/build_defs/repo/git_worker.bzl b/tools/build_defs/repo/git_worker.bzl
index c663cdaabf8032..3e9ba3a10e40bf 100644
--- a/tools/build_defs/repo/git_worker.bzl
+++ b/tools/build_defs/repo/git_worker.bzl
@@ -79,8 +79,8 @@ def git_repo(ctx, directory):
recursive_init_submodules = ctx.attr.recursive_init_submodules,
)
- ctx.report_progress("Cloning %s of %s" % (reset_ref, ctx.attr.remote))
- if (ctx.attr.verbose):
+ _report_progress(ctx, git_repo)
+ if ctx.attr.verbose:
print("git.bzl: Cloning or updating %s repository %s using strip_prefix of [%s]" %
(
" (%s)" % shallow if shallow else "",
@@ -95,6 +95,12 @@ def git_repo(ctx, directory):
return struct(commit = actual_commit, shallow_since = shallow_date)
+def _report_progress(ctx, git_repo, *, shallow_failed = False):
+ warning = ""
+ if shallow_failed:
+ warning = " (shallow fetch failed, fetching full history)"
+ ctx.report_progress("Cloning %s of %s%s" % (git_repo.reset_ref, git_repo.remote, warning))
+
def _update(ctx, git_repo):
ctx.delete(git_repo.directory)
@@ -133,6 +139,7 @@ def fetch(ctx, git_repo):
# "ignore what is specified and fetch all tags".
# The arguments below work correctly for both before 1.9 and after 1.9,
# as we directly specify the list of references to fetch.
+ _report_progress(ctx, git_repo, shallow_failed = True)
_git(
ctx,
git_repo,
| null | test | test | 2023-02-16T18:01:13 | "2021-01-20T01:55:02Z" | djmarcin | test |
bazelbuild/bazel/17165_17491 | bazelbuild/bazel | bazelbuild/bazel/17165 | bazelbuild/bazel/17491 | [
"keyword_pr_to_issue"
] | 1be0ac3e73698e31a349ece629c887b06e102a0b | 102275da3358099f5b8077a25e49c6216013eec3 | [
"Hello @cjohnstoniv, Can you provide an example code to reproduce the above error. Thanks!",
"Unfortunately not easily as the code base we build this on is private and I cannot share it. Also it's built using a localjdk workspace config so none of that would be repeatable on anyone else's machine (unless they have java in the same path).\r\n\r\nThe issue is quite straightforward / obvious though. The `Optional.isEmpty` method was added in Java 9+ so it would (as expected) fail in any Java 8 JVMs. My ask is can we just make this 1 line Java 8 compliant by making it `!optional.isPresent()` instead.\r\n\r\nIf Bazel still intends to support Java 8+ then this would be a requirement to make sure that the coverage tools remain Java 8 compliant. Unless the intention is Java 8+ compilation and not runtime.\r\n\r\nThis all works just fine on Bazel 5.4.0 and if you look at the diffs between 5.4.0 and 6.0.0, you can see this class updated to Java 9+ only complaint code.",
"I personally don't see a reason not to make this one line compatible with Java 8. But even if you are *targeting* Java 8, I would expect the coverage tool to be built in the `exec` configuration and (by default) use a remote JDK 11. Using a more modern JDK just for tools could help you in the meantime. ",
"We want to run our runtime on Java 8 too as unfortunately our org still has a lot of software still running on Oracle Java 8 JDKs (gross, I know). So from a Bazel build/test perspective we are trying to keep it all as consistent as possible. Testing with Java 11 runtime but with Java 8 target, isn't the same as compiling and testing on the same JDK version. There are plenty of things like needing to add-opens/exports to make Java 8 compiled code run in Java 11 runtimes.\r\n\r\nIf the answer is the devs don't feel making this Java 8 compatible is the right thing to do, then we should update the docs to make it clear that Java 8 is supported purely from compilation and not from runtime.",
"I don't mean \"compile with Java 11, run with Java 8\". What I am referring to is using something like `--java_runtime_version=local_jdk_8 --tool_java_runtime_version=remotejdk_11` to:\r\n* build and test all regular targets with JDK 8\r\n* build and execute tools run as part of the build itself (for example the coverage tools) with JDK 11\r\n\r\n@cjohnstoniv Could you share at least the parts of your `.bazelrc` and `WORKSPACE` that configure Java toolchains?\r\n\r\n",
".bazelrc\r\n\r\n```\r\nbuild --embed_label=9.0.LTS-SNAPSHOT\r\nbuild --java_language_version=8\r\nbuild --tool_java_language_version=11\r\nbuild --tool_java_runtime_version=remotejdk_11\r\nbuild --java_runtime_version=localjdk_8\r\nbuild --verbose_failures\r\nbuild --experimental_ui_max_stdouterr_bytes=100048576\r\nstartup --max_idle_secs=300\r\ntest --test_output=errors\r\ntest --test_verbose_timeout_warnings\r\ncoverage --collect_code_coverage\r\ncoverage --combined_report=lcov\r\ncoverage --coverage_report_generator=@bazel_aladdin//sonarqube:SonarQubeCoverageGenerator\r\nbuild --remote_cache=grpc://[SOME IP]:8980\r\nbuild --remote_max_connections=200\r\ncoverage --experimental_split_coverage_postprocessing\r\ncoverage --experimental_fetch_all_coverage_outputs\r\nbuild --disk_cache=/Users/chjohnst/mazel/.cache\r\n```\r\n\r\nWORKSPACE toolchains:\r\n\r\n```\r\nload(\"@bazel_tools//tools/jdk:local_java_repository.bzl\", \"local_java_repository\")\r\n\r\nlocal_java_repository(\r\n name = \"localjdk\",\r\n version = '8',\r\n java_home = \"/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home\"\r\n)\r\n```\r\n\r\n@fmeum based on your comments above, I was under the impression that using `--tool_java_language_version=11 --tool_java_runtime_version=remotejdk_11` would have solved the issue (before we had --tool_java_language_version=8 --tool_java_runtime_version=remotejdk_11). But I still see the same error in the test logs:\r\n\r\nException in thread \"Thread-0\" java.lang.NoSuchMethodError: java.util.Optional.isEmpty()Z\r\n at com.google.testing.coverage.JacocoLCOVFormatter$1.getExecPathForEntryName(JacocoLCOVFormatter.java:73)\r\n at com.google.testing.coverage.JacocoLCOVFormatter$1.visitBundle(JacocoLCOVFormatter.java:117)\r\n at com.google.testing.coverage.JacocoCoverageRunner.createReport(JacocoCoverageRunner.java:156)\r\n at com.google.testing.coverage.JacocoCoverageRunner.create(JacocoCoverageRunner.java:132)\r\n at com.google.testing.coverage.JacocoCoverageRunner$2.run(JacocoCoverageRunner.java:568)\r\nGCov does not exist at the given path: ''\r\n",
"If that also doesn't work I am personally out of ideas why you are seeing this issue. team-Rules-Java can probably help here.",
"I'll see if I can find some time later this week from my personal PC to upload a small Java project that recreates the issue so others can test.\r\n\r\nOddly when I think about it, I would've expected the tools compilation stage to fail when I had set `--tool_java_language_version=8` as it would have tried compiling Java 11 code on Java 8; but instead it fails with a runtime NoSuchMethodError which suggests the tool is compiling on Java 11+ but for whatever reason is not running on Java 11+.",
"[broken-java8-coverage.zip](https://github.com/bazelbuild/bazel/files/10460205/broken-java8-coverage.zip)\r\n\r\nAttached is a sample project that recreates the issue following the following steps (assumes you downloaded the zip to an empty dir, also assumes linux OS, modify the less location for other OS's, you may also have to modify your Java 8 localjdk location in WORKSPACE file):\r\n\r\n`unzip broken-java8-coverage.zip; bazelisk coverage //...; less bazel-out/k8-fastbuild/testlogs/unit-tests/test.log`\r\n\r\nYou will see that despite the tool java level and runtime being 11, the test runner still fails to calculate coverage due to the Java 9+ added Optional method.",
"Also not sure if anyone has any experience with the Bazel distribution build but I tried checking out the 6.0 tag and compiling my own version of Bazel with changes to the JacocoLCOVFormatter class; however I found that seemingly when I run `compile.sh` and/or `bazel build //src:bazel` my changes to the class aren't picked up. I've confirmed this at least by making non-compilable changes to the class (i.e bad characters) and the bazel build runs just fine.\r\n\r\nIs there someway I can rebuild/retest the JacocoLCOVFormatter class? I was trying to test what would happen if we made the `isEmpty()` call `!isPresent()` instead.",
"@cushon This may he another instance of https://github.com/bazelbuild/bazel/issues/17281: The tool Java language level/runtime version not behaving as one may expect. Could you also provide some insight for this particular situation?",
"@comius \r\n\r\nI can reproduce (thanks for https://github.com/bazelbuild/bazel/issues/17165#issuecomment-1397472443)!\r\n\r\n```\r\nException in thread \"Thread-0\" java.lang.NoSuchMethodError: java.util.Optional.isEmpty()Z\r\n at com.google.testing.coverage.JacocoLCOVFormatter$1.getExecPathForEntryName(JacocoLCOVFormatter.java:73)\r\n...\r\n at com.google.testing.coverage.JacocoCoverageRunner$2.run(JacocoCoverageRunner.java:568)\r\n```\r\n\r\nIt looks like `JacocoCoverageRunner` is being built in the exec configuration, and then apparently being run in the target configuration as part of test execution:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/834ba08f9e780810743ff8eb39b125c0bf9e36b6/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java#L279-L287\r\n\r\nI'm not sure what the intent there was, but either it shouldn't be running on the target JDK, or it should be built in the target configuration.",
"In Bazel `JacocoCoverageRunner` appears to be taken from `remote_coverage_tools` in precompiled form, but the packaging process probably uses JDK 11 with `-target 8`, which doesn't catch this.",
"Is there any thoughts to a solution for this? Can we not just make the coverage tool's code Java 8 compliant so we know it will run in Java 8 JVM? This is assuming the isEmpty() usage is the only place we use Java 11+ code, but I also imagine there aren't any real needs for Java 11+ code other than \"nice-to-haves\".",
"https://github.com/bazelbuild/bazel/pull/17338 is in review and fixes this. @cushon Can you say whether Ivo's input is truly needed? He appears to be quite busy.\n\nIt's unfortunately hard to cover with tests as that would require maintaining a JDK 8 on all CI machine. But if this breaks in the future, it can probably be fixed again as long as Java 8 is supported.",
"I still get this issue on 6.1.0, the project above still recreates this issue.",
"Rules requires a Java tools update and it's possible that didn't make it into the release.\n\n@hvadehra Is there already a release with the change?",
"https://github.com/bazelbuild/java_tools/releases/tag/java_v11.12 was released a few days ago which should contain https://github.com/bazelbuild/bazel/commit/c26665102d0d524bb42be8cd205c7b31a22a75c9",
"So can we reopen this issue then? It seems that even if the patch did go out, it's not actually fixing the issue defined here/demonstrated by the example.",
"The fix went into the Java tools, but the commit bumping the pinned version of these tools didn't go into 6.1.0. It does look like it will be cherry-picked into 6.2.0.",
"@cjohnstoniv You should be able to manually update remote_java_tools to v11.12 in your WORKSPACE too."
] | [] | "2023-02-14T22:15:55Z" | [
"type: bug",
"team-Rules-Java",
"untriaged"
] | Bazel 6.0.0 Java 8 Coverage Broken | ### Description of the bug:
When building with Bazel 6.0.0 and building a Java 8 (compile + runtime, with a local JDK setup) workspace fails to calculate any coverage.
There error I see in the test logs is:
Exception in thread "Thread-0" java.lang.NoSuchMethodError: java.util.Optional.isEmpty()Z
at com.google.testing.coverage.JacocoLCOVFormatter$1.getExecPathForEntryName(JacocoLCOVFormatter.java:73)
at com.google.testing.coverage.JacocoLCOVFormatter$1.visitBundle(JacocoLCOVFormatter.java:117)
at com.google.testing.coverage.JacocoCoverageRunner.createReport(JacocoCoverageRunner.java:156)
at com.google.testing.coverage.JacocoCoverageRunner.create(JacocoCoverageRunner.java:132)
at com.google.testing.coverage.JacocoCoverageRunner$2.run(JacocoCoverageRunner.java:568)
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Execute `bazel coverage` on any Java 8 (with a local OpenJDK 8 setup) workspace and look at the coverage files, they are empty.
### Which operating system are you running Bazel on?
Mac & Linux
### What is the output of `bazel info release`?
release 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
Is JacocoLCOVFormatter only Java 11 supported now? Is there any way that maybe we can just change it to use `!optional.isPresent()` to make it Java 8 compatible? | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java"
] | [
"src/java_tools/junitrunner/java/com/google/testing/coverage/JacocoLCOVFormatter.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java
index ad4de48f61a6bb..594b6a76276941 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java
@@ -282,8 +282,6 @@ The Java target version (e.g., '6' or '7'). It specifies for which Java runtime
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("jacocorunner", LABEL)
- // This needs to be in the execution configuration.
- .cfg(ExecutionTransitionFactory.create())
.allowedFileTypes(FileTypeSet.ANY_FILE)
.exec())
/* <!-- #BLAZE_RULE(java_toolchain).ATTRIBUTE(proguard_allowlister) -->
| diff --git a/src/java_tools/junitrunner/java/com/google/testing/coverage/JacocoLCOVFormatter.java b/src/java_tools/junitrunner/java/com/google/testing/coverage/JacocoLCOVFormatter.java
index b2c2bc58c31de6..53e62cdf3fe7f7 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/coverage/JacocoLCOVFormatter.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/coverage/JacocoLCOVFormatter.java
@@ -70,7 +70,7 @@ public IReportVisitor createVisitor(
private Map<String, ISourceFileCoverage> sourceToFileCoverage = new TreeMap<>();
private String getExecPathForEntryName(String classPath) {
- if (execPathsOfUninstrumentedFiles.isEmpty()) {
+ if (!execPathsOfUninstrumentedFiles.isPresent()) {
return classPath;
}
| test | test | 2023-02-15T16:36:01 | "2023-01-08T18:13:28Z" | cjohnstoniv | test |
bazelbuild/bazel/17458_17504 | bazelbuild/bazel | bazelbuild/bazel/17458 | bazelbuild/bazel/17504 | [
"keyword_pr_to_issue"
] | bf8d30a3782a0fe55036a8692066a8f43622dd03 | 0c62801773ca2906bf446c8be6ef688eed16d5f4 | [
"Thanks for the detailed report, I prepared a fix at https://github.com/bazelbuild/bazel/issues/17458 that can be cherry-picked into Bazel 6.1.",
"I'm seeing this issue with bazel 6.1.2. (It worked in 5.3.2.) Looking at https://github.com/bazelbuild/bazel/commit/420659a9ad2a98f57e057d8c22eb621e3b12803e, it looks like it made it into various `7.0.0-pre.*` builds, but not into any `6.*` build. Is it possible to cherry-pick it?"
] | [] | "2023-02-15T19:41:55Z" | [
"type: bug",
"team-Rules-Java",
"untriaged"
] | @bazel_tools//tools/java/runfiles:auto_bazel_repository_processor does not compile with JDK 8 | ### Description of the bug:
Our internal build uses JDK 11 to build code against JDK 8, using the JDK 8 bootclasspath. When upgrading to Bazel 6, the Java runfiles library fails to compile:
```
external/bazel_tools/tools/java/runfiles/AutoBazelRepositoryProcessor.java:84: error: method iterate in interface Stream<T#2> cannot be applied to given types;
Stream.iterate(
^
required: T#1,UnaryOperator<T#1>
found: TypeElement,(element)-[...]ement,Element::g[...]ement
reason: cannot infer type-variable(s) T#1
(actual and formal argument lists differ in length)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>iterate(T#1,UnaryOperator<T#1>)
T#2 extends Object declared in interface Stream
Target @bazel_tools//tools/java/runfiles:auto_bazel_repository_processor failed to build
```
This appears to be occurring because the three-argument `Stream.iterate` method used here:
https://github.com/bazelbuild/bazel/blob/338bbc02132da7de8681196b6a0afbb6297038aa/tools/java/runfiles/AutoBazelRepositoryProcessor.java#L84-L90
does not exist in JDK 8, there is only a [two-argument one](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#iterate-T-java.util.function.UnaryOperator-). It was added in JDK 9 (JDK 11 docs [here](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html#iterate(T,java.util.function.Predicate,java.util.function.UnaryOperator)).
A simple enough fix would be to replace this `Stream` call with a `for` loop, which seems to work for me locally. I can prepare a PR should this be desirable. My understanding is that while Bazel itself needs JDK 11, Bazel should still be able to compile code for JDK 8, including libraries intended to be loaded by end-users like this one.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Since this only uses the standard library, you can just use `javac` from JDK 8 without invoking Bazel:
```javac tools/java/runfiles/AutoBazelRepositoryProcessor.java```
Reproduced using OpenJDK 11 using the OpenJDK 8 bootclasspath, and OpenJDK 8 itself.
### Which operating system are you running Bazel on?
Linux (Alma 8 aarch64, CentOS 7 amd64)
### What is the output of `bazel info release`?
6.0.0-vmware
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
https://github.com/bazelbuild/bazel/issues/17281 is in the same area, but does not correspond to this precise issue.
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"tools/java/runfiles/AutoBazelRepositoryProcessor.java"
] | [
"tools/java/runfiles/AutoBazelRepositoryProcessor.java"
] | [] | diff --git a/tools/java/runfiles/AutoBazelRepositoryProcessor.java b/tools/java/runfiles/AutoBazelRepositoryProcessor.java
index ae356d800f6d03..f323cf211ccfc5 100644
--- a/tools/java/runfiles/AutoBazelRepositoryProcessor.java
+++ b/tools/java/runfiles/AutoBazelRepositoryProcessor.java
@@ -14,22 +14,18 @@
package com.google.devtools.build.runfiles;
-import static java.util.stream.Collectors.joining;
-import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.io.PrintWriter;
-import java.util.Collections;
-import java.util.List;
+import java.util.ArrayDeque;
+import java.util.Deque;
import java.util.Set;
-import java.util.stream.Stream;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
-import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
@@ -51,7 +47,7 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
.flatMap(element -> roundEnv.getElementsAnnotatedWith(element).stream())
.map(element -> (TypeElement) element)
.forEach(this::emitClass);
- return true;
+ return false;
}
private void emitClass(TypeElement annotatedClass) {
@@ -80,18 +76,14 @@ private void emitClass(TypeElement annotatedClass) {
// AutoBazelRepository_Outer_Middle_Inner.
// Note: There can be collisions when local classes are involved, but since the definition of a
// class depends only on the containing Bazel target, this does not result in ambiguity.
- List<String> nestedClassNames =
- Stream.iterate(
- annotatedClass,
- element -> element instanceof TypeElement,
- Element::getEnclosingElement)
- .map(Element::getSimpleName)
- .map(Name::toString)
- .collect(toList());
- Collections.reverse(nestedClassNames);
- String generatedClassSimpleName =
- Stream.concat(Stream.of("AutoBazelRepository"), nestedClassNames.stream())
- .collect(joining("_"));
+ Deque<String> classNameSegments = new ArrayDeque<>();
+ Element element = annotatedClass;
+ while (element instanceof TypeElement) {
+ classNameSegments.addFirst(element.getSimpleName().toString());
+ element = element.getEnclosingElement();
+ }
+ classNameSegments.addFirst("AutoBazelRepository");
+ String generatedClassSimpleName = String.join("_", classNameSegments);
String generatedClassPackage =
processingEnv.getElementUtils().getPackageOf(annotatedClass).getQualifiedName().toString();
| null | train | test | 2023-02-16T17:17:40 | "2023-02-09T20:26:52Z" | nacl | test |
bazelbuild/bazel/16956_17506 | bazelbuild/bazel | bazelbuild/bazel/16956 | bazelbuild/bazel/17506 | [
"keyword_pr_to_issue"
] | a60e201398a29a6d61bd1fa28c2a50aad766c012 | ec365958735b5f71e6fdcbcf75fe431c57c14b7d | [
"I think that this could be fixed by appropriately merging the logic in https://cs.opensource.google/bazel/bazel/+/47c93b7e38cf9498617777fcb28928179e7f9013:src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java;l=113-194 with that in https://cs.opensource.google/bazel/bazel/+/47c93b7e38cf9498617777fcb28928179e7f9013:src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java;l=264-273.",
"Fixed by commit 773d232f528276338098578a28c19c742e3b4e7e"
] | [] | "2023-02-15T21:36:02Z" | [
"type: bug",
"P3",
"team-Rules-CPP",
"help wanted"
] | Wrong cc toolchain solib path in rpath for external repos with sibling layout | ### Description of the bug:
We are setting up bazel for Android Emulator. The cc toolchain we've setup:
1. Uses a hermetic clang compiler.
2. Enables the `static_link_cpp_runtimes` feature and feeds libc++ to the `(dynamic | static)_runtime_lib` attributes of the [`cc_toolchain`](https://bazel.build/reference/be/c-cpp#cc_toolchain) rule.
And due to the layout of the source tree (a top-level "external" directory), we have to pass `--experimental_sibling_repository_layout` to solve the conflict with external repositories.
With this setup, we find that we are unable to correctly build dynamically linked binaries in external repositories. The rpath for `dynamic_runtime_lib` (libc++) is set incorrectly. Since `cc_test` is always linked dynamically, this is prohibiting us to run any cc_test in external repos.
---
e.g., with the following setup:
* The custom toolchain is located at `@//toolchains/cc:linux_clang_x64`
* The binary target is `@zlib//:zlib_test`
* CPU is `k8`
The following rpaths are set by bazel:
```
❯ objdump -p zlib_test
...
Dynamic Section:
RUNPATH $ORIGIN/_solib_k8/
:$ORIGIN/zlib_test.runfiles/zlib/_solib_k8/
:$ORIGIN/_solib__toolchains_Scc_Clinux_Uclang_Ux64/
:$ORIGIN/zlib_test.runfiles/zlib/_solib__toolchains_Scc_Clinux_Uclang_Ux64/
NEEDED liblibzlib.so
NEEDED libc++.so.1
...
```
However, what bazel generates in the execroot file tree is:
```
❯ tree ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin
bin
├── libzlib.a
├── libzlib.so
├── libzlib.so-2.params
├── _solib_k8
│ └── liblibzlib.so -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin/libzlib.so
├── zlib_test
├── zlib_test-2.params
├── zlib_test.runfiles
│ ├── __main__
│ │ ├── external
│ │ │ └── zlib
│ │ │ ├── _solib_k8
│ │ │ │ └── liblibzlib.so -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin/_solib_k8/liblibzlib.so
│ │ │ └── zlib_test -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin/zlib_test
│ │ └── _solib__toolchains_Scc_Clinux_Uclang_Ux64
│ │ ├── libc++.so -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/k8-fastbuild/bin/_solib__toolchains_Scc_Clinux_Uclang_Ux64/libc++.so
│ │ └── libc++.so.1 -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/k8-fastbuild/bin/_solib__toolchains_Scc_Clinux_Uclang_Ux64/libc++.so.1
│ └── zlib
│ ├── _solib_k8
│ │ └── liblibzlib.so -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin/_solib_k8/liblibzlib.so
│ └── zlib_test -> ~/.cache/bazel/_bazel_<username>/<md5>/execroot/__main__/bazel-out/zlib/k8-fastbuild/bin/zlib_test
...
```
Form the execroot tree, it seems that the correct rpath to find libc++ should be either:
1) `$ORIGIN/../../../k8-fastbuild/bin/_solib__toolchains_Scc_Clinux_Uclang_Ux64`, or
2) `$ORIGIN/zlib_test.runfiles/__main__/_solib__toolchains_Scc_Clinux_Uclang_Ux64`
However bazel generates:
1) `$ORIGIN/_solib__toolchains_Scc_Clinux_Uclang_Ux64`
2) `$ORIGIN/zlib_test.runfiles/zlib/_solib__toolchains_Scc_Clinux_Uclang_Ux64`
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Create a toolchain config and a toolchain that feeds libs into the `dynamic_runtime_lib` attribute, and enable feature `static_link_cpp_runtimes`.
2. Define an external repo and create a cc binary target in it.
3. Turn on `--experimental_sibling_repository_layout` flag and build the target
4. Inspect the created binary or the linking command to check rpath.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
release 7.0.0-pre.20221111.3
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
No.
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/cpp/BUILD",
"src/test/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollectorTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
index a0052121121e84..abf3c1babf78be 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollector.java
@@ -15,6 +15,7 @@
import static com.google.common.collect.ImmutableList.toImmutableList;
+import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -22,6 +23,7 @@
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleErrorConsumer;
import com.google.devtools.build.lib.cmdline.LabelConstants;
+import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration;
@@ -30,7 +32,9 @@
import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType;
import com.google.devtools.build.lib.rules.cpp.Link.LinkingMode;
import com.google.devtools.build.lib.util.Pair;
+import com.google.devtools.build.lib.vfs.OsPathPolicy;
import com.google.devtools.build.lib.vfs.PathFragment;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
@@ -38,6 +42,9 @@
/** Class that goes over linker inputs and produces {@link LibraryToLinkValue}s */
public class LibrariesToLinkCollector {
+ private static final OsPathPolicy OS = OsPathPolicy.getFilePathOs();
+ private static final Joiner PATH_JOINER = Joiner.on(PathFragment.SEPARATOR_CHAR);
+
private final boolean isNativeDeps;
private final PathFragment toolchainLibrariesSolibDir;
private final CppConfiguration cppConfiguration;
@@ -50,11 +57,10 @@ public class LibrariesToLinkCollector {
private final Artifact thinltoParamFile;
private final FeatureConfiguration featureConfiguration;
private final boolean needWholeArchive;
- private final ImmutableList<String> potentialExecRoots;
- private final ImmutableList<String> rpathRoots;
private final boolean needToolchainLibrariesRpath;
- private final Map<Artifact, Artifact> ltoMap;
private final RuleErrorConsumer ruleErrorConsumer;
+ private final Artifact output;
+ private final String workspaceName;
public LibrariesToLinkCollector(
boolean isNativeDeps,
@@ -87,114 +93,13 @@ public LibrariesToLinkCollector(
this.linkerInputs = linkerInputs;
this.needWholeArchive = needWholeArchive;
this.ruleErrorConsumer = ruleErrorConsumer;
+ this.output = output;
+ this.workspaceName = workspaceName;
needToolchainLibrariesRpath =
toolchainLibrariesSolibDir != null
&& (linkType.isDynamicLibrary()
|| (linkType == LinkTargetType.EXECUTABLE && linkingMode == LinkingMode.DYNAMIC));
-
- // Calculate the correct relative value for the "-rpath" link option (which sets
- // the search path for finding shared libraries).
- if (isNativeDeps && cppConfiguration.shareNativeDeps()) {
- // For shared native libraries, special symlinking is applied to ensure C++
- // toolchain libraries are available under $ORIGIN/_solib_[arch]. So we set the RPATH to find
- // them.
- //
- // Note that we have to do this because $ORIGIN points to different paths for
- // different targets. In other words, blaze-bin/d1/d2/d3/a_shareddeps.so and
- // blaze-bin/d4/b_shareddeps.so have different path depths. The first could
- // reference a standard blaze-bin/_solib_[arch] via $ORIGIN/../../../_solib[arch],
- // and the second could use $ORIGIN/../_solib_[arch]. But since this is a shared
- // artifact, both are symlinks to the same place, so
- // there's no *one* RPATH setting that fits all targets involved in the sharing.
- potentialExecRoots = ImmutableList.of();
- rpathRoots = ImmutableList.of(ccToolchainProvider.getSolibDirectory() + "/");
- } else {
- // The runtime location of the solib directory relative to the binary depends on four factors:
- //
- // * whether the binary is contained in the main repository or an external repository;
- // * whether the binary is executed directly or from a runfiles tree;
- // * whether the binary is staged as a symlink (sandboxed execution; local execution if the
- // binary is in the runfiles of another target) or a regular file (remote execution) - the
- // dynamic linker follows sandbox and runfiles symlinks into its location under the
- // unsandboxed execroot, which thus becomes the effective $ORIGIN;
- // * whether --experimental_sibling_repository_layout is enabled or not.
- //
- // The rpaths emitted into the binary thus have to cover the following cases (assuming that
- // the binary target is located in the pkg `pkg` and has name `file`) for the directory used
- // as $ORIGIN by the dynamic linker and the directory containing the solib directories:
- //
- // 1. main, direct, symlink:
- // $ORIGIN: $EXECROOT/pkg
- // solib root: $EXECROOT
- // 2. main, direct, regular file:
- // $ORIGIN: $EXECROOT/pkg
- // solib root: $EXECROOT/pkg/file.runfiles/main_repo
- // 3. main, runfiles, symlink:
- // $ORIGIN: $EXECROOT/pkg
- // solib root: $EXECROOT
- // 4. main, runfiles, regular file:
- // $ORIGIN: other_target.runfiles/main_repo/pkg
- // solib root: other_target.runfiles/main_repo
- // 5a. external, direct, symlink:
- // $ORIGIN: $EXECROOT/external/other_repo/pkg
- // solib root: $EXECROOT
- // 5b. external, direct, symlink, with --experimental_sibling_repository_layout:
- // $ORIGIN: $EXECROOT/../other_repo/pkg
- // solib root: $EXECROOT/../other_repo
- // 6a. external, direct, regular file:
- // $ORIGIN: $EXECROOT/external/other_repo/pkg
- // solib root: $EXECROOT/external/other_repo/pkg/file.runfiles/main_repo
- // 6b. external, direct, regular file, with --experimental_sibling_repository_layout:
- // $ORIGIN: $EXECROOT/../other_repo/pkg
- // solib root: $EXECROOT/../other_repo/pkg/file.runfiles/other_repo
- // 7a. external, runfiles, symlink:
- // $ORIGIN: $EXECROOT/external/other_repo/pkg
- // solib root: $EXECROOT
- // 7b. external, runfiles, symlink, with --experimental_sibling_repository_layout:
- // $ORIGIN: $EXECROOT/../other_repo/pkg
- // solib root: $EXECROOT/../other_repo
- // 8a. external, runfiles, regular file:
- // $ORIGIN: other_target.runfiles/some_repo/pkg
- // solib root: other_target.runfiles/main_repo
- // 8b. external, runfiles, regular file, with --experimental_sibling_repository_layout:
- // $ORIGIN: other_target.runfiles/some_repo/pkg
- // solib root: other_target.runfiles/some_repo
- //
- // Cases 1, 3, 4, 5, 7, and 8b are covered by an rpath that walks up the root relative path.
- // Cases 2 and 6 covered by walking into file.runfiles/main_repo.
- // Case 8a is covered by walking up some_repo/pkg and then into main_repo.
- boolean isExternal =
- output.getRunfilesPath().startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
- boolean usesLegacyRepositoryLayout = output.getRoot().isLegacy();
- ImmutableList.Builder<String> execRoots = ImmutableList.builder();
- // Handles cases 1, 3, 4, 5, and 7.
- execRoots.add("../".repeat(output.getRootRelativePath().segmentCount() - 1));
- // Handle cases 2 and 6.
- String solibRepositoryName;
- if (isExternal && !usesLegacyRepositoryLayout) {
- // Case 6b
- solibRepositoryName = output.getRunfilesPath().getSegment(1);
- } else {
- // Cases 2 and 6a
- solibRepositoryName = workspaceName;
- }
- execRoots.add(output.getFilename() + ".runfiles/" + solibRepositoryName + "/");
- if (isExternal && usesLegacyRepositoryLayout) {
- // Handles case 8a. The runfiles path is of the form ../some_repo/pkg/file and we need to
- // walk up some_repo/pkg and then down into main_repo.
- execRoots.add(
- "../".repeat(output.getRunfilesPath().segmentCount() - 2) + workspaceName + "/");
- }
-
- potentialExecRoots = execRoots.build();
- rpathRoots =
- potentialExecRoots.stream()
- .map((execRoot) -> execRoot + ccToolchainProvider.getSolibDirectory() + "/")
- .collect(toImmutableList());
- }
-
- ltoMap = generateLtoMap();
}
/**
@@ -236,6 +141,252 @@ public NestedSet<String> getRuntimeLibrarySearchDirectories() {
}
}
+ private NestedSet<String> collectToolchainRuntimeLibrarySearchDirectories(
+ ImmutableList<String> potentialSolibParents) {
+ NestedSetBuilder<String> runtimeLibrarySearchDirectories = NestedSetBuilder.linkOrder();
+ if (!needToolchainLibrariesRpath) {
+ return runtimeLibrarySearchDirectories.build();
+ }
+
+ String toolchainLibrariesSolibName = toolchainLibrariesSolibDir.getBaseName();
+ if (!(isNativeDeps && cppConfiguration.shareNativeDeps())) {
+ for (String potentialExecRoot : findToolchainSolibParents(potentialSolibParents)) {
+ runtimeLibrarySearchDirectories.add(potentialExecRoot + toolchainLibrariesSolibName + "/");
+ }
+ }
+ if (isNativeDeps) {
+ runtimeLibrarySearchDirectories.add("../" + toolchainLibrariesSolibName + "/");
+ runtimeLibrarySearchDirectories.add(".");
+ }
+ runtimeLibrarySearchDirectories.add(toolchainLibrariesSolibName + "/");
+
+ return runtimeLibrarySearchDirectories.build();
+ }
+
+ private ImmutableList<String> findPotentialSolibParents() {
+ // The runtime location of the solib directory relative to the binary depends on four factors:
+ //
+ // * whether the binary is contained in the main repository or an external repository;
+ // * whether the binary is executed directly or from a runfiles tree;
+ // * whether the binary is staged as a symlink (sandboxed execution; local execution if the
+ // binary is in the runfiles of another target) or a regular file (remote execution) - the
+ // dynamic linker follows sandbox and runfiles symlinks into its location under the
+ // unsandboxed execroot, which thus becomes the effective $ORIGIN;
+ // * whether --experimental_sibling_repository_layout is enabled or not.
+ //
+ // The rpaths emitted into the binary thus have to cover the following cases (assuming that
+ // the binary target is located in the pkg `pkg` and has name `file`) for the directory used
+ // as $ORIGIN by the dynamic linker and the directory containing the solib directories:
+ //
+ // 1. main, direct, symlink:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: $EXECROOT
+ // 2. main, direct, regular file:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: $EXECROOT/pkg/file.runfiles/main_repo
+ // 3. main, runfiles, symlink:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: $EXECROOT
+ // 4. main, runfiles, regular file:
+ // $ORIGIN: other_target.runfiles/main_repo/pkg
+ // solib root: other_target.runfiles/main_repo
+ // 5a. external, direct, symlink:
+ // $ORIGIN: $EXECROOT/external/other_repo/pkg
+ // solib root: $EXECROOT
+ // 5b. external, direct, symlink, with --experimental_sibling_repository_layout:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: $EXECROOT/../other_repo
+ // 6a. external, direct, regular file:
+ // $ORIGIN: $EXECROOT/external/other_repo/pkg
+ // solib root: $EXECROOT/external/other_repo/pkg/file.runfiles/main_repo
+ // 6b. external, direct, regular file, with --experimental_sibling_repository_layout:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: $EXECROOT/../other_repo/pkg/file.runfiles/other_repo
+ // 7a. external, runfiles, symlink:
+ // $ORIGIN: $EXECROOT/external/other_repo/pkg
+ // solib root: $EXECROOT
+ // 7b. external, runfiles, symlink, with --experimental_sibling_repository_layout:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: $EXECROOT/../other_repo
+ // 8a. external, runfiles, regular file:
+ // $ORIGIN: other_target.runfiles/some_repo/pkg
+ // solib root: other_target.runfiles/main_repo
+ // 8b. external, runfiles, regular file, with --experimental_sibling_repository_layout:
+ // $ORIGIN: other_target.runfiles/some_repo/pkg
+ // solib root: other_target.runfiles/some_repo
+ //
+ // Cases 1, 3, 4, 5, 7, and 8b are covered by an rpath that walks up the root relative path.
+ // Cases 2 and 6 covered by walking into file.runfiles/main_repo.
+ // Case 8a is covered by walking up some_repo/pkg and then into main_repo.
+ boolean isExternal =
+ output.getRunfilesPath().startsWith(LabelConstants.EXTERNAL_RUNFILES_PATH_PREFIX);
+ boolean usesLegacyRepositoryLayout = output.getRoot().isLegacy();
+ ImmutableList.Builder<String> solibParents = ImmutableList.builder();
+ // Handles cases 1, 3, 4, 5, and 7.
+ solibParents.add("../".repeat(output.getRootRelativePath().segmentCount() - 1));
+ // Handle cases 2 and 6.
+ String solibRepositoryName;
+ if (isExternal && !usesLegacyRepositoryLayout) {
+ // Case 6b
+ solibRepositoryName = output.getRunfilesPath().getSegment(1);
+ } else {
+ // Cases 2 and 6a
+ solibRepositoryName = workspaceName;
+ }
+ solibParents.add(output.getFilename() + ".runfiles/" + solibRepositoryName + "/");
+ if (isExternal && usesLegacyRepositoryLayout) {
+ // Handles case 8a. The runfiles path is of the form ../some_repo/pkg/file and we need to
+ // walk up some_repo/pkg and then down into main_repo.
+ solibParents.add(
+ "../".repeat(output.getRunfilesPath().segmentCount() - 2) + workspaceName + "/");
+ }
+
+ return solibParents.build();
+ }
+
+ private ImmutableList<String> findToolchainSolibParents(
+ ImmutableList<String> potentialSolibParents) {
+ boolean usesLegacyRepositoryLayout = output.getRoot().isLegacy();
+ // When -experimental_sibling_repository_layout is not enabled, the toolchain solib sits next to
+ // the solib_<cpu> directory - so that it shares the same parents.
+ if (usesLegacyRepositoryLayout) {
+ return potentialSolibParents;
+ }
+
+ // When -experimental_sibling_repository_layout is enabled, the toolchain solib is located in
+ // these 2 places:
+ // 1. The `bin` directory of the repository where the toolchain target is declared (this is the
+ // parent directory of `toolchainLibrariesSolibDir`).
+ // 2. In `target.runfiles/<toolchain repo>`
+ //
+ // And the following factors affect what $ORIGIN is resolved to:
+ // * whether the binary is contained in the main repository or an external repository;
+ // * whether the binary is executed directly or from a runfiles tree;
+ // * whether the binary is staged as a symlink (sandboxed execution; local execution if the
+ // binary is in the runfiles of another target) or a regular file (remote execution) - the
+ // dynamic linker follows sandbox and runfiles symlinks into its location under the
+ // unsandboxed execroot, which thus becomes the effective $ORIGIN;
+ //
+ // The rpaths emitted into the binary thus have to cover the following cases (assuming that
+ // the binary target is located in the pkg `pkg` and has name `file`) for the directory used
+ // as $ORIGIN by the dynamic linker and the directory containing the solib directories:
+ // 1. main, direct, symlink:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: <toolchain repo bin>
+ // 2. main, direct, regular file:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: $EXECROOT/pkg/file.runfiles/<toolchain repo>
+ // 3. main, runfiles, symlink:
+ // $ORIGIN: $EXECROOT/pkg
+ // solib root: <toolchain repo bin>
+ // 4. main, runfiles, regular file:
+ // $ORIGIN: other_target.runfiles/main_repo/pkg
+ // solib root: other_target.runfiles/<toolchain repo>
+ // 5. external, direct, symlink:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: <toolchain repo bin>
+ // 6. external, direct, regular file:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: $EXECROOT/../other_repo/pkg/file.runfiles/<toolchain repo>
+ // 7. external, runfiles, symlink:
+ // $ORIGIN: $EXECROOT/../other_repo/pkg
+ // solib root: <toolchain repo bin>
+ // 8. external, runfiles, regular file:
+ // $ORIGIN: other_target.runfiles/some_repo/pkg
+ // solib root: other_target.runfiles/<toolchain repo>
+ //
+ // For cases 1, 3, 5, 7, we need to compute the relative path from the output artifact to
+ // toolchain repo's bin directory. For 2 and 6, we walk down into `file.runfiles/<toolchain
+ // repo>`. For 4 and 8, we need to compute the relative path from the output runfile to
+ // <toolchain repo> under runfiles.
+ ImmutableList.Builder<String> solibParents = ImmutableList.builder();
+
+ // Cases 1, 3, 5, 7
+ PathFragment toolchainBinExecPath = toolchainLibrariesSolibDir.getParentDirectory();
+ PathFragment binaryOriginExecPath = output.getExecPath().getParentDirectory();
+ solibParents.add(
+ getRelative(binaryOriginExecPath, toolchainBinExecPath).getPathString()
+ + PathFragment.SEPARATOR_CHAR);
+
+ // Cases 2 and 6
+ String toolchainRunfilesRepoName =
+ getRunfilesRepoName(ccToolchainProvider.getCcToolchainLabel().getRepository());
+ solibParents.add(
+ PATH_JOINER.join(output.getFilename() + ".runfiles", toolchainRunfilesRepoName)
+ + PathFragment.SEPARATOR_CHAR);
+
+ // Cases 4 and 8
+ String binaryRepoName = getRunfilesRepoName(output.getOwnerLabel().getRepository());
+ PathFragment toolchainBinRunfilesPath = PathFragment.create(toolchainRunfilesRepoName);
+ PathFragment binaryOriginRunfilesPath =
+ PathFragment.create(binaryRepoName)
+ .getRelative(output.getRepositoryRelativePath())
+ .getParentDirectory();
+ solibParents.add(
+ getRelative(binaryOriginRunfilesPath, toolchainBinRunfilesPath).getPathString()
+ + PathFragment.SEPARATOR_CHAR);
+
+ return solibParents.build();
+ }
+
+ private String getRunfilesRepoName(RepositoryName repo) {
+ if (repo.isMain()) {
+ return workspaceName;
+ }
+ return repo.getName();
+ }
+
+ /**
+ * Returns the relative {@link PathFragment} from "from" to "to".
+ *
+ * <p>Example 1: <code>
+ * getRelative({@link PathFragment}.create("foo"), {@link PathFragment}.create("foo/bar/wiz"))
+ * </code> returns <code>"bar/wiz"</code>.
+ *
+ * <p>Example 2: <code>
+ * getRelative({@link PathFragment}.create("foo/bar/wiz"),
+ * {@link PathFragment}.create("foo/wiz"))
+ * </code> returns <code>"../../wiz"</code>.
+ *
+ * <p>The following requirements / assumptions are made: 1) paths must be both relative; 2) they
+ * are assumed to be relative to the same location; 3) when the {@code from} path starts with
+ * {@code ..} prefixes, the prefix length must not exceed {@code ..} prefixes of the {@code to}
+ * path.
+ */
+ static PathFragment getRelative(PathFragment from, PathFragment to) {
+ if (from.isAbsolute() || to.isAbsolute()) {
+ throw new IllegalArgumentException("Paths must be both relative.");
+ }
+
+ final ImmutableList<String> fromSegments = from.splitToListOfSegments();
+ final ImmutableList<String> toSegments = to.splitToListOfSegments();
+ final int fromSegCount = fromSegments.size();
+ final int toSegCount = toSegments.size();
+
+ int commonSegCount = 0;
+ while (commonSegCount < fromSegCount
+ && commonSegCount < toSegCount
+ && OS.equals(fromSegments.get(commonSegCount), toSegments.get(commonSegCount))) {
+ commonSegCount++;
+ }
+
+ if (commonSegCount < fromSegCount && fromSegments.get(commonSegCount).equals("..")) {
+ throw new IllegalArgumentException(
+ "Unable to compute relative path from \""
+ + from.getPathString()
+ + "\" to \""
+ + to.getPathString()
+ + "\": too many leading \"..\" segments in from path.");
+ }
+ PathFragment relativePath =
+ PathFragment.create(
+ PATH_JOINER.join(Collections.nCopies(fromSegCount - commonSegCount, "..")));
+ if (commonSegCount < toSegCount) {
+ relativePath = relativePath.getRelative(to.subFragment(commonSegCount, toSegCount));
+ }
+ return relativePath;
+ }
+
/**
* When linking a shared library fully or mostly static then we need to link in *all* dependent
* files, not just what the shared library needs for its own code. This is done by wrapping all
@@ -247,48 +398,43 @@ public NestedSet<String> getRuntimeLibrarySearchDirectories() {
*/
public CollectedLibrariesToLink collectLibrariesToLink() {
NestedSetBuilder<String> librarySearchDirectories = NestedSetBuilder.linkOrder();
- NestedSetBuilder<String> runtimeLibrarySearchDirectories = NestedSetBuilder.linkOrder();
ImmutableSet.Builder<String> rpathRootsForExplicitSoDeps = ImmutableSet.builder();
NestedSetBuilder<LinkerInput> expandedLinkerInputsBuilder = NestedSetBuilder.linkOrder();
// List of command line parameters that need to be placed *outside* of
// --whole-archive ... --no-whole-archive.
SequenceBuilder librariesToLink = new SequenceBuilder();
- String toolchainLibrariesSolibName =
- toolchainLibrariesSolibDir != null ? toolchainLibrariesSolibDir.getBaseName() : null;
+ ImmutableList<String> potentialSolibParents;
+ ImmutableList<String> rpathRoots;
+ // Calculate the correct relative value for the "-rpath" link option (which sets
+ // the search path for finding shared libraries).
if (isNativeDeps && cppConfiguration.shareNativeDeps()) {
- if (needToolchainLibrariesRpath) {
- runtimeLibrarySearchDirectories.add("../" + toolchainLibrariesSolibName + "/");
- }
+ // For shared native libraries, special symlinking is applied to ensure C++
+ // toolchain libraries are available under $ORIGIN/_solib_[arch]. So we set the RPATH to find
+ // them.
+ //
+ // Note that we have to do this because $ORIGIN points to different paths for
+ // different targets. In other words, blaze-bin/d1/d2/d3/a_shareddeps.so and
+ // blaze-bin/d4/b_shareddeps.so have different path depths. The first could
+ // reference a standard blaze-bin/_solib_[arch] via $ORIGIN/../../../_solib[arch],
+ // and the second could use $ORIGIN/../_solib_[arch]. But since this is a shared
+ // artifact, both are symlinks to the same place, so
+ // there's no *one* RPATH setting that fits all targets involved in the sharing.
+ potentialSolibParents = ImmutableList.of();
+ rpathRoots = ImmutableList.of(ccToolchainProvider.getSolibDirectory() + "/");
} else {
- // For all other links, calculate the relative path from the output file to _solib_[arch]
- // (the directory where all shared libraries are stored, which resides under the blaze-bin
- // directory. In other words, given blaze-bin/my/package/binary, rpathRoot would be
- // "../../_solib_[arch]".
- if (needToolchainLibrariesRpath) {
- for (String potentialExecRoot : potentialExecRoots) {
- runtimeLibrarySearchDirectories.add(
- potentialExecRoot + toolchainLibrariesSolibName + "/");
- }
- }
- if (isNativeDeps) {
- // We also retain the $ORIGIN/ path to solibs that are in _solib_<arch>, as opposed to
- // the package directory)
- if (needToolchainLibrariesRpath) {
- runtimeLibrarySearchDirectories.add("../" + toolchainLibrariesSolibName + "/");
- }
- }
- }
-
- if (needToolchainLibrariesRpath) {
- if (isNativeDeps) {
- runtimeLibrarySearchDirectories.add(".");
- }
- runtimeLibrarySearchDirectories.add(toolchainLibrariesSolibName + "/");
+ potentialSolibParents = findPotentialSolibParents();
+ rpathRoots =
+ potentialSolibParents.stream()
+ .map((execRoot) -> execRoot + ccToolchainProvider.getSolibDirectory() + "/")
+ .collect(toImmutableList());
}
+ Map<Artifact, Artifact> ltoMap = generateLtoMap();
Pair<Boolean, Boolean> includeSolibsPair =
addLinkerInputs(
+ rpathRoots,
+ ltoMap,
librarySearchDirectories,
rpathRootsForExplicitSoDeps,
librariesToLink,
@@ -307,7 +453,8 @@ public CollectedLibrariesToLink collectLibrariesToLink() {
}
allRuntimeLibrarySearchDirectories.addAll(rpathRootsForExplicitSoDeps.build());
if (includeToolchainLibrariesSolibDir) {
- allRuntimeLibrarySearchDirectories.addTransitive(runtimeLibrarySearchDirectories.build());
+ allRuntimeLibrarySearchDirectories.addTransitive(
+ collectToolchainRuntimeLibrarySearchDirectories(potentialSolibParents));
}
return new CollectedLibrariesToLink(
@@ -318,6 +465,8 @@ public CollectedLibrariesToLink collectLibrariesToLink() {
}
private Pair<Boolean, Boolean> addLinkerInputs(
+ ImmutableList<String> rpathRoots,
+ Map<Artifact, Artifact> ltoMap,
NestedSetBuilder<String> librarySearchDirectories,
ImmutableSet.Builder<String> rpathEntries,
SequenceBuilder librariesToLink,
@@ -366,9 +515,10 @@ private Pair<Boolean, Boolean> addLinkerInputs(
librariesToLink,
expandedLinkerInputsBuilder,
librarySearchDirectories,
+ rpathRoots,
rpathEntries);
} else {
- addStaticInputLinkOptions(input, librariesToLink, expandedLinkerInputsBuilder);
+ addStaticInputLinkOptions(input, ltoMap, librariesToLink, expandedLinkerInputsBuilder);
}
}
return Pair.of(includeSolibDir, includeToolchainLibrariesSolibDir);
@@ -384,6 +534,7 @@ private void addDynamicInputLinkOptions(
SequenceBuilder librariesToLink,
NestedSetBuilder<LinkerInput> expandedLinkerInputsBuilder,
NestedSetBuilder<String> librarySearchDirectories,
+ ImmutableList<String> rpathRoots,
ImmutableSet.Builder<String> rpathRootsForExplicitSoDeps) {
Preconditions.checkState(
input.getArtifactCategory() == ArtifactCategory.DYNAMIC_LIBRARY
@@ -470,6 +621,7 @@ private void addDynamicInputLinkOptions(
*/
private void addStaticInputLinkOptions(
LinkerInput input,
+ Map<Artifact, Artifact> ltoMap,
SequenceBuilder librariesToLink,
NestedSetBuilder<LinkerInput> expandedLinkerInputsBuilder) {
ArtifactCategory artifactCategory = input.getArtifactCategory();
@@ -528,7 +680,7 @@ private void addStaticInputLinkOptions(
LinkerInputs.simpleLinkerInput(
member,
ArtifactCategory.OBJECT_FILE,
- /* disableWholeArchive = */ false,
+ /* disableWholeArchive= */ false,
member.getRootRelativePathString()));
}
ImmutableList<Artifact> nonLtoArchiveMembers = nonLtoArchiveMembersBuilder.build();
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/BUILD b/src/test/java/com/google/devtools/build/lib/rules/cpp/BUILD
index c5cfa476849af1..c89878351c2793 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/BUILD
@@ -726,3 +726,20 @@ java_test(
"//third_party:truth",
],
)
+
+java_test(
+ name = "LibrariesToLinkCollectorTest",
+ srcs = ["LibrariesToLinkCollectorTest.java"],
+ deps = [
+ "//src/main/java/com/google/devtools/build/lib/actions:artifacts",
+ "//src/main/java/com/google/devtools/build/lib/analysis:configured_target",
+ "//src/main/java/com/google/devtools/build/lib/rules/cpp",
+ "//src/main/java/com/google/devtools/build/lib/vfs",
+ "//src/main/java/com/google/devtools/build/lib/vfs:pathfragment",
+ "//src/test/java/com/google/devtools/build/lib/analysis/util",
+ "//src/test/java/com/google/devtools/build/lib/packages:testutil",
+ "//src/test/java/com/google/devtools/build/lib/testutil:TestConstants",
+ "//third_party:junit4",
+ "//third_party:truth",
+ ],
+)
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollectorTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollectorTest.java
new file mode 100644
index 00000000000000..f29ec5044d9071
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/LibrariesToLinkCollectorTest.java
@@ -0,0 +1,273 @@
+// Copyright 2022 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.
+package com.google.devtools.build.lib.rules.cpp;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.devtools.build.lib.rules.cpp.LibrariesToLinkCollector.getRelative;
+import static org.junit.Assert.assertThrows;
+
+import com.google.devtools.build.lib.actions.Artifact;
+import com.google.devtools.build.lib.analysis.ConfiguredTarget;
+import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.packages.util.Crosstool.CcToolchainConfig;
+import com.google.devtools.build.lib.packages.util.ResourceLoader;
+import com.google.devtools.build.lib.testutil.TestConstants;
+import com.google.devtools.build.lib.vfs.FileSystemUtils;
+import com.google.devtools.build.lib.vfs.PathFragment;
+import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public final class LibrariesToLinkCollectorTest extends BuildViewTestCase {
+
+ @Test
+ public void getRalitive_returnsRelativePaths() {
+ assertThat(getRelative(PathFragment.create("foo"), PathFragment.create("foo/bar/baz")))
+ .isEqualTo(PathFragment.create("bar/baz"));
+ assertThat(getRelative(PathFragment.create("foo/bar"), PathFragment.create("foo/bar/baz")))
+ .isEqualTo(PathFragment.create("baz"));
+ assertThat(getRelative(PathFragment.create(""), PathFragment.create("foo")))
+ .isEqualTo(PathFragment.create("foo"));
+ assertThat(getRelative(PathFragment.create(""), PathFragment.create("foo/bar")))
+ .isEqualTo(PathFragment.create("foo/bar"));
+ assertThat(
+ getRelative(PathFragment.create("foo/bar"), PathFragment.create("foo/bar"))
+ .getPathString())
+ .isEmpty();
+
+ assertThat(getRelative(PathFragment.create("foo/bar/baz"), PathFragment.create("foo")))
+ .isEqualTo(PathFragment.create("../.."));
+ assertThat(getRelative(PathFragment.create("foo/bar/baz"), PathFragment.create("foo/bar")))
+ .isEqualTo(PathFragment.create(".."));
+ assertThat(getRelative(PathFragment.create("foo"), PathFragment.create("")))
+ .isEqualTo(PathFragment.create(".."));
+ assertThat(getRelative(PathFragment.create("foo/bar"), PathFragment.create("")))
+ .isEqualTo(PathFragment.create("../.."));
+ assertThat(getRelative(PathFragment.create("foo/baz"), PathFragment.create("foo/bar")))
+ .isEqualTo(PathFragment.create("../bar"));
+ assertThat(getRelative(PathFragment.create("bar"), PathFragment.create("foo")))
+ .isEqualTo(PathFragment.create("../foo"));
+
+ assertThat(getRelative(PathFragment.create("foo"), PathFragment.create("../foo")))
+ .isEqualTo(PathFragment.create("../../foo"));
+ assertThat(getRelative(PathFragment.create(".."), PathFragment.create("../../foo")))
+ .isEqualTo(PathFragment.create("../foo"));
+ assertThat(getRelative(PathFragment.create("../bar"), PathFragment.create("../../foo")))
+ .isEqualTo(PathFragment.create("../../foo"));
+ }
+
+ @Test
+ public void getRelative_throwsOnInvalidCases() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> getRelative(PathFragment.create("/bar"), PathFragment.create("/foo")));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> getRelative(PathFragment.create(".."), PathFragment.create("")));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> getRelative(PathFragment.create("../../bar"), PathFragment.create("../foo")));
+ }
+
+ /* TODO: Add an integration test (maybe in cc_integration_test.sh) when a modular toolchain config
+ is available.*/
+ @Test
+ public void dynamicLink_siblingLayout_externalBinary_rpath() throws Exception {
+ FileSystemUtils.appendIsoLatin1(
+ scratch.resolve("WORKSPACE"), "local_repository(name = 'src', path = 'src')");
+ invalidatePackages();
+
+ scratch.file("src/WORKSPACE");
+ scratch.file(
+ "src/test/BUILD",
+ "cc_binary(",
+ " name = 'foo',",
+ " srcs = ['some-dir/bar.so', 'some-other-dir/qux.so'],",
+ ")");
+ scratch.file("src/test/some-dir/bar.so");
+ scratch.file("src/test/some-other-dir/qux.so");
+
+ analysisMock.ccSupport().setupCcToolchainConfig(mockToolsConfig, CcToolchainConfig.builder());
+ mockToolsConfig.create(
+ "toolchain/cc_toolchain_config.bzl",
+ ResourceLoader.readFromResources(
+ "com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl"));
+ scratch.file(
+ "toolchain/BUILD",
+ "load(':cc_toolchain_config.bzl', 'cc_toolchain_config')",
+ "filegroup(",
+ " name = 'empty',",
+ ")",
+ "filegroup(",
+ " name = 'static_runtime',",
+ " srcs = ['librt.a'],",
+ ")",
+ "filegroup(",
+ " name = 'dynamic_runtime',",
+ " srcs = ['librt.so'],",
+ ")",
+ "filegroup(",
+ " name = 'files',",
+ " srcs = ['librt.a', 'librt.so'],",
+ ")",
+ "cc_toolchain(",
+ " name = 'c_toolchain',",
+ " toolchain_identifier = 'toolchain-identifier-k8',",
+ " toolchain_config = ':k8-compiler_config',",
+ " all_files = ':files',",
+ " ar_files = ':empty',",
+ " as_files = ':empty',",
+ " compiler_files = ':empty',",
+ " dwp_files = ':empty',",
+ " linker_files = ':empty',",
+ " strip_files = ':empty',",
+ " objcopy_files = ':empty',",
+ " dynamic_runtime_lib = ':dynamic_runtime',",
+ " static_runtime_lib = ':static_runtime',",
+ ")",
+ CcToolchainConfig.builder()
+ .withFeatures(
+ CppRuleClasses.STATIC_LINK_CPP_RUNTIMES,
+ CppRuleClasses.SUPPORTS_DYNAMIC_LINKER,
+ "runtime_library_search_directories")
+ .build()
+ .getCcToolchainConfigRule(),
+ "toolchain(",
+ " name = 'toolchain',",
+ " toolchain_type = '" + TestConstants.TOOLS_REPOSITORY + "//tools/cpp:toolchain_type',",
+ " toolchain = ':c_toolchain',",
+ ")");
+ scratch.file("toolchain/librt.a");
+ scratch.file("toolchain/librt.so");
+ analysisMock.ccSupport().setupCcToolchainConfig(mockToolsConfig, CcToolchainConfig.builder());
+
+ setBuildLanguageOptions("--experimental_sibling_repository_layout");
+ useConfiguration(
+ "--extra_toolchains=//toolchain:toolchain",
+ "--dynamic_mode=fully",
+ "--incompatible_enable_cc_toolchain_resolution");
+
+ ConfiguredTarget target = getConfiguredTarget("@src//test:foo");
+ assertThat(target).isNotNull();
+ Artifact binary = getExecutable(target);
+ CppLinkAction linkAction = (CppLinkAction) getGeneratingAction(binary);
+ assertThat(linkAction).isNotNull();
+
+ String workspace = getTarget("//toolchain:toolchain").getPackage().getWorkspaceName();
+ List<String> linkArgs = linkAction.getArguments();
+ assertThat(linkArgs)
+ .contains(
+ "--runtime_library=../../../../k8-fastbuild/bin/_solib__toolchain_Cc_Utoolchain/");
+ assertThat(linkArgs)
+ .contains(
+ "--runtime_library=foo.runfiles/" + workspace + "/_solib__toolchain_Cc_Utoolchain/");
+ assertThat(linkArgs)
+ .contains("--runtime_library=../../" + workspace + "/_solib__toolchain_Cc_Utoolchain/");
+ }
+
+ @Test
+ public void dynamicLink_siblingLayout_externalToolchain_rpath() throws Exception {
+ FileSystemUtils.appendIsoLatin1(
+ scratch.resolve("WORKSPACE"), "local_repository(name = 'toolchain', path = 'toolchain')");
+ invalidatePackages();
+
+ scratch.file(
+ "src/test/BUILD",
+ "cc_binary(",
+ " name = 'foo',",
+ " srcs = ['some-dir/bar.so', 'some-other-dir/qux.so'],",
+ ")");
+ scratch.file("src/test/some-dir/bar.so");
+ scratch.file("src/test/some-other-dir/qux.so");
+
+ // The cc_toolchain_config.bzl cannot be placed in the external "toolchain" repo (b/269187186)
+ mockToolsConfig.create(
+ "cc_toolchain_config.bzl",
+ ResourceLoader.readFromResources(
+ "com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl"));
+ scratch.file("BUILD");
+
+ scratch.file("toolchain/WORKSPACE");
+ scratch.file(
+ "toolchain/BUILD",
+ "load('@//:cc_toolchain_config.bzl', 'cc_toolchain_config')",
+ "filegroup(",
+ " name = 'empty',",
+ ")",
+ "filegroup(",
+ " name = 'static_runtime',",
+ " srcs = ['librt.a'],",
+ ")",
+ "filegroup(",
+ " name = 'dynamic_runtime',",
+ " srcs = ['librt.so'],",
+ ")",
+ "filegroup(",
+ " name = 'files',",
+ " srcs = ['librt.a', 'librt.so'],",
+ ")",
+ "cc_toolchain(",
+ " name = 'c_toolchain',",
+ " toolchain_identifier = 'toolchain-identifier-k8',",
+ " toolchain_config = ':k8-compiler_config',",
+ " all_files = ':files',",
+ " ar_files = ':empty',",
+ " as_files = ':empty',",
+ " compiler_files = ':empty',",
+ " dwp_files = ':empty',",
+ " linker_files = ':empty',",
+ " strip_files = ':empty',",
+ " objcopy_files = ':empty',",
+ " dynamic_runtime_lib = ':dynamic_runtime',",
+ " static_runtime_lib = ':static_runtime',",
+ ")",
+ CcToolchainConfig.builder()
+ .withFeatures(
+ CppRuleClasses.STATIC_LINK_CPP_RUNTIMES,
+ CppRuleClasses.SUPPORTS_DYNAMIC_LINKER,
+ "runtime_library_search_directories")
+ .build()
+ .getCcToolchainConfigRule(),
+ "toolchain(",
+ " name = 'toolchain',",
+ " toolchain_type = '" + TestConstants.TOOLS_REPOSITORY + "//tools/cpp:toolchain_type',",
+ " toolchain = ':c_toolchain',",
+ ")");
+ scratch.file("toolchain/librt.a");
+ scratch.file("toolchain/librt.so");
+ analysisMock.ccSupport().setupCcToolchainConfig(mockToolsConfig, CcToolchainConfig.builder());
+
+ setBuildLanguageOptions("--experimental_sibling_repository_layout");
+ useConfiguration(
+ "--extra_toolchains=@toolchain//:toolchain",
+ "--dynamic_mode=fully",
+ "--incompatible_enable_cc_toolchain_resolution");
+
+ ConfiguredTarget target = getConfiguredTarget("//src/test:foo");
+ assertThat(target).isNotNull();
+ Artifact binary = getExecutable(target);
+ CppLinkAction linkAction = (CppLinkAction) getGeneratingAction(binary);
+ assertThat(linkAction).isNotNull();
+
+ List<String> linkArgs = linkAction.getArguments();
+ assertThat(linkArgs)
+ .contains(
+ "--runtime_library=../../../../toolchain/k8-fastbuild/bin/_solib___Cc_Utoolchain/");
+ assertThat(linkArgs)
+ .contains("--runtime_library=foo.runfiles/toolchain/_solib___Cc_Utoolchain/");
+ assertThat(linkArgs).contains("--runtime_library=../../../toolchain/_solib___Cc_Utoolchain/");
+ }
+}
| train | test | 2023-02-16T22:03:30 | "2022-12-08T01:05:02Z" | yuzhy8701 | test |
bazelbuild/bazel/15088_17512 | bazelbuild/bazel | bazelbuild/bazel/15088 | bazelbuild/bazel/17512 | [
"keyword_pr_to_issue"
] | a0fa77cc36d02f5f230335556a1829b298b2f219 | 1a438b41b74d94fd8b6ff4dcf20b4526530e3c6e | [
"cc @comius @c-mita ",
"It's seems the issue is that cc_tests unconditionally pulls those coverage tools dependencies.\r\nhttps://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java;l=255-270"
] | [] | "2023-02-16T10:10:12Z" | [
"type: bug",
"P2",
"team-Rules-CPP"
] | `cc_test` rules trigger remote JDK download (~200 MB) | ### Description of the problem / feature request:
`cc_test` rules trigger remote JDK download (~200 MB), which is undesirable when operating under constraints on storage capacity and/or network capacity. https://en.wikipedia.org/wiki/Principle_of_least_astonishment also applies.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
$ rm -rf $HOME/.cache/bazel
$ git clone https://github.com/google/re2.git
$ cd re2
$ bazel build //:all --experimental_repository_resolved_file=resolved.bzl
$ grep openjdk resolved.bzl
$ bazel query 'somepath(//:all, @remote_coverage_tools//:all)'
```
### What operating system are you running Bazel on?
Linux
### What's the output of `bazel info release`?
```
release 5.0.0
```
| [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java",
"src/main/java/com/google/devtools/build/lib/rules/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java",
"src/main/java/com/google/devtools/build/lib/rules/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java",
"src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java",
"src/test/shell/bazel/cc_integration_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BUILD b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
index b7dd37dce0f342..350541aee2ad63 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
@@ -252,7 +252,6 @@ java_library(
"test/AnalysisTestActionBuilder.java",
"test/BaselineCoverageAction.java",
"test/CoverageCommon.java",
- "test/CoverageConfiguration.java",
"test/InstrumentedFileManifestAction.java",
"test/InstrumentedFilesCollector.java",
"test/TestActionBuilder.java",
@@ -360,6 +359,7 @@ java_library(
":test/analysis_failure_propagation_exception",
":test/analysis_test_result_info",
":test/baseline_coverage_result",
+ ":test/coverage_configuration",
":test/execution_info",
":test/instrumented_files_info",
":test/test_configuration",
@@ -2527,6 +2527,24 @@ java_library(
],
)
+java_library(
+ name = "test/coverage_configuration",
+ srcs = ["test/CoverageConfiguration.java"],
+ deps = [
+ ":config/build_options",
+ ":config/core_option_converters",
+ ":config/core_options",
+ ":config/fragment",
+ ":config/fragment_options",
+ "//src/main/java/com/google/devtools/build/lib/analysis/starlark/annotations",
+ "//src/main/java/com/google/devtools/build/lib/cmdline",
+ "//src/main/java/com/google/devtools/build/lib/concurrent",
+ "//src/main/java/com/google/devtools/build/lib/starlarkbuildapi/test",
+ "//src/main/java/com/google/devtools/common/options",
+ "//third_party:jsr305",
+ ],
+)
+
java_library(
name = "test/coverage_report",
srcs = ["test/CoverageReport.java"],
@@ -2588,6 +2606,7 @@ java_library(
":config/fragment_options",
":config/per_label_options",
":options_diff_predicate",
+ ":test/coverage_configuration",
":test/test_sharding_strategy",
"//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/packages",
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java b/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
index bc14130e9cb3fb..7f4460242e7e20 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BaseRuleClasses.java
@@ -143,13 +143,16 @@ public static LabelLateBoundDefault<TestConfiguration> coverageSupportAttribute(
"//tools/test:coverage_report_generator";
@SerializationConstant @AutoCodec.VisibleForSerialization
- static final Resolver<TestConfiguration, Label> COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER =
- (rule, attributes, configuration) -> configuration.getCoverageReportGenerator();
+ static final Resolver<CoverageConfiguration, Label>
+ COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER =
+ (rule, attributes, configuration) -> configuration.reportGenerator();
- public static LabelLateBoundDefault<TestConfiguration> coverageReportGeneratorAttribute(
+ public static LabelLateBoundDefault<CoverageConfiguration> coverageReportGeneratorAttribute(
Label defaultValue) {
return LabelLateBoundDefault.fromTargetConfiguration(
- TestConfiguration.class, defaultValue, COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER);
+ CoverageConfiguration.class,
+ defaultValue,
+ COVERAGE_REPORT_GENERATOR_CONFIGURATION_RESOLVER);
}
public static LabelLateBoundDefault<CoverageConfiguration> getCoverageOutputGeneratorLabel() {
diff --git a/src/main/java/com/google/devtools/build/lib/rules/BUILD b/src/main/java/com/google/devtools/build/lib/rules/BUILD
index 630f65a4d016c5..2a256ca6b2e02a 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/rules/BUILD
@@ -59,6 +59,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:artifacts",
"//src/main/java/com/google/devtools/build/lib/analysis:analysis_cluster",
+ "//src/main/java/com/google/devtools/build/lib/analysis:test/coverage_configuration",
"//src/main/java/com/google/devtools/build/lib/analysis:test/test_configuration",
"//src/main/java/com/google/devtools/build/lib/analysis:test/test_trimming_transition_factory",
"//src/main/java/com/google/devtools/build/lib/cmdline",
| diff --git a/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java
index 7aaccfa4d4eec2..3825f0f657d2ec 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/test/CoverageConfiguration.java
@@ -52,6 +52,22 @@ public static class CoverageOptions extends FragmentOptions {
+ "currently be a filegroup that contains a single file, the binary. Defaults to "
+ "'//tools/test:lcov_merger'.")
public Label coverageOutputGenerator;
+
+ @Option(
+ name = "coverage_report_generator",
+ converter = LabelConverter.class,
+ defaultValue = "@bazel_tools//tools/test:coverage_report_generator",
+ documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
+ effectTags = {
+ OptionEffectTag.CHANGES_INPUTS,
+ OptionEffectTag.AFFECTS_OUTPUTS,
+ OptionEffectTag.LOADING_AND_ANALYSIS
+ },
+ help =
+ "Location of the binary that is used to generate coverage reports. This must "
+ + "currently be a filegroup that contains a single file, the binary. Defaults to "
+ + "'//tools/test:coverage_report_generator'.")
+ public Label coverageReportGenerator;
}
private final CoverageOptions coverageOptions;
@@ -75,4 +91,12 @@ public Label outputGenerator() {
}
return coverageOptions.coverageOutputGenerator;
}
+
+ @Nullable
+ public Label reportGenerator() {
+ if (coverageOptions == null) {
+ return null;
+ }
+ return coverageOptions.coverageReportGenerator;
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java
index 7ff420cd9001d8..7da18906591961 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/test/TestConfiguration.java
@@ -25,6 +25,7 @@
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.analysis.config.PerLabelOptions;
import com.google.devtools.build.lib.analysis.config.RequiresOptions;
+import com.google.devtools.build.lib.analysis.test.CoverageConfiguration.CoverageOptions;
import com.google.devtools.build.lib.analysis.test.TestShardingStrategy.ShardingStrategyConverter;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.TestTimeout;
@@ -51,7 +52,9 @@ public class TestConfiguration extends Fragment {
// changes in --trim_test_configuration itself or related flags always prompt invalidation
return true;
}
- if (!changedOption.getField().getDeclaringClass().equals(TestOptions.class)) {
+ Class<?> affectedOptionsClass = changedOption.getField().getDeclaringClass();
+ if (!affectedOptionsClass.equals(TestOptions.class)
+ && !affectedOptionsClass.equals(CoverageOptions.class)) {
// options outside of TestOptions always prompt invalidation
return true;
}
@@ -240,23 +243,6 @@ public static class TestOptions extends FragmentOptions {
)
public Label coverageSupport;
- @Option(
- name = "coverage_report_generator",
- converter = LabelConverter.class,
- defaultValue = "@bazel_tools//tools/test:coverage_report_generator",
- documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
- effectTags = {
- OptionEffectTag.CHANGES_INPUTS,
- OptionEffectTag.AFFECTS_OUTPUTS,
- OptionEffectTag.LOADING_AND_ANALYSIS
- },
- help =
- "Location of the binary that is used to generate coverage reports. This must "
- + "currently be a filegroup that contains a single file, the binary. Defaults to "
- + "'//tools/test:coverage_report_generator'."
- )
- public Label coverageReportGenerator;
-
@Option(
name = "experimental_fetch_all_coverage_outputs",
defaultValue = "false",
@@ -357,10 +343,6 @@ public Label getCoverageSupport() {
return options.coverageSupport;
}
- public Label getCoverageReportGenerator() {
- return options.coverageReportGenerator;
- }
-
/**
* @return number of times the given test should run. If the test doesn't match any of the
* filters, runs it once.
diff --git a/src/test/shell/bazel/cc_integration_test.sh b/src/test/shell/bazel/cc_integration_test.sh
index c02c27a0ba2997..93e653bddf967a 100755
--- a/src/test/shell/bazel/cc_integration_test.sh
+++ b/src/test/shell/bazel/cc_integration_test.sh
@@ -1772,8 +1772,9 @@ EOF
fi
}
-function test_cc_test_no_lcov_merger_dep_without_coverage() {
- # Regression test for https://github.com/bazelbuild/bazel/issues/16961
+function test_cc_test_no_coverage_tools_dep_without_coverage() {
+ # Regression test for https://github.com/bazelbuild/bazel/issues/16961 and
+ # https://github.com/bazelbuild/bazel/issues/15088.
local package="${FUNCNAME[0]}"
mkdir -p "${package}"
@@ -1785,12 +1786,9 @@ cc_test(
EOF
touch "${package}"/test.cc
- # FIXME: cc_test still unconditionally depends on the LCOV merger binary through
- # @remote_coverage_tools//:coverage_output_generator, which is also unnecessary:
- # https://github.com/bazelbuild/bazel/issues/15088
- out=$(bazel cquery "somepath(//${package}:test,@remote_coverage_tools//:lcov_merger)")
+ out=$(bazel cquery "somepath(//${package}:test,@remote_coverage_tools//:all)")
if [[ -n "$out" ]]; then
- fail "Expected no dependency on lcov_merger, but got: $out"
+ fail "Expected no dependency on remote coverage tools, but got: $out"
fi
}
| train | test | 2023-02-19T03:01:47 | "2022-03-21T14:42:42Z" | junyer | test |
bazelbuild/bazel/17541_17733 | bazelbuild/bazel | bazelbuild/bazel/17541 | bazelbuild/bazel/17733 | [
"keyword_pr_to_issue"
] | db5c9ec1e552c42f43280d7cd6ad6213ac191f36 | 94575fd8cf2a9062bc522f40b63d0bc526d2c22e | [
"Hi @FahriBilici, Above issue related to [Tensorflow](https://github.com/tensorflow/tensorflow) lite. Can you please check the above issue with the specific repo of [tensorflow](https://github.com/tensorflow/tensorflow). Please reach us back if the above issue is still relevant to Bazel, with complete details. Thanks!",
"@sgowroji This is indeed a bug in Bazel itself. Note how the error message says that `ios` is not a valid Apple platform type but then goes on to list it as valid - but with a Turkish lowercase i. \n\nI believe that this can be fixed by using `Ascii.toLowerCase` and `Ascii.equalsIgnoreCase` in the methods of https://cs.opensource.google/bazel/bazel/+/669c298f71b5f8fbef8f62c85543cda3eab4dfcc:src/main/java/com/google/devtools/build/lib/rules/apple/ApplePlatform.java;drc=669c298f71b5f8fbef8f62c85543cda3eab4dfcc;l=246. Can't fix it myself right now, could you assign it (probably to the Apple team)?",
"Yes I truly believe the issue displayed because of case sensitivity.",
"I submitted a fix: https://github.com/bazelbuild/bazel/pull/17687\r\n\r\nBazel didn't really work at all with a Turkish locale (e.g. it fails when it encounters a `size = \"medium\"` on a test). The workaround is to specify a different locale with:\r\n```\r\nbazel --host_jvm_args=-Duser.country=US --host_jvm_args=-Duser.language=en build ...\r\n```"
] | [] | "2023-03-10T20:47:55Z" | [
"type: bug",
"platform: apple",
"untriaged",
"team-Rules-ObjC"
] | ERROR: While parsing option --apple_platform_type=ios: Not a valid Apple platform type: 'ios' (should be ıos, watchos, tvos, macos or catalyst) | ### Description of the bug:
I am following tensorflow installation locally from [here](https://www.tensorflow.org/lite/guide/build_ios). I run configure then run this code:
`bazel build --config=ios_fat -c opt --cxxopt=--std=c++17 \
//tensorflow/lite/ios:TensorFlowLiteC_framework`
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
following the link provided after cloning tensorflow from github.
### Which operating system are you running Bazel on?
macos monterey (intel)
### What is the output of `bazel info release`?
5.3.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
-
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
-
```
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/cpp/blaze.cc"
] | [
"src/main/cpp/blaze.cc"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index ee0b32268bf47d..459dd524c62dc8 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -402,6 +402,13 @@ static vector<string> GetServerExeArgs(const blaze_util::Path &jvm_path,
// Force use of latin1 for file names.
result.push_back("-Dfile.encoding=ISO-8859-1");
+ // Force into the root locale to ensure consistent behavior of string
+ // operations across machines (e.g. in the tr_TR locale, capital ASCII 'I'
+ // turns into a special Unicode 'i' when converted to lower case).
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html#ROOT
+ result.push_back("-Duser.country=");
+ result.push_back("-Duser.language=");
+ result.push_back("-Duser.variant=");
if (startup_options.host_jvm_debug) {
BAZEL_LOG(USER)
| null | train | test | 2023-03-11T19:52:45 | "2023-02-20T22:39:14Z" | FahriBilici | test |
bazelbuild/bazel/17342_17764 | bazelbuild/bazel | bazelbuild/bazel/17342 | bazelbuild/bazel/17764 | [
"keyword_pr_to_issue"
] | c9e3eeb2f34d66e2c8bcccd32786ea75c357497e | 6c8930347025ef22e21d7793dd9202033dd79151 | [
"Pinging this issue. @rickeylev I noticed you've been making changes around the Python rules here. Would you be able to take a look? This issue is coming up more and more as more projects are upgraded to Bazel 6.",
"What is this \"RUN_UNDER_RUNFILES\" environment variable? Is there some doc about this? As near as I can tell it's only set when Bazel runs a target as a test?\r\n\r\nAnyways, yeah, bug. I was able to repro.\r\n\r\nPosterity/notes to self: This was PR #15590",
"@rickeylev thank you for getting this done so quickly. Can you merge this into the Bazel 6.1 branch so that it can go out as soon as possible?",
"I suppose so. I've never done or requested a backport, so I'll have to ask around how to do that.",
"@rickeylev this mentions how: https://github.com/bazelbuild/bazel/issues/17212#issuecomment-1439198224",
"Hi all, can this wait till the next release (6.2)? We've already created the third release candidate for 6.1 and plan to do the final release on Monday, so we won't be able to include this.",
"Hi,\r\n\r\nYes, if it's too late for 6.1, then 6.2 is fine.",
"@bazel-io fork 6.2.0",
"I was seeing this on 6.3.2 and tried upgrading to 7.1.1 to see if it fixed it, but it still happens.\r\n\r\nAnyone else still seeing this?"
] | [] | "2023-03-13T20:41:48Z" | [
"type: bug",
"team-Rules-Python"
] | Zipapps no longer deleting Bazel.runfiles_* directories placed in /tmp | ### Description of the bug:
As of Bazel 6.0.0, a change was made to [bazel/rules/python/python_stub_template.txt](https://github.com/bazelbuild/bazel/commit/9d0163002ca63f4cdbaff9420380d72e2a6e38b3#diff-fa3ae340fea197099f8d4b5101d1d71bccc3ceece3517b4ea9126e2d448eab01) that [gates the deletion](https://github.com/bazelbuild/bazel/commit/9d0163002ca63f4cdbaff9420380d72e2a6e38b3#diff-fa3ae340fea197099f8d4b5101d1d71bccc3ceece3517b4ea9126e2d448eab01R336-R337) of the `Bazel.runfiles_*` directory that is created in `/tmp`. This is because it depends on workspace being set, and workspace is only set [when `RUN_UNDER_RUNFILES` is set](https://github.com/bazelbuild/bazel/commit/9d0163002ca63f4cdbaff9420380d72e2a6e38b3#diff-fa3ae340fea197099f8d4b5101d1d71bccc3ceece3517b4ea9126e2d448eab01R501-R507). This is a regression from the previous behavior where the directory placed in `/tmp` would be deleted as long as it was [running under a zip](https://github.com/bazelbuild/bazel/commit/9d0163002ca63f4cdbaff9420380d72e2a6e38b3#diff-fa3ae340fea197099f8d4b5101d1d71bccc3ceece3517b4ea9126e2d448eab01L296-L303). This should be fixed so that the `Bazel.runfiles_*` directories are cleaned up whenever it is running under a zip.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Build a zipapp target on Bazel 6.0.0 (without `RUN_UNDER_RUNFILES` set) and on whatever machine you consume that zipapp there will be a `Bazel.runfiles_<sha>` directory with the zipapp contents left around from execution.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
release 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [
"src/test/shell/bazel/python_version_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
index bd387ebdd9bd86..19514526104b4c 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
@@ -202,6 +202,8 @@ def ExtractZip(zip_path, dest_dir):
def CreateModuleSpace():
temp_dir = tempfile.mkdtemp('', 'Bazel.runfiles_')
ExtractZip(os.path.dirname(__file__), temp_dir)
+ # IMPORTANT: Later code does `rm -fr` on dirname(module_space) -- it's
+ # important that deletion code be in sync with this directory structure
return os.path.join(temp_dir, 'runfiles')
# Returns repository roots to add to the import path.
@@ -301,7 +303,7 @@ def UnresolveSymlinks(output_filename):
os.unlink(unfixed_file)
def ExecuteFile(python_program, main_filename, args, env, module_space,
- coverage_entrypoint, workspace):
+ coverage_entrypoint, workspace, delete_module_space):
# type: (str, str, list[str], dict[str, str], str, str|None, str|None) -> ...
"""Executes the given Python file using the various environment settings.
@@ -316,8 +318,9 @@ def ExecuteFile(python_program, main_filename, args, env, module_space,
module_space: (str) Path to the module space/runfiles tree directory
coverage_entrypoint: (str|None) Path to the coverage tool entry point file.
workspace: (str|None) Name of the workspace to execute in. This is expected to be a
- directory under the runfiles tree, and will recursively delete the
- runfiles directory if set.
+ directory under the runfiles tree.
+ delete_module_space: (bool), True if the module space should be deleted
+ after a successful (exit code zero) program run, False if not.
"""
# We want to use os.execv instead of subprocess.call, which causes
# problems with signal passing (making it difficult to kill
@@ -327,16 +330,15 @@ def ExecuteFile(python_program, main_filename, args, env, module_space,
# - On Windows, os.execv doesn't handle arguments with spaces
# correctly, and it actually starts a subprocess just like
# subprocess.call.
- # - When running in a workspace (i.e., if we're running from a zip),
- # we need to clean up the workspace after the process finishes so
- # control must return here.
+ # - When running in a workspace or zip file, we need to clean up the
+ # workspace after the process finishes so control must return here.
# - If we may need to emit a host config warning after execution, we
# can't execv because we need control to return here. This only
# happens for targets built in the host config.
# - For coverage targets, at least coveragepy requires running in
# two invocations, which also requires control to return here.
#
- if not (IsWindows() or workspace or coverage_entrypoint):
+ if not (IsWindows() or workspace or coverage_entrypoint or delete_module_space):
_RunExecv(python_program, main_filename, args, env)
if coverage_entrypoint is not None:
@@ -349,7 +351,10 @@ def ExecuteFile(python_program, main_filename, args, env, module_space,
cwd=workspace
)
- if workspace:
+ if delete_module_space:
+ # NOTE: dirname() is called because CreateModuleSpace() creates a
+ # sub-directory within a temporary directory, and we want to remove the
+ # whole temporary directory.
shutil.rmtree(os.path.dirname(module_space), True)
sys.exit(ret_code)
@@ -438,8 +443,10 @@ def Main():
if IsRunningFromZip():
module_space = CreateModuleSpace()
+ delete_module_space = True
else:
module_space = FindModuleSpace(main_rel_path)
+ delete_module_space = False
python_imports = '%imports%'
python_path_entries = CreatePythonPathEntries(python_imports, module_space)
@@ -524,9 +531,11 @@ def Main():
try:
sys.stdout.flush()
+ # NOTE: ExecuteFile may call execve() and lines after this will never run.
ExecuteFile(
python_program, main_filename, args, new_env, module_space,
- cov_tool, workspace
+ cov_tool, workspace,
+ delete_module_space = delete_module_space,
)
except EnvironmentError:
| diff --git a/src/test/shell/bazel/python_version_test.sh b/src/test/shell/bazel/python_version_test.sh
index c7a44708432bc8..485707a67bf7a8 100755
--- a/src/test/shell/bazel/python_version_test.sh
+++ b/src/test/shell/bazel/python_version_test.sh
@@ -201,6 +201,32 @@ EOF
expect_log "I am mockpy!"
}
+# Test that running a zip app without RUN_UNDER_RUNFILES=1 removes the
+# temporary directory it creates
+function test_build_python_zip_cleans_up_temporary_module_space() {
+
+ mkdir test
+ cat > test/BUILD << EOF
+py_binary(
+ name = "pybin",
+ srcs = ["pybin.py"],
+)
+EOF
+ cat > test/pybin.py << EOF
+print(__file__)
+EOF
+
+ bazel build //test:pybin --build_python_zip &> $TEST_log || fail "bazel build failed"
+ pybin_location=$(bazel-bin/test/pybin)
+
+ # The pybin location is "<ms root>/runfiles/<workspace>/test/pybin.py",
+ # so we have to go up 4 directories to get to the module space root
+ module_space_dir=$(dirname $(dirname $(dirname $(dirname "$pybin_location"))))
+ if [[ -d "$module_space_dir" ]]; then
+ fail "expected module space directory to be deleted, but $module_space_dir still exists"
+ fi
+}
+
function test_get_python_zip_file_via_output_group() {
touch foo.py
cat > BUILD <<'EOF'
| train | test | 2023-03-13T20:56:28 | "2023-01-26T18:44:28Z" | sethasadi | test |
bazelbuild/bazel/17749_17786 | bazelbuild/bazel | bazelbuild/bazel/17749 | bazelbuild/bazel/17786 | [
"keyword_pr_to_issue"
] | 3a7236beb8c0692c327aaeb5341801280d0cd870 | a87b8e0b6b17feed7e649a85f17162510fa8d652 | [
"Seems to be a much more general issue:\r\n```\r\n$ bazel cquery --output=starlark --starlark:expr=\"providers(target)\" :alias\r\nNone\r\n```"
] | [
"The original change at https://github.com/bazelbuild/bazel/pull/17753/files doesn't impact lines 99-111. Does that matter?",
"Yeah, that was the change I made. I removed this extra code that shouldn't have been included:) Looks like the file here is outdated."
] | "2023-03-15T18:47:22Z" | [
"type: bug",
"P2",
"team-Configurability"
] | `alias` targets should expose `FilesToRunProvider` if `actual` has one | ### Description of the bug:
I have code which runs a `cquery` to gets the executable of a `FilesToRunProvider`:
`bazel cquery --output=starlark --starlark:expr="providers(target).get(\"FilesToRunProvider\").executable.path"`
This doesn't work for `alias` targets which point to binary targets. It probably should.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
BUILD file:
```starlark
py_binary(
name = "bin",
srcs = ["bin.py"],
)
alias(
name = "alias",
actual = ":bin",
)
```
Run: `bazel cquery --output=starlark --starlark:expr="providers(target).get(\"FilesToRunProvider\").executable.path" :alias`
expect to get an output path. Instead, get an error because `providers(target).get("FilesToRunProvider")` is `None`.
### Which operating system are you running Bazel on?
_No response_
### What is the output of `bazel info release`?
release 6.1.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java",
"src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java",
"src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java",
"src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java",
"src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java",
"src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java",
"src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java"
] | [
"src/test/shell/integration/configured_query_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java b/src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java
index c8c600ab4d557b..df3f79b7a524a1 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java
@@ -20,6 +20,7 @@
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skyframe.BuildConfigurationKey;
import javax.annotation.Nullable;
+import net.starlark.java.eval.Dict;
import net.starlark.java.eval.Structure;
/**
@@ -95,4 +96,13 @@ default Label getOriginalLabel() {
default ImmutableMap<Label, ConfigMatchingProvider> getConfigConditions() {
return ImmutableMap.of();
}
+
+ /**
+ * This is only intended to be called from the query dialects of Starlark.
+ *
+ * @return a map of provider names to their values
+ */
+ default Dict<String, Object> getProvidersDict() {
+ return null;
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java b/src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java
index e5156c1cf3eee5..0c3330d0f5586c 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/configuredtargets/AbstractConfiguredTarget.java
@@ -35,7 +35,6 @@
import com.google.devtools.build.lib.skyframe.BuildConfigurationKey;
import java.util.function.Consumer;
import javax.annotation.Nullable;
-import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Starlark;
@@ -255,12 +254,4 @@ public String getRuleClassString() {
public void repr(Printer printer) {
printer.append("<unknown target " + getLabel() + ">");
}
-
- /**
- * Returns a map of provider names to their values. This is only intended to be called from the
- * query dialects of Starlark. Implement in subclasses which can have providers.
- */
- public Dict<String, Object> getProvidersDict() {
- return null;
- }
}
diff --git a/src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java b/src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java
index 267ec00df96c8b..d107529352ec4a 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/cquery/StarlarkOutputFormatterCallback.java
@@ -21,7 +21,6 @@
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
-import com.google.devtools.build.lib.analysis.configuredtargets.AbstractConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
@@ -121,10 +120,7 @@ public Object buildOptions(ConfiguredTarget target) {
@Param(name = "target"),
})
public Object providers(ConfiguredTarget target) {
- if (!(target instanceof AbstractConfiguredTarget)) {
- return Starlark.NONE;
- }
- Dict<String, Object> ret = ((AbstractConfiguredTarget) target).getProvidersDict();
+ Dict<String, Object> ret = target.getProvidersDict();
if (ret == null) {
return Starlark.NONE;
}
diff --git a/src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java b/src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java
index b68e2fa9bcae57..6c3981cb2af9ab 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/AliasConfiguredTarget.java
@@ -38,6 +38,7 @@
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.skyframe.BuildConfigurationKey;
import javax.annotation.Nullable;
+import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.StarlarkSemantics;
@@ -196,6 +197,11 @@ public Label getOriginalLabel() {
return label;
}
+ @Override
+ public Dict<String, Object> getProvidersDict() {
+ return actual.getProvidersDict();
+ }
+
@Override
public void repr(Printer printer) {
printer.append("<alias target " + label + " of " + actual.getLabel() + ">");
| diff --git a/src/test/shell/integration/configured_query_test.sh b/src/test/shell/integration/configured_query_test.sh
index 1d80a9539e9c43..53106731086f02 100755
--- a/src/test/shell/integration/configured_query_test.sh
+++ b/src/test/shell/integration/configured_query_test.sh
@@ -1268,6 +1268,37 @@ EOF
assert_contains "some_value" output
}
+function test_starlark_output_providers_starlark_provider_for_alias() {
+ local -r pkg=$FUNCNAME
+ mkdir -p $pkg
+ cat > $pkg/BUILD <<EOF
+load(":my_rule.bzl", "my_rule")
+my_rule(name="myrule")
+alias(name="myalias", actual="myrule")
+EOF
+ cat > $pkg/my_rule.bzl <<'EOF'
+# A no-op rule that manifests a provider
+MyRuleInfo = provider(fields={"label": "a_rule_label"})
+
+def _my_rule_impl(ctx):
+ return [MyRuleInfo(label="some_value")]
+
+my_rule = rule(
+ implementation = _my_rule_impl,
+ attrs = {},
+)
+EOF
+ cat > $pkg/outfunc.bzl <<EOF
+def format(target):
+ p = providers(target)
+ return p["//$pkg:my_rule.bzl%MyRuleInfo"].label
+EOF
+ bazel cquery "//$pkg:myalias" --output=starlark --starlark:file="$pkg/outfunc.bzl" >output \
+ 2>"$TEST_log" || fail "Expected success"
+
+ assert_contains "some_value" output
+}
+
function test_bazelignore_error_cquery_nocrash() {
local -r pkg=$FUNCNAME
| test | test | 2023-03-20T15:54:16 | "2023-03-13T13:11:19Z" | illicitonion | test |
bazelbuild/bazel/15605_17868 | bazelbuild/bazel | bazelbuild/bazel/15605 | bazelbuild/bazel/17868 | [
"keyword_pr_to_issue"
] | d38050916d6e9aaa62d4bc2ecb7bc521c1cb275e | dee2ac0587657e7dd8ec25ef8a9cef3c92a69359 | [
"What is the most useful and still rational behavior here? You could plausibly argue four approaches:\r\n\r\n1. keep the value of the first key seen\r\n2. keep the value of the last key seen\r\n3. merge the values of duplicates if the value is an object\r\n4. error\r\n",
"experiment:\r\n```\r\n$ node -e 'console.log(JSON.parse(\"{\\\"a\\\": 1, \\\"a\\\": 2}\"))'\r\n{ a: 2 }\r\n```\r\n\r\nSo the answer I'd most like coming from a NodeJS ecosystem is to take your option 2.\r\n\r\nI dunno if that's formally documented in the nodejs spec.",
"Taking the last entry seems preferable over taking the first, since it's more consistent with `dict.update`, the `dict()` constructor, etc. But it's not clear whether that's better or worse than failing. We could also make it an option, i.e. a named arg to decode, but I'm not sure I want to complicate that API.",
"ping! @brandjon will you take PRs for this?",
"[ECMA-262](https://262.ecma-international.org/13.0/#sec-json.parse) says under 25.5.1.1\r\n> Note 2 In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.\r\n\r\nThis aligns with option 2.",
"ping! @brandjon would you accept a PR? Another user on Slack tripped over this.",
"Different JSON parsers diverge on this point: https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object\r\n\r\nJavascript, and anything that tries to be compatible with Javascript, of course allows duplicate keys and keeps the last value.\r\n\r\nC and C++ based JSON parsers typically don't allow duplicate keys.\r\n\r\nI have no strong opinion on which way to go, but given the need to integrate with npm, we may as well follow Javascript's behavior.",
"I think the critical observation is that Bazel is meant to be the orchestration for a bunch of third-party package managers and tools, so it should follow the https://en.wikipedia.org/wiki/Robustness_principle\r\nMeaning, even if parsers typically reject some input, Bazel's job is to \"be permissive in what it accepts\" to maximize compatibility.\r\nSame argument I made for https://github.com/bazelbuild/bazel/commit/c9e2be52a067dd9abf5efa4f5f55bb5b98cf5d3b",
"Rationale for accepting the change:\r\n\r\n* The JSON RFC apparently leaves this unspecified, so we're not prohibited from doing it.\r\n* JavaScript will allow it, with the unsurprising (and consistent with `dict`) semantics that last key wins.\r\n* It supports this Node-related use case.\r\n\r\n(The \"Robustness principle\" can be problematic -- think HTML. But we're maintaining a parser, not writing a new standard.)",
"@brandjon @tetromino I don't suppose you guys know which release this will hit? ",
"Given that this doesn't change the behavior on inputs that didn't hard fail before this change, I would propose to cherry-pick it into 6.2.0. Otherwise it would naturally make its way into 7.0.0.",
"I am asking for a cherry-pick at https://github.com/bazelbuild/bazel/pull/17868"
] | [] | "2023-03-23T17:14:41Z" | [
"type: bug",
"P4",
"team-Starlark-Interpreter"
] | json.decode is too strict; fails on duplicate keys | ### Description of the bug:
A couple of packages are published to npm with a JSON descriptor which is valid in every context it's used.
However `json.decode` fails on this part of the file:
```
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true,
"ignoreCatch": true
}
```
More context here:
https://github.com/aspect-build/rules_js/issues/148
I agree with the library author that it's really a Bazel bug, which should follow the https://en.wikipedia.org/wiki/Robustness_principle of "be permissive in what you accept". Author points this out:
https://github.com/wooorm/decode-named-character-reference/issues/2
https://github.com/wooorm/stringify-entities/issues/11
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
json.decode("""
{
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true,
"ignoreCatch": true
}
}
""")
```
### What is the output of `bazel info release`?
5.x
| [
"src/main/java/net/starlark/java/lib/json/Json.java"
] | [
"src/main/java/net/starlark/java/lib/json/Json.java"
] | [
"src/test/java/net/starlark/java/eval/testdata/json.star"
] | diff --git a/src/main/java/net/starlark/java/lib/json/Json.java b/src/main/java/net/starlark/java/lib/json/Json.java
index c97972d8599f97..b366c740a18022 100644
--- a/src/main/java/net/starlark/java/lib/json/Json.java
+++ b/src/main/java/net/starlark/java/lib/json/Json.java
@@ -287,7 +287,8 @@ private void appendQuoted(String s) {
+ " a decimal point or an exponent. Although JSON has no syntax "
+ " for non-finite values, very large values may be decoded as infinity.\n"
+ "<li>a JSON object is parsed as a new unfrozen Starlark dict."
- + " Keys must be unique strings.\n"
+ + " If the same key string occurs more than once in the object, the last"
+ + " value for the key is kept.\n"
+ "<li>a JSON array is parsed as new unfrozen Starlark list.\n"
+ "</ul>\n"
+ "Decoding fails if x is not a valid JSON encoding.\n",
@@ -398,11 +399,7 @@ private Object parse() throws EvalException {
}
i++; // ':'
Object value = parse();
- int sz = dict.size();
dict.putEntry((String) key, value); // can't fail
- if (dict.size() == sz) {
- throw Starlark.errorf("object has duplicate key: %s", Starlark.repr(key));
- }
c = next();
if (c != ',') {
if (c != '}') {
| diff --git a/src/test/java/net/starlark/java/eval/testdata/json.star b/src/test/java/net/starlark/java/eval/testdata/json.star
index 51180b44860b2d..ff43163505cf78 100644
--- a/src/test/java/net/starlark/java/eval/testdata/json.star
+++ b/src/test/java/net/starlark/java/eval/testdata/json.star
@@ -80,6 +80,9 @@ assert_eq(json.decode('"\\u0123"'), 'ģ')
assert_eq(json.decode('\t[\t1,\r2,\n3]\n'), [1, 2, 3]) # whitespace other than ' '
assert_eq(json.decode('\n{\t"a":\r1\t}\n'), {'a': 1}) # same, with dict
assert_eq(json.decode(r'"\\\/\"\n\r\t"'), "\\/\"\n\r\t") # TODO(adonovan): test \b\f when Starlark/Java supports them
+assert_eq(json.decode('{"x": 1, "x": 2}'), {"x": 2})
+assert_eq(json.decode('{"x": {"y": 1, "y": 2}}'), {"x": {"y": 2}})
+assert_eq(json.decode('{"x": {"y": 1, "z": 1}, "x": {"y": 2}}'), {"x": {"y": 2}})
# We accept UTF-16 strings that have been arbitrarily truncated,
# as many Java and JavaScript programs emit them.
@@ -123,7 +126,6 @@ assert_fails(lambda: json.decode('[1, 2}'), "got \"}\", want ',' or ']'")
assert_fails(lambda: json.decode('{"one": 1'), "unexpected end of file")
assert_fails(lambda: json.decode('{"one" 1'), 'after object key, got "1", want \':\'')
assert_fails(lambda: json.decode('{"one": 1 "two": 2'), "in object, got ..\"., want ',' or '}'")
-assert_fails(lambda: json.decode('{"x": 1, "x": 2}'), 'object has duplicate key: "x"')
assert_fails(lambda: json.decode('{1:2}'), "got int for object key, want string")
assert_fails(lambda: json.decode('{"one": 1,'), "unexpected end of file")
assert_fails(lambda: json.decode('{"one": 1, }'), 'unexpected character "}"')
| train | test | 2023-03-23T12:59:27 | "2022-06-02T13:20:25Z" | alexeagle | test |
bazelbuild/bazel/17101_17934 | bazelbuild/bazel | bazelbuild/bazel/17101 | bazelbuild/bazel/17934 | [
"keyword_pr_to_issue"
] | d24f7cb0d98dc1f9b6eeada726d38424b94d72e6 | 3ea18cc033ed078f83fc6644c9d20fb69d6d2657 | [
"@meteorcloudy @Wyverald I would be interested in hearing your thoughts on whether this should be possible.",
"Can you explain a bit why having `dev_dependency` for the module extension proxy call isn't enough? Under which use case, do we have to share dev and non-dev dependencies with the same module extension proxy call? ",
"Having the `dev_dependency` parameter on `use_extension` is indeed enough as users can just create a new proxy when they want to add a different type of dependency.\n\nThis feature request is only about making the information that a certain proxy (in particular, the set of tags created with it) was created with `dev_dependency = True` available to the module extension. \n\nThe very concrete use case I have for this information is the `auto_use_repo` idea mentioned in #17048. If a module extension wants to emit the correct `use_repo` calls that should be made in the root module's `MODULE.bazel`, it has to be able to distinguish tags from dev and non-dev proxies.",
"I understand the idea of `auto_use_repo`, but have no idea how it should work (neither on how Gazelle's `update-repos` rep o works). I thought since the tags can only be used via the extension proxy created by `use_extension`, we shouldn't need the `dev_dependency = True` on tags?",
"Let's consider the following example `MODULE.bazel` of a root module:\r\n\r\n```\r\nfoo_deps = use_extension(\"@rules_foo//foo:extensions.bzl\", \"foo_deps\")\r\nfoo_deps.package(name = \"fmt\")\r\nfoo_deps.package(name = \"json\")\r\n# Managed by auto_use_repo\r\nuse_repo(foo_deps, \"fmt\", \"json\")\r\n\r\nfoo_dev_deps = use_extension(\"@rules_foo//foo:extensions.bzl\", \"foo_deps\", dev_dependency = True)\r\nfoo_dev_deps.package(name = \"testing\")\r\n# Managed by auto_use_repo\r\nuse_repo(foo_dev_deps, \"testing\")\r\n```\r\n\r\nIn this situation, the `foo_deps` extension would create a repository with a file that contains a list of all repos added due to tags defined by the root module. `auto_use_repo` could consume the list and ensure that the `use_repo` calls are up to date.\r\n\r\nHowever, with the currently available features, `foo_deps` can't know that `testing` is a dev dependency and should thus be added to the `use_repo(foo_dev_deps, ...)` call whereas `fmt` is a regular dependency and thus has to be added to the `use_repo(foo_deps, ...)` call.\r\n\r\nOne way to fulfill this feature request would be to add `module_ctx.is_dev_dependency(module_tag)`, which would return `True` if and only if the argument is a module tag created by a module extension proxy in turn created by a call to `use_extension` with `dev_dependency = True`. If that were available, `foo_deps` could create the following `repositories.json` file that `auto_use_repo` could use to add the used repositories to the correct `use_repo` call:\r\n\r\n```json\r\n[{\"name\": \"fmt\"}, {\"name\": \"json\"}, {\"name\": \"testing\", \"dev_dependency\": true}]\r\n```\r\n\r\nI expect this to be useful in other situation, such as if `foo_deps` wants to add usage or license metadata to the repositories it creates.",
"Thanks for the example -- that helped me understand the use case better. I'd like to think a bit more about how the API should look like.",
"Thanks!! Do I understand it correctly that we probably don't need to add `dev_dependency` to the `tag` API, but implementing `module_ctx.is_dev_dependency` is enough?",
"> Thanks!! Do I understand it correctly that we probably don't need to add `dev_dependency` to the `tag` API, but implementing `module_ctx.is_dev_dependency` is enough?\r\n\r\nYes, exactly. Tags are already implicitly dev dependencies if they come from a proxy that is marked with `dev_dependency`, so I don't think adding `dev_dependency` to tags would increase expressivity.\r\n",
"Thank you for contributing to the Bazel repository! This issue has been marked as stale since it has not had any activity in the last 30 days. It will be closed in the next 7 days unless any other activity occurs or one of the following labels is added: \"not stale\", \"awaiting-bazeler\".",
"Not stale",
"@bazel-io fork 6.2.0"
] | [] | "2023-03-30T20:13:02Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Allow module extensions to check whether a tag is a dev dependency | ### Description of the feature request:
With Bzlmod, a module extension should be able to check whether the extension proxy that was used to add a given module tag had `dev_dependency = True` or not.
### What underlying problem are you trying to solve with this feature?
While this information isn't directly required to resolve dependencies, the distinction in prod and dev dependencies becomes important in a umber of situations:
1. A module extension may want to emit a list of repos the root module should bring into scope with `use_repo`, but dev dependencies have to be brought into scope with a `use_repo` call on a module extension proxy created with `dev_dependency = True`.
2. Module extensions wrapping external package managers may want to use this information when associating license metadata with packages.
### Which operating system are you running Bazel on?
Any
### What is the output of `bazel info release`?
6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
https://github.com/bazelbuild/bazel/issues/17048
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
index 6dbf5e3e4a6748..0cf2fd58a9a15d 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
@@ -24,6 +24,8 @@
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import java.util.Map;
import javax.annotation.Nullable;
+import net.starlark.java.annot.Param;
+import net.starlark.java.annot.ParamType;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
@@ -99,4 +101,20 @@ protected ImmutableMap<String, String> getRemoteExecProperties() throws EvalExce
public StarlarkList<StarlarkBazelModule> getModules() {
return modules;
}
+
+ @StarlarkMethod(
+ name = "is_dev_dependency",
+ doc =
+ "Returns whether the given tag was specified on the result of a <a "
+ + "href=\"globals.html#use_extension\">use_extension</a> call with "
+ + "<code>devDependency = True</code>.",
+ parameters = {
+ @Param(
+ name = "tag",
+ doc = "A tag obtained from <a href=\"bazel_module.html#tags\">bazel_module.tags</a>.",
+ allowedTypes = {@ParamType(type = TypeCheckedTag.class)})
+ })
+ public boolean isDevDependency(TypeCheckedTag tag) {
+ return tag.isDevDependency();
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
index 3ff8e9e65933a8..d48359d212a605 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
@@ -25,6 +25,7 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.docgen.annot.DocumentMethods;
+import com.google.devtools.build.lib.bazel.bzlmod.ModuleFileGlobals.ModuleExtensionUsageBuilder.ModuleExtensionProxy;
import com.google.devtools.build.lib.bazel.bzlmod.Version.ParseException;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import java.util.ArrayList;
@@ -63,7 +64,7 @@ public class ModuleFileGlobals {
private final boolean ignoreDevDeps;
private final Module.Builder module;
private final Map<String, ModuleKey> deps = new LinkedHashMap<>();
- private final List<ModuleExtensionProxy> extensionProxies = new ArrayList<>();
+ private final List<ModuleExtensionUsageBuilder> extensionUsageBuilders = new ArrayList<>();
private final Map<String, ModuleOverride> overrides = new HashMap<>();
private final Map<String, RepoNameUsage> repoNameUsages = new HashMap<>();
@@ -373,38 +374,37 @@ public void registerToolchains(Sequence<?> toolchainLabels) throws EvalException
},
useStarlarkThread = true)
public ModuleExtensionProxy useExtension(
- String extensionBzlFile, String extensionName, boolean devDependency, StarlarkThread thread)
- throws EvalException {
- ModuleExtensionProxy newProxy =
- new ModuleExtensionProxy(extensionBzlFile, extensionName, thread.getCallerLocation());
+ String extensionBzlFile, String extensionName, boolean devDependency, StarlarkThread thread) {
+ ModuleExtensionUsageBuilder newUsageBuilder =
+ new ModuleExtensionUsageBuilder(
+ extensionBzlFile, extensionName, thread.getCallerLocation());
if (ignoreDevDeps && devDependency) {
// This is a no-op proxy.
- return newProxy;
+ return newUsageBuilder.getProxy(devDependency);
}
- // Find an existing proxy object corresponding to this extension.
- for (ModuleExtensionProxy proxy : extensionProxies) {
- if (proxy.extensionBzlFile.equals(extensionBzlFile)
- && proxy.extensionName.equals(extensionName)) {
- return proxy;
+ // Find an existing usage builder corresponding to this extension.
+ for (ModuleExtensionUsageBuilder usageBuilder : extensionUsageBuilders) {
+ if (usageBuilder.extensionBzlFile.equals(extensionBzlFile)
+ && usageBuilder.extensionName.equals(extensionName)) {
+ return usageBuilder.getProxy(devDependency);
}
}
// If no such proxy exists, we can just use a new one.
- extensionProxies.add(newProxy);
- return newProxy;
+ extensionUsageBuilders.add(newUsageBuilder);
+ return newUsageBuilder.getProxy(devDependency);
}
- @StarlarkBuiltin(name = "module_extension_proxy", documented = false)
- class ModuleExtensionProxy implements Structure {
+ class ModuleExtensionUsageBuilder {
private final String extensionBzlFile;
private final String extensionName;
private final Location location;
private final HashBiMap<String, String> imports;
private final ImmutableList.Builder<Tag> tags;
- ModuleExtensionProxy(String extensionBzlFile, String extensionName, Location location) {
+ ModuleExtensionUsageBuilder(String extensionBzlFile, String extensionName, Location location) {
this.extensionBzlFile = extensionBzlFile;
this.extensionName = extensionName;
this.location = location;
@@ -422,50 +422,69 @@ ModuleExtensionUsage buildUsage() {
.build();
}
- void addImport(String localRepoName, String exportedName, Location location)
- throws EvalException {
- RepositoryName.validateUserProvidedRepoName(localRepoName);
- RepositoryName.validateUserProvidedRepoName(exportedName);
- addRepoNameUsage(localRepoName, "by a use_repo() call", location);
- if (imports.containsValue(exportedName)) {
- String collisionRepoName = imports.inverse().get(exportedName);
- throw Starlark.errorf(
- "The repo exported as '%s' by module extension '%s' is already imported at %s",
- exportedName, extensionName, repoNameUsages.get(collisionRepoName).getWhere());
- }
- imports.put(localRepoName, exportedName);
+ /**
+ * Creates a proxy with the specified dev_dependency bit that shares accumulated imports and
+ * tags with all other such proxies, thus preserving their order across dev/non-dev deps.
+ */
+ ModuleExtensionProxy getProxy(boolean devDependency) {
+ return new ModuleExtensionProxy(devDependency);
}
- @Nullable
- @Override
- public Object getValue(String tagName) throws EvalException {
- return new StarlarkValue() {
- @StarlarkMethod(
- name = "call",
- selfCall = true,
- documented = false,
- extraKeywords = @Param(name = "kwargs"),
- useStarlarkThread = true)
- public void call(Dict<String, Object> kwargs, StarlarkThread thread) {
- tags.add(
- Tag.builder()
- .setTagName(tagName)
- .setAttributeValues(kwargs)
- .setLocation(thread.getCallerLocation())
- .build());
+ @StarlarkBuiltin(name = "module_extension_proxy", documented = false)
+ class ModuleExtensionProxy implements Structure {
+
+ private final boolean devDependency;
+
+ private ModuleExtensionProxy(boolean devDependency) {
+ this.devDependency = devDependency;
+ }
+
+ void addImport(String localRepoName, String exportedName, Location location)
+ throws EvalException {
+ RepositoryName.validateUserProvidedRepoName(localRepoName);
+ RepositoryName.validateUserProvidedRepoName(exportedName);
+ addRepoNameUsage(localRepoName, "by a use_repo() call", location);
+ if (imports.containsValue(exportedName)) {
+ String collisionRepoName = imports.inverse().get(exportedName);
+ throw Starlark.errorf(
+ "The repo exported as '%s' by module extension '%s' is already imported at %s",
+ exportedName, extensionName, repoNameUsages.get(collisionRepoName).getWhere());
}
- };
- }
+ imports.put(localRepoName, exportedName);
+ }
- @Override
- public ImmutableCollection<String> getFieldNames() {
- return ImmutableList.of();
- }
+ @Nullable
+ @Override
+ public Object getValue(String tagName) throws EvalException {
+ return new StarlarkValue() {
+ @StarlarkMethod(
+ name = "call",
+ selfCall = true,
+ documented = false,
+ extraKeywords = @Param(name = "kwargs"),
+ useStarlarkThread = true)
+ public void call(Dict<String, Object> kwargs, StarlarkThread thread) {
+ tags.add(
+ Tag.builder()
+ .setTagName(tagName)
+ .setAttributeValues(kwargs)
+ .setDevDependency(devDependency)
+ .setLocation(thread.getCallerLocation())
+ .build());
+ }
+ };
+ }
- @Nullable
- @Override
- public String getErrorMessageForUnknownField(String field) {
- return null;
+ @Override
+ public ImmutableCollection<String> getFieldNames() {
+ return ImmutableList.of();
+ }
+
+ @Nullable
+ @Override
+ public String getErrorMessageForUnknownField(String field) {
+ return null;
+ }
}
}
@@ -821,8 +840,8 @@ public Module buildModule() {
.setDeps(ImmutableMap.copyOf(deps))
.setOriginalDeps(ImmutableMap.copyOf(deps))
.setExtensionUsages(
- extensionProxies.stream()
- .map(ModuleExtensionProxy::buildUsage)
+ extensionUsageBuilders.stream()
+ .map(ModuleExtensionUsageBuilder::buildUsage)
.collect(toImmutableList()))
.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
index 6d89b5a778cc29..498aacd427c49a 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
@@ -33,6 +33,9 @@ public abstract class Tag {
/** All keyword arguments supplied to the tag instance. */
public abstract Dict<String, Object> getAttributeValues();
+ /** Whether this tag was created using a proxy created with dev_dependency = True. */
+ public abstract boolean isDevDependency();
+
/** The source location in the module file where this tag was created. */
public abstract Location getLocation();
@@ -48,6 +51,8 @@ public abstract static class Builder {
public abstract Builder setAttributeValues(Dict<String, Object> value);
+ public abstract Builder setDevDependency(boolean value);
+
public abstract Builder setLocation(Location value);
public abstract Tag build();
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
index 30c52dc3b97a77..54261a2349f863 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
@@ -34,10 +34,12 @@
public class TypeCheckedTag implements Structure {
private final TagClass tagClass;
private final Object[] attrValues;
+ private final boolean devDependency;
- private TypeCheckedTag(TagClass tagClass, Object[] attrValues) {
+ private TypeCheckedTag(TagClass tagClass, Object[] attrValues, boolean devDependency) {
this.tagClass = tagClass;
this.attrValues = attrValues;
+ this.devDependency = devDependency;
}
/** Creates a {@link TypeCheckedTag}. */
@@ -95,7 +97,15 @@ public static TypeCheckedTag create(TagClass tagClass, Tag tag, LabelConverter l
attrValues[i] = Attribute.valueToStarlark(attr.getDefaultValueUnchecked());
}
}
- return new TypeCheckedTag(tagClass, attrValues);
+ return new TypeCheckedTag(tagClass, attrValues, tag.isDevDependency());
+ }
+
+ /**
+ * Whether the tag was specified on an extension proxy created with <code>dev_dependency=True
+ * </code>.
+ */
+ public boolean isDevDependency() {
+ return devDependency;
}
@Override
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
index cc4dbaba79f53b..2af63ead6d9d35 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
@@ -283,6 +283,7 @@ public static TagClass createTagClass(Attribute... attrs) {
public static class TestTagBuilder {
private final Dict.Builder<String, Object> attrValuesBuilder = Dict.builder();
private final String tagName;
+ private boolean devDependency = false;
private TestTagBuilder(String tagName) {
this.tagName = tagName;
@@ -294,11 +295,18 @@ public TestTagBuilder addAttr(String attrName, Object attrValue) {
return this;
}
+ @CanIgnoreReturnValue
+ public TestTagBuilder setDevDependency() {
+ devDependency = true;
+ return this;
+ }
+
public Tag build() {
return Tag.builder()
.setTagName(tagName)
.setLocation(Location.BUILTIN)
.setAttributeValues(attrValuesBuilder.buildImmutable())
+ .setDevDependency(devDependency)
.build();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
index f8ad86388377d7..69b3adba649dc4 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
@@ -446,7 +446,7 @@ public void multipleModules_devDependency() throws Exception {
" data_str = 'modules:'",
" for mod in ctx.modules:",
" for tag in mod.tags.tag:",
- " data_str += ' ' + tag.data",
+ " data_str += ' ' + tag.data + ' ' + str(ctx.is_dev_dependency(tag))",
" data_repo(name='ext_repo',data=data_str)",
"tag=tag_class(attrs={'data':attr.string()})",
"ext=module_extension(implementation=_ext_impl,tag_classes={'tag':tag})");
@@ -457,7 +457,8 @@ public void multipleModules_devDependency() throws Exception {
if (result.hasError()) {
throw result.getError().getException();
}
- assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("modules: root [email protected]");
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo("modules: root True [email protected] False");
}
@Test
@@ -497,7 +498,7 @@ public void multipleModules_ignoreDevDependency() throws Exception {
" data_str = 'modules:'",
" for mod in ctx.modules:",
" for tag in mod.tags.tag:",
- " data_str += ' ' + tag.data",
+ " data_str += ' ' + tag.data + ' ' + str(ctx.is_dev_dependency(tag))",
" data_repo(name='ext_repo',data=data_str)",
"tag=tag_class(attrs={'data':attr.string()})",
"ext=module_extension(implementation=_ext_impl,tag_classes={'tag':tag})");
@@ -511,7 +512,8 @@ public void multipleModules_ignoreDevDependency() throws Exception {
if (result.hasError()) {
throw result.getError().getException();
}
- assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("modules: [email protected]");
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo("modules: [email protected] False");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
index 7da2e62ffe4098..bbdeb0d4d4d33a 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
@@ -484,6 +484,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key", "val")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 4, 11))
.build())
@@ -501,6 +502,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key1", "val1")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 7, 12))
.build())
@@ -511,6 +513,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key2", "val2")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 8, 12))
.build())
@@ -529,6 +532,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("coord", "junit")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 12, 10))
.build())
@@ -539,6 +543,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("coord", "guava")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 14, 10))
.build())
@@ -551,12 +556,16 @@ public void testModuleExtensions_duplicateProxy_asRoot() throws Exception {
scratch.file(
rootDirectory.getRelative("MODULE.bazel").getPathString(),
"myext1 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext1.tag(name = 'tag1')",
"use_repo(myext1, 'alpha')",
"myext2 = use_extension('//:defs.bzl','myext')",
+ "myext2.tag(name = 'tag2')",
"use_repo(myext2, 'beta')",
"myext3 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext3.tag(name = 'tag3')",
"use_repo(myext3, 'gamma')",
"myext4 = use_extension('//:defs.bzl','myext')",
+ "myext4.tag(name = 'tag4')",
"use_repo(myext4, 'delta')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of());
@@ -580,6 +589,50 @@ public void testModuleExtensions_duplicateProxy_asRoot() throws Exception {
ImmutableBiMap.of(
"alpha", "alpha", "beta", "beta", "gamma", "gamma", "delta",
"delta"))
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag1")
+ .buildImmutable())
+ .setDevDependency(true)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 2, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag2")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 5, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag3")
+ .buildImmutable())
+ .setDevDependency(true)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 8, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag4")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 11, 11))
+ .build())
.build())
.build());
}
@@ -593,12 +646,16 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
createModuleKey("mymod", "1.0"),
"module(name='mymod',version='1.0')",
"myext1 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext1.tag(name = 'tag1')",
"use_repo(myext1, 'alpha')",
"myext2 = use_extension('//:defs.bzl','myext')",
+ "myext2.tag(name = 'tag2')",
"use_repo(myext2, 'beta')",
"myext3 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext3.tag(name = 'tag3')",
"use_repo(myext3, 'gamma')",
"myext4 = use_extension('//:defs.bzl','myext')",
+ "myext4.tag(name = 'tag4')",
"use_repo(myext4, 'delta')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
@@ -617,8 +674,30 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
ModuleExtensionUsage.builder()
.setExtensionBzlFile("//:defs.bzl")
.setExtensionName("myext")
- .setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 4, 23))
+ .setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 5, 23))
.setImports(ImmutableBiMap.of("beta", "beta", "delta", "delta"))
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag2")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("[email protected]/MODULE.bazel", 6, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag4")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("[email protected]/MODULE.bazel", 12, 11))
+ .build())
.build())
.build());
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
index f6eec3267f87d8..1151480aaee6e3 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
@@ -61,10 +61,11 @@ public void basic() throws Exception {
TypeCheckedTag typeCheckedTag =
TypeCheckedTag.create(
createTagClass(attr("foo", Type.INTEGER).build()),
- buildTag("tag_name").addAttr("foo", StarlarkInt.of(3)).build(),
- /*labelConverter=*/ null);
+ buildTag("tag_name").addAttr("foo", StarlarkInt.of(3)).setDevDependency().build(),
+ /* labelConverter= */ null);
assertThat(typeCheckedTag.getFieldNames()).containsExactly("foo");
assertThat(getattr(typeCheckedTag, "foo")).isEqualTo(StarlarkInt.of(3));
+ assertThat(typeCheckedTag.isDevDependency()).isTrue();
}
@Test
@@ -87,6 +88,7 @@ public void label() throws Exception {
Label.parseAbsoluteUnchecked("@myrepo//mypkg:thing1"),
Label.parseAbsoluteUnchecked("@myrepo//pkg:thing2"),
Label.parseAbsoluteUnchecked("@other_repo//pkg:thing3")));
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
@@ -95,12 +97,13 @@ public void label_withoutDefaultValue() throws Exception {
TypeCheckedTag.create(
createTagClass(
attr("foo", BuildType.LABEL).allowedFileTypes(FileTypeSet.ANY_FILE).build()),
- buildTag("tag_name").build(),
+ buildTag("tag_name").setDevDependency().build(),
new LabelConverter(
PackageIdentifier.parse("@myrepo//mypkg"),
createRepositoryMapping(createModuleKey("test", "1.0"), "repo", "other_repo")));
assertThat(typeCheckedTag.getFieldNames()).containsExactly("foo");
assertThat(getattr(typeCheckedTag, "foo")).isEqualTo(Starlark.NONE);
+ assertThat(typeCheckedTag.isDevDependency()).isTrue();
}
@Test
@@ -119,6 +122,7 @@ public void stringListDict_default() throws Exception {
Dict.builder()
.put("key", StarlarkList.immutableOf("value1", "value2"))
.buildImmutable());
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
@@ -139,6 +143,7 @@ public void multipleAttributesAndDefaults() throws Exception {
assertThat(getattr(typeCheckedTag, "bar")).isEqualTo(StarlarkInt.of(3));
assertThat(getattr(typeCheckedTag, "quux"))
.isEqualTo(StarlarkList.immutableOf("quuxValue1", "quuxValue2"));
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
| val | test | 2023-03-31T16:55:22 | "2023-01-01T11:04:26Z" | fmeum | test |
bazelbuild/bazel/17908_17934 | bazelbuild/bazel | bazelbuild/bazel/17908 | bazelbuild/bazel/17934 | [
"keyword_pr_to_issue"
] | d24f7cb0d98dc1f9b6eeada726d38424b94d72e6 | 3ea18cc033ed078f83fc6644c9d20fb69d6d2657 | [] | [] | "2023-03-30T20:13:02Z" | [
"P1",
"type: process",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Automatic use_repo fixups for module extensions" | Proposal: https://docs.google.com/document/d/1dj8SN5L6nwhNOufNqjBhYkk5f-BJI_FPYWKxlB3GAmA/edit | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
index 6dbf5e3e4a6748..0cf2fd58a9a15d 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
@@ -24,6 +24,8 @@
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import java.util.Map;
import javax.annotation.Nullable;
+import net.starlark.java.annot.Param;
+import net.starlark.java.annot.ParamType;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
@@ -99,4 +101,20 @@ protected ImmutableMap<String, String> getRemoteExecProperties() throws EvalExce
public StarlarkList<StarlarkBazelModule> getModules() {
return modules;
}
+
+ @StarlarkMethod(
+ name = "is_dev_dependency",
+ doc =
+ "Returns whether the given tag was specified on the result of a <a "
+ + "href=\"globals.html#use_extension\">use_extension</a> call with "
+ + "<code>devDependency = True</code>.",
+ parameters = {
+ @Param(
+ name = "tag",
+ doc = "A tag obtained from <a href=\"bazel_module.html#tags\">bazel_module.tags</a>.",
+ allowedTypes = {@ParamType(type = TypeCheckedTag.class)})
+ })
+ public boolean isDevDependency(TypeCheckedTag tag) {
+ return tag.isDevDependency();
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
index 3ff8e9e65933a8..d48359d212a605 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
@@ -25,6 +25,7 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.docgen.annot.DocumentMethods;
+import com.google.devtools.build.lib.bazel.bzlmod.ModuleFileGlobals.ModuleExtensionUsageBuilder.ModuleExtensionProxy;
import com.google.devtools.build.lib.bazel.bzlmod.Version.ParseException;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import java.util.ArrayList;
@@ -63,7 +64,7 @@ public class ModuleFileGlobals {
private final boolean ignoreDevDeps;
private final Module.Builder module;
private final Map<String, ModuleKey> deps = new LinkedHashMap<>();
- private final List<ModuleExtensionProxy> extensionProxies = new ArrayList<>();
+ private final List<ModuleExtensionUsageBuilder> extensionUsageBuilders = new ArrayList<>();
private final Map<String, ModuleOverride> overrides = new HashMap<>();
private final Map<String, RepoNameUsage> repoNameUsages = new HashMap<>();
@@ -373,38 +374,37 @@ public void registerToolchains(Sequence<?> toolchainLabels) throws EvalException
},
useStarlarkThread = true)
public ModuleExtensionProxy useExtension(
- String extensionBzlFile, String extensionName, boolean devDependency, StarlarkThread thread)
- throws EvalException {
- ModuleExtensionProxy newProxy =
- new ModuleExtensionProxy(extensionBzlFile, extensionName, thread.getCallerLocation());
+ String extensionBzlFile, String extensionName, boolean devDependency, StarlarkThread thread) {
+ ModuleExtensionUsageBuilder newUsageBuilder =
+ new ModuleExtensionUsageBuilder(
+ extensionBzlFile, extensionName, thread.getCallerLocation());
if (ignoreDevDeps && devDependency) {
// This is a no-op proxy.
- return newProxy;
+ return newUsageBuilder.getProxy(devDependency);
}
- // Find an existing proxy object corresponding to this extension.
- for (ModuleExtensionProxy proxy : extensionProxies) {
- if (proxy.extensionBzlFile.equals(extensionBzlFile)
- && proxy.extensionName.equals(extensionName)) {
- return proxy;
+ // Find an existing usage builder corresponding to this extension.
+ for (ModuleExtensionUsageBuilder usageBuilder : extensionUsageBuilders) {
+ if (usageBuilder.extensionBzlFile.equals(extensionBzlFile)
+ && usageBuilder.extensionName.equals(extensionName)) {
+ return usageBuilder.getProxy(devDependency);
}
}
// If no such proxy exists, we can just use a new one.
- extensionProxies.add(newProxy);
- return newProxy;
+ extensionUsageBuilders.add(newUsageBuilder);
+ return newUsageBuilder.getProxy(devDependency);
}
- @StarlarkBuiltin(name = "module_extension_proxy", documented = false)
- class ModuleExtensionProxy implements Structure {
+ class ModuleExtensionUsageBuilder {
private final String extensionBzlFile;
private final String extensionName;
private final Location location;
private final HashBiMap<String, String> imports;
private final ImmutableList.Builder<Tag> tags;
- ModuleExtensionProxy(String extensionBzlFile, String extensionName, Location location) {
+ ModuleExtensionUsageBuilder(String extensionBzlFile, String extensionName, Location location) {
this.extensionBzlFile = extensionBzlFile;
this.extensionName = extensionName;
this.location = location;
@@ -422,50 +422,69 @@ ModuleExtensionUsage buildUsage() {
.build();
}
- void addImport(String localRepoName, String exportedName, Location location)
- throws EvalException {
- RepositoryName.validateUserProvidedRepoName(localRepoName);
- RepositoryName.validateUserProvidedRepoName(exportedName);
- addRepoNameUsage(localRepoName, "by a use_repo() call", location);
- if (imports.containsValue(exportedName)) {
- String collisionRepoName = imports.inverse().get(exportedName);
- throw Starlark.errorf(
- "The repo exported as '%s' by module extension '%s' is already imported at %s",
- exportedName, extensionName, repoNameUsages.get(collisionRepoName).getWhere());
- }
- imports.put(localRepoName, exportedName);
+ /**
+ * Creates a proxy with the specified dev_dependency bit that shares accumulated imports and
+ * tags with all other such proxies, thus preserving their order across dev/non-dev deps.
+ */
+ ModuleExtensionProxy getProxy(boolean devDependency) {
+ return new ModuleExtensionProxy(devDependency);
}
- @Nullable
- @Override
- public Object getValue(String tagName) throws EvalException {
- return new StarlarkValue() {
- @StarlarkMethod(
- name = "call",
- selfCall = true,
- documented = false,
- extraKeywords = @Param(name = "kwargs"),
- useStarlarkThread = true)
- public void call(Dict<String, Object> kwargs, StarlarkThread thread) {
- tags.add(
- Tag.builder()
- .setTagName(tagName)
- .setAttributeValues(kwargs)
- .setLocation(thread.getCallerLocation())
- .build());
+ @StarlarkBuiltin(name = "module_extension_proxy", documented = false)
+ class ModuleExtensionProxy implements Structure {
+
+ private final boolean devDependency;
+
+ private ModuleExtensionProxy(boolean devDependency) {
+ this.devDependency = devDependency;
+ }
+
+ void addImport(String localRepoName, String exportedName, Location location)
+ throws EvalException {
+ RepositoryName.validateUserProvidedRepoName(localRepoName);
+ RepositoryName.validateUserProvidedRepoName(exportedName);
+ addRepoNameUsage(localRepoName, "by a use_repo() call", location);
+ if (imports.containsValue(exportedName)) {
+ String collisionRepoName = imports.inverse().get(exportedName);
+ throw Starlark.errorf(
+ "The repo exported as '%s' by module extension '%s' is already imported at %s",
+ exportedName, extensionName, repoNameUsages.get(collisionRepoName).getWhere());
}
- };
- }
+ imports.put(localRepoName, exportedName);
+ }
- @Override
- public ImmutableCollection<String> getFieldNames() {
- return ImmutableList.of();
- }
+ @Nullable
+ @Override
+ public Object getValue(String tagName) throws EvalException {
+ return new StarlarkValue() {
+ @StarlarkMethod(
+ name = "call",
+ selfCall = true,
+ documented = false,
+ extraKeywords = @Param(name = "kwargs"),
+ useStarlarkThread = true)
+ public void call(Dict<String, Object> kwargs, StarlarkThread thread) {
+ tags.add(
+ Tag.builder()
+ .setTagName(tagName)
+ .setAttributeValues(kwargs)
+ .setDevDependency(devDependency)
+ .setLocation(thread.getCallerLocation())
+ .build());
+ }
+ };
+ }
- @Nullable
- @Override
- public String getErrorMessageForUnknownField(String field) {
- return null;
+ @Override
+ public ImmutableCollection<String> getFieldNames() {
+ return ImmutableList.of();
+ }
+
+ @Nullable
+ @Override
+ public String getErrorMessageForUnknownField(String field) {
+ return null;
+ }
}
}
@@ -821,8 +840,8 @@ public Module buildModule() {
.setDeps(ImmutableMap.copyOf(deps))
.setOriginalDeps(ImmutableMap.copyOf(deps))
.setExtensionUsages(
- extensionProxies.stream()
- .map(ModuleExtensionProxy::buildUsage)
+ extensionUsageBuilders.stream()
+ .map(ModuleExtensionUsageBuilder::buildUsage)
.collect(toImmutableList()))
.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
index 6d89b5a778cc29..498aacd427c49a 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Tag.java
@@ -33,6 +33,9 @@ public abstract class Tag {
/** All keyword arguments supplied to the tag instance. */
public abstract Dict<String, Object> getAttributeValues();
+ /** Whether this tag was created using a proxy created with dev_dependency = True. */
+ public abstract boolean isDevDependency();
+
/** The source location in the module file where this tag was created. */
public abstract Location getLocation();
@@ -48,6 +51,8 @@ public abstract static class Builder {
public abstract Builder setAttributeValues(Dict<String, Object> value);
+ public abstract Builder setDevDependency(boolean value);
+
public abstract Builder setLocation(Location value);
public abstract Tag build();
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
index 30c52dc3b97a77..54261a2349f863 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTag.java
@@ -34,10 +34,12 @@
public class TypeCheckedTag implements Structure {
private final TagClass tagClass;
private final Object[] attrValues;
+ private final boolean devDependency;
- private TypeCheckedTag(TagClass tagClass, Object[] attrValues) {
+ private TypeCheckedTag(TagClass tagClass, Object[] attrValues, boolean devDependency) {
this.tagClass = tagClass;
this.attrValues = attrValues;
+ this.devDependency = devDependency;
}
/** Creates a {@link TypeCheckedTag}. */
@@ -95,7 +97,15 @@ public static TypeCheckedTag create(TagClass tagClass, Tag tag, LabelConverter l
attrValues[i] = Attribute.valueToStarlark(attr.getDefaultValueUnchecked());
}
}
- return new TypeCheckedTag(tagClass, attrValues);
+ return new TypeCheckedTag(tagClass, attrValues, tag.isDevDependency());
+ }
+
+ /**
+ * Whether the tag was specified on an extension proxy created with <code>dev_dependency=True
+ * </code>.
+ */
+ public boolean isDevDependency() {
+ return devDependency;
}
@Override
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
index cc4dbaba79f53b..2af63ead6d9d35 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BzlmodTestUtil.java
@@ -283,6 +283,7 @@ public static TagClass createTagClass(Attribute... attrs) {
public static class TestTagBuilder {
private final Dict.Builder<String, Object> attrValuesBuilder = Dict.builder();
private final String tagName;
+ private boolean devDependency = false;
private TestTagBuilder(String tagName) {
this.tagName = tagName;
@@ -294,11 +295,18 @@ public TestTagBuilder addAttr(String attrName, Object attrValue) {
return this;
}
+ @CanIgnoreReturnValue
+ public TestTagBuilder setDevDependency() {
+ devDependency = true;
+ return this;
+ }
+
public Tag build() {
return Tag.builder()
.setTagName(tagName)
.setLocation(Location.BUILTIN)
.setAttributeValues(attrValuesBuilder.buildImmutable())
+ .setDevDependency(devDependency)
.build();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
index f8ad86388377d7..69b3adba649dc4 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
@@ -446,7 +446,7 @@ public void multipleModules_devDependency() throws Exception {
" data_str = 'modules:'",
" for mod in ctx.modules:",
" for tag in mod.tags.tag:",
- " data_str += ' ' + tag.data",
+ " data_str += ' ' + tag.data + ' ' + str(ctx.is_dev_dependency(tag))",
" data_repo(name='ext_repo',data=data_str)",
"tag=tag_class(attrs={'data':attr.string()})",
"ext=module_extension(implementation=_ext_impl,tag_classes={'tag':tag})");
@@ -457,7 +457,8 @@ public void multipleModules_devDependency() throws Exception {
if (result.hasError()) {
throw result.getError().getException();
}
- assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("modules: root [email protected]");
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo("modules: root True [email protected] False");
}
@Test
@@ -497,7 +498,7 @@ public void multipleModules_ignoreDevDependency() throws Exception {
" data_str = 'modules:'",
" for mod in ctx.modules:",
" for tag in mod.tags.tag:",
- " data_str += ' ' + tag.data",
+ " data_str += ' ' + tag.data + ' ' + str(ctx.is_dev_dependency(tag))",
" data_repo(name='ext_repo',data=data_str)",
"tag=tag_class(attrs={'data':attr.string()})",
"ext=module_extension(implementation=_ext_impl,tag_classes={'tag':tag})");
@@ -511,7 +512,8 @@ public void multipleModules_ignoreDevDependency() throws Exception {
if (result.hasError()) {
throw result.getError().getException();
}
- assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("modules: [email protected]");
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo("modules: [email protected] False");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
index 7da2e62ffe4098..bbdeb0d4d4d33a 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
@@ -484,6 +484,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key", "val")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 4, 11))
.build())
@@ -501,6 +502,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key1", "val1")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 7, 12))
.build())
@@ -511,6 +513,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("key2", "val2")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 8, 12))
.build())
@@ -529,6 +532,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("coord", "junit")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 12, 10))
.build())
@@ -539,6 +543,7 @@ public void testModuleExtensions_good() throws Exception {
Dict.<String, Object>builder()
.put("coord", "guava")
.buildImmutable())
+ .setDevDependency(false)
.setLocation(
Location.fromFileLineColumn("[email protected]/MODULE.bazel", 14, 10))
.build())
@@ -551,12 +556,16 @@ public void testModuleExtensions_duplicateProxy_asRoot() throws Exception {
scratch.file(
rootDirectory.getRelative("MODULE.bazel").getPathString(),
"myext1 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext1.tag(name = 'tag1')",
"use_repo(myext1, 'alpha')",
"myext2 = use_extension('//:defs.bzl','myext')",
+ "myext2.tag(name = 'tag2')",
"use_repo(myext2, 'beta')",
"myext3 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext3.tag(name = 'tag3')",
"use_repo(myext3, 'gamma')",
"myext4 = use_extension('//:defs.bzl','myext')",
+ "myext4.tag(name = 'tag4')",
"use_repo(myext4, 'delta')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of());
@@ -580,6 +589,50 @@ public void testModuleExtensions_duplicateProxy_asRoot() throws Exception {
ImmutableBiMap.of(
"alpha", "alpha", "beta", "beta", "gamma", "gamma", "delta",
"delta"))
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag1")
+ .buildImmutable())
+ .setDevDependency(true)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 2, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag2")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 5, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag3")
+ .buildImmutable())
+ .setDevDependency(true)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 8, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag4")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("<root>/MODULE.bazel", 11, 11))
+ .build())
.build())
.build());
}
@@ -593,12 +646,16 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
createModuleKey("mymod", "1.0"),
"module(name='mymod',version='1.0')",
"myext1 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext1.tag(name = 'tag1')",
"use_repo(myext1, 'alpha')",
"myext2 = use_extension('//:defs.bzl','myext')",
+ "myext2.tag(name = 'tag2')",
"use_repo(myext2, 'beta')",
"myext3 = use_extension('//:defs.bzl','myext',dev_dependency=True)",
+ "myext3.tag(name = 'tag3')",
"use_repo(myext3, 'gamma')",
"myext4 = use_extension('//:defs.bzl','myext')",
+ "myext4.tag(name = 'tag4')",
"use_repo(myext4, 'delta')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
@@ -617,8 +674,30 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
ModuleExtensionUsage.builder()
.setExtensionBzlFile("//:defs.bzl")
.setExtensionName("myext")
- .setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 4, 23))
+ .setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 5, 23))
.setImports(ImmutableBiMap.of("beta", "beta", "delta", "delta"))
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag2")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("[email protected]/MODULE.bazel", 6, 11))
+ .build())
+ .addTag(
+ Tag.builder()
+ .setTagName("tag")
+ .setAttributeValues(
+ Dict.<String, Object>builder()
+ .put("name", "tag4")
+ .buildImmutable())
+ .setDevDependency(false)
+ .setLocation(
+ Location.fromFileLineColumn("[email protected]/MODULE.bazel", 12, 11))
+ .build())
.build())
.build());
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
index f6eec3267f87d8..1151480aaee6e3 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/TypeCheckedTagTest.java
@@ -61,10 +61,11 @@ public void basic() throws Exception {
TypeCheckedTag typeCheckedTag =
TypeCheckedTag.create(
createTagClass(attr("foo", Type.INTEGER).build()),
- buildTag("tag_name").addAttr("foo", StarlarkInt.of(3)).build(),
- /*labelConverter=*/ null);
+ buildTag("tag_name").addAttr("foo", StarlarkInt.of(3)).setDevDependency().build(),
+ /* labelConverter= */ null);
assertThat(typeCheckedTag.getFieldNames()).containsExactly("foo");
assertThat(getattr(typeCheckedTag, "foo")).isEqualTo(StarlarkInt.of(3));
+ assertThat(typeCheckedTag.isDevDependency()).isTrue();
}
@Test
@@ -87,6 +88,7 @@ public void label() throws Exception {
Label.parseAbsoluteUnchecked("@myrepo//mypkg:thing1"),
Label.parseAbsoluteUnchecked("@myrepo//pkg:thing2"),
Label.parseAbsoluteUnchecked("@other_repo//pkg:thing3")));
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
@@ -95,12 +97,13 @@ public void label_withoutDefaultValue() throws Exception {
TypeCheckedTag.create(
createTagClass(
attr("foo", BuildType.LABEL).allowedFileTypes(FileTypeSet.ANY_FILE).build()),
- buildTag("tag_name").build(),
+ buildTag("tag_name").setDevDependency().build(),
new LabelConverter(
PackageIdentifier.parse("@myrepo//mypkg"),
createRepositoryMapping(createModuleKey("test", "1.0"), "repo", "other_repo")));
assertThat(typeCheckedTag.getFieldNames()).containsExactly("foo");
assertThat(getattr(typeCheckedTag, "foo")).isEqualTo(Starlark.NONE);
+ assertThat(typeCheckedTag.isDevDependency()).isTrue();
}
@Test
@@ -119,6 +122,7 @@ public void stringListDict_default() throws Exception {
Dict.builder()
.put("key", StarlarkList.immutableOf("value1", "value2"))
.buildImmutable());
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
@@ -139,6 +143,7 @@ public void multipleAttributesAndDefaults() throws Exception {
assertThat(getattr(typeCheckedTag, "bar")).isEqualTo(StarlarkInt.of(3));
assertThat(getattr(typeCheckedTag, "quux"))
.isEqualTo(StarlarkList.immutableOf("quuxValue1", "quuxValue2"));
+ assertThat(typeCheckedTag.isDevDependency()).isFalse();
}
@Test
| train | test | 2023-03-31T16:55:22 | "2023-03-29T05:22:19Z" | fmeum | test |
bazelbuild/bazel/14723_18115 | bazelbuild/bazel | bazelbuild/bazel/14723 | bazelbuild/bazel/18115 | [
"keyword_pr_to_issue"
] | 6ba54ac0cde124d4e009f0fe6788e8a1e884fec9 | a35f59286a412ab2e1b838f858ee818451c21534 | [
"I just skimmed this, but at first glance that surprises me. Bazel should, generally, be correct for any changes. `team-Core` should be able to give you better insight.",
"Are you invoking Bazel with any special flags? `--cache_computed_file_digests` could cause this problem, although I would expect the node id to still catch that the file has changed. I used your test case on both Mac and Bazel, but couldn't reproduce:\r\n\r\n```\r\n$ bazel build //:expand1\r\nStarting local Bazel server and connecting to it...\r\nINFO: Analyzed target //:expand1 (5 packages loaded, 10 targets configured).\r\nINFO: Found 1 target...\r\nTarget //:expand1 up-to-date:\r\n bazel-bin/expanded1\r\nINFO: Elapsed time: 2.257s, Critical Path: 0.03s\r\nINFO: 3 processes: 2 internal, 1 linux-sandbox.\r\nINFO: Build completed successfully, 3 total actions\r\n$ cat bazel-bin/expanded1\r\nfoo : alpha\r\n$ cp template_archive_delta.tar template_archive.tar\r\n$ bazel build //:expand1\r\nINFO: Analyzed target //:expand1 (0 packages loaded, 0 targets configured).\r\nINFO: Found 1 target...\r\nTarget //:expand1 up-to-date:\r\n bazel-bin/expanded1\r\nINFO: Elapsed time: 0.124s, Critical Path: 0.01s\r\nINFO: 3 processes: 2 internal, 1 linux-sandbox.\r\nINFO: Build completed successfully, 3 total actions\r\n$ cat bazel-bin/expanded1\r\nfoo : delta\r\n$ ls -l bazel-bin/\r\ntotal 8\r\n-r-xr-xr-x 1 janakr primarygroup 12 Mar 8 12:25 expanded1\r\n-r-xr-xr-x 1 janakr primarygroup 13 Jan 1 1970 template1\r\n```",
"@janakdr On Linux, I was able to reproduce the issue with Bazel 4.1.0 and 4.2.0, but not 5.0.0.",
"Thanks @fmeum . Your original comment seems to be deleted, but you also correctly pointed out there that `--cache_computed_file_digests` has a default non-zero value in Bazel, which would mostly explain the issue (I just verified that the inodes are the same). @miscott2 is upgrading to 5.0 a reasonable solution for you? Separately we should understand what the difference between 4.2 and 5.0 is, to make sure that we're doing the right thing now.\r\n\r\nI see a potential area for improvement regardless: in most of Bazel, we use the [ctime](https://cs.github.com/bazelbuild/bazel/blob/3fc17f3c482592fbda95789d5bf5e8f7b8afbe6a/src/main/java/com/google/devtools/build/lib/actions/FileContentsProxy.java#L35) as part of our file data but for the digest cache we only use [mtime](https://cs.github.com/bazelbuild/bazel/blob/3fc17f3c482592fbda95789d5bf5e8f7b8afbe6a/src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java#L58). Adding ctime should make this cache more robust.",
"@janakdr I deleted my original comment because I noticed that setting `--cache_computed_file_digests=0` did *not* seem to reliably fix the issue for me - I didn't want to drop a red herring. This makes me all the more interested in finding out which change between 4.2 and 5.0 ended up fixing this. Do you plan to run a bisect?",
"Thanks everyone for your comments/efforts. Yes upgrading to Bazel 5.0 is absolutely fine as a solution for us as we were planning to do so imminently anyway.",
"Since I won't be able to work on this, I'm going to close, since a workaround exists. It would be nice to understand what went wrong in case it's still lurking, but I can't say the team should prioritize it.\r\n\r\ncc @alexjski for interest",
"I ran into a correctness issue under similar circumstances as the original issue with bazel 7.0.0-pre.20230316.2 + Linux 6.2.8 + sandbox_base pointing to tmpfs + ext4 . I built a tarball in a rule with a fixed mtime and then extracted it in another rule which lead to this issue when changing constants in a cpp file. Sometimes it would take 2 or 3 changes of the constant before the issue occurred. In my case, ```touch```ing the extracted output files was enough to fix the correctness issue. I tested with ```--cache_computed_file_digests=0``` and this also fixed the issue. Bazel relying on the mtime in this way is extremely surprising behaviour and should really be better documented (#14401) and honestly probably disabled by default. \r\n\r\n",
"I looked into this again and was able to reproduce the issue with Bazel 6.1.1 and last_green, but *not* with the original reproducer: In order to reproduce, I need to `mv` instead of `cp` the tar files between builds.\r\n\r\nIt looks like this is fixed by adding ctime to the cache key as suggested by @janakdr in https://github.com/bazelbuild/bazel/issues/14723#issuecomment-1062060278. I submitted #18003, which includes an integration test, but will have to investigate other test failures this causes.\r\n\r\n@meteorcloudy As this is an incremental correctness issue, a fix should probably go into the planned 5.4.1 and 6.1.2 releases.",
"@bazel-io flag",
"@bazel-io fork 6.2.0"
] | [] | "2023-04-17T14:51:19Z" | [
"type: bug",
"P1",
"more data needed",
"team-Core"
] | Action outputs with fixed timestamps cause problems | ### Description of the problem / feature request:
If an output file from a Bazel action has a fixed timestamp then if the content of the file change but the size of the file doesn't it won't trigger the re-running of any actions that depends on this file.
### Feature requests: what underlying problem are you trying to solve with this feature?
Some of the inputs to our build are archives containing template files that are expanded during the build. The archives are produced by another build system and to ensure that build system is reproducible the timestamps of the template files are set to 1970 in the archive. During the build we extract the templates files from the archive (retaining their timestamp as this is the default behavior of tar), expand the template and then use the expanded template in a further action. When we checkout a different refpoint of our code sometimes the archive has changed but the templates are still the same size and this results in actions not being re-run when they should be.
I understand that Bazel can't rehash all input files but I was a bit surprised that when an action is run that all output files are not rehashed. Perhaps this is too much of an edge case to worry about but I thought it was worth raising.
We've worked around the issue by not retaining timestamps when we extract files from the archives but wanted to check if Bazel should handle this.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Create a workspace with the following BUILD and .bzl files
```
$cat BUILD
load("rules.bzl", "my_expand")
genrule(
name = "my_templates",
srcs = ["template_archive.tar"],
outs = ["template1"],
cmd = "tar -C $(@D) -xf template_archive.tar",
)
my_expand(
name = "expand1",
input = "template1",
output = "expanded1",
to_sub = {"test":"foo"}
)
```
```
$cat rules.bzl
def _my_expand_impl(ctx):
ctx.actions.expand_template(
template = ctx.file.input,
output = ctx.outputs.output,
substitutions = ctx.attr.to_sub
)
my_expand = rule(
implementation = _my_expand_impl,
attrs = {
"input": attr.label(allow_single_file=True),
"output": attr.output(),
"to_sub" : attr.string_dict(),
}
)
```
Now create a set of archives with different template files
```
echo "test : alpha" > template1
tar -cf template_archive_alpha.tar --mtime='1970-01-01' template1
echo "test : delta" > template1
tar -cf template_archive_delta.tar --mtime='1970-01-01' template1
echo "test : beta" > template1
tar -cf template_archive_beta.tar --mtime='1970-01-01' template1
```
Put the alpha archive in place as the input, build and verify that the expanded template is as expected.
```
$cp template_archive_alpha.tar template_archive.tar
$bazel ...
INFO: Analyzed 2 targets (0 packages loaded, 0 targets configured).
INFO: Found 2 targets...
INFO: Elapsed time: 0.106s, Critical Path: 0.03s
INFO: 2 processes: 1 internal, 1 linux-sandbox.
INFO: Build completed successfully, 2 total actions
$cat bazel-bin/expanded1
foo : alpha
```
Switch to the delta archive as the input, build and verify that the expanded template has not been updated.
```
$cp template_archive_delta.tar template_archive.tar
$bazel ...
INFO: Analyzed 2 targets (0 packages loaded, 0 targets configured).
INFO: Found 2 targets...
INFO: Elapsed time: 0.095s, Critical Path: 0.03s
INFO: 2 processes: 1 internal, 1 linux-sandbox.
INFO: Build completed successfully, 2 total actions
$cat bazel-bin/expanded1
foo : alpha
```
Even though the extracted template has been updated
```
$cat bazel-bin/template1
test : delta
```
Verify that performing a Bazel clean and building results in the correct output.
```
$bazel clean
INFO: Starting clean (this may take a while). Consider using --async if the clean takes more than several minutes.
$bazel build ...
INFO: Analyzed 2 targets (5 packages loaded, 10 targets configured).
INFO: Found 2 targets...
INFO: Elapsed time: 0.186s, Critical Path: 0.03s
INFO: 3 processes: 2 internal, 1 linux-sandbox.
INFO: Build completed successfully, 3 total actions
$cat bazel-bin/expanded1
foo : delta
```
Switching to/from the alpha/delta archives and the beta archive works fine presumably because the size of the template files change (beta being 4 characters and alpha/delta being 5 characters).
### What operating system are you running Bazel on?
Linux
### What's the output of `bazel info release`?
release 4.1.0- (@non-git)
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
I don't have full details to hand about how we built Bazel but I'm confident that any changes have not impacted the behavior described above.
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
N/A
### Have you found anything relevant by searching the web?
No. I'm not even confident if Bazel should handle this scenario but I think it's worth asking.
### Any other information, logs, or outputs that you want to share?
No | [
"src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java",
"src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java",
"src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java",
"src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java",
"src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java",
"src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java",
"src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java",
"src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java",
"src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/test/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandlerTest.java",
"src/test/shell/integration/execution_phase_tests.sh",
"src/test/shell/integration/loading_phase_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java b/src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java
index 52464a9d342500..0d494b6cff6fd4 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandler.java
@@ -665,7 +665,8 @@ private static FileArtifactValue fileArtifactValueFromStat(
}
private static void setPathReadOnlyAndExecutableIfFile(Path path) throws IOException {
- if (path.isFile(Symlinks.NOFOLLOW)) {
+ FileStatus stat = path.statIfFound(Symlinks.NOFOLLOW);
+ if (stat != null && stat.isFile() && stat.getPermissions() != 0555) {
setPathReadOnlyAndExecutable(path);
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java b/src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java
index f392d10800748d..3885121968ffa5 100644
--- a/src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/unix/UnixFileSystem.java
@@ -98,7 +98,10 @@ public long getNodeId() {
return status.getInodeNumber();
}
- int getPermissions() { return status.getPermissions(); }
+ @Override
+ public int getPermissions() {
+ return status.getPermissions();
+ }
@Override
public String toString() { return status.toString(); }
diff --git a/src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java b/src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java
index d3841ea8ad0306..a428193edfa5c6 100644
--- a/src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java
+++ b/src/main/java/com/google/devtools/build/lib/vfs/DigestUtils.java
@@ -54,6 +54,9 @@ private static class CacheKey {
/** File system identifier of the file (typically the inode number). */
private final long nodeId;
+ /** Last change time of the file. */
+ private final long changeTime;
+
/** Last modification time of the file. */
private final long modifiedTime;
@@ -70,6 +73,7 @@ private static class CacheKey {
public CacheKey(Path path, FileStatus status) throws IOException {
this.path = path.asFragment();
this.nodeId = status.getNodeId();
+ this.changeTime = status.getLastChangeTime();
this.modifiedTime = status.getLastModifiedTime();
this.size = status.getSize();
}
@@ -84,6 +88,7 @@ public boolean equals(Object object) {
CacheKey key = (CacheKey) object;
return path.equals(key.path)
&& nodeId == key.nodeId
+ && changeTime == key.changeTime
&& modifiedTime == key.modifiedTime
&& size == key.size;
}
@@ -94,6 +99,7 @@ public int hashCode() {
int result = 17;
result = 31 * result + path.hashCode();
result = 31 * result + Longs.hashCode(nodeId);
+ result = 31 * result + Longs.hashCode(changeTime);
result = 31 * result + Longs.hashCode(modifiedTime);
result = 31 * result + Longs.hashCode(size);
return result;
diff --git a/src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java b/src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java
index f6112beaf89a2a..5827576381cd9a 100644
--- a/src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java
+++ b/src/main/java/com/google/devtools/build/lib/vfs/FileStatus.java
@@ -85,4 +85,16 @@ public interface FileStatus {
* ought to cause the node ID of b to change, but appending / modifying b should not.
*/
long getNodeId() throws IOException;
+
+ /**
+ * Returns the file's permissions in POSIX format (e.g. 0755) if possible without performing
+ * additional IO, otherwise (or if unsupported by the file system) returns -1.
+ *
+ * <p>If accurate group and other permissions aren't available, the returned value should attempt
+ * to mimic a umask of 022 (i.e. read and execute permissions extend to group and other, write
+ * does not).
+ */
+ default int getPermissions() {
+ return -1;
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java b/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java
index 5686308aeab5dc..51b9b65f580aad 100644
--- a/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java
+++ b/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryContentInfo.java
@@ -120,6 +120,22 @@ public long getNodeId() {
return System.identityHashCode(this);
}
+ @Override
+ public final int getPermissions() {
+ int permissions = 0;
+ // Emulate the default umask of 022.
+ if (isReadable) {
+ permissions |= 0444;
+ }
+ if (isWritable) {
+ permissions |= 0200;
+ }
+ if (isExecutable) {
+ permissions |= 0111;
+ }
+ return permissions;
+ }
+
@Override
public final InMemoryContentInfo inode() {
return this;
diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java
index 25cba40bd0d3a4..7b8e691ce4500b 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileOperations.java
@@ -15,7 +15,9 @@
package com.google.devtools.build.lib.windows;
import com.google.devtools.build.lib.jni.JniLoader;
+import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.file.AccessDeniedException;
/** File operations on Windows. */
public class WindowsFileOperations {
@@ -82,6 +84,12 @@ public Status getStatus() {
// IS_SYMLINK_OR_JUNCTION_ERROR = 1;
private static final int IS_SYMLINK_OR_JUNCTION_DOES_NOT_EXIST = 2;
+ // Keep GET_CHANGE_TIME_* values in sync with src/main/native/windows/file.cc.
+ private static final int GET_CHANGE_TIME_SUCCESS = 0;
+ // private static final int GET_CHANGE_TIME_ERROR = 1;
+ private static final int GET_CHANGE_TIME_DOES_NOT_EXIST = 2;
+ private static final int GET_CHANGE_TIME_ACCESS_DENIED = 3;
+
// Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int CREATE_JUNCTION_SUCCESS = 0;
// CREATE_JUNCTION_ERROR = 1;
@@ -114,6 +122,9 @@ public Status getStatus() {
private static native int nativeIsSymlinkOrJunction(
String path, boolean[] result, String[] error);
+ private static native int nativeGetChangeTime(
+ String path, boolean followReparsePoints, long[] result, String[] error);
+
private static native boolean nativeGetLongPath(String path, String[] result, String[] error);
private static native int nativeCreateJunction(String name, String target, String[] error);
@@ -143,6 +154,25 @@ public static boolean isSymlinkOrJunction(String path) throws IOException {
throw new IOException(String.format("Cannot tell if '%s' is link: %s", path, error[0]));
}
+ /** Returns the time at which the file was last changed, including metadata changes. */
+ public static long getLastChangeTime(String path, boolean followReparsePoints)
+ throws IOException {
+ long[] result = new long[] {0};
+ String[] error = new String[] {null};
+ switch (nativeGetChangeTime(asLongPath(path), followReparsePoints, result, error)) {
+ case GET_CHANGE_TIME_SUCCESS:
+ return result[0];
+ case GET_CHANGE_TIME_DOES_NOT_EXIST:
+ throw new FileNotFoundException(path);
+ case GET_CHANGE_TIME_ACCESS_DENIED:
+ throw new AccessDeniedException(path);
+ default:
+ // This is GET_CHANGE_TIME_ERROR (1). The JNI code puts a custom message in 'error[0]'.
+ break;
+ }
+ throw new IOException(String.format("Cannot get last change time of '%s': %s", path, error[0]));
+ }
+
/**
* Returns the long path associated with the input `path`.
*
diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
index 30afecc1c2415f..2c4eda788c0f22 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
@@ -156,6 +156,8 @@ protected FileStatus stat(PathFragment path, boolean followSymlinks) throws IOEx
}
final boolean isSymbolicLink = !followSymlinks && fileIsSymbolicLink(file);
+ final long lastChangeTime =
+ WindowsFileOperations.getLastChangeTime(getNioPath(path).toString(), followSymlinks);
FileStatus status =
new FileStatus() {
@Override
@@ -193,8 +195,7 @@ public long getLastModifiedTime() throws IOException {
@Override
public long getLastChangeTime() {
- // This is the best we can do with Java NIO...
- return attributes.lastModifiedTime().toMillis();
+ return lastChangeTime;
}
@Override
@@ -202,6 +203,12 @@ public long getNodeId() {
// TODO(bazel-team): Consider making use of attributes.fileKey().
return -1;
}
+
+ @Override
+ public int getPermissions() {
+ // Files on Windows are implicitly readable and executable.
+ return 0555 | (attributes.isReadOnly() ? 0 : 0200);
+ }
};
return status;
diff --git a/src/main/native/windows/file-jni.cc b/src/main/native/windows/file-jni.cc
index d920b0825021ba..4ed2470c4029df 100644
--- a/src/main/native/windows/file-jni.cc
+++ b/src/main/native/windows/file-jni.cc
@@ -62,6 +62,29 @@ Java_com_google_devtools_build_lib_windows_WindowsFileOperations_nativeIsSymlink
return static_cast<jint>(result);
}
+extern "C" JNIEXPORT jint JNICALL
+Java_com_google_devtools_build_lib_windows_WindowsFileOperations_nativeGetChangeTime(
+ JNIEnv* env, jclass clazz, jstring path, jboolean follow_reparse_points,
+ jlongArray result_holder, jobjectArray error_msg_holder) {
+ std::wstring wpath(bazel::windows::GetJavaWstring(env, path));
+ std::wstring error;
+ jlong ctime = 0;
+ int result =
+ bazel::windows::GetChangeTime(wpath.c_str(), follow_reparse_points,
+ reinterpret_cast<int64_t*>(&ctime), &error);
+ if (result == bazel::windows::GetChangeTimeResult::kSuccess) {
+ env->SetLongArrayRegion(result_holder, 0, 1, &ctime);
+ } else {
+ if (!error.empty() && CanReportError(env, error_msg_holder)) {
+ ReportLastError(
+ bazel::windows::MakeErrorMessage(
+ WSTR(__FILE__), __LINE__, L"nativeGetChangeTime", wpath, error),
+ env, error_msg_holder);
+ }
+ }
+ return static_cast<jint>(result);
+}
+
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_devtools_build_lib_windows_WindowsFileOperations_nativeGetLongPath(
JNIEnv* env, jclass clazz, jstring path, jobjectArray result_holder,
diff --git a/src/main/native/windows/file.cc b/src/main/native/windows/file.cc
index 72d3e4a2263fc9..f20831e09bcfff 100644
--- a/src/main/native/windows/file.cc
+++ b/src/main/native/windows/file.cc
@@ -21,6 +21,7 @@
#include <WinIoCtl.h>
#include <stdint.h> // uint8_t
#include <versionhelpers.h>
+#include <winbase.h>
#include <windows.h>
#include <memory>
@@ -119,6 +120,54 @@ int IsSymlinkOrJunction(const WCHAR* path, bool* result, wstring* error) {
}
}
+int GetChangeTime(const WCHAR* path, bool follow_reparse_points,
+ int64_t* result, wstring* error) {
+ if (!IsAbsoluteNormalizedWindowsPath(path)) {
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__, L"GetChangeTime",
+ path, L"expected an absolute Windows path");
+ }
+ return GetChangeTimeResult::kError;
+ }
+
+ AutoHandle handle;
+ DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
+ if (!follow_reparse_points) {
+ flags |= FILE_FLAG_OPEN_REPARSE_POINT;
+ }
+ handle = CreateFileW(path, 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ nullptr, OPEN_EXISTING, flags, nullptr);
+
+ if (!handle.IsValid()) {
+ DWORD err = GetLastError();
+ if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
+ return GetChangeTimeResult::kDoesNotExist;
+ } else if (err == ERROR_ACCESS_DENIED) {
+ return GetChangeTimeResult::kAccessDenied;
+ }
+ if (error) {
+ *error =
+ MakeErrorMessage(WSTR(__FILE__), __LINE__, L"CreateFileW", path, err);
+ }
+ return GetChangeTimeResult::kError;
+ }
+
+ FILE_BASIC_INFO info;
+ if (!GetFileInformationByHandleEx(handle, FileBasicInfo, (LPVOID)&info,
+ sizeof(FILE_BASIC_INFO))) {
+ DWORD err = GetLastError();
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"GetFileInformationByHandleEx", path, err);
+ }
+ return GetChangeTimeResult::kError;
+ }
+
+ *result = info.ChangeTime.QuadPart;
+ return GetChangeTimeResult::kSuccess;
+}
+
wstring GetLongPath(const WCHAR* path, unique_ptr<WCHAR[]>* result) {
if (!IsAbsoluteNormalizedWindowsPath(path)) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"GetLongPath", path,
diff --git a/src/main/native/windows/file.h b/src/main/native/windows/file.h
index 590137fc842107..2850357ffc6088 100644
--- a/src/main/native/windows/file.h
+++ b/src/main/native/windows/file.h
@@ -82,6 +82,16 @@ struct IsSymlinkOrJunctionResult {
};
};
+// Keep in sync with j.c.g.devtools.build.lib.windows.WindowsFileOperations
+struct GetChangeTimeResult {
+ enum {
+ kSuccess = 0,
+ kError = 1,
+ kDoesNotExist = 2,
+ kAccessDenied = 3,
+ };
+};
+
// Keep in sync with j.c.g.devtools.build.lib.windows.WindowsFileOperations
struct DeletePathResult {
enum {
@@ -136,6 +146,13 @@ struct ReadSymlinkOrJunctionResult {
// see http://superuser.com/a/343079. In Bazel we only ever create junctions.
int IsSymlinkOrJunction(const WCHAR* path, bool* result, wstring* error);
+// Retrieves the FILETIME at which `path` was last changed, including metadata.
+//
+// `path` should be an absolute, normalized, Windows-style path, with "\\?\"
+// prefix if it's longer than MAX_PATH.
+int GetChangeTime(const WCHAR* path, bool follow_reparse_points,
+ int64_t* result, wstring* error);
+
// Computes the long version of `path` if it has any 8dot3 style components.
// Returns the empty string upon success, or a human-readable error message upon
// failure.
| diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandlerTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandlerTest.java
index 267093cbd1ab71..075956f3ed8f79 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandlerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ActionMetadataHandlerTest.java
@@ -300,9 +300,10 @@ public void resettingOutputs() throws Exception {
// Reset this output, which will make the handler stat the file again.
handler.resetOutputs(ImmutableList.of(artifact));
- chmodCalls.clear(); // Permit a second chmod call for the artifact.
+ chmodCalls.clear();
assertThat(handler.getMetadata(artifact).getSize()).isEqualTo(10);
- assertThat(chmodCalls).containsExactly(outputPath);
+ // The handler should not have chmodded the file as it already has the correct permission.
+ assertThat(chmodCalls).isEmpty();
}
@Test
diff --git a/src/test/shell/integration/execution_phase_tests.sh b/src/test/shell/integration/execution_phase_tests.sh
index 4c70716a003b58..1846edf53dacd8 100755
--- a/src/test/shell/integration/execution_phase_tests.sh
+++ b/src/test/shell/integration/execution_phase_tests.sh
@@ -431,4 +431,102 @@ EOF
true # reset the last exit code so the test won't be considered failed
}
+
+# Regression test for https://github.com/bazelbuild/bazel/issues/14723
+function test_fixed_mtime_move_detected_as_change() {
+ mkdir -p pkg
+ cat > pkg/BUILD <<'EOF'
+load("rules.bzl", "my_expand")
+
+genrule(
+ name = "my_templates",
+ srcs = ["template_archive.tar"],
+ outs = ["template1"],
+ cmd = "tar -C $(RULEDIR) -xf $<",
+)
+
+my_expand(
+ name = "expand1",
+ input = "template1",
+ output = "expanded1",
+ to_sub = {"test":"foo"}
+)
+EOF
+ cat > pkg/rules.bzl <<'EOF'
+def _my_expand_impl(ctx):
+ ctx.actions.expand_template(
+ template = ctx.file.input,
+ output = ctx.outputs.output,
+ substitutions = ctx.attr.to_sub
+ )
+
+my_expand = rule(
+ implementation = _my_expand_impl,
+ attrs = {
+ "input": attr.label(allow_single_file=True),
+ "output": attr.output(),
+ "to_sub" : attr.string_dict(),
+ }
+)
+EOF
+
+ echo "test : alpha" > template1
+ touch -t 197001010000 template1
+ tar -cf pkg/template_archive_alpha.tar template1
+
+ echo "test : delta" > template1
+ touch -t 197001010000 template1
+ tar -cf pkg/template_archive_delta.tar template1
+
+ mv pkg/template_archive_alpha.tar pkg/template_archive.tar
+ bazel build //pkg:expand1 || fail "Expected success"
+ assert_equals "foo : alpha" "$(cat bazel-bin/pkg/expanded1)"
+
+ mv pkg/template_archive_delta.tar pkg/template_archive.tar
+ bazel build //pkg:expand1 || fail "Expected success"
+ assert_equals "foo : delta" "$(cat bazel-bin/pkg/expanded1)"
+}
+
+# Regression test for https://github.com/bazelbuild/bazel/issues/14723
+function test_fixed_mtime_source_file() {
+ mkdir -p pkg
+ cat > pkg/BUILD <<'EOF'
+load("rules.bzl", "my_expand")
+
+my_expand(
+ name = "expand1",
+ input = "template1",
+ output = "expanded1",
+ to_sub = {"test":"foo"}
+)
+EOF
+ cat > pkg/rules.bzl <<'EOF'
+def _my_expand_impl(ctx):
+ ctx.actions.expand_template(
+ template = ctx.file.input,
+ output = ctx.outputs.output,
+ substitutions = ctx.attr.to_sub
+ )
+
+my_expand = rule(
+ implementation = _my_expand_impl,
+ attrs = {
+ "input": attr.label(allow_single_file=True),
+ "output": attr.output(),
+ "to_sub" : attr.string_dict(),
+ }
+)
+EOF
+
+ echo "test : alpha" > pkg/template1
+ touch -t 197001010000 pkg/template1
+ bazel build //pkg:expand1 || fail "Expected success"
+ assert_equals "foo : alpha" "$(cat bazel-bin/pkg/expanded1)"
+
+ echo "test : delta" > pkg/template1
+ touch -t 197001010000 pkg/template1
+ bazel build //pkg:expand1 || fail "Expected success"
+ assert_equals "foo : delta" "$(cat bazel-bin/pkg/expanded1)"
+}
+
run_suite "Integration tests of ${PRODUCT_NAME} using the execution phase."
diff --git a/src/test/shell/integration/loading_phase_test.sh b/src/test/shell/integration/loading_phase_test.sh
index d4f83765522f63..644d46b2cbdaee 100755
--- a/src/test/shell/integration/loading_phase_test.sh
+++ b/src/test/shell/integration/loading_phase_test.sh
@@ -292,24 +292,24 @@ function test_incremental_deleting_package_roots() {
local -r pkg="${FUNCNAME}"
mkdir -p "$pkg" || fail "could not create \"$pkg\""
- local other_root=$TEST_TMPDIR/other_root/${WORKSPACE_NAME}
+ local other_root=other_root/${WORKSPACE_NAME}
mkdir -p $other_root/$pkg/a
touch $other_root/WORKSPACE
echo 'sh_library(name="external")' > $other_root/$pkg/a/BUILD
mkdir -p $pkg/a
echo 'sh_library(name="internal")' > $pkg/a/BUILD
- bazel query --package_path=$other_root:. $pkg/a:all >& $TEST_log \
+ bazel query --package_path=%workspace%/$other_root:. $pkg/a:all >& $TEST_log \
|| fail "Expected success"
expect_log "//$pkg/a:external"
expect_not_log "//$pkg/a:internal"
rm -r $other_root
- bazel query --package_path=$other_root:. $pkg/a:all >& $TEST_log \
+ bazel query --package_path=%workspace%/$other_root:. $pkg/a:all >& $TEST_log \
|| fail "Expected success"
expect_log "//$pkg/a:internal"
expect_not_log "//$pkg/a:external"
mkdir -p $other_root
- bazel query --package_path=$other_root:. $pkg/a:all >& $TEST_log \
+ bazel query --package_path=%workspace%/$other_root:. $pkg/a:all >& $TEST_log \
|| fail "Expected success"
expect_log "//$pkg/a:internal"
expect_not_log "//$pkg/a:external"
| train | test | 2023-04-05T20:26:03 | "2022-02-04T16:58:17Z" | miscott2 | test |
bazelbuild/bazel/17675_18133 | bazelbuild/bazel | bazelbuild/bazel/17675 | bazelbuild/bazel/18133 | [
"keyword_pr_to_issue"
] | a0cb57fd7e7dfafd54070b5fdfbd4b4254ce6e95 | 1a60fad7d0a8d04399cca0e5bc5d9ee5b01858eb | [
"Hi @mafanasyev-tri, Can you provide an sample example to test the same. Thanks! ",
"Updated ticket description to include test case."
] | [] | "2023-04-18T13:23:40Z" | [
"type: bug",
"untriaged",
"team-Rules-Python"
] | Python wrapper sometimes puts manifest filename into RUNFILES_DIR | ### Description of the bug:
py_binary rules come with a auto-generated [wrapper script](https://github.com/bazelbuild/bazel/blob/master/tools/python/python_bootstrap_template.txt) which automatically detects runfiles and sets either `RUNFILES_DIR` or `RUNFILES_MANIFEST_FILE`, depending on what is found first.
This script has a bug: if `progname.runfiles_manifest` file is missing, but `programe.runfiles/MANIFEST` is present, the script erroneously sets `RUNFILES_DIR` to manifest file location. This causes all sorts of failures down the line (for example when using bazel's `runfiles.bash` rules)
Code in question: https://github.com/bazelbuild/bazel/blob/4427a1fb0cf537da82e1ca4841e0cecda99e1107/tools/python/python_bootstrap_template.txt#L239
(compare to previous stanza)
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
To demonstrate it, we need any bazel repo which uses python runfiles lib. Bazel's own `rules_pkg` is one example.
First, check out and run the test. It should work:
```
git clone https://github.com/bazelbuild/rules_pkg.git
cd rules_pkg
bazel run //tests:stamp_test # This works
```
Now naively package the runfiles dir and try to use it. Note we've got `stamp_test.runfiles/MANIFEST` (inside runfiles) but forgot `stamp_test.runfiles_manifest`:
```
rm -rf /tmp/work && mkdir /tmp/work && cp -r bazel-bin/tests/stamp_test bazel-bin/tests/stamp_test.runfiles /tmp/work && /tmp/work/stamp_test
...
NotADirectoryError: [Errno 20] Not a directory: '/tmp/work/stamp_test.runfiles/MANIFEST/rules_pkg/tests/stamped_zip.zip'
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (errors=2)
```
observe how it treats `stamp_test.runfiles/MANIFEST` file as a directory and fails.
### Which operating system are you running Bazel on?
Various Ubuntu versions (18.04, 20.04, 22.04)
### What is the output of `bazel info release`?
This is present in HEAD and was introduced in 2018. Testcases above were tested on 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
https://github.com/bazelbuild/bazel.git
4427a1fb0cf537da82e1ca4841e0cecda99e1107
4427a1fb0cf537da82e1ca4841e0cecda99e1107
```
### Have you found anything relevant by searching the web?
Nothing. I am guessing very few people use custom bazel packaging scripts that only copy one file but not both.
### Any other information, logs, or outputs that you want to share?
We have a workaround which is to copy both files, and it probably is more correct that way, too. I am reporting this bug for the unlikely case someone else encounters it.
Workarounds for my test case above:
- Include both manifest files:
```
rm -rf /tmp/work && mkdir /tmp/work && cp -r bazel-bin/tests/stamp_test{,.runfiles,.runfiles_manifest} /tmp/work && /tmp/work/stamp_test
..
OK
```
- Do not include any manifest files
```
rm -rf /tmp/work && mkdir /tmp/work && cp -r bazel-bin/tests/stamp_test{,.runfiles} /tmp/work && rm -f /tmp/work/stamp_test.runfiles/MANIFEST && /tmp/work/stamp_test
..
OK
```
| [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
index 19514526104b4c..92dd6b82fa0dae 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
@@ -215,7 +215,13 @@ def GetRepositoriesImports(module_space, import_all):
return [os.path.join(module_space, '%workspace_name%')]
def RunfilesEnvvar(module_space):
- """Finds the runfiles manifest or the runfiles directory."""
+ """Finds the runfiles manifest or the runfiles directory.
+
+ Returns:
+ A tuple of (var_name, var_value) where var_name is either 'RUNFILES_DIR' or
+ 'RUNFILES_MANIFEST_FILE' and var_value is the path to that directory or
+ file, or (None, None) if runfiles couldn't be found.
+ """
# If this binary is the data-dependency of another one, the other sets
# RUNFILES_MANIFEST_FILE or RUNFILES_DIR for our sake.
runfiles = os.environ.get('RUNFILES_MANIFEST_FILE', None)
@@ -236,9 +242,12 @@ def RunfilesEnvvar(module_space):
return ('RUNFILES_MANIFEST_FILE', runfiles)
# Look for the runfiles "input" manifest, argv[0] + ".runfiles/MANIFEST"
+ # Normally .runfiles_manifest and MANIFEST are both present, but the
+ # former will be missing for zip-based builds or if someone copies the
+ # runfiles tree elsewhere.
runfiles = os.path.join(module_space, 'MANIFEST')
if os.path.exists(runfiles):
- return ('RUNFILES_DIR', runfiles)
+ return ('RUNFILES_MANIFEST_FILE', runfiles)
# If running in a sandbox and no environment variables are set, then
# Look for the runfiles next to the binary.
| null | val | test | 2023-04-18T14:28:40 | "2023-03-07T03:38:53Z" | mafanasyev-tri | test |
bazelbuild/bazel/17908_18174 | bazelbuild/bazel | bazelbuild/bazel/17908 | bazelbuild/bazel/18174 | [
"keyword_pr_to_issue"
] | 755cf95b0df132c1d3fb80ccff6d5b52de708514 | 6c6111085e57f4b8869a5d2bdead0f8a536950ea | [] | [] | "2023-04-21T14:54:55Z" | [
"P1",
"type: process",
"team-ExternalDeps",
"area-Bzlmod"
] | Implement "Automatic use_repo fixups for module extensions" | Proposal: https://docs.google.com/document/d/1dj8SN5L6nwhNOufNqjBhYkk5f-BJI_FPYWKxlB3GAmA/edit | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionMetadata.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java",
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/StarlarkBazelModuleTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
index bc24b3319356fd..bd02cc51fcdec3 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
@@ -142,6 +142,7 @@ java_library(
"Discovery.java",
"GsonTypeAdapterUtil.java",
"ModuleExtensionContext.java",
+ "ModuleExtensionMetadata.java",
"ModuleFileFunction.java",
"ModuleFileGlobals.java",
"Selection.java",
@@ -168,7 +169,6 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/events",
"//src/main/java/com/google/devtools/build/lib/packages",
- "//src/main/java/com/google/devtools/build/lib/packages/semantics",
"//src/main/java/com/google/devtools/build/lib/rules:repository/repository_directory_value",
"//src/main/java/com/google/devtools/build/lib/rules:repository/repository_function",
"//src/main/java/com/google/devtools/build/lib/skyframe:bzl_load_value",
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java
index d791789dc46bbb..b5beb7880a0ed8 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/DelegateTypeAdapterFactory.java
@@ -18,6 +18,7 @@
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
@@ -29,8 +30,10 @@
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable;
import net.starlark.java.eval.Dict;
@@ -92,6 +95,14 @@ private DelegateTypeAdapterFactory(
raw -> new ArrayList<>((List<?>) raw),
delegate -> ImmutableList.copyOf((List<?>) delegate));
+ public static final TypeAdapterFactory IMMUTABLE_SET =
+ new DelegateTypeAdapterFactory<>(
+ ImmutableSet.class,
+ Set.class,
+ LinkedHashSet.class,
+ raw -> new LinkedHashSet<>((Set<?>) raw),
+ delegate -> ImmutableSet.copyOf((Set<?>) delegate));
+
@SuppressWarnings("unchecked")
@Override
@Nullable
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java
index 3cb6d22954126a..4a7a8b43908914 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/GsonTypeAdapterUtil.java
@@ -18,6 +18,7 @@
import static com.google.devtools.build.lib.bazel.bzlmod.DelegateTypeAdapterFactory.IMMUTABLE_BIMAP;
import static com.google.devtools.build.lib.bazel.bzlmod.DelegateTypeAdapterFactory.IMMUTABLE_LIST;
import static com.google.devtools.build.lib.bazel.bzlmod.DelegateTypeAdapterFactory.IMMUTABLE_MAP;
+import static com.google.devtools.build.lib.bazel.bzlmod.DelegateTypeAdapterFactory.IMMUTABLE_SET;
import com.google.common.base.Splitter;
import com.google.devtools.build.lib.bazel.bzlmod.Version.ParseException;
@@ -95,6 +96,7 @@ public ModuleKey read(JsonReader jsonReader) throws IOException {
.registerTypeAdapterFactory(IMMUTABLE_MAP)
.registerTypeAdapterFactory(IMMUTABLE_LIST)
.registerTypeAdapterFactory(IMMUTABLE_BIMAP)
+ .registerTypeAdapterFactory(IMMUTABLE_SET)
.registerTypeAdapter(Version.class, VERSION_TYPE_ADAPTER)
.registerTypeAdapter(ModuleKey.class, MODULE_KEY_TYPE_ADAPTER)
.registerTypeAdapter(AttributeValues.class, new AttributeValuesAdapter())
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java
index ca56fb4ac28bd5..86fae25df40b45 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/Module.java
@@ -261,6 +261,8 @@ public Builder addExtensionUsage(ModuleExtensionUsage value) {
return this;
}
+ abstract ModuleKey getKey();
+
abstract String getName();
abstract Optional<String> getRepoName();
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
index 0cf2fd58a9a15d..049b93053ea03b 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionContext.java
@@ -29,6 +29,8 @@
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
+import net.starlark.java.eval.NoneType;
+import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.StarlarkList;
import net.starlark.java.eval.StarlarkSemantics;
@@ -117,4 +119,68 @@ public StarlarkList<StarlarkBazelModule> getModules() {
public boolean isDevDependency(TypeCheckedTag tag) {
return tag.isDevDependency();
}
+
+ @StarlarkMethod(
+ name = "extension_metadata",
+ doc =
+ "Constructs an opaque object that can be returned from the module extension's"
+ + " implementation function to provide metadata about the repositories generated by"
+ + " the extension to Bazel.",
+ parameters = {
+ @Param(
+ name = "root_module_direct_deps",
+ doc =
+ "The names of the repositories that the extension considers to be direct"
+ + " dependencies of the root module. If the root module imports additional"
+ + " repositories or does not import all of these repositories via <a"
+ + " href=\"../globals/module.html#use_repo\"><code>use_repo</code></a>, Bazel"
+ + " will print a warning and a fixup command when the extension is"
+ + " evaluated.<p>If one of <code>root_module_direct_deps</code> and"
+ + " <code>root_module_direct_dev_deps</code> is specified, the other has to be"
+ + " as well. The lists specified by these two parameters must be"
+ + " disjoint.<p>Exactly one of <code>root_module_direct_deps</code> and"
+ + " <code>root_module_direct_dev_deps</code> can be set to the special value"
+ + " <code>\"all\"</code>, which is treated as if a list with the names of"
+ + " allrepositories generated by the extension was specified as the value.",
+ positional = false,
+ named = true,
+ defaultValue = "None",
+ allowedTypes = {
+ @ParamType(type = Sequence.class, generic1 = String.class),
+ @ParamType(type = String.class),
+ @ParamType(type = NoneType.class)
+ }),
+ @Param(
+ name = "root_module_direct_dev_deps",
+ doc =
+ "The names of the repositories that the extension considers to be direct dev"
+ + " dependencies of the root module. If the root module imports additional"
+ + " repositories or does not import all of these repositories via <a"
+ + " href=\"../globals/module.html#use_repo\"><code>use_repo</code></a> on an"
+ + " extension proxy created with <code><a"
+ + " href=\"../globals/module.html#use_extension>use_extension</a>(...,"
+ + " dev_dependency = True)</code>, Bazel will print a warning and a fixup"
+ + " command when the extension is evaluated.<p>If one of"
+ + " <code>root_module_direct_deps</code> and"
+ + " <code>root_module_direct_dev_deps</code> is specified, the other has to be"
+ + " as well. The lists specified by these two parameters must be"
+ + " disjoint.<p>Exactly one of <code>root_module_direct_deps</code> and"
+ + " <code>root_module_direct_dev_deps</code> can be set to the special value"
+ + " <code>\"all\"</code>, which is treated as if a list with the names of"
+ + " allrepositories generated by the extension was specified as the value.",
+ positional = false,
+ named = true,
+ defaultValue = "None",
+ allowedTypes = {
+ @ParamType(type = Sequence.class, generic1 = String.class),
+ @ParamType(type = String.class),
+ @ParamType(type = NoneType.class)
+ }),
+ })
+ public ModuleExtensionMetadata extensionMetadata(
+ Object rootModuleDirectDepsUnchecked, Object rootModuleDirectDevDepsUnchecked)
+ throws EvalException {
+ return ModuleExtensionMetadata.create(
+ rootModuleDirectDepsUnchecked, rootModuleDirectDevDepsUnchecked);
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionMetadata.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionMetadata.java
new file mode 100644
index 00000000000000..fde1c8fcd6887c
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionMetadata.java
@@ -0,0 +1,350 @@
+// Copyright 2021 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.
+
+package com.google.devtools.build.lib.bazel.bzlmod;
+
+import static com.google.common.collect.ImmutableList.toImmutableList;
+import static com.google.common.collect.ImmutableSet.toImmutableSet;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Sets;
+import com.google.devtools.build.docgen.annot.DocCategory;
+import com.google.devtools.build.lib.cmdline.RepositoryName;
+import com.google.devtools.build.lib.events.Event;
+import com.google.devtools.build.lib.events.EventHandler;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+import net.starlark.java.annot.StarlarkBuiltin;
+import net.starlark.java.eval.EvalException;
+import net.starlark.java.eval.Sequence;
+import net.starlark.java.eval.Starlark;
+import net.starlark.java.eval.StarlarkList;
+import net.starlark.java.eval.StarlarkValue;
+import net.starlark.java.syntax.Location;
+
+/** The Starlark object passed to the implementation function of module extension metadata. */
+@StarlarkBuiltin(
+ name = "extension_metadata",
+ category = DocCategory.BUILTIN,
+ doc =
+ "Return values of this type from a module extension's implementation function to "
+ + "provide metadata about the repositories generated by the extension to Bazel.")
+public class ModuleExtensionMetadata implements StarlarkValue {
+ @Nullable private final ImmutableSet<String> explicitRootModuleDirectDeps;
+ @Nullable private final ImmutableSet<String> explicitRootModuleDirectDevDeps;
+ private final UseAllRepos useAllRepos;
+
+ private ModuleExtensionMetadata(
+ @Nullable Set<String> explicitRootModuleDirectDeps,
+ @Nullable Set<String> explicitRootModuleDirectDevDeps,
+ UseAllRepos useAllRepos) {
+ this.explicitRootModuleDirectDeps =
+ explicitRootModuleDirectDeps != null
+ ? ImmutableSet.copyOf(explicitRootModuleDirectDeps)
+ : null;
+ this.explicitRootModuleDirectDevDeps =
+ explicitRootModuleDirectDevDeps != null
+ ? ImmutableSet.copyOf(explicitRootModuleDirectDevDeps)
+ : null;
+ this.useAllRepos = useAllRepos;
+ }
+
+ static ModuleExtensionMetadata create(
+ Object rootModuleDirectDepsUnchecked, Object rootModuleDirectDevDepsUnchecked)
+ throws EvalException {
+ if (rootModuleDirectDepsUnchecked == Starlark.NONE
+ && rootModuleDirectDevDepsUnchecked == Starlark.NONE) {
+ return new ModuleExtensionMetadata(null, null, UseAllRepos.NO);
+ }
+
+ // When root_module_direct_deps = "all", accept both root_module_direct_dev_deps = None and
+ // root_module_direct_dev_deps = [], but not root_module_direct_dev_deps = ["some_repo"].
+ if (rootModuleDirectDepsUnchecked.equals("all")
+ && rootModuleDirectDevDepsUnchecked.equals(StarlarkList.immutableOf())) {
+ return new ModuleExtensionMetadata(null, null, UseAllRepos.REGULAR);
+ }
+
+ if (rootModuleDirectDevDepsUnchecked.equals("all")
+ && rootModuleDirectDepsUnchecked.equals(StarlarkList.immutableOf())) {
+ return new ModuleExtensionMetadata(null, null, UseAllRepos.DEV);
+ }
+
+ if (rootModuleDirectDepsUnchecked.equals("all")
+ || rootModuleDirectDevDepsUnchecked.equals("all")) {
+ throw Starlark.errorf(
+ "if one of root_module_direct_deps and root_module_direct_dev_deps is "
+ + "\"all\", the other must be an empty list");
+ }
+
+ if (rootModuleDirectDepsUnchecked instanceof String
+ || rootModuleDirectDevDepsUnchecked instanceof String) {
+ throw Starlark.errorf(
+ "root_module_direct_deps and root_module_direct_dev_deps must be "
+ + "None, \"all\", or a list of strings");
+ }
+ if ((rootModuleDirectDepsUnchecked == Starlark.NONE)
+ != (rootModuleDirectDevDepsUnchecked == Starlark.NONE)) {
+ throw Starlark.errorf(
+ "root_module_direct_deps and root_module_direct_dev_deps must both be "
+ + "specified or both be unspecified");
+ }
+
+ Sequence<String> rootModuleDirectDeps =
+ Sequence.cast(rootModuleDirectDepsUnchecked, String.class, "root_module_direct_deps");
+ Sequence<String> rootModuleDirectDevDeps =
+ Sequence.cast(
+ rootModuleDirectDevDepsUnchecked, String.class, "root_module_direct_dev_deps");
+
+ Set<String> explicitRootModuleDirectDeps = new LinkedHashSet<>();
+ for (String dep : rootModuleDirectDeps) {
+ try {
+ RepositoryName.validateUserProvidedRepoName(dep);
+ } catch (EvalException e) {
+ throw Starlark.errorf("in root_module_direct_deps: %s", e.getMessage());
+ }
+ if (!explicitRootModuleDirectDeps.add(dep)) {
+ throw Starlark.errorf("in root_module_direct_deps: duplicate entry '%s'", dep);
+ }
+ }
+
+ Set<String> explicitRootModuleDirectDevDeps = new LinkedHashSet<>();
+ for (String dep : rootModuleDirectDevDeps) {
+ try {
+ RepositoryName.validateUserProvidedRepoName(dep);
+ } catch (EvalException e) {
+ throw Starlark.errorf("in root_module_direct_dev_deps: %s", e.getMessage());
+ }
+ if (explicitRootModuleDirectDeps.contains(dep)) {
+ throw Starlark.errorf(
+ "in root_module_direct_dev_deps: entry '%s' is also in " + "root_module_direct_deps",
+ dep);
+ }
+ if (!explicitRootModuleDirectDevDeps.add(dep)) {
+ throw Starlark.errorf("in root_module_direct_dev_deps: duplicate entry '%s'", dep);
+ }
+ }
+
+ return new ModuleExtensionMetadata(
+ explicitRootModuleDirectDeps, explicitRootModuleDirectDevDeps, UseAllRepos.NO);
+ }
+
+ public void evaluate(
+ Collection<ModuleExtensionUsage> usages, Set<String> allRepos, EventHandler handler)
+ throws EvalException {
+ generateFixupMessage(usages, allRepos).ifPresent(handler::handle);
+ }
+
+ Optional<Event> generateFixupMessage(
+ Collection<ModuleExtensionUsage> usages, Set<String> allRepos) throws EvalException {
+ var rootUsages =
+ usages.stream()
+ .filter(usage -> usage.getUsingModule().equals(ModuleKey.ROOT))
+ .collect(toImmutableList());
+ if (rootUsages.isEmpty()) {
+ // The root module doesn't use the current extension. Do not suggest fixes as the user isn't
+ // expected to modify any other module's MODULE.bazel file.
+ return Optional.empty();
+ }
+
+ var rootModuleDirectDevDeps = getRootModuleDirectDevDeps(allRepos);
+ var rootModuleDirectDeps = getRootModuleDirectDeps(allRepos);
+ if (rootModuleDirectDevDeps.isEmpty() && rootModuleDirectDeps.isEmpty()) {
+ return Optional.empty();
+ }
+
+ Preconditions.checkState(
+ rootModuleDirectDevDeps.isPresent() && rootModuleDirectDeps.isPresent());
+ return generateFixupMessage(
+ rootUsages, allRepos, rootModuleDirectDeps.get(), rootModuleDirectDevDeps.get());
+ }
+
+ private static Optional<Event> generateFixupMessage(
+ List<ModuleExtensionUsage> rootUsages,
+ Set<String> allRepos,
+ Set<String> expectedImports,
+ Set<String> expectedDevImports) {
+ var actualDevImports =
+ rootUsages.stream()
+ .flatMap(usage -> usage.getDevImports().stream())
+ .collect(toImmutableSet());
+ var actualImports =
+ rootUsages.stream()
+ .flatMap(usage -> usage.getImports().keySet().stream())
+ .filter(repo -> !actualDevImports.contains(repo))
+ .collect(toImmutableSet());
+
+ // All label strings that map to the same Label are equivalent for buildozer as it implements
+ // the same normalization of label strings with no or empty repo name.
+ ModuleExtensionUsage firstUsage = rootUsages.get(0);
+ String extensionBzlFile = firstUsage.getExtensionBzlFile();
+ String extensionName = firstUsage.getExtensionName();
+ Location location = firstUsage.getLocation();
+
+ var importsToAdd = ImmutableSortedSet.copyOf(Sets.difference(expectedImports, actualImports));
+ var importsToRemove =
+ ImmutableSortedSet.copyOf(Sets.difference(actualImports, expectedImports));
+ var devImportsToAdd =
+ ImmutableSortedSet.copyOf(Sets.difference(expectedDevImports, actualDevImports));
+ var devImportsToRemove =
+ ImmutableSortedSet.copyOf(Sets.difference(actualDevImports, expectedDevImports));
+
+ if (importsToAdd.isEmpty()
+ && importsToRemove.isEmpty()
+ && devImportsToAdd.isEmpty()
+ && devImportsToRemove.isEmpty()) {
+ return Optional.empty();
+ }
+
+ var message =
+ String.format(
+ "The module extension %s defined in %s reported incorrect imports "
+ + "of repositories via use_repo():\n\n",
+ extensionName, extensionBzlFile);
+
+ var allActualImports = ImmutableSortedSet.copyOf(Sets.union(actualImports, actualDevImports));
+ var allExpectedImports =
+ ImmutableSortedSet.copyOf(Sets.union(expectedImports, expectedDevImports));
+
+ var invalidImports = ImmutableSortedSet.copyOf(Sets.difference(allActualImports, allRepos));
+ if (!invalidImports.isEmpty()) {
+ message +=
+ String.format(
+ "Imported, but not created by the extension (will cause the build to fail):\n"
+ + " %s\n\n",
+ String.join(", ", invalidImports));
+ }
+
+ var missingImports =
+ ImmutableSortedSet.copyOf(Sets.difference(allExpectedImports, allActualImports));
+ if (!missingImports.isEmpty()) {
+ message +=
+ String.format(
+ "Not imported, but reported as direct dependencies by the extension (may cause the"
+ + " build to fail):\n"
+ + " %s\n\n",
+ String.join(", ", missingImports));
+ }
+
+ var indirectDepImports =
+ ImmutableSortedSet.copyOf(
+ Sets.difference(Sets.intersection(allActualImports, allRepos), allExpectedImports));
+ if (!indirectDepImports.isEmpty()) {
+ message +=
+ String.format(
+ "Imported, but reported as indirect dependencies by the extension:\n %s\n\n",
+ String.join(", ", indirectDepImports));
+ }
+
+ var fixupCommands =
+ Stream.of(
+ makeUseRepoCommand(
+ "use_repo_add", false, importsToAdd, extensionBzlFile, extensionName),
+ makeUseRepoCommand(
+ "use_repo_remove", false, importsToRemove, extensionBzlFile, extensionName),
+ makeUseRepoCommand(
+ "use_repo_add", true, devImportsToAdd, extensionBzlFile, extensionName),
+ makeUseRepoCommand(
+ "use_repo_remove", true, devImportsToRemove, extensionBzlFile, extensionName))
+ .flatMap(Optional::stream);
+
+ return Optional.of(
+ Event.warn(
+ location,
+ message
+ + String.format(
+ "%s ** You can use the following buildozer command(s) to fix these"
+ + " issues:%s\n\n"
+ + "%s",
+ "\033[35m\033[1m",
+ "\033[0m",
+ fixupCommands.collect(Collectors.joining("\n")))));
+ }
+
+ private static Optional<String> makeUseRepoCommand(
+ String cmd,
+ boolean devDependency,
+ Collection<String> repos,
+ String extensionBzlFile,
+ String extensionName) {
+ if (repos.isEmpty()) {
+ return Optional.empty();
+ }
+ return Optional.of(
+ String.format(
+ "buildozer '%s%s %s %s %s' //MODULE.bazel:all",
+ cmd,
+ devDependency ? " dev" : "",
+ extensionBzlFile,
+ extensionName,
+ String.join(" ", repos)));
+ }
+
+ private Optional<ImmutableSet<String>> getRootModuleDirectDeps(Set<String> allRepos)
+ throws EvalException {
+ switch (useAllRepos) {
+ case NO:
+ if (explicitRootModuleDirectDeps != null) {
+ Set<String> invalidRepos = Sets.difference(explicitRootModuleDirectDeps, allRepos);
+ if (!invalidRepos.isEmpty()) {
+ throw Starlark.errorf(
+ "root_module_direct_deps contained the following repositories "
+ + "not generated by the extension: %s",
+ String.join(", ", invalidRepos));
+ }
+ }
+ return Optional.ofNullable(explicitRootModuleDirectDeps);
+ case REGULAR:
+ return Optional.of(ImmutableSet.copyOf(allRepos));
+ case DEV:
+ return Optional.of(ImmutableSet.of());
+ }
+ throw new IllegalStateException("not reached");
+ }
+
+ private Optional<ImmutableSet<String>> getRootModuleDirectDevDeps(Set<String> allRepos)
+ throws EvalException {
+ switch (useAllRepos) {
+ case NO:
+ if (explicitRootModuleDirectDevDeps != null) {
+ Set<String> invalidRepos = Sets.difference(explicitRootModuleDirectDevDeps, allRepos);
+ if (!invalidRepos.isEmpty()) {
+ throw Starlark.errorf(
+ "root_module_direct_dev_deps contained the following "
+ + "repositories not generated by the extension: %s",
+ String.join(", ", invalidRepos));
+ }
+ }
+ return Optional.ofNullable(explicitRootModuleDirectDevDeps);
+ case REGULAR:
+ return Optional.of(ImmutableSet.of());
+ case DEV:
+ return Optional.of(ImmutableSet.copyOf(allRepos));
+ }
+ throw new IllegalStateException("not reached");
+ }
+
+ private enum UseAllRepos {
+ NO,
+ REGULAR,
+ DEV,
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java
index 64be185428b300..31cff67ecace10 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionUsage.java
@@ -17,6 +17,7 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.ryanharter.auto.value.gson.GenerateTypeAdapter;
import net.starlark.java.syntax.Location;
@@ -34,6 +35,9 @@ public abstract class ModuleExtensionUsage {
/** The name of the extension. */
public abstract String getExtensionName();
+ /** The module that contains this particular extension usage. */
+ public abstract ModuleKey getUsingModule();
+
/**
* The location where this proxy object was created (by the {@code use_extension} call). Note that
* if there were multiple {@code use_extension} calls on same extension, then this only stores the
@@ -48,6 +52,12 @@ public abstract class ModuleExtensionUsage {
*/
public abstract ImmutableBiMap<String, String> getImports();
+ /**
+ * The repo names as exported by the module extension that were imported using a proxy marked as a
+ * dev dependency.
+ */
+ public abstract ImmutableSet<String> getDevImports();
+
/** All the tags specified by this module for this extension. */
public abstract ImmutableList<Tag> getTags();
@@ -63,10 +73,14 @@ public abstract static class Builder {
public abstract Builder setExtensionName(String value);
+ public abstract Builder setUsingModule(ModuleKey value);
+
public abstract Builder setLocation(Location value);
public abstract Builder setImports(ImmutableBiMap<String, String> value);
+ public abstract Builder setDevImports(ImmutableSet<String> value);
+
public abstract Builder setTags(ImmutableList<Tag> value);
abstract ImmutableList.Builder<Tag> tagsBuilder();
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
index 7e1909a82c5272..a141e2c4c7df49 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
@@ -24,6 +24,7 @@
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.docgen.annot.DocumentMethods;
import com.google.devtools.build.lib.bazel.bzlmod.ModuleFileGlobals.ModuleExtensionUsageBuilder.ModuleExtensionProxy;
import com.google.devtools.build.lib.bazel.bzlmod.Version.ParseException;
@@ -61,6 +62,7 @@ public class ModuleFileGlobals {
Pattern.compile("(>|<|-|<=|>=)(\\d+\\.){2}\\d+");
private boolean moduleCalled = false;
+ private boolean hadNonModuleCall = false;
private final boolean ignoreDevDeps;
private final Module.Builder module;
private final Map<String, ModuleKey> deps = new LinkedHashMap<>();
@@ -206,6 +208,9 @@ public void module(
if (moduleCalled) {
throw Starlark.errorf("the module() directive can only be called once");
}
+ if (hadNonModuleCall) {
+ throw Starlark.errorf("if module() is called, it must be called before any other functions");
+ }
moduleCalled = true;
if (!name.isEmpty()) {
validateModuleName(name);
@@ -296,6 +301,7 @@ private static ImmutableList<String> checkAllCompatibilityVersions(
public void bazelDep(
String name, String version, String repoName, boolean devDependency, StarlarkThread thread)
throws EvalException {
+ hadNonModuleCall = true;
if (repoName.isEmpty()) {
repoName = name;
}
@@ -328,6 +334,7 @@ public void bazelDep(
allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)},
doc = "The labels of the platforms to register."))
public void registerExecutionPlatforms(Sequence<?> platformLabels) throws EvalException {
+ hadNonModuleCall = true;
module.addExecutionPlatformsToRegister(
checkAllAbsolutePatterns(platformLabels, "register_execution_platforms"));
}
@@ -345,6 +352,7 @@ public void registerExecutionPlatforms(Sequence<?> platformLabels) throws EvalEx
allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)},
doc = "The labels of the toolchains to register."))
public void registerToolchains(Sequence<?> toolchainLabels) throws EvalException {
+ hadNonModuleCall = true;
module.addToolchainsToRegister(
checkAllAbsolutePatterns(toolchainLabels, "register_toolchains"));
}
@@ -374,7 +382,14 @@ public void registerToolchains(Sequence<?> toolchainLabels) throws EvalException
},
useStarlarkThread = true)
public ModuleExtensionProxy useExtension(
- String extensionBzlFile, String extensionName, boolean devDependency, StarlarkThread thread) {
+ String rawExtensionBzlFile,
+ String extensionName,
+ boolean devDependency,
+ StarlarkThread thread) {
+ hadNonModuleCall = true;
+
+ String extensionBzlFile = normalizeLabelString(rawExtensionBzlFile);
+
ModuleExtensionUsageBuilder newUsageBuilder =
new ModuleExtensionUsageBuilder(
extensionBzlFile, extensionName, thread.getCallerLocation());
@@ -397,11 +412,28 @@ public ModuleExtensionProxy useExtension(
return newUsageBuilder.getProxy(devDependency);
}
+ private String normalizeLabelString(String rawExtensionBzlFile) {
+ // Normalize the label by adding the current module's repo_name if the label doesn't specify a
+ // repository name. This is necessary as ModuleExtensionUsages are grouped by the string value
+ // of this label, but later mapped to their Label representation. If multiple strings map to the
+ // same Label, this would result in a crash.
+ // ownName can't change anymore as calling module() after this results in an error.
+ String ownName = module.getRepoName().orElse(module.getName());
+ if (module.getKey().equals(ModuleKey.ROOT) && rawExtensionBzlFile.startsWith("@//")) {
+ return "@" + ownName + rawExtensionBzlFile.substring(1);
+ } else if (rawExtensionBzlFile.startsWith("//")) {
+ return "@" + ownName + rawExtensionBzlFile;
+ } else {
+ return rawExtensionBzlFile;
+ }
+ }
+
class ModuleExtensionUsageBuilder {
private final String extensionBzlFile;
private final String extensionName;
private final Location location;
private final HashBiMap<String, String> imports;
+ private final ImmutableSet.Builder<String> devImports;
private final ImmutableList.Builder<Tag> tags;
ModuleExtensionUsageBuilder(String extensionBzlFile, String extensionName, Location location) {
@@ -409,6 +441,7 @@ class ModuleExtensionUsageBuilder {
this.extensionName = extensionName;
this.location = location;
this.imports = HashBiMap.create();
+ this.devImports = ImmutableSet.builder();
this.tags = ImmutableList.builder();
}
@@ -416,8 +449,10 @@ ModuleExtensionUsage buildUsage() {
return ModuleExtensionUsage.builder()
.setExtensionBzlFile(extensionBzlFile)
.setExtensionName(extensionName)
+ .setUsingModule(module.getKey())
.setLocation(location)
.setImports(ImmutableBiMap.copyOf(imports))
+ .setDevImports(devImports.build())
.setTags(tags.build())
.build();
}
@@ -451,6 +486,9 @@ void addImport(String localRepoName, String exportedName, Location location)
exportedName, extensionName, repoNameUsages.get(collisionRepoName).getWhere());
}
imports.put(localRepoName, exportedName);
+ if (devDependency) {
+ devImports.add(exportedName);
+ }
}
@Nullable
@@ -514,6 +552,7 @@ public void useRepo(
Dict<String, Object> kwargs,
StarlarkThread thread)
throws EvalException {
+ hadNonModuleCall = true;
Location location = thread.getCallerLocation();
for (String arg : Sequence.cast(args, String.class, "args")) {
extensionProxy.addImport(arg, arg, location);
@@ -596,6 +635,7 @@ public void singleVersionOverride(
Iterable<?> patchCmds,
StarlarkInt patchStrip)
throws EvalException {
+ hadNonModuleCall = true;
Version parsedVersion;
try {
parsedVersion = Version.parse(version);
@@ -649,6 +689,7 @@ public void singleVersionOverride(
})
public void multipleVersionOverride(String moduleName, Iterable<?> versions, String registry)
throws EvalException {
+ hadNonModuleCall = true;
ImmutableList.Builder<Version> parsedVersionsBuilder = new ImmutableList.Builder<>();
try {
for (String version : Sequence.cast(versions, String.class, "versions").getImmutableList()) {
@@ -732,6 +773,7 @@ public void archiveOverride(
Iterable<?> patchCmds,
StarlarkInt patchStrip)
throws EvalException {
+ hadNonModuleCall = true;
ImmutableList<String> urlList =
urls instanceof String
? ImmutableList.of((String) urls)
@@ -803,6 +845,7 @@ public void gitOverride(
Iterable<?> patchCmds,
StarlarkInt patchStrip)
throws EvalException {
+ hadNonModuleCall = true;
addOverride(
moduleName,
GitOverride.create(
@@ -832,6 +875,7 @@ public void gitOverride(
positional = false),
})
public void localPathOverride(String moduleName, String path) throws EvalException {
+ hadNonModuleCall = true;
addOverride(moduleName, LocalPathOverride.create(path));
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
index 0418870181811b..38360edb1fd724 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
@@ -183,8 +183,26 @@ public SkyValue compute(SkyKey skyKey, Environment env)
createContext(env, usagesValue, starlarkSemantics, extensionId, extension);
threadContext.storeInThread(thread);
try {
- Starlark.fastcall(
- thread, extension.getImplementation(), new Object[] {moduleContext}, new Object[0]);
+ Object returnValue =
+ Starlark.fastcall(
+ thread, extension.getImplementation(), new Object[] {moduleContext}, new Object[0]);
+ if (returnValue != Starlark.NONE && !(returnValue instanceof ModuleExtensionMetadata)) {
+ throw new SingleExtensionEvalFunctionException(
+ ExternalDepsException.withMessage(
+ Code.BAD_MODULE,
+ "expected module extension %s in %s to return None or extension_metadata, got %s",
+ extensionId.getExtensionName(),
+ extensionId.getBzlFileLabel(),
+ Starlark.type(returnValue)),
+ Transience.PERSISTENT);
+ }
+ if (returnValue instanceof ModuleExtensionMetadata) {
+ ModuleExtensionMetadata metadata = (ModuleExtensionMetadata) returnValue;
+ metadata.evaluate(
+ usagesValue.getExtensionUsages().values(),
+ threadContext.getGeneratedRepos().keySet(),
+ env.getListener());
+ }
} catch (NeedsSkyframeRestartException e) {
// Clean up and restart by returning null.
try {
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
index 3762ba587a24e6..8c2c76bf5bc1d1 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
@@ -45,6 +45,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/bazel/repository/starlark",
"//src/main/java/com/google/devtools/build/lib/clock",
"//src/main/java/com/google/devtools/build/lib/cmdline",
+ "//src/main/java/com/google/devtools/build/lib/events",
"//src/main/java/com/google/devtools/build/lib/packages",
"//src/main/java/com/google/devtools/build/lib/packages/semantics",
"//src/main/java/com/google/devtools/build/lib/pkgcache",
@@ -76,6 +77,7 @@ java_library(
"//src/main/java/net/starlark/java/syntax",
"//src/test/java/com/google/devtools/build/lib/analysis/util",
"//src/test/java/com/google/devtools/build/lib/testutil",
+ "//src/test/java/com/google/devtools/build/lib/testutil:JunitUtils",
"//third_party:auto_value",
"//third_party:caffeine",
"//third_party:gson",
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
index bcacdab1c8bb5b..b1979e9a6515ef 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
@@ -25,6 +25,7 @@
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ServerDirectories;
@@ -234,6 +235,8 @@ private static ModuleExtensionUsage createModuleExtensionUsage(
.setExtensionBzlFile(bzlFile)
.setExtensionName(name)
.setImports(importsBuilder.buildOrThrow())
+ .setDevImports(ImmutableSet.of())
+ .setUsingModule(ModuleKey.ROOT)
.setLocation(Location.BUILTIN)
.build();
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
index c4ac3a67d72a88..06033115a3f683 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
@@ -16,6 +16,7 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.bazel.bzlmod.BzlmodTestUtil.createModuleKey;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertEventCount;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.base.Suppliers;
@@ -39,6 +40,7 @@
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryName;
+import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.packages.PackageFactory;
import com.google.devtools.build.lib.packages.WorkspaceFileValue;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
@@ -332,6 +334,88 @@ public void simpleExtension() throws Exception {
assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("foo:fu bar:ba");
}
+ @Test
+ public void simpleExtension_nonCanonicalLabel() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "module(name='my_module', version = '1.0')",
+ "bazel_dep(name='data_repo', version='1.0')",
+ "ext1 = use_extension('//:defs.bzl', 'ext')",
+ "ext1.tag(name='foo', data='fu')",
+ "use_repo(ext1, 'foo')",
+ "ext2 = use_extension('@my_module//:defs.bzl', 'ext')",
+ "ext2.tag(name='bar', data='ba')",
+ "use_repo(ext2, 'bar')",
+ "ext3 = use_extension('@//:defs.bzl', 'ext')",
+ "ext3.tag(name='quz', data='qu')",
+ "use_repo(ext3, 'quz')");
+ scratch.file(
+ workspaceRoot.getRelative("defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "tag = tag_class(attrs = {'name':attr.string(),'data':attr.string()})",
+ "def _ext_impl(ctx):",
+ " for mod in ctx.modules:",
+ " for tag in mod.tags.tag:",
+ " data_repo(name=tag.name,data=tag.data)",
+ "ext = module_extension(implementation=_ext_impl, tag_classes={'tag':tag})");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@foo//:data.bzl', foo_data='data')",
+ "load('@bar//:data.bzl', bar_data='data')",
+ "load('@quz//:data.bzl', quz_data='data')",
+ "data = 'foo:'+foo_data+' bar:'+bar_data+' quz:'+quz_data");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ if (result.hasError()) {
+ throw result.getError().getException();
+ }
+ assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("foo:fu bar:ba quz:qu");
+ }
+
+ @Test
+ public void simpleExtension_nonCanonicalLabel_repoName() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "module(name='my_module', version = '1.0', repo_name='my_name')",
+ "bazel_dep(name='data_repo', version='1.0')",
+ "ext1 = use_extension('//:defs.bzl', 'ext')",
+ "ext1.tag(name='foo', data='fu')",
+ "use_repo(ext1, 'foo')",
+ "ext2 = use_extension('@my_name//:defs.bzl', 'ext')",
+ "ext2.tag(name='bar', data='ba')",
+ "use_repo(ext2, 'bar')",
+ "ext3 = use_extension('@//:defs.bzl', 'ext')",
+ "ext3.tag(name='quz', data='qu')",
+ "use_repo(ext3, 'quz')");
+ scratch.file(
+ workspaceRoot.getRelative("defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "tag = tag_class(attrs = {'name':attr.string(),'data':attr.string()})",
+ "def _ext_impl(ctx):",
+ " for mod in ctx.modules:",
+ " for tag in mod.tags.tag:",
+ " data_repo(name=tag.name,data=tag.data)",
+ "ext = module_extension(implementation=_ext_impl, tag_classes={'tag':tag})");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@foo//:data.bzl', foo_data='data')",
+ "load('@bar//:data.bzl', bar_data='data')",
+ "load('@quz//:data.bzl', quz_data='data')",
+ "data = 'foo:'+foo_data+' bar:'+bar_data+' quz:'+quz_data");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ if (result.hasError()) {
+ throw result.getError().getException();
+ }
+ assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("foo:fu bar:ba quz:qu");
+ }
+
@Test
public void multipleModules() throws Exception {
scratch.file(
@@ -1374,4 +1458,437 @@ public void testReportRepoAndBzlCycles_extRepoLoadSelfCycle() throws Exception {
+ "| @_main~my_ext~candy1//:data.bzl\n"
+ "`-- @_main~my_ext~candy1");
}
+
+ @Test
+ public void extensionMetadata_exactlyOneArgIsNone() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return ctx.extension_metadata(root_module_direct_deps=['foo'])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "root_module_direct_deps and root_module_direct_dev_deps must both be specified or both be"
+ + " unspecified");
+ }
+
+ @Test
+ public void extensionMetadata_exactlyOneArgIsNoneDev() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return ctx.extension_metadata(root_module_direct_dev_deps=['foo'])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "root_module_direct_deps and root_module_direct_dev_deps must both be specified or both be"
+ + " unspecified");
+ }
+
+ @Test
+ public void extensionMetadata_allUsedTwice() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_deps='all',root_module_direct_dev_deps='all')");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "if one of root_module_direct_deps and root_module_direct_dev_deps is \"all\", the other"
+ + " must be an empty list");
+ }
+
+ @Test
+ public void extensionMetadata_allAndNone() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return ctx.extension_metadata(root_module_direct_deps='all')");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "if one of root_module_direct_deps and root_module_direct_dev_deps is \"all\", the other"
+ + " must be an empty list");
+ }
+
+ @Test
+ public void extensionMetadata_unsupportedString() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return ctx.extension_metadata(root_module_direct_deps='not_all')");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "root_module_direct_deps and root_module_direct_dev_deps must be None, \"all\", or a list"
+ + " of strings");
+ }
+
+ @Test
+ public void extensionMetadata_unsupportedStringDev() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return ctx.extension_metadata(root_module_direct_dev_deps='not_all')");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "root_module_direct_deps and root_module_direct_dev_deps must be None, \"all\", or a list"
+ + " of strings");
+ }
+
+ @Test
+ public void extensionMetadata_invalidRepoName() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_deps=['~invalid'],root_module_direct_dev_deps=[])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "in root_module_direct_deps: invalid user-provided repo name '~invalid': valid names may"
+ + " contain only A-Z, a-z, 0-9, '-', '_', '.', and must start with a letter");
+ }
+
+ @Test
+ public void extensionMetadata_invalidDevRepoName() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_dev_deps=['~invalid'],root_module_direct_deps=[])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "in root_module_direct_dev_deps: invalid user-provided repo name '~invalid': valid names"
+ + " may contain only A-Z, a-z, 0-9, '-', '_', '.', and must start with a letter");
+ }
+
+ @Test
+ public void extensionMetadata_duplicateRepo() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_deps=['dep','dep'],root_module_direct_dev_deps=[])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent("in root_module_direct_deps: duplicate entry 'dep'");
+ }
+
+ @Test
+ public void extensionMetadata_duplicateDevRepo() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_deps=[],root_module_direct_dev_deps=['dep','dep'])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent("in root_module_direct_dev_deps: duplicate entry 'dep'");
+ }
+
+ @Test
+ public void extensionMetadata_duplicateRepoAcrossTypes() throws Exception {
+ var result =
+ evaluateSimpleModuleExtension(
+ "return"
+ + " ctx.extension_metadata(root_module_direct_deps=['dep'],root_module_direct_dev_deps=['dep'])");
+
+ assertThat(result.hasError()).isTrue();
+ assertContainsEvent(
+ "in root_module_direct_dev_deps: entry 'dep' is also in root_module_direct_deps");
+ }
+
+ @Test
+ public void extensionMetadata() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='ext', version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('@ext//:defs.bzl', 'ext')",
+ "use_repo(ext, 'direct_dep', 'indirect_dep', 'invalid_dep')",
+ "ext_dev = use_extension('@ext//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'direct_dev_dep', 'indirect_dev_dep', 'invalid_dev_dep')");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@direct_dep//:data.bzl', direct_dep_data='data')",
+ "data = direct_dep_data");
+
+ registry.addModule(
+ createModuleKey("ext", "1.0"),
+ "module(name='ext',version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('//:defs.bzl', 'ext')",
+ "use_repo(ext, 'indirect_dep')",
+ "ext_dev = use_extension('//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'indirect_dev_dep')");
+ scratch.file(modulesRoot.getRelative("ext~1.0/WORKSPACE").getPathString());
+ scratch.file(modulesRoot.getRelative("ext~1.0/BUILD").getPathString());
+ scratch.file(
+ modulesRoot.getRelative("ext~1.0/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "def _ext_impl(ctx):",
+ " data_repo(name='direct_dep')",
+ " data_repo(name='direct_dev_dep')",
+ " data_repo(name='missing_direct_dep')",
+ " data_repo(name='missing_direct_dev_dep')",
+ " data_repo(name='indirect_dep')",
+ " data_repo(name='indirect_dev_dep')",
+ " return ctx.extension_metadata(",
+ " root_module_direct_deps=['direct_dep', 'missing_direct_dep'],",
+ " root_module_direct_dev_deps=['direct_dev_dep', 'missing_direct_dev_dep'],",
+ " )",
+ "ext=module_extension(implementation=_ext_impl)");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ // Evaluation fails due to the import of a repository not generated by the extension, but we
+ // only want to assert that the warning is emitted.
+ reporter.removeHandler(failFastHandler);
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ assertThat(result.hasError()).isTrue();
+
+ assertEventCount(1, eventCollector);
+ assertContainsEvent(
+ "WARNING <root>/MODULE.bazel:3:20: The module extension ext defined in @ext//:defs.bzl"
+ + " reported incorrect imports of repositories via use_repo():\n"
+ + "\n"
+ + "Imported, but not created by the extension (will cause the build to fail):\n"
+ + " invalid_dep, invalid_dev_dep\n"
+ + "\n"
+ + "Not imported, but reported as direct dependencies by the extension (may cause the"
+ + " build to fail):\n"
+ + " missing_direct_dep, missing_direct_dev_dep\n"
+ + "\n"
+ + "Imported, but reported as indirect dependencies by the extension:\n"
+ + " indirect_dep, indirect_dev_dep\n"
+ + "\n"
+ + "\033[35m\033[1m ** You can use the following buildozer command(s) to fix these"
+ + " issues:\033[0m\n"
+ + "\n"
+ + "buildozer 'use_repo_add @ext//:defs.bzl ext missing_direct_dep' //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_remove @ext//:defs.bzl ext indirect_dep invalid_dep'"
+ + " //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_add dev @ext//:defs.bzl ext missing_direct_dev_dep'"
+ + " //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_remove dev @ext//:defs.bzl ext indirect_dev_dep invalid_dev_dep'"
+ + " //MODULE.bazel:all",
+ ImmutableSet.of(EventKind.WARNING));
+ }
+
+ @Test
+ public void extensionMetadata_all() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='ext', version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('@ext//:defs.bzl', 'ext')",
+ "use_repo(ext, 'direct_dep', 'indirect_dep', 'invalid_dep')",
+ "ext_dev = use_extension('@ext//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'direct_dev_dep', 'indirect_dev_dep', 'invalid_dev_dep')");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@direct_dep//:data.bzl', direct_dep_data='data')",
+ "data = direct_dep_data");
+
+ registry.addModule(
+ createModuleKey("ext", "1.0"),
+ "module(name='ext',version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('//:defs.bzl', 'ext')",
+ "use_repo(ext, 'indirect_dep')",
+ "ext_dev = use_extension('//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'indirect_dev_dep')");
+ scratch.file(modulesRoot.getRelative("ext~1.0/WORKSPACE").getPathString());
+ scratch.file(modulesRoot.getRelative("ext~1.0/BUILD").getPathString());
+ scratch.file(
+ modulesRoot.getRelative("ext~1.0/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "def _ext_impl(ctx):",
+ " data_repo(name='direct_dep')",
+ " data_repo(name='direct_dev_dep')",
+ " data_repo(name='missing_direct_dep')",
+ " data_repo(name='missing_direct_dev_dep')",
+ " data_repo(name='indirect_dep')",
+ " data_repo(name='indirect_dev_dep')",
+ " return ctx.extension_metadata(",
+ " root_module_direct_deps='all',",
+ " root_module_direct_dev_deps=[],",
+ " )",
+ "ext=module_extension(implementation=_ext_impl)");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ reporter.removeHandler(failFastHandler);
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getException())
+ .hasMessageThat()
+ .isEqualTo(
+ "module extension \"ext\" from \"@ext~1.0//:defs.bzl\" does not generate repository "
+ + "\"invalid_dep\", yet it is imported as \"invalid_dep\" in the usage at "
+ + "<root>/MODULE.bazel:3:20");
+
+ assertEventCount(1, eventCollector);
+ assertContainsEvent(
+ "WARNING <root>/MODULE.bazel:3:20: The module extension ext defined in @ext//:defs.bzl"
+ + " reported incorrect imports of repositories via use_repo():\n"
+ + "\n"
+ + "Imported, but not created by the extension (will cause the build to fail):\n"
+ + " invalid_dep, invalid_dev_dep\n"
+ + "\n"
+ + "Not imported, but reported as direct dependencies by the extension (may cause the"
+ + " build to fail):\n"
+ + " missing_direct_dep, missing_direct_dev_dep\n"
+ + "\n"
+ + "\033[35m\033[1m ** You can use the following buildozer command(s) to fix these"
+ + " issues:\033[0m\n"
+ + "\n"
+ + "buildozer 'use_repo_add @ext//:defs.bzl ext direct_dev_dep indirect_dev_dep"
+ + " missing_direct_dep missing_direct_dev_dep' //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_remove @ext//:defs.bzl ext invalid_dep' //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_remove dev @ext//:defs.bzl ext direct_dev_dep indirect_dev_dep"
+ + " invalid_dev_dep' //MODULE.bazel:all",
+ ImmutableSet.of(EventKind.WARNING));
+ }
+
+ @Test
+ public void extensionMetadata_allDev() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='ext', version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('@ext//:defs.bzl', 'ext')",
+ "use_repo(ext, 'direct_dep', 'indirect_dep', 'invalid_dep')",
+ "ext_dev = use_extension('@ext//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'direct_dev_dep', 'indirect_dev_dep', 'invalid_dev_dep')");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@direct_dep//:data.bzl', direct_dep_data='data')",
+ "data = direct_dep_data");
+
+ registry.addModule(
+ createModuleKey("ext", "1.0"),
+ "module(name='ext',version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('//:defs.bzl', 'ext')",
+ "use_repo(ext, 'indirect_dep')",
+ "ext_dev = use_extension('//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'indirect_dev_dep')");
+ scratch.file(modulesRoot.getRelative("ext~1.0/WORKSPACE").getPathString());
+ scratch.file(modulesRoot.getRelative("ext~1.0/BUILD").getPathString());
+ scratch.file(
+ modulesRoot.getRelative("ext~1.0/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "def _ext_impl(ctx):",
+ " data_repo(name='direct_dep')",
+ " data_repo(name='direct_dev_dep')",
+ " data_repo(name='missing_direct_dep')",
+ " data_repo(name='missing_direct_dev_dep')",
+ " data_repo(name='indirect_dep')",
+ " data_repo(name='indirect_dev_dep')",
+ " return ctx.extension_metadata(",
+ " root_module_direct_deps=[],",
+ " root_module_direct_dev_deps='all',",
+ " )",
+ "ext=module_extension(implementation=_ext_impl)");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ // Evaluation fails due to the import of a repository not generated by the extension, but we
+ // only want to assert that the warning is emitted.
+ reporter.removeHandler(failFastHandler);
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getException())
+ .hasMessageThat()
+ .isEqualTo(
+ "module extension \"ext\" from \"@ext~1.0//:defs.bzl\" does not generate repository "
+ + "\"invalid_dep\", yet it is imported as \"invalid_dep\" in the usage at "
+ + "<root>/MODULE.bazel:3:20");
+
+ assertEventCount(1, eventCollector);
+ assertContainsEvent(
+ "WARNING <root>/MODULE.bazel:3:20: The module extension ext defined in @ext//:defs.bzl"
+ + " reported incorrect imports of repositories via use_repo():\n"
+ + "\n"
+ + "Imported, but not created by the extension (will cause the build to fail):\n"
+ + " invalid_dep, invalid_dev_dep\n"
+ + "\n"
+ + "Not imported, but reported as direct dependencies by the extension (may cause the"
+ + " build to fail):\n"
+ + " missing_direct_dep, missing_direct_dev_dep\n"
+ + "\n"
+ + "\033[35m\033[1m ** You can use the following buildozer command(s) to fix these"
+ + " issues:\033[0m\n"
+ + "\n"
+ + "buildozer 'use_repo_remove @ext//:defs.bzl ext direct_dep indirect_dep invalid_dep'"
+ + " //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_add dev @ext//:defs.bzl ext direct_dep indirect_dep"
+ + " missing_direct_dep missing_direct_dev_dep' //MODULE.bazel:all\n"
+ + "buildozer 'use_repo_remove dev @ext//:defs.bzl ext invalid_dev_dep'"
+ + " //MODULE.bazel:all",
+ ImmutableSet.of(EventKind.WARNING));
+ }
+
+ @Test
+ public void extensionMetadata_noRootUsage() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='ext', version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+
+ registry.addModule(
+ createModuleKey("ext", "1.0"),
+ "module(name='ext',version='1.0')",
+ "bazel_dep(name='data_repo',version='1.0')",
+ "ext = use_extension('//:defs.bzl', 'ext')",
+ "use_repo(ext, 'indirect_dep')",
+ "ext_dev = use_extension('//:defs.bzl', 'ext', dev_dependency = True)",
+ "use_repo(ext_dev, 'indirect_dev_dep')");
+ scratch.file(modulesRoot.getRelative("ext~1.0/WORKSPACE").getPathString());
+ scratch.file(modulesRoot.getRelative("ext~1.0/BUILD").getPathString());
+ scratch.file(
+ modulesRoot.getRelative("ext~1.0/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "def _ext_impl(ctx):",
+ " data_repo(name='direct_dep')",
+ " data_repo(name='direct_dev_dep')",
+ " data_repo(name='missing_direct_dep')",
+ " data_repo(name='missing_direct_dev_dep')",
+ " data_repo(name='indirect_dep', data='indirect_dep_data')",
+ " data_repo(name='indirect_dev_dep')",
+ " return ctx.extension_metadata(",
+ " root_module_direct_deps='all',",
+ " root_module_direct_dev_deps=[],",
+ " )",
+ "ext=module_extension(implementation=_ext_impl)");
+ scratch.file(
+ modulesRoot.getRelative("ext~1.0/data.bzl").getPathString(),
+ "load('@indirect_dep//:data.bzl', indirect_dep_data='data')",
+ "data = indirect_dep_data");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("@ext~1.0//:data.bzl"));
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("indirect_dep_data");
+
+ assertEventCount(0, eventCollector);
+ }
+
+ private EvaluationResult<SingleExtensionEvalValue> evaluateSimpleModuleExtension(
+ String returnStatement) throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "ext = use_extension('//:defs.bzl', 'ext')");
+ scratch.file(
+ workspaceRoot.getRelative("defs.bzl").getPathString(),
+ "def _ext_impl(ctx):",
+ " " + returnStatement,
+ "ext = module_extension(implementation=_ext_impl)");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+
+ ModuleExtensionId extensionId =
+ ModuleExtensionId.create(Label.parseCanonical("//:defs.bzl"), "ext");
+ reporter.removeHandler(failFastHandler);
+ return evaluator.evaluate(
+ ImmutableList.of(SingleExtensionEvalValue.key(extensionId)), evaluationContext);
+ }
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
index ecd8353f8b4605..d55e990a487364 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileFunctionTest.java
@@ -459,7 +459,8 @@ public void testModuleExtensions_good() throws Exception {
"maven.dep(coord='guava')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
- SkyKey skyKey = ModuleFileValue.key(createModuleKey("mymod", "1.0"), null);
+ ModuleKey myMod = createModuleKey("mymod", "1.0");
+ SkyKey skyKey = ModuleFileValue.key(myMod, null);
EvaluationResult<ModuleFileValue> result =
evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
if (result.hasError()) {
@@ -473,10 +474,12 @@ public void testModuleExtensions_good() throws Exception {
.setRegistry(registry)
.addExtensionUsage(
ModuleExtensionUsage.builder()
- .setExtensionBzlFile("//:defs.bzl")
+ .setExtensionBzlFile("@mymod//:defs.bzl")
.setExtensionName("myext1")
+ .setUsingModule(myMod)
.setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 2, 23))
.setImports(ImmutableBiMap.of("repo1", "repo1"))
+ .setDevImports(ImmutableSet.of())
.addTag(
Tag.builder()
.setTagName("tag")
@@ -492,10 +495,12 @@ public void testModuleExtensions_good() throws Exception {
.build())
.addExtensionUsage(
ModuleExtensionUsage.builder()
- .setExtensionBzlFile("//:defs.bzl")
+ .setExtensionBzlFile("@mymod//:defs.bzl")
.setExtensionName("myext2")
+ .setUsingModule(myMod)
.setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 5, 23))
.setImports(ImmutableBiMap.of("other_repo1", "repo1", "repo2", "repo2"))
+ .setDevImports(ImmutableSet.of())
.addTag(
Tag.builder()
.setTagName("tag1")
@@ -525,9 +530,11 @@ public void testModuleExtensions_good() throws Exception {
ModuleExtensionUsage.builder()
.setExtensionBzlFile("@rules_jvm_external//:defs.bzl")
.setExtensionName("maven")
+ .setUsingModule(myMod)
.setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 10, 22))
.setImports(
ImmutableBiMap.of("mvn", "maven", "junit", "junit", "guava", "guava"))
+ .setDevImports(ImmutableSet.of())
.addTag(
Tag.builder()
.setTagName("dep")
@@ -587,13 +594,15 @@ public void testModuleExtensions_duplicateProxy_asRoot() throws Exception {
.setKey(ModuleKey.ROOT)
.addExtensionUsage(
ModuleExtensionUsage.builder()
- .setExtensionBzlFile("//:defs.bzl")
+ .setExtensionBzlFile("@//:defs.bzl")
.setExtensionName("myext")
+ .setUsingModule(ModuleKey.ROOT)
.setLocation(Location.fromFileLineColumn("<root>/MODULE.bazel", 1, 23))
.setImports(
ImmutableBiMap.of(
"alpha", "alpha", "beta", "beta", "gamma", "gamma", "delta",
"delta"))
+ .setDevImports(ImmutableSet.of("alpha", "gamma"))
.addTag(
Tag.builder()
.setTagName("tag")
@@ -668,7 +677,8 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
"use_repo(myext4, 'delta')");
ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
- SkyKey skyKey = ModuleFileValue.key(createModuleKey("mymod", "1.0"), null);
+ ModuleKey myMod = createModuleKey("mymod", "1.0");
+ SkyKey skyKey = ModuleFileValue.key(myMod, null);
EvaluationResult<ModuleFileValue> result =
evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
if (result.hasError()) {
@@ -681,10 +691,12 @@ public void testModuleExtensions_duplicateProxy_asDep() throws Exception {
.setRegistry(registry)
.addExtensionUsage(
ModuleExtensionUsage.builder()
- .setExtensionBzlFile("//:defs.bzl")
+ .setExtensionBzlFile("@mymod//:defs.bzl")
.setExtensionName("myext")
+ .setUsingModule(myMod)
.setLocation(Location.fromFileLineColumn("[email protected]/MODULE.bazel", 5, 23))
.setImports(ImmutableBiMap.of("beta", "beta", "delta", "delta"))
+ .setDevImports(ImmutableSet.of())
.addTag(
Tag.builder()
.setTagName("tag")
@@ -967,4 +979,34 @@ public void moduleRepoName_conflict() throws Exception {
assertContainsEvent("The repo name 'bbb' is already being used as the module's own repo name");
}
+
+ @Test
+ public void module_calledTwice() throws Exception {
+ scratch.file(
+ rootDirectory.getRelative("MODULE.bazel").getPathString(),
+ "module(name='aaa',version='0.1',repo_name='bbb')",
+ "module(name='aaa',version='0.1',repo_name='bbb')");
+ FakeRegistry registry = registryFactory.newFakeRegistry("/foo");
+ ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
+
+ reporter.removeHandler(failFastHandler); // expect failures
+ evaluator.evaluate(ImmutableList.of(ModuleFileValue.KEY_FOR_ROOT_MODULE), evaluationContext);
+
+ assertContainsEvent("the module() directive can only be called once");
+ }
+
+ @Test
+ public void module_calledLate() throws Exception {
+ scratch.file(
+ rootDirectory.getRelative("MODULE.bazel").getPathString(),
+ "use_extension('//:extensions.bzl', 'my_ext')",
+ "module(name='aaa',version='0.1',repo_name='bbb')");
+ FakeRegistry registry = registryFactory.newFakeRegistry("/foo");
+ ModuleFileFunction.REGISTRIES.set(differencer, ImmutableList.of(registry.getUrl()));
+
+ reporter.removeHandler(failFastHandler); // expect failures
+ evaluator.evaluate(ImmutableList.of(ModuleFileValue.KEY_FOR_ROOT_MODULE), evaluationContext);
+
+ assertContainsEvent("if module() is called, it must be called before any other functions");
+ }
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/StarlarkBazelModuleTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/StarlarkBazelModuleTest.java
index 16fea23fe95156..3f655551f24383 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/StarlarkBazelModuleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/StarlarkBazelModuleTest.java
@@ -24,6 +24,7 @@
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Type;
@@ -43,8 +44,10 @@ private static ModuleExtensionUsage.Builder getBaseUsageBuilder() {
return ModuleExtensionUsage.builder()
.setExtensionBzlFile("//:rje.bzl")
.setExtensionName("maven")
+ .setUsingModule(ModuleKey.ROOT)
.setLocation(Location.BUILTIN)
- .setImports(ImmutableBiMap.of());
+ .setImports(ImmutableBiMap.of())
+ .setDevImports(ImmutableSet.of());
}
/** A builder for ModuleExtension that sets all the mandatory but irrelevant fields. */
| train | test | 2023-04-21T16:29:25 | "2023-03-29T05:22:19Z" | fmeum | test |
bazelbuild/bazel/10363_18185 | bazelbuild/bazel | bazelbuild/bazel/10363 | bazelbuild/bazel/18185 | [
"keyword_pr_to_issue"
] | c1fea137312248d606bbb73bac1ab4a4e87557a2 | 5772747c4618df76113d801be72d718e562d0fb1 | [
"We saw such bugs before; we refined the file deletion logic to deal with ever more situations, alas it's still incomplete apparently.\r\n\r\nDo you know anything else about those files? Are they marked read-only?\r\n\r\n@buchgr -- do you think those files might be held open?",
"Well, on the server this is quite frequent. It affects all binaries (.exe and .dll), and my best guess is that it is connected to anti-virus or Windows defender is scanning the file, and therefore locking it.\r\n\r\nWhen the server is entered, there is no problem to remove the binary, and nothing that is locking it.",
"I have some more info, most likely it is Windows Defender that locks the files, and the locking can last from minutes up to 30+ min. (so the unlocking period is not permanent, it is only very long)\r\n\r\nOnly specific files are affected, so far: .dll, .exe, .bin, .a and maybe .exp\r\n\r\nMost of the time the locking period is short, and then it only affects repeated jobs on the server side.\r\nHowever, when the locking period is long, also local users are affected.\r\n\r\n\"Unlocker\" can unlock the files in all cases, so the current solution is to walk through the output tree, and delete any locked binaries before the build (which takes quite some time on Windows.)",
"Is there any update on this issue? I'm still facing the same issue on Bazel 4.1.0 on Windows 10.",
"Having this issue sometimes. It'd be great if it printed out the path for the file so I could use some other way to delete it.\r\n\r\nedit: I found that `bazel clean` will list the file, but I'll have trouble deleting it normally even with sudo. doing `sudo rm -rf /home/$USER/.cache/bazel` seems to delete them on wsl, but also nukes bazel completely, requiring it to rebuild and reacquire everything.",
"I'm seeing this a lot when building android targets with `bazel mobile-install`. It's incredibly irritating because it doesn't tell me which files to remove and in order to continue I have to `bazel clean`, which then forces me to rebuild *everything* (and re-sync IntelliJ) even though I suspect only some outputs related to the `android_binary` are the problem. It would be nice if there was a way to `bazel clean` a single target.",
"I just encountered this bug on a Windows machine in GitHub Actions while building a jar file that does not contain any native code.",
"I debugged another instance in which this happend and traced it back to being caused by an attempted rebuild of the rules_kotlin worker while it was still running due to a previous build request.\r\n\r\n@larsrc-google Is the case of using non-prebuilt workers fully supported? It looks like all worker processes would need to be shut down before the worker dependencies can be rebuilt - at least on Windows, where deleting a file that is held open by a process isn't possible.",
"That does make sense. That is a Windows-specific problem, and I don't have a good immediate solution. ",
"@larsrc-google A workaround that shouldn't be too costly could be to restart all workers on Windows when the analysis cache is discarded. What do you think?"
] | [] | "2023-04-23T19:40:38Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: failed to delete output files before executing action (.dll) | ### Description of the problem / feature request:
When compiling on Windows, sometimes .dll cannot be deleted.
The typical error message is: " xx.dll: failed to delete output files before executing action"
I am using remote_cache with remote_download_minimal, and it seems those items that actually are left in the local cache, sometimes cannot be deleted.
Manually you can delete the .dlls just fine, so a workaround for now is to search the local cache for .dlls and delete them before server side compilation.
I have previously seen problems when defender or anti-virus is temporarily locking files. However this failure is permanent: Bazel cannot delete the files, the user can.
### Feature requests: what underlying problem are you trying to solve with this feature?
1. Get a better error message when this error occurs (permission, read error etc).
2. Create a more stable way to delete files on windows (retry?, unlocking?)
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
It is sporadic, but probably connected to remote_cache
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
1.2.0
### Have you found anything relevant by searching the web?
Nothing
### Any other information, logs, or outputs that you want to share?
No.
| [
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java"
] | [
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java"
] | [
"src/test/java/com/google/devtools/build/lib/actions/ActionExecutionExceptionTest.java",
"src/test/java/com/google/devtools/build/lib/actions/BUILD"
] | diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java
index 613a15187a6d47..d81adfd419c5de 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java
+++ b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionException.java
@@ -57,7 +57,7 @@ public ActionExecutionException(
ActionAnalysisMetadata action,
boolean catastrophe,
DetailedExitCode detailedExitCode) {
- super(message, cause);
+ super(combineMessages(message, cause), cause);
this.action = action;
this.catastrophe = catastrophe;
this.detailedExitCode = checkNotNull(detailedExitCode);
@@ -96,7 +96,7 @@ public ActionExecutionException(
NestedSet<Cause> rootCauses,
boolean catastrophe,
DetailedExitCode detailedExitCode) {
- super(message, cause);
+ super(combineMessages(message, cause), cause);
this.action = action;
this.rootCauses = rootCauses;
this.catastrophe = catastrophe;
@@ -203,4 +203,12 @@ public DetailedExitCode getDetailedExitCode() {
public boolean showError() {
return getMessage() != null;
}
+
+ @Nullable
+ private static String combineMessages(String message, @Nullable Throwable cause) {
+ if (cause == null || cause.getMessage() == null) {
+ return message;
+ }
+ return message + ": " + cause.getMessage();
+ }
}
| diff --git a/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionExceptionTest.java b/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionExceptionTest.java
new file mode 100644
index 00000000000000..8fc50ff9e2f20b
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionExceptionTest.java
@@ -0,0 +1,45 @@
+// 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.
+
+package com.google.devtools.build.lib.actions;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
+import com.google.devtools.build.lib.actions.util.TestAction.DummyAction;
+import com.google.devtools.build.lib.server.FailureDetails.Execution;
+import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
+import com.google.devtools.build.lib.util.DetailedExitCode;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** {@link ActionExecutionException}Test */
+@RunWith(JUnit4.class)
+public final class ActionExecutionExceptionTest {
+
+ @Test
+ public void containsCauseMessage() {
+ Exception e =
+ new ActionExecutionException(
+ "message",
+ new Exception("cause"),
+ new DummyAction(ActionsTestUtil.DUMMY_ARTIFACT, ActionsTestUtil.DUMMY_ARTIFACT),
+ false,
+ DetailedExitCode.of(
+ FailureDetail.newBuilder().setExecution(Execution.getDefaultInstance()).build()));
+ assertThat(e).hasMessageThat().contains("message");
+ assertThat(e).hasMessageThat().contains("cause");
+ }
+}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/BUILD b/src/test/java/com/google/devtools/build/lib/actions/BUILD
index 0cabee71ee39ea..ac8d1b48587ef4 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/actions/BUILD
@@ -63,6 +63,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/skyframe/serialization/testutils",
"//src/main/java/com/google/devtools/build/lib/skyframe/serialization/testutils:depsutils",
"//src/main/java/com/google/devtools/build/lib/util",
+ "//src/main/java/com/google/devtools/build/lib/util:detailed_exit_code",
"//src/main/java/com/google/devtools/build/lib/util:filetype",
"//src/main/java/com/google/devtools/build/lib/util:string",
"//src/main/java/com/google/devtools/build/lib/vfs",
| val | test | 2023-04-21T23:47:24 | "2019-12-04T11:19:35Z" | ozio85 | test |
bazelbuild/bazel/18248_18259 | bazelbuild/bazel | bazelbuild/bazel/18248 | bazelbuild/bazel/18259 | [
"keyword_pr_to_issue"
] | 034f6464a19c560ba6d9e0159183075177d7ffb9 | 286306e8358542ce272f7442075bf157a2a62ec7 | [
"I'd also like to note this is rather hard to work around.\r\n\r\nFabian suggested creating an extension that creates a \"middleman\" repo. The extension detects if its the root module, and, if so, populates the middleman with references to the real toolchains. If not, then it puts a fake toolchain in so downstream users inheriting the register_toolchains() call don't break. Implementing this, however, is...well I haven't really figured out a good way, yet. You can't alias `:all`; alias() doesn't work with toolchains; symlinking the underlying build file introduces more complications with repo visibility. Maybe I'm missing something obvious, but it's turning into a headache."
] | [] | "2023-04-28T12:44:51Z" | [
"type: feature request",
"team-ExternalDeps",
"untriaged"
] | Allow dev_dependency register_toolchains calls | ### Description of the feature request:
Allow `register_toolchains(dev_dependency=True)` so that MODULE files can register toolchains only necessary for development and testing.
The specific case I'm dealing with is documentation generation: generating docs for my code is a dev-time only activity, but it uses tools that use toolchains.
Unfortunately, any `register_toolchains()` call in my module will propagate to consumers. This puts me in a catch-22: if I add register_toolchains(), my users are broken (because it'll try to register toolchains that were never setup). If I don't add it, my docgen tools can't run.
This idea is easily expanded: One might have various tools only necessary for development purposes (lints, test runners, debuggers, type checkers, etc), and it makes sense those tools would rely on some language toolchain. But those toolchains aren't necessary for any users, nor should they depend on them in any way.
cc
@fmeum as he mentioned he proposed this idea in the past
@Wyverald pretty sure he owns bzlmod
### What underlying problem are you trying to solve with this feature?
Making it possible to have dev-time only dependencies that rely on toolchains.
### Which operating system are you running Bazel on?
linux
### What is the output of `bazel info release`?
release 6.1.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
[email protected]:rickeylev/rules_testing.git
79fd58291d29e22fe92542ca8c35f4af9ee8021a
79fd58291d29e22fe92542ca8c35f4af9ee8021a
```
### Have you found anything relevant by searching the web?
nothing found
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java"
] | [
"src/test/java/com/google/devtools/build/lib/skyframe/RegisteredExecutionPlatformsFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
index c2800b99f70759..a3d92a8026a583 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleFileGlobals.java
@@ -347,13 +347,27 @@ public void bazelDep(
+ " selected. Should be absolute target patterns (ie. beginning with either"
+ " <code>@</code> or <code>//</code>). See <a href=\"${link toolchains}\">toolchain"
+ " resolution</a> for more information.",
+ parameters = {
+ @Param(
+ name = "dev_dependency",
+ doc =
+ "If true, the execution platforms will not be registered if the current module is"
+ + " not the root module or `--ignore_dev_dependency` is enabled.",
+ named = true,
+ positional = false,
+ defaultValue = "False"),
+ },
extraPositionals =
@Param(
name = "platform_labels",
allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)},
doc = "The labels of the platforms to register."))
- public void registerExecutionPlatforms(Sequence<?> platformLabels) throws EvalException {
+ public void registerExecutionPlatforms(boolean devDependency, Sequence<?> platformLabels)
+ throws EvalException {
hadNonModuleCall = true;
+ if (ignoreDevDeps && devDependency) {
+ return;
+ }
module.addExecutionPlatformsToRegister(
checkAllAbsolutePatterns(platformLabels, "register_execution_platforms"));
}
@@ -365,13 +379,27 @@ public void registerExecutionPlatforms(Sequence<?> platformLabels) throws EvalEx
+ " Should be absolute target patterns (ie. beginning with either <code>@</code> or"
+ " <code>//</code>). See <a href=\"${link toolchains}\">toolchain resolution</a> for"
+ " more information.",
+ parameters = {
+ @Param(
+ name = "dev_dependency",
+ doc =
+ "If true, the toolchains will not be registered if the current module is not the"
+ + " root module or `--ignore_dev_dependency` is enabled.",
+ named = true,
+ positional = false,
+ defaultValue = "False"),
+ },
extraPositionals =
@Param(
name = "toolchain_labels",
allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)},
doc = "The labels of the toolchains to register."))
- public void registerToolchains(Sequence<?> toolchainLabels) throws EvalException {
+ public void registerToolchains(boolean devDependency, Sequence<?> toolchainLabels)
+ throws EvalException {
hadNonModuleCall = true;
+ if (ignoreDevDeps && devDependency) {
+ return;
+ }
module.addToolchainsToRegister(
checkAllAbsolutePatterns(toolchainLabels, "register_toolchains"));
}
| diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredExecutionPlatformsFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredExecutionPlatformsFunctionTest.java
index f44837d61141d6..cda1434744fe9c 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredExecutionPlatformsFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredExecutionPlatformsFunctionTest.java
@@ -342,6 +342,7 @@ public void testRegisteredExecutionPlatforms_bzlmod() throws Exception {
scratch.overwriteFile(
"MODULE.bazel",
"register_execution_platforms('//:plat')",
+ "register_execution_platforms('//:dev_plat',dev_dependency=True)",
"bazel_dep(name='bbb',version='1.0')",
"bazel_dep(name='ccc',version='1.1')");
registry
@@ -349,11 +350,13 @@ public void testRegisteredExecutionPlatforms_bzlmod() throws Exception {
createModuleKey("bbb", "1.0"),
"module(name='bbb',version='1.0')",
"register_execution_platforms('//:plat')",
+ "register_execution_platforms('//:dev_plat',dev_dependency=True)",
"bazel_dep(name='ddd',version='1.0')")
.addModule(
createModuleKey("ccc", "1.1"),
"module(name='ccc',version='1.1')",
"register_execution_platforms('//:plat')",
+ "register_execution_platforms('//:dev_plat',dev_dependency=True)",
"bazel_dep(name='ddd',version='1.1')")
// [email protected] is not selected
.addModule(
@@ -372,7 +375,8 @@ public void testRegisteredExecutionPlatforms_bzlmod() throws Exception {
moduleRoot.getRelative(repo).getRelative("BUILD").getPathString(),
"platform(name='plat')");
}
- scratch.overwriteFile("BUILD", "platform(name='plat');platform(name='wsplat')");
+ scratch.overwriteFile(
+ "BUILD", "platform(name='plat')", "platform(name='dev_plat')", "platform(name='wsplat')");
rewriteWorkspace("register_execution_platforms('//:wsplat')");
SkyKey executionPlatformsKey = RegisteredExecutionPlatformsValue.key(targetConfigKey);
@@ -388,6 +392,7 @@ public void testRegisteredExecutionPlatforms_bzlmod() throws Exception {
assertExecutionPlatformLabels(result.get(executionPlatformsKey))
.containsExactly(
Label.parseCanonical("//:plat"),
+ Label.parseCanonical("//:dev_plat"),
Label.parseCanonical("@@bbb~1.0//:plat"),
Label.parseCanonical("@@ccc~1.1//:plat"),
Label.parseCanonical("@@eee~1.0//:plat"),
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
index 5adfeb0b2f4660..2374e2c62126cb 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
@@ -307,6 +307,7 @@ public void testRegisteredToolchains_bzlmod() throws Exception {
scratch.overwriteFile(
"MODULE.bazel",
"register_toolchains('//:tool')",
+ "register_toolchains('//:dev_tool',dev_dependency=True)",
"bazel_dep(name='bbb',version='1.0')",
"bazel_dep(name='ccc',version='1.1')",
"bazel_dep(name='toolchain_def',version='1.0')");
@@ -315,12 +316,14 @@ public void testRegisteredToolchains_bzlmod() throws Exception {
createModuleKey("bbb", "1.0"),
"module(name='bbb',version='1.0')",
"register_toolchains('//:tool')",
+ "register_toolchains('//:dev_tool',dev_dependency=True)",
"bazel_dep(name='ddd',version='1.0')",
"bazel_dep(name='toolchain_def',version='1.0')")
.addModule(
createModuleKey("ccc", "1.1"),
"module(name='ccc',version='1.1')",
"register_toolchains('//:tool')",
+ "register_toolchains('//:dev_tool',dev_dependency=True)",
"bazel_dep(name='ddd',version='1.1')",
"bazel_dep(name='toolchain_def',version='1.0')")
// [email protected] is not selected
@@ -328,11 +331,13 @@ public void testRegisteredToolchains_bzlmod() throws Exception {
createModuleKey("ddd", "1.0"),
"module(name='ddd',version='1.0')",
"register_toolchains('//:tool')",
+ "register_toolchains('//:dev_tool',dev_dependency=True)",
"bazel_dep(name='toolchain_def',version='1.0')")
.addModule(
createModuleKey("ddd", "1.1"),
"module(name='ddd',version='1.1')",
"register_toolchains('@eee//:tool', '//:tool')",
+ "register_toolchains('@eee//:dev_tool',dev_dependency=True)",
"bazel_dep(name='eee',version='1.0')",
"bazel_dep(name='toolchain_def',version='1.0')")
.addModule(
@@ -369,11 +374,13 @@ public void testRegisteredToolchains_bzlmod() throws Exception {
scratch.file(
moduleRoot.getRelative(repo).getRelative("BUILD").getPathString(),
"load('@toolchain_def//:toolchain_def.bzl', 'declare_toolchain')",
- "declare_toolchain(name='tool')");
+ "declare_toolchain(name='tool')",
+ "declare_toolchain(name='dev_tool')");
}
scratch.overwriteFile(
"BUILD",
"load('@toolchain_def//:toolchain_def.bzl', 'declare_toolchain')",
+ "declare_toolchain(name='dev_tool')",
"declare_toolchain(name='tool')",
"declare_toolchain(name='wstool')");
rewriteWorkspace("register_toolchains('//:wstool')");
@@ -391,6 +398,7 @@ public void testRegisteredToolchains_bzlmod() throws Exception {
assertToolchainLabels(result.get(toolchainsKey))
.containsAtLeast(
Label.parseCanonical("//:tool_impl"),
+ Label.parseCanonical("//:dev_tool_impl"),
Label.parseCanonical("@@bbb~1.0//:tool_impl"),
Label.parseCanonical("@@ccc~1.1//:tool_impl"),
Label.parseCanonical("@@eee~1.0//:tool_impl"),
| val | test | 2023-04-28T15:28:31 | "2023-04-27T21:33:27Z" | rickeylev | test |
bazelbuild/bazel/13441_18412 | bazelbuild/bazel | bazelbuild/bazel/13441 | bazelbuild/bazel/18412 | [
"keyword_pr_to_issue"
] | caf00d542e16d546f88b3512461825dbde7d18b8 | 2a026e6b382eea299963b4bbd0ee94aa3fba0db0 | [
"@Wyverald Just noticed that this could also be relevant to your proposal."
] | [] | "2023-05-15T22:58:35Z" | [
"type: bug",
"P2",
"team-ExternalDeps"
] | Repository rule restart behavior depends on attribute names | ### Description of the problem / feature request:
As the documentation clearly states, repository rules will be restarted whenever the content of any file used and referred to by a label changes. If a repository rule depends on a filegroup for example and the contents of a file in that filegroup changes, the rule will not be restarted.
However, the logic that finds all files referred to directly by attributes stops on the first label-attribute that doesn't resolve to an existing files. On top of that, the order in which the attributes are checked seems to depend on the names of those attributes. That means that a repository rule depending on both a direct file and a filegroup can have the direct file as a restarting dependency or not, depending on the names of the attributes.
The restarting behavior can also be confirmed in the `@<external_name>.marker` files in the output base, where it only in some cases lists the direct file on a `FILE:`-line.
### Feature requests: what underlying problem are you trying to solve with this feature?
Make repository rule restarting behavior well defined and more predictable.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Small example with a repository downloading a file with a dependency on two empty local files `foo` and `bar`:
``` python
# WORKSPACE
load("my_http_download.bzl", "my_http_download")
my_http_download(
name = "example",
foo = "//:foo",
bar = "//:bar",
)
```
``` python
# my_http_download.bzl
def _my_http_download(ctx):
ctx.download(
url = "https://example.com",
output = "index.html",
)
ctx.file("WORKSPACE")
ctx.file("BUILD", content="exports_files(['index.html'])")
my_http_download = repository_rule(
implementation = _my_http_download,
attrs = {
"foo": attr.label(),
"bar": attr.label(),
}
)
```
``` python
# BUILD
filegroup(
name = "foo_filegroup",
srcs = ["foo"],
visibility = ["//visibility:public"],
)
filegroup(
name = "bar_filegroup",
srcs = ["bar"],
visibility = ["//visibility:public"],
)
```
and `bazel build @example//:index.html`
* Changing the dependency on `//:foo` into `//:foo_filegroup` makes the rule only restart when `bar` changes (as expected).
* Changing the dependency on `//:bar` into `//:bar_filegroup` (but keeping the dependency on `//:foo`) makes the rule NOT restart when `foo` changes.
If the name of the `foo` attribute changes to `afoo` the incorrect behavior is the other way around:
* Changing the dependency on `//:bar` into `//:bar_filegroup` makes the rule only restart when `foo` changes (as expected).
* Changing the dependency on `//:foo` into `//:foo_filegroup` (but keeping the dependency on `//:bar`) makes the rule NOT restart when `bar` changes.
### What operating system are you running Bazel on?
Arch Linux, same behavior observed on CentOS 7.
### What's the output of `bazel info release`?
release 4.0.0
### Have you found anything relevant by searching the web?
The checking on direct files seems to happen here: https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java#L189
As the `EvalException` is caught outside the loop, the other attributes are not checked anymore after throwing. | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java"
] | [
"src/test/shell/bazel/starlark_prefetching_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
index 2a8b59d80e5d25..dd8ad14c9b9fc8 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
@@ -31,6 +31,7 @@
import com.google.devtools.build.lib.packages.StructProvider;
import com.google.devtools.build.lib.pkgcache.PathPackageLocator;
import com.google.devtools.build.lib.repository.RepositoryFetchProgress;
+import com.google.devtools.build.lib.rules.repository.NeedsSkyframeRestartException;
import com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException;
import com.google.devtools.build.lib.rules.repository.WorkspaceAttributeMapper;
import com.google.devtools.build.lib.runtime.ProcessWrapper;
@@ -516,26 +517,42 @@ public String toString() {
*/
// TODO(wyv): somehow migrate this to the base context too.
public void enforceLabelAttributes() throws EvalException, InterruptedException {
+ // TODO: If a labels fails to resolve to an existing regular file, we do not add a dependency on
+ // that fact - if the file is created later or changes its type, it will not trigger a rerun of
+ // the repository function.
StructImpl attr = getAttr();
for (String name : attr.getFieldNames()) {
Object value = attr.getValue(name);
if (value instanceof Label) {
- getPathFromLabel((Label) value);
+ dependOnLabelIgnoringErrors((Label) value);
}
if (value instanceof Sequence) {
for (Object entry : (Sequence) value) {
if (entry instanceof Label) {
- getPathFromLabel((Label) entry);
+ dependOnLabelIgnoringErrors((Label) entry);
}
}
}
if (value instanceof Dict) {
for (Object entry : ((Dict) value).keySet()) {
if (entry instanceof Label) {
- getPathFromLabel((Label) entry);
+ dependOnLabelIgnoringErrors((Label) entry);
}
}
}
}
}
+
+ private void dependOnLabelIgnoringErrors(Label label)
+ throws InterruptedException, NeedsSkyframeRestartException {
+ try {
+ getPathFromLabel(label);
+ } catch (NeedsSkyframeRestartException e) {
+ throw e;
+ } catch (EvalException e) {
+ // EvalExceptions indicate labels not referring to existing files. This is fine,
+ // as long as they are never resolved to files in the execution of the rule; we allow
+ // non-strict rules.
+ }
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
index 83772d1fd28194..140697445739bb 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
@@ -198,11 +198,6 @@ public RepositoryDirectoryValue.Builder fetch(
} catch (NeedsSkyframeRestartException e) {
// Missing values are expected; just restart before we actually start the rule
return null;
- } catch (EvalException e) {
- // EvalExceptions indicate labels not referring to existing files. This is fine,
- // as long as they are never resolved to files in the execution of the rule; we allow
- // non-strict rules. So now we have to start evaluating the actual rule, even if that
- // means the rule might get restarted for legitimate reasons.
}
// This rule is mainly executed for its side effect. Nevertheless, the return value is
| diff --git a/src/test/shell/bazel/starlark_prefetching_test.sh b/src/test/shell/bazel/starlark_prefetching_test.sh
index f12c7426c617bd..69e5bfda740c30 100755
--- a/src/test/shell/bazel/starlark_prefetching_test.sh
+++ b/src/test/shell/bazel/starlark_prefetching_test.sh
@@ -227,4 +227,48 @@ EOF
bazel build @ext//:foo || fail "expected success"
}
+# Regression test for https://github.com/bazelbuild/bazel/issues/13441
+function test_files_tracked_with_non_existing_files() {
+ cat > rules.bzl <<'EOF'
+def _repo_impl(ctx):
+ ctx.symlink(ctx.path(Label("@//:WORKSPACE")).dirname, "link")
+ print("b.txt: " + ctx.read("link/b.txt"))
+ print("c.txt: " + ctx.read("link/c.txt"))
+
+ ctx.file("BUILD")
+ ctx.file("WORKSPACE")
+
+repo = repository_rule(
+ _repo_impl,
+ attrs = {"_files": attr.label_list(
+ default = [
+ Label("@//:a.txt"),
+ Label("@//:b.txt"),
+ Label("@//:c.txt"),
+ ],
+ )},
+)
+EOF
+
+ cat > WORKSPACE <<'EOF'
+load(":rules.bzl", "repo")
+repo(name = "ext")
+EOF
+ touch BUILD
+
+ # a.txt is intentionally not created
+ echo "bbbb" > b.txt
+ echo "cccc" > c.txt
+
+ # The missing file dependency is tolerated.
+ bazel build @ext//:all &> "$TEST_log" || fail "Expected repository rule to build"
+ expect_log "b.txt: bbbb"
+ expect_log "c.txt: cccc"
+
+ echo "not_cccc" > c.txt
+ bazel build @ext//:all &> "$TEST_log" || fail "Expected repository rule to build"
+ expect_log "b.txt: bbbb"
+ expect_log "c.txt: not_cccc"
+}
+
run_suite "Starlark repo prefetching tests"
| test | test | 2023-06-05T20:00:38 | "2021-05-07T10:11:51Z" | getim | test |
bazelbuild/bazel/18291_18414 | bazelbuild/bazel | bazelbuild/bazel/18291 | bazelbuild/bazel/18414 | [
"keyword_pr_to_issue"
] | 40d3998a45326ff8bf61d971710ea3e6de8c0261 | 7bdd173605514eb15ee69db79a5418b701d6c10d | [] | [] | "2023-05-15T23:15:58Z" | [
"type: bug",
"team-ExternalDeps",
"untriaged"
] | Bazel Unrecoverable Error with Capital Letters in SHA256 String | ### Description of the bug:
If there is a capital letter present in the SHA256 string bazel crashes with the fatal error contained below. Some tools, specifically [Get-FileHash](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-7.3) on Windows return upper case SHA256 strings.
The `Illegal hexadecimal character` error message does not make it clear that the problem is that uppercase letters are not valid in a bazel SHA256 string.
The code should either be updated so that letter case doesn't matter or the error message should specifically state that upper case letters are not accepted.
---
```
java.lang.RuntimeException: Unrecoverable error while evaluating node 'REPOSITORY_DIRECTORY:@bazel_skylib' (requested by nodes 'PACKAGE_LOOKUP:@bazel_skylib//')
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:642)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: net.starlark.java.eval.Starlark$UncheckedEvalException: IllegalArgumentException thrown during Starlark evaluation (LOADING)
at <starlark>.download_and_extract(<builtin>:0)
at <starlark>._http_archive_impl(/private/var/tmp/_bazel_abeattie/6d30cdea4ede9832a87c4794c274b995/external/bazel_tools/tools/build_defs/repo/http.bzl:132)
Caused by: java.lang.IllegalArgumentException: Illegal hexadecimal character: D
at com.google.common.hash.HashCode.decode(HashCode.java:360)
at com.google.common.hash.HashCode.fromString(HashCode.java:346)
at com.google.devtools.build.lib.bazel.repository.downloader.Checksum.fromString(Checksum.java:47)
at com.google.devtools.build.lib.bazel.repository.starlark.StarlarkBaseExternalContext.validateChecksum(StarlarkBaseExternalContext.java:302)
at com.google.devtools.build.lib.bazel.repository.starlark.StarlarkBaseExternalContext.downloadAndExtract(StarlarkBaseExternalContext.java:650)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at net.starlark.java.eval.MethodDescriptor.call(MethodDescriptor.java:162)
at net.starlark.java.eval.BuiltinFunction.fastcall(BuiltinFunction.java:77)
at net.starlark.java.eval.Starlark.fastcall(Starlark.java:638)
at net.starlark.java.eval.Eval.evalCall(Eval.java:682)
at net.starlark.java.eval.Eval.eval(Eval.java:497)
at net.starlark.java.eval.Eval.execAssignment(Eval.java:109)
at net.starlark.java.eval.Eval.exec(Eval.java:268)
at net.starlark.java.eval.Eval.execStatements(Eval.java:82)
at net.starlark.java.eval.Eval.execFunctionBody(Eval.java:66)
at net.starlark.java.eval.StarlarkFunction.fastcall(StarlarkFunction.java:173)
at net.starlark.java.eval.Starlark.fastcall(Starlark.java:638)
at net.starlark.java.eval.Starlark.call(Starlark.java:604)
at com.google.devtools.build.lib.bazel.repository.starlark.StarlarkRepositoryFunction.fetch(StarlarkRepositoryFunction.java:220)
at com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction.fetchRepository(RepositoryDelegatorFunction.java:413)
at com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction.compute(RepositoryDelegatorFunction.java:344)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:571)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:382)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
```
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Fails:
```
http_archive(
name = "bazel_skylib",
sha256 = "74D544D96F4A5BB630D465CA8BBCFE231E3594E5AAE57E1EDBF17A6EB3CA2506",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
],
)
```
Succeeds:
```
http_archive(
name = "bazel_skylib",
sha256 = "74d544d96f4a5bb630d465ca8bbcfe231e3594e5aae57e1edbf17a6eb3ca2506",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
],
)
```
### Which operating system are you running Bazel on?
Windows & MacOS
### What is the output of `bazel info release`?
6.1.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java"
] | [
"src/test/shell/bazel/external_integration_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java
index a63e1b4f4a5bf9..09b3aeea884ac0 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/Checksum.java
@@ -14,6 +14,7 @@
package com.google.devtools.build.lib.bazel.repository.downloader;
+import com.google.common.base.Ascii;
import com.google.common.hash.HashCode;
import com.google.devtools.build.lib.bazel.repository.cache.RepositoryCache.KeyType;
import java.util.Base64;
@@ -44,7 +45,7 @@ public static Checksum fromString(KeyType keyType, String hash) throws InvalidCh
if (!keyType.isValid(hash)) {
throw new InvalidChecksumException(keyType, hash);
}
- return new Checksum(keyType, HashCode.fromString(hash));
+ return new Checksum(keyType, HashCode.fromString(Ascii.toLowerCase(hash)));
}
/** Constructs a new Checksum from a hash in Subresource Integrity format. */
| diff --git a/src/test/shell/bazel/external_integration_test.sh b/src/test/shell/bazel/external_integration_test.sh
index 7216fd1412760a..a6092e9110164b 100755
--- a/src/test/shell/bazel/external_integration_test.sh
+++ b/src/test/shell/bazel/external_integration_test.sh
@@ -221,6 +221,22 @@ EOF
assert_contains "test content" "${base_external_path}/test_dir/test_file"
}
+function test_http_archive_upper_case_sha() {
+ cat >> $(create_workspace_with_default_repos WORKSPACE) <<EOF
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+http_archive(
+ name = 'test_zstd_repo',
+ url = 'file://$(rlocation io_bazel/src/test/shell/bazel/testdata/zstd_test_archive.tar.zst)',
+ sha256 = '12B0116F2A3C804859438E102A8A1D5F494C108D1B026DA9F6CA55FB5107C7E9',
+ build_file_content = 'filegroup(name="x", srcs=glob(["*"]))',
+)
+EOF
+ bazel build @test_zstd_repo//...
+
+ base_external_path=bazel-out/../external/test_zstd_repo
+ assert_contains "test content" "${base_external_path}/test_dir/test_file"
+}
+
function test_http_archive_no_server() {
cat >> $(create_workspace_with_default_repos WORKSPACE) <<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
| test | test | 2023-06-02T20:42:25 | "2023-05-03T07:37:37Z" | alexbeattie42 | test |
bazelbuild/bazel/17281_18415 | bazelbuild/bazel | bazelbuild/bazel/17281 | bazelbuild/bazel/18415 | [
"keyword_pr_to_issue"
] | 27b4fe81640aa8f94f63bfc8fcb9820f34687114 | 575665283e0ff4830bb87ea4e48b4b6f0e714405 | [
"@comius @cushon Could you take a look? It may end up just being a doc issue, but it does seem likely to break users of the Java runfiles library updating to Bazel 6.",
"I think the issue might be that the JDK version that's used to run JavaBuilder isn't controlled by `--tool_java_runtime=` version, it's configured with the `java_toolchain.java_runtime` attribute.\r\n\r\nPart of the motivation for that is that it lets us ensure JavaBuilder is running on a relative recent JDK version, even if a build wants to use an older `--tool_java_runtime=`. But it also makes it harder to use a newer `--tool_java_runtime=`.\r\n\r\nInternally we're using the latest available JDK as the `java_toolchain.java_runtime`. One option is to just update the default to a newer version, but the latest javac versions have dropped support for `-source 7 -target 7`, so that's probably an aggressive default for Bazel.\r\n\r\nAnother option here might just be to document how to configure a custom `java_toolchain` that sets a matching `java_runtime`.",
"What I find surprising is that setting `--java_runtime_version=remotejdk_17 --tool_java_runtime_version=remotejdk_17` doesn't fix this, only `--java_language_version=17` does. Is that expected? I would have assume that `--java_language_version` only affects the `-source` and `-target` values, but not the runtime used to run `JavaBuilder`.\r\n\r\nIs there a way to set up the toolchain so that a recent JDK is used for compilation (both target and tool) but target compilation outputs remain compatible with old JDKs and are also tested against these old JDKs?",
"> Is there a way to set up the toolchain so that a recent JDK is used for compilation (both target and tool) but target compilation outputs remain compatible with old JDKs and are also tested against these old JDKs?\r\n\r\nI remembered that this is eventually going to be improved by https://github.com/bazelbuild/bazel/commit/75e0f7dfea71a7bd40b4bdb601f64217650e8d47 making it into a `java_tools` release, which will update the default `java_toolchain.java_runtime` to JDK 17\r\n\r\nThe issue you encountered in this bug could still come up for `--tool_java_language_version`s newer than 17, though. It would be nice if a bleeding-edge `--tool_java_language_version` just worked without having to define a custom `java_toolchain`.\r\n\r\n> I would have assume that `--java_language_version` only affects the `-source` and `-target` values, but not the runtime used to run JavaBuilder.\r\n\r\nI agree this is having surprising results here, it's the result of all three of those being configured with `java_toolchain` attributes. The default java_toolchain for the target platform is still `@bazel_tools//tools/jdk:toolchain_java8`, which with Bazel 6.0.0 is setting a JDK 11 `java_runtime`:\r\n\r\n```\r\n$ bazel shutdown; bazel build --toolchain_resolution_debug=//tools/jdk:toolchain_type //:Main --tool_java_language_version=17 --tool_java_runtime_version=remotejdk_17 |& grep 'Selected toolchain'\r\nINFO: ToolchainResolution: Type @bazel_tools//tools/jdk:toolchain_type: target platform @local_config_platform//:host: execution @local_config_platform//:host: Selected toolchain @bazel_tools//tools/jdk:toolchain_java8\r\nINFO: ToolchainResolution: Type @bazel_tools//tools/jdk:toolchain_type: target platform @local_config_platform//:host: execution @local_config_platform//:host: Selected toolchain @bazel_tools//tools/jdk:toolchain_jdk_17\r\n```\r\n\r\n```\r\n$ bazel query --output build @bazel_tools//tools/jdk:toolchain_java8\r\n...\r\n java_runtime = \"@bazel_tools//tools/jdk:remote_jdk11\",\r\n```",
"Thanks for the explanations. Does that mean that the language level of annotation processors is limited by the Java runtime used in the target configuration? If that's the case, would it help if processors were compiled for the target rather than the exec configuration?",
"The language level of annotations processors is limited by the `java_toolchain.java_runtime`.\r\n\r\nIdeally we'd want to ensure that the provided configurations satisfy the following constraints.\r\n\r\n| | | |\r\n| -- | -- | -- |\r\n`--java_runtime_version=` | `>=` | `--java_language_level=`\r\n`--tool_java_runtime_version=` | `>=` | `--tool_java_language_level=`\r\n`java_toolchain.java_runtime` | `>=` | `--tool_java_language_level=`\r\n`java_toolchain.java_runtime` | `>=` | `--java_language_level=`\r\n\r\ni.e. to build code at the Java N language level, you need a JavaBuilder running on JDK >= N to compile it, and a JDK >= N to execute it",
"Thank you for contributing to the Bazel repository! This issue has been marked as stale since it has not had any activity in the last 30 days. It will be closed in the next 7 days unless any other activity occurs or one of the following labels is added: \"not stale\", \"awaiting-bazeler\".",
"Possibly related: https://github.com/bazelbuild/rules_jvm_external/issues/895",
"One more note on that is that another way it satisfy the `java_toolchain.java_runtime >=` constraint is to keep that version upgraded to the latest available JDK. We've been doing that at Google, but it might be too aggressive for Bazel when there are breaking changes like [JDK-8173605](https://bugs.openjdk.org/browse/JDK-8173605)",
"I also ran into this bug building bazel project on Mac. Can we bump the priority?",
"Warnings have been added in Bazel 7 or anything using a recent rules_java release."
] | [] | "2023-05-15T23:21:06Z" | [
"type: bug",
"P2",
"team-Rules-Java",
"not stale"
] | Build with annotation processor fails with higher tool Java language version | ### Description of the bug:
When a Java target uses a `java_plugin` that runs an annotation processor and the `--tool_java_language_version` is higher than the `--java_language_version`, the build fails even if `--java_runtime_version` specifies a JDK version that is at least as high as `--tool_java_language_version`.
Given that this behavior is already triggered by depending on `@bazel_tools//tools/java/runfiles`, we experienced this as a regression when migrating to Bazel 6.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
With this WORKSPACE:
```
# WORKSPACE
# BUILD
java_binary(
name = "Main",
srcs = ["Main.java"],
main_class = "Main",
deps = ["@bazel_tools//tools/java/runfiles"],
)
# Main.java
public class Main {
public static void main(String[] args) {}
}
```
1. `bazel build //:Main` passes
2. `bazel build //:Main --tool_java_language_version=17 --tool_java_runtime_version=remotejdk_17` fails with `Caused by: java.lang.UnsupportedClassVersionError: com/google/devtools/build/runfiles/AutoBazelRepositoryProcessor has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0`
3. `bazel build //:Main --tool_java_language_version=17 --tool_java_runtime_version=remotejdk_17 --java_runtime_version=remotejdk_17` fails with the same error
4. `bazel build //:Main --tool_java_language_version=17 --tool_java_runtime_version=remotejdk_17 --java_runtime_version=remotejdk_17 --java_language_version=11` fails with the same error
5. `bazel build //:Main --tool_java_language_version=17 --tool_java_runtime_version=remotejdk_17 --java_runtime_version=remotejdk_17 --java_language_version=17` passes
I would argue that the failure in 2. is already unexpected: If the Java language levels in tools can't be higher than that for the target configuration, then what is the purpose of the flag? I always assumed that it exists to allow tooling to use modern Java features while limiting the rest of the codebase to something more compatible (e.g. Java 11).
The failures in 3. and 4. are definitely unexpected: Based on https://bazel.build/docs/bazel-and-java#hermetic-testing, I would have expected JDK 17 to be used for compilation with a `-target` value of 11 (3.) or 17 (4.). In both cases, the annotation processor compiled for a Java 17 runtime should be runnable. Instead, using `--verbose_failures`, it looks like `remotejdk_11` is still used for compilation.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"tools/jdk/local_java_repository.bzl"
] | [
"tools/jdk/local_java_repository.bzl"
] | [] | diff --git a/tools/jdk/local_java_repository.bzl b/tools/jdk/local_java_repository.bzl
index 0af39c1dd08c38..6a9a4c99d18529 100644
--- a/tools/jdk/local_java_repository.bzl
+++ b/tools/jdk/local_java_repository.bzl
@@ -62,6 +62,7 @@ def local_java_runtime(name, java_home, version, runtime_name = None, visibility
name = runtime_name,
java_home = java_home,
visibility = visibility,
+ version = int(version) if version.isdigit() else 0,
)
native.config_setting(
| null | train | test | 2023-05-18T00:26:50 | "2023-01-20T10:34:03Z" | fmeum | test |
bazelbuild/bazel/17941_18419 | bazelbuild/bazel | bazelbuild/bazel/17941 | bazelbuild/bazel/18419 | [
"keyword_pr_to_issue"
] | a5c0d85b5531c25b3ae97f9e1ffb0e8bbaaf6636 | e023bd398eb5eb3d16cf1f81ae990460acf44209 | [
"Looks like the Python rules do not add `symlinks` and `root_symlinks` to the ZIP file, which causes the `_repo_mapping` file to be missing. I will try to fix this.",
"https://github.com/bazelbuild/bazel/pull/17942 is the easy part, but this is unfortunately complicated on a deeper level: \r\n\r\nThe `_repo_mapping` file is currently injected directly in https://cs.opensource.google/bazel/bazel/+/6f12510e39153e316f35ab0a1ec376ece7f1b0a9:src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java;l=421, which makes it invisible to the `runfiles` Starlark API.\r\n\r\nWe could instead add it in a way similar to https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java;l=125, but that would construct a new `Runfiles` object for every target.\r\n\r\n~An alternative could be to add the artifact to every `Runfiles` object directly upon construction (as long as Bzlmod is enabled) and then only register the generating action in `RunfilesSupport`.~ Edit: This doesn't work as those `Runfiles` objects wouldn't be mergeable anymore.\r\n\r\n@Wyverald @lberki I could use your help here as I don't have a good grasp on the potential performance implications of these approaches.",
"~Looked into this some more. Even if `RunfilesSupport` adds the repo mapping artifact to root symlinks, the Python rules still wouldn't see it as it is added only after the rule implementation has run. Maybe we need to expose it on `RuleContext`?~\r\n\r\n*Edit*: Cleared up some confusion I had, which led me to this insight: Computing the repo mapping requires the runfiles, so it simply isn't known before the rule commits to its runfiles. Getting it in the context of the rule only seems to be necessary if the rule wants to build a runfiles structure manually for itself - if it did this for some other rule, that rule's repo mapping would be in its runfiles. So unless the Python rules can build the ZIP as part of a separate rule using a macro, maybe `RepoMappingManifestAction` would need to be exposed to Starlark so that users can build their own manifests for arbitrary `runfiles` objects?",
"Let me see if I understand this correctly: the current way Python rules build ZIP files is that they dissect a `Runfiles` object and put the path to artifact mapping on a command line. But repo mappings make it impossible to determine that mapping solely from the `Runfiles` object. Is that correct?\r\n\r\nShooting from the hip, with the current toolbox, I could imagine creating a \"fake\" Python binary which is then put on the inputs of an action and then that action does not execute it, but simply extracts its runfiles tree. Would that work?\r\n",
"@lberki That's exactly correct. If forcing such rules to become macros that obtain the runfiles from an actual target is acceptable, then that is certainly the easiest solution.\r\n\r\n@rickeylev Could the executable Python rules go through a separate target to generate the runfiles that are then packaged up into the executable ZIP file?",
"Is the limitation that makes a macro necessary that `FilesToRunProvider` can only be created once per rule and outside the control of Starlark code and that the only way one can currently add a runfiles tree to the inputs of an action is by using `ctx.actions.run(tools=)` ?",
"> Is the limitation that makes a macro necessary that `FilesToRunProvider` can only be created once per rule and outside the control of Starlark code and that the only way one can currently add a runfiles tree to the inputs of an action is by using `ctx.actions.run(tools=)` ?\r\n\r\nThat is part of the reason. But even if there were a way to turn `Runfiles` into a `FilesToRunProvider` from Starlark, the logic that adds the repository mapping manifest is part of `RunfilesSupport` and `RunfilesSupplier` and may thus not invoked correctly in that way. This may require additional changes.\r\n\r\n",
"> Could the executable Python rules go through a separate target to generate the runfiles that are then packaged up into the executable ZIP file?\r\n\r\nMaybe? That last mile logic to generate the executable for the zip-file case is a bit hairy.\r\n\r\nDoes every target have the repo mapping? Or just certain ones? I'm thinking just have an extra target generated along side with the necessary info, e.g.\r\n\r\n```\r\ndef py_binary(name, ...\r\n repo_mapping(\"_\" + name + \"_repo_map\")\r\n py_binary_rule(..., _INTERNAL_ONLY_REPO_MAP = \"_\" + name + \"_repo_map\")\r\n\r\ndef repo_mapping_impl(ctx):\r\n return [DefaultInfo()] # repo mapping automatically added, right?\r\n\r\ndef py_binary_impl(ctx):\r\n repo_map = ctx.attr._INTERNAL_ONLY_REPO_MAP.runfiles\r\n```\r\n\r\nCouple other thoughts:\r\n* PyBuiltins.java is where various Java-hooks can go. If the necessary info can be easily gotten via Java, that's the place to put such hooks.\r\n* The `input_manifests` arg _might_ be of help? There's a (now unused) helper in PyBuiltins that converts a runfiles object into a RunfilesSupplier.",
"@rickeylev With Bzlmod enabled, every target has the repo mapping as a root symlinks that is injected in `getRunfilesInputs`: https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/analysis/Runfiles.java;drc=0ce17480390cdced2df8d59249561613e81f446f;l=421\nIt may thus not be accessible by rule implementations directly.\n\nThe artifact itself is created in `RunfilesSupport`: https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java;l=135;bpv=1;bpt=1\n\nWe may have to make it available from there.",
"Exposing the RepoMappingManifestAction is part of the problem, but most of what it does is computed beforehand and are inputs into that action. Manually doing that logic does look feasible, though.\r\n\r\nLooking at how RunfilesSupport builds the repo mapping, the two pieces we need are `ruleContext.getTransitivePackagesForRunfileRepoMappingManifest()` and something to get `Package.getPackageIdentifier().getRepository()` (or an equivalent).\r\n\r\nUnfortunately, these both use the `Package` object, which I don't think has a Starlark equivalent. Can an object that doesn't implement the Starlark classes be passed from Java to Starlark? If so, we can just pass them onto another helper in PyBuiltins to operate on. If not, we'll have to convert Package to something else (probably a string or struct), or move more logic to Java (the map building is pretty simple, so this looks quite feasible).\r\n\r\nMaking a Starlark implemented rule's RunfilesSupport available to it during its execution is somewhere near impossible, in particular for the Python rules, so that isn't really an option. Problem 1 is RunfilesSupport is created _after_ the rule function completes. If you try to manually create a RunfilesSupport object during execution (`PyBuiltins.new_empty_runfiles_with_middleman` does such), then it creates the same actions multiple times, which triggers duplicate action conflict detection logic later. Problem 2 is, for the Python rules, the duplicate detection ends up triggering the empty runfiles supplier code multiple times during the analysis phase, which requires flattening the runfiles, and the net effect is a huge CPU and memory regression. If there is some sort of solution involving Starlark+RunfilesSupport, I don't know it :).\r\n\r\nEr, hm. Is that repo mapping code flattening the runfiles during analysis phase? That doesn't sound good, well, a problem for another time.\r\n\r\nIf the action did more of the heavy lifting (computing the map), it would make this easier overall _and_ probably also solve the runfiles-being-flattened-during-analysis issue. We could probably reduce it to a simple helper in PyBuiltins that looked something like:\r\n\r\n```\r\npublic void createRepoMappingManifest(StarlarkRuleContext starlarkCtx, Runfiles runfiles) {\r\n starlarkCtx.registerAction(new RepoMappingAction(\r\n starlarkCtx.getRuleContext().getTransitivePackagesForRunfileRepoMappingManifest(),\r\n runfiles\r\n ));\r\n}\r\n```",
"As far as I remember the repo mapping manifest action isn't really doing much work since actions must be serializable, but `Package`s are not. That's also why the `NestedSet` is indeed flattened during analysis time. \n\nWe only need a tiny fraction of the Package information, so maybe that could be solved with some kind of custom serialization logic for `RepoMappingManifestAction` instead? I don't know much about this area though.",
"I was playing around with this tonight and may have come up with a somewhat simple work around: declare the repo mapping file and add it to the zip, but rely on the subsequent RunfilesSupport code to actually create the file. I think this might also have a bonus: because the same file isn't created twice, duplicate detection doesn't have to run. We can make it a bit less hacky by factoring out a \"get file name\" function from Runfiles.createRepoMappingManifestAction. I'll poke this some more tomorrow to see how promising it is.\r\n\r\nAs a side note, this is the second time I've encountered Starlark code wanting to get at some of the things in RunfilesSupport (the other case was par files, which wanted RunfilesSupport for a similar reason), so maybe there is some missing functionality somewhere.",
"Alright, today's experiment was trying to use a separate target, which looks iffy and unappealing.\r\n\r\n* The repo mapping is only generated and added to the runfiles of executable/test targets. This is due to StarlarkRuleConfiguredTargetUtil#addSimpleProviders (see the RunfilesSupport.withExecutable() call, guarded by the \"is executable or test\" check\r\n* When it is added, its added to the middleman artifact. See RunfilesSupport.createRunfilesMiddleman, where the repoMappingManifest is added to the nested set fed into the middleman\r\n* The code in Runfiles.getRunfilesInputs adds repoMappingManifest to the runfiles manifest, but not the runfiles itself. (and I think this is the manifest that may not be present, depending on a flag?) (Ah, I seem to recall that the manifest and inputs work in tandem: the manifest tells what path to materialize a file under when the runfiles tree is created, and the inputs tell what inputs are actually available)\r\n\r\nThe net effect is, when you look at a target's runfiles, you don't see the repo mapping because it's in the middleman artifact, which I think is a secret dependency of the executable somehow.\r\n\r\nSo, I ran the target through `ctx.resolve_tools()`. This returns the middle man artifact (contained within a depset of all necessary files) and an Starlark-opaque RunfilesSupplier object. Well, we have the RunfilesSupplier now, so I fed that into a java hook to call RunfilesSuppler.getRepoMappingManifest(). This sort of works. It did give a repo mapping file.\r\n\r\nHowever, the resulting repo mapping is only correct if the outer target and inner target have the same dependencies (including implicit deps). In my experiments, I used a stub executable with no dependencies as the \"inner\" target. It's repo map was just the current workspace. The actual repo map includes the various implicit dependencies of py_binary itself (rules_python, platforms, bazel_tools, some others).\r\n\r\nSo to make this work, the inner target needs to copy all the passed in user values and the implicit deps of py_binary, forward along the transitive runfiles (if it doesn't, the repo map won't be correct) (and this particular runfiles object is unused), produce an unused executable file (to satisfy some starlark validations), and then the outer rule needs to dig out the repo mapping somehow. Note that all the attributes have to continue to exist on the outer rule so that things like aspects can still traverse them. I think there might be a more direct route to get the repo mapping than going through the middleman artifact (I think a java hook to go Target->FilesToRunProvider#getRunfilesSupport is possible), but that doesn't help with the generation of its content.\r\n\r\nSo, technically it's possible, but it is pretty wasteful. I'm very wary of generating essentially a copy of py_binary() -- the extra target isn't free; we already know this has a real cost. Within Google, we were forced to do this to make PAR files work and saw the effects in the performance metrics, and only deemed it OK because we didn't really have a choice and plan to make it an opt-in behavior instead of always-on behavior.\r\n\r\nAh -- I see the RepoMappingManifestAction PR got merged! I'll experiment with that -- looks pretty straight forward.",
"@bazel-io flag",
"@bazel-io fork 6.3.0",
"@fmeum @rickeylev should this be now cherry-picked and included in the release-6.3.0?\r\n",
"That would be great, yes.\r\n\r\nNote that this fix (https://github.com/bazelbuild/bazel/commit/4e60992432a49dda255eb005544ae8c03b30e243) requires https://github.com/bazelbuild/bazel/pull/18419/commits/ee46d1a6e1a3ce65384d87e9f6cc5d939e631018",
"> That would be great, yes.\r\n> \r\n> Note that this fix ([4e60992](https://github.com/bazelbuild/bazel/commit/4e60992432a49dda255eb005544ae8c03b30e243)) requires [ee46d1a](https://github.com/bazelbuild/bazel/commit/ee46d1a6e1a3ce65384d87e9f6cc5d939e631018)\r\n\r\n@rickeylev @fmeum I did make sure the commit https://github.com/bazelbuild/bazel/commit/ee46d1a6e1a3ce65384d87e9f6cc5d939e631018 was merged. However, it seems like additional commits needs to be cherry-picked first in order for the commit to be cherrypicked in the release branch. Could you please submit a PR or let us know what commits to include? Currently, there are 3 files that are missing in the release-6.3.0 branch (src/main/java/com/google/devtools/build/lib/rules/python/PyBuiltins.java, src/main/starlark/builtins_bzl/common/python/py_executable_bazel.bzl, src/main/starlark/builtins_bzl/common/python/py_internal.bzl).",
"Ahhh, I forgot most of the Starlark rewrite work didn't make the 6.0 cut. It won't be feasible to port this to 6.x. Even if we did, it'd require re-implementing the fix based on the (now deleted) Java implementation of the rules.",
"> Ahhh, I forgot most of the Starlark rewrite work didn't make the 6.0 cut. It won't be feasible to port this to 6.x. Even if we did, it'd require re-implementing the fix based on the (now deleted) Java implementation of the rules.\r\n\r\ncc: @Wyverald @meteorcloudy "
] | [] | "2023-05-16T09:58:56Z" | [
"type: bug",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | bzlmod + build_python_zip breaks runfiles resolution | ### Description of the bug:
When building a py_binary with `--build_python_zip` and bzlmod enabled, the runfiles cannot be correctly resolved.
Things would work if I remove the `--build_python_zip` option or switch back to the old WORKSPACE style.
I suspect this has something to do with the way bzlmod handle repo mapping.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
I have a very small example to reproduce the issue: https://github.com/coquelicot/broken-bzlmod-pyzip
Here's the log from my machine:
```bash
» bazel run example
INFO: Build option --build_python_zip has changed, discarding analysis cache.
INFO: Analyzed target //:example (0 packages loaded, 539 targets configured).
INFO: Found 1 target...
Target //:example up-to-date:
bazel-bin/example
INFO: Elapsed time: 0.280s, Critical Path: 0.01s
INFO: 4 processes: 4 internal.
INFO: Build completed successfully, 4 total actions
INFO: Running command line: bazel-bin/example
sample
```
```bash
» bazel run --build_python_zip example
INFO: Build option --build_python_zip has changed, discarding analysis cache.
INFO: Analyzed target //:example (0 packages loaded, 539 targets configured).
INFO: Found 1 target...
Target //:example up-to-date:
bazel-bin/example
bazel-bin/example.zip
INFO: Elapsed time: 0.274s, Critical Path: 0.01s
INFO: 4 processes: 3 internal, 1 linux-sandbox.
INFO: Build completed successfully, 4 total actions
INFO: Running command line: bazel-bin/example
Traceback (most recent call last):
File "/tmp/Bazel.runfiles_tuww8rqk/runfiles/_main/example.py", line 11, in <module>
main()
File "/tmp/Bazel.runfiles_tuww8rqk/runfiles/_main/example.py", line 6, in main
with open(path, "r") as fin:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/Bazel.runfiles_tuww8rqk/runfiles/pyzip/data.txt'
```
### Which operating system are you running Bazel on?
linux
### What is the output of `bazel info release`?
release 6.1.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
The way runfiles are implemented seems to be different with bzlmod: https://github.com/bazelbuild/bazel/issues/16124
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/BUILD",
"src/test/java/com/google/devtools/build/lib/analysis/RunfilesRepoMappingManifestTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BUILD b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
index c8b032e3eb9730..546afe042eb40c 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BUILD
@@ -995,9 +995,9 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
+ "//src/main/java/com/google/devtools/build/lib/packages",
"//src/main/java/com/google/devtools/build/lib/util",
"//src/main/java/net/starlark/java/eval",
- "//third_party:auto_value",
"//third_party:guava",
"//third_party:jsr305",
],
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java b/src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java
index 2714680906f90a..59534d2c72f1be 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/RepoMappingManifestAction.java
@@ -13,61 +13,69 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
+import static com.google.common.collect.ImmutableSet.toImmutableSet;
+import static com.google.common.collect.ImmutableSortedMap.toImmutableSortedMap;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.util.Comparator.comparing;
-import com.google.auto.value.AutoValue;
-import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedMap;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.actions.CommandLineExpansionException;
+import com.google.devtools.build.lib.actions.CommandLineItem.MapFn;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction;
import com.google.devtools.build.lib.analysis.actions.DeterministicWriter;
+import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.cmdline.RepositoryName;
+import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
+import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.util.Fingerprint;
import java.io.PrintWriter;
-import java.util.List;
+import java.util.Map.Entry;
import java.util.UUID;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
/** Creates a manifest file describing the repos and mappings relevant for a runfile tree. */
-public class RepoMappingManifestAction extends AbstractFileWriteAction {
- private static final UUID MY_UUID = UUID.fromString("458e351c-4d30-433d-b927-da6cddd4737f");
-
- private final ImmutableList<Entry> entries;
- private final String workspaceName;
+public final class RepoMappingManifestAction extends AbstractFileWriteAction {
- /** An entry in the repo mapping manifest file. */
- @AutoValue
- public abstract static class Entry {
- public static Entry of(
- RepositoryName sourceRepo, String targetRepoApparentName, RepositoryName targetRepo) {
- return new AutoValue_RepoMappingManifestAction_Entry(
- sourceRepo, targetRepoApparentName, targetRepo);
- }
+ private static final UUID MY_UUID = UUID.fromString("458e351c-4d30-433d-b927-da6cddd4737f");
- public abstract RepositoryName sourceRepo();
+ // Uses MapFn's args parameter just like Fingerprint#addString to compute a cacheable fingerprint
+ // of just the repo name and mapping of a given Package.
+ private static final MapFn<Package> REPO_AND_MAPPING_DIGEST_FN =
+ (pkg, args) -> {
+ args.accept(pkg.getPackageIdentifier().getRepository().getName());
- public abstract String targetRepoApparentName();
+ var mapping = pkg.getRepositoryMapping().entries();
+ args.accept(String.valueOf(mapping.size()));
+ mapping.forEach(
+ (apparentName, canonicalName) -> {
+ args.accept(apparentName);
+ args.accept(canonicalName.getName());
+ });
+ };
- public abstract RepositoryName targetRepo();
- }
+ private final NestedSet<Package> transitivePackages;
+ private final NestedSet<Artifact> runfilesArtifacts;
+ private final String workspaceName;
public RepoMappingManifestAction(
- ActionOwner owner, Artifact output, List<Entry> entries, String workspaceName) {
+ ActionOwner owner,
+ Artifact output,
+ NestedSet<Package> transitivePackages,
+ NestedSet<Artifact> runfilesArtifacts,
+ String workspaceName) {
super(owner, NestedSetBuilder.emptySet(Order.STABLE_ORDER), output, /*makeExecutable=*/ false);
- this.entries =
- ImmutableList.sortedCopyOf(
- comparing((Entry e) -> e.sourceRepo().getName())
- .thenComparing(Entry::targetRepoApparentName),
- entries);
+ this.transitivePackages = transitivePackages;
+ this.runfilesArtifacts = runfilesArtifacts;
this.workspaceName = workspaceName;
}
@@ -78,7 +86,7 @@ public String getMnemonic() {
@Override
protected String getRawProgressMessage() {
- return "writing repo mapping manifest for " + getOwner().getLabel();
+ return "Writing repo mapping manifest for " + getOwner().getLabel();
}
@Override
@@ -88,35 +96,61 @@ protected void computeKey(
Fingerprint fp)
throws CommandLineExpansionException, EvalException, InterruptedException {
fp.addUUID(MY_UUID);
+ actionKeyContext.addNestedSetToFingerprint(REPO_AND_MAPPING_DIGEST_FN, fp, transitivePackages);
+ actionKeyContext.addNestedSetToFingerprint(fp, runfilesArtifacts);
fp.addString(workspaceName);
- for (Entry entry : entries) {
- fp.addString(entry.sourceRepo().getName());
- fp.addString(entry.targetRepoApparentName());
- fp.addString(entry.targetRepo().getName());
- }
}
@Override
public DeterministicWriter newDeterministicWriter(ActionExecutionContext ctx)
throws InterruptedException, ExecException {
return out -> {
- PrintWriter writer = new PrintWriter(out, /*autoFlush=*/ false, ISO_8859_1);
- for (Entry entry : entries) {
- if (entry.targetRepoApparentName().isEmpty()) {
- // The apparent repo name can only be empty for the main repo. We skip this line as
- // Rlocation paths can't reference an empty apparent name anyway.
- continue;
- }
- // The canonical name of the main repo is the empty string, which is not a valid name for a
- // directory, so the "workspace name" is used the name of the directory under the runfiles
- // tree for it.
- String targetRepoDirectoryName =
- entry.targetRepo().isMain() ? workspaceName : entry.targetRepo().getName();
- writer.format(
- "%s,%s,%s\n",
- entry.sourceRepo().getName(), entry.targetRepoApparentName(), targetRepoDirectoryName);
- }
+ PrintWriter writer = new PrintWriter(out, /* autoFlush= */ false, ISO_8859_1);
+
+ ImmutableSet<RepositoryName> reposContributingRunfiles =
+ runfilesArtifacts.toList().stream()
+ .filter(a -> a.getOwner() != null)
+ .map(a -> a.getOwner().getRepository())
+ .collect(toImmutableSet());
+ transitivePackages.toList().stream()
+ .collect(
+ toImmutableSortedMap(
+ comparing(RepositoryName::getName),
+ pkg -> pkg.getPackageIdentifier().getRepository(),
+ Package::getRepositoryMapping,
+ // All packages in a given repository have the same repository mapping, so the
+ // particular way of resolving duplicates does not matter.
+ (first, second) -> first))
+ .forEach(
+ (repoName, mapping) ->
+ writeRepoMapping(writer, reposContributingRunfiles, repoName, mapping));
writer.flush();
};
}
+
+ private void writeRepoMapping(
+ PrintWriter writer,
+ ImmutableSet<RepositoryName> reposContributingRunfiles,
+ RepositoryName repoName,
+ RepositoryMapping repoMapping) {
+ for (Entry<String, RepositoryName> mappingEntry :
+ ImmutableSortedMap.copyOf(repoMapping.entries()).entrySet()) {
+ if (mappingEntry.getKey().isEmpty()) {
+ // The apparent repo name can only be empty for the main repo. We skip this line as
+ // Rlocation paths can't reference an empty apparent name anyway.
+ continue;
+ }
+ if (!reposContributingRunfiles.contains(mappingEntry.getValue())) {
+ // We only write entries for repos that actually contribute runfiles.
+ continue;
+ }
+ // The canonical name of the main repo is the empty string, which is not a valid name for a
+ // directory, so the "workspace name" is used the name of the directory under the runfiles
+ // tree for it.
+ String targetRepoDirectoryName =
+ mappingEntry.getValue().isMain() ? workspaceName : mappingEntry.getValue().getName();
+ writer.format(
+ "%s,%s,%s\n", repoName.getName(), mappingEntry.getKey(), targetRepoDirectoryName);
+ }
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
index 3772cf7cb700da..b6154a2ed4d4a5 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/RunfilesSupport.java
@@ -14,26 +14,20 @@
package com.google.devtools.build.lib.analysis;
-import static com.google.common.collect.ImmutableSet.toImmutableSet;
-
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionEnvironment;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.CommandLine;
-import com.google.devtools.build.lib.analysis.RepoMappingManifestAction.Entry;
import com.google.devtools.build.lib.analysis.SourceManifestAction.ManifestType;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.SymlinkTreeAction;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.analysis.config.RunUnder;
-import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
-import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
@@ -41,7 +35,6 @@
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.Collection;
-import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -558,45 +551,9 @@ private static Artifact createRepoMappingManifestAction(
new RepoMappingManifestAction(
ruleContext.getActionOwner(),
repoMappingManifest,
- collectRepoMappings(
- Preconditions.checkNotNull(
- ruleContext.getTransitivePackagesForRunfileRepoMappingManifest()),
- runfiles),
+ ruleContext.getTransitivePackagesForRunfileRepoMappingManifest(),
+ runfiles.getAllArtifacts(),
ruleContext.getWorkspaceName()));
return repoMappingManifest;
}
-
- /** Returns the list of entries (unsorted) that should appear in the repo mapping manifest. */
- private static ImmutableList<Entry> collectRepoMappings(
- NestedSet<Package> transitivePackages, Runfiles runfiles) {
- // NOTE: It might appear that the flattening of `transitivePackages` is better suited to the
- // execution phase rather than here in the analysis phase, but we can't do that since it would
- // necessitate storing `transitivePackages` in an action, which breaks skyframe serialization
- // since packages cannot be serialized here.
-
- ImmutableSet<RepositoryName> reposContributingRunfiles =
- runfiles.getAllArtifacts().toList().stream()
- .filter(a -> a.getOwner() != null)
- .map(a -> a.getOwner().getRepository())
- .collect(toImmutableSet());
- Set<RepositoryName> seenRepos = new HashSet<>();
- ImmutableList.Builder<Entry> entries = ImmutableList.builder();
- for (Package pkg : transitivePackages.toList()) {
- if (!seenRepos.add(pkg.getPackageIdentifier().getRepository())) {
- // Any package from the same repo would have the same repo mapping.
- continue;
- }
- for (Map.Entry<String, RepositoryName> repoMappingEntry :
- pkg.getRepositoryMapping().entries().entrySet()) {
- if (reposContributingRunfiles.contains(repoMappingEntry.getValue())) {
- entries.add(
- Entry.of(
- pkg.getPackageIdentifier().getRepository(),
- repoMappingEntry.getKey(),
- repoMappingEntry.getValue()));
- }
- }
- }
- return entries.build();
- }
}
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/BUILD b/src/test/java/com/google/devtools/build/lib/analysis/BUILD
index d89744dfd73bd8..a7d493fe1de797 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/analysis/BUILD
@@ -361,16 +361,14 @@ java_test(
srcs = ["RunfilesRepoMappingManifestTest.java"],
deps = [
"//src/main/java/com/google/devtools/build/lib/actions",
- "//src/main/java/com/google/devtools/build/lib/analysis:blaze_directories",
+ "//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/analysis:repo_mapping_manifest_action",
- "//src/main/java/com/google/devtools/build/lib/bazel/bzlmod:resolution",
"//src/main/java/com/google/devtools/build/lib/bazel/bzlmod:resolution_impl",
"//src/main/java/com/google/devtools/build/lib/bazel/repository:repository_options",
"//src/main/java/com/google/devtools/build/lib/skyframe:precomputed_value",
- "//src/main/java/com/google/devtools/build/lib/skyframe:sky_functions",
+ "//src/main/java/com/google/devtools/build/lib/util",
"//src/main/java/com/google/devtools/build/lib/vfs",
- "//src/main/java/com/google/devtools/build/skyframe",
- "//src/main/java/com/google/devtools/build/skyframe:skyframe-objects",
+ "//src/main/java/net/starlark/java/eval",
"//src/test/java/com/google/devtools/build/lib/analysis/util",
"//src/test/java/com/google/devtools/build/lib/bazel/bzlmod:util",
"//third_party:guava",
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/RunfilesRepoMappingManifestTest.java b/src/test/java/com/google/devtools/build/lib/analysis/RunfilesRepoMappingManifestTest.java
index edb5955f579b64..377164876ce25a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/RunfilesRepoMappingManifestTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/RunfilesRepoMappingManifestTest.java
@@ -20,6 +20,7 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Action;
+import com.google.devtools.build.lib.actions.CommandLineExpansionException;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.bazel.bzlmod.BazelLockFileFunction;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleResolutionFunction;
@@ -30,8 +31,10 @@
import com.google.devtools.build.lib.bazel.repository.RepositoryOptions.LockfileMode;
import com.google.devtools.build.lib.skyframe.PrecomputedValue;
import com.google.devtools.build.lib.skyframe.PrecomputedValue.Injected;
+import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.Path;
import java.util.Map.Entry;
+import net.starlark.java.eval.EvalException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -95,10 +98,22 @@ public void setupBareBinaryRule() throws Exception {
"bare_binary(name='bare_binary')");
}
- private ImmutableList<String> getRepoMappingManifestForTarget(String label) throws Exception {
+ private RepoMappingManifestAction getRepoMappingManifestActionForTarget(String label)
+ throws Exception {
Action action = getGeneratingAction(getRunfilesSupport(label).getRepoMappingManifest());
assertThat(action).isInstanceOf(RepoMappingManifestAction.class);
- return ((RepoMappingManifestAction) action)
+ return (RepoMappingManifestAction) action;
+ }
+
+ private String computeKey(RepoMappingManifestAction action)
+ throws CommandLineExpansionException, EvalException, InterruptedException {
+ Fingerprint fp = new Fingerprint();
+ action.computeKey(actionKeyContext, /* artifactExpander= */ null, fp);
+ return fp.hexDigestAndReset();
+ }
+
+ private ImmutableList<String> getRepoMappingManifestForTarget(String label) throws Exception {
+ return getRepoMappingManifestActionForTarget(label)
.newDeterministicWriter(null)
.getBytes()
.toStringUtf8()
@@ -228,4 +243,82 @@ public void runfilesFromToolchain() throws Exception {
"tooled_rule~1.0,bare_rule,bare_rule~1.0")
.inOrder();
}
+
+ @Test
+ public void actionRerunsOnRepoMappingChange_workspaceName() throws Exception {
+ rewriteWorkspace("workspace(name='aaa_ws')");
+ scratch.overwriteFile(
+ "MODULE.bazel",
+ "module(name='aaa',version='1.0')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ scratch.overwriteFile(
+ "BUILD", "load('@bare_rule//:defs.bzl', 'bare_binary')", "bare_binary(name='aaa')");
+
+ RepoMappingManifestAction actionBeforeChange = getRepoMappingManifestActionForTarget("//:aaa");
+
+ rewriteWorkspace("workspace(name='not_aaa_ws')");
+
+ RepoMappingManifestAction actionAfterChange = getRepoMappingManifestActionForTarget("//:aaa");
+ assertThat(computeKey(actionBeforeChange)).isNotEqualTo(computeKey(actionAfterChange));
+ }
+
+ @Test
+ public void actionRerunsOnRepoMappingChange_repoName() throws Exception {
+ rewriteWorkspace("workspace(name='aaa_ws')");
+ scratch.overwriteFile(
+ "MODULE.bazel",
+ "module(name='aaa',version='1.0')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ scratch.overwriteFile(
+ "BUILD", "load('@bare_rule//:defs.bzl', 'bare_binary')", "bare_binary(name='aaa')");
+
+ RepoMappingManifestAction actionBeforeChange = getRepoMappingManifestActionForTarget("//:aaa");
+
+ scratch.overwriteFile(
+ "MODULE.bazel",
+ "module(name='aaa',version='1.0',repo_name='not_aaa')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ invalidatePackages();
+
+ RepoMappingManifestAction actionAfterChange = getRepoMappingManifestActionForTarget("//:aaa");
+ assertThat(computeKey(actionBeforeChange)).isNotEqualTo(computeKey(actionAfterChange));
+ }
+
+ @Test
+ public void actionRerunsOnRepoMappingChange_newEntry() throws Exception {
+ rewriteWorkspace("workspace(name='aaa_ws')");
+ scratch.overwriteFile(
+ "MODULE.bazel",
+ "module(name='aaa',version='1.0')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ scratch.overwriteFile(
+ "BUILD", "load('@bare_rule//:defs.bzl', 'bare_binary')", "bare_binary(name='aaa')");
+
+ registry.addModule(
+ createModuleKey("bbb", "1.0"),
+ "module(name='bbb',version='1.0')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ scratch.overwriteFile(
+ moduleRoot.getRelative("bbb~1.0").getRelative("WORKSPACE").getPathString());
+ scratch.overwriteFile(moduleRoot.getRelative("bbb~1.0").getRelative("BUILD").getPathString());
+ scratch.overwriteFile(
+ moduleRoot.getRelative("bbb~1.0").getRelative("def.bzl").getPathString(), "BBB = '1'");
+
+ RepoMappingManifestAction actionBeforeChange = getRepoMappingManifestActionForTarget("//:aaa");
+
+ scratch.overwriteFile(
+ "MODULE.bazel",
+ "module(name='aaa',version='1.0')",
+ "bazel_dep(name='bbb',version='1.0')",
+ "bazel_dep(name='bare_rule',version='1.0')");
+ scratch.overwriteFile(
+ "BUILD",
+ "load('@bare_rule//:defs.bzl', 'bare_binary')",
+ "load('@bbb//:def.bzl', 'BBB')",
+ "bare_binary(name='aaa')");
+ invalidatePackages();
+
+ RepoMappingManifestAction actionAfterChange = getRepoMappingManifestActionForTarget("//:aaa");
+ assertThat(computeKey(actionBeforeChange)).isNotEqualTo(computeKey(actionAfterChange));
+ }
}
| train | test | 2023-05-19T11:13:38 | "2023-03-31T08:08:45Z" | coquelicot | test |
bazelbuild/bazel/15073_18552 | bazelbuild/bazel | bazelbuild/bazel/15073 | bazelbuild/bazel/18552 | [
"keyword_pr_to_issue"
] | 31c46ba5b6c4040741b0eb3c2b8e37cf1002cb25 | e111cd65387932edcfb306aca92eaeb6e82756ec | [
"Maybe this is a similar bug that should be fixed like https://github.com/bazelbuild/bazel/commit/edfe2a17e3434cce660757f59b14f2e9d6ab944e?",
"/cc @buildbreaker2021",
"We also encounter this problem. Unfortunately this causes us to not be able to compile Android on windows. Which is a major block for our project. Is there a rough estimate of when this will be fixed? Or is there any way we can workaround this? Thanks.",
"The worst thing here is that this issue is not even particularly complicated, even with `WindowsOsPathPolicy` rework included (the right thing to do: support for case sensitive directories on Windows 10+ will solve a lot of problems). Yet, it breaks a whole lot of plain C libraries on Windows putting a big question mark on Bazel's viability in general.\r\n\r\nWhich is a pity.\r\n",
"> The worst thing here is that this issue is not even particularly complicated, even with `WindowsOsPathPolicy` rework included (the right thing to do: support for case sensitive directories on Windows 10+ will solve a lot of problems). Yet, it breaks a whole lot of plain C libraries on Windows putting a big question mark on Bazel's viability in general.\r\n> \r\n> Which is a pity.\r\n\r\nCurrently, you can workaround this by replacing `--cxxopt` with `--per_file_copt=.*\\.cpp\\$@`.\r\n\r\nBut I agree that it's very confusing why this issue is a feature request and is P4.",
"It won't work for flags which are set in the actual BUILD files. The primary issue here, is that bazel offers no way to say \"this file is plain C\" explicitly. So, in a project with several dozens of third party dependencies a lot of patching and testing is needed to get anywhere with Bazel v5.\r\n\r\nBazel v4 sort of works, but then it can not be used with VS2022 due to another open issue.\r\n",
"> Bazel v4 sort of works, but then it can not be used with VS2022 due to another open issue.\r\n\r\nI thought this is not a problem for a msbuild based toolchain because msbuild only gives a warning? For us, it's a block issue because we're doing android cross compile on Windows and pass C++ flag to C compile simply failed.\r\n\r\nAnother interesting workaround is that we found somehow the C++ flags defined in toolchain won't be passed to C targets. So we end up moving the C++ flags to toolchain. But yeah it's lucky for us to be able to workaround this bug. For some complex project this may not work.",
"VS2022 is broken pretty badly, we had to go back to VS2019/bazel v4 for now. We may figure something out going forward; possibly by making all sources C++ compatible (this appears to be the best option on the cost/benefit scale).\r\n\r\nStill, not nice.\r\n",
"@oquenchil This issue seems to have wide user impact on Windows. Is it caused by starlarkfifying the cc rules? Do you know which exact change caused this and how hard is it to fix this?",
"@meteorcloudy Looks like is caused by #14005. The `.c` extension is matched with `.C` cause bazel treat it as a C++ source. I think this can be fixed like https://github.com/bazelbuild/bazel/commit/edfe2a17e3434cce660757f59b14f2e9d6ab944e . I understand bazel team has many things to do and may not have the capacity to fix this. If you have the bandwidth to review a PR I can give this a try.",
"Not sure why `.c` and `.C` should mean different file types on Windows because file names are already case insensitive. Is this a Linux convention? Can you just change files with `.C` to `.cpp`? \r\nBut given we are already making an exception in https://github.com/bazelbuild/bazel/commit/edfe2a17e3434cce660757f59b14f2e9d6ab944e, a PR to fix this sounds plausible, @oquenchil @comius should decide eventually.",
"> Can you just change files with `.C` to `.cpp`?\r\n\r\nWe don't actually have any `.C` files. I think it's bazel that treated all `.c` files as `.C` files causing the problem.\r\n\r\n",
"@meteorcloudy Also see #15550 for some further info.",
"Any progress on this issue? Bazel cannot compile C targets under Windows anymore since version 5. I don't think this warrants classification as a \"feature request\" or \"P4\".",
"Bazel can compile things on Windows, it just requires jumping through ugly loops with `--per_file_copt=` and possibly some patching.\r\n\r\nBut yes, this issue is bad and the lack of proper support for case sensitive abilities of NTFS is also unfortunate - that is, bazel would have worked fine on Windows with some extra configs if not for the rather stupid case forcing inside the Windows path resolver.\r\n\r\n",
"From the [documentation](https://bazel.build/docs/user-manual): `--cxxopts: This is similar to --copt, but only applies to C++ compilation, not to C compilation or linking.` In obvious contradiction bazel 5.3.2 passes `--cxxopts` arguments to C files. This is clearly a bug and not a \"feature request\". @oquenchil\r\n\r\nI find if concerning that something that elementary is broken in bazel and swiped under the rug.",
"This bug is still causing significant problems in a project, forcing us to use an old bazel version which causes further compatibility issues and surfaces other bugs without fixes. Will it ever be looked at?",
"It's almost like Windows is not an important OS for developers any more. :-D\r\n\r\nYet, Windows is still the most used developer OS by a huge margin.\r\n",
"@oquenchil I think this shouldn't be a P4 issue, can you take a look?\r\n\r\nIf anyone has a fix for this, a PR is also very welcome!",
"Hi, I've created a PR. It's basically learned from https://github.com/bazelbuild/bazel/commit/edfe2a17e3434cce660757f59b14f2e9d6ab944e . I'm not very familiar to java actually, so please tell me if I did anything wrong. I've tested it on my environment and added a test.",
"Created the referenced Cherrypick @kkpattern Any objections agains the attempt?",
"> Created the referenced Cherrypick @kkpattern Any objections agains the attempt?\r\n\r\nNot at all😃.",
"Why is this closed? Observed in the latest 5.x and 6.x builds.\r\n\r\nThis is C code! `sign.c` is a C source file! `--host_cxxopt=-std=c++17` causes `-std=c++17` to be passed to C compilation!!!\r\n\r\n```\r\n/home/.../.cache/bazel/_bazel_build/install/a09dbb90c658248f08f9aa0eba11997d/process-wrapper '--timeout=0' '--kill_delay=15' '--stats=/home/.../.cache/bazel/_bazel_build/36f2a9693014a18078cf75940b43707b/sandbox/processwrapper-sandbox/114/stats.out' \\\r\n\r\n/usr/bin/gcc-9 -MD -MF bazel-out/k8-dbg-gcc/bin/external/boringssl/_objs/crypto/sign.pic.d \\\r\n '-frandom-seed=bazel-out/k8-dbg-gcc/bin/external/boringssl/_objs/crypto/sign.pic.o' \\\r\n '-DBAZEL_CURRENT_REPOSITORY=\"boringssl\"' \\\r\n -iquote external/boringssl -iquote bazel-out/k8-dbg-gcc/bin/external/boringssl \\\r\n -isystem external/boringssl/src/include \\\r\n -isystem bazel-out/k8-dbg-gcc/bin/external/boringssl/src/include \\\r\n '-std=c++17' \\ # WUHT?????\r\n -g -O0 -fno-omit-frame-pointer -fPIC -fno-canonical-system-headers \\\r\n '-fdiagnostics-color=always' -Wa,--noexecstack -Wall -Werror '-Wformat=2' \\\r\n -Wsign-compare -Wmissing-field-initializers -Wwrite-strings -Wshadow \\\r\n -fno-common '-D_XOPEN_SOURCE=700' '-std=c11' -Wmissing-prototypes \\\r\n -Wold-style-definition -Wstrict-prototypes -c external/boringssl/src/crypto/evp/sign.c \\\r\n -o bazel-out/k8-dbg-gcc/bin/external/boringssl/_objs/crypto/sign.pic.o\r\n```",
"6.3.0 should contain the fix? https://github.com/bazelbuild/bazel/pull/18552",
"I did a simple test. When compile with MSVC with ` --cxxopt=/std:c++17`, bazel 5.1.1 added the flag to a C source file:\r\n\r\n```\r\nC:\\...\\cl.exe ... -D__TIME__=\"redacted\" /std:c++17 ... /c hello.c\r\n ^^^^^^^^^\r\n```\r\n\r\nwhile bazel 6.3.2 didn't:\r\n\r\n```\r\nC:\\...\\cl.exe ... -D__TIME__=\"redacted\" ... /c hello.c\r\n```",
"I'm using Ubuntu 22.04... so I'm seeing the problem on Linux. Given that we're not using Bzlmod (because of incompatibilities), it's possible that I have a dependency of a dependency that's getting an old version of cc_tools or something. It's frustrating because it my build is broken because of two rather trivial bugs that _look_ like they're in bazel. (Where does @local_config_cc come from, after all???)"
] | [] | "2023-06-01T12:56:26Z" | [
"type: bug",
"P2",
"team-Rules-CPP",
"help wanted"
] | --host_cxxopt and --cxxopt are passed to the compiler also for .c files on Windows | <!--
ATTENTION! Please read and follow:
- if this is a _question_ about how to build / test / query / deploy using Bazel, or a _discussion starter_, send it to [email protected]
- if this is a _bug_ or _feature request_, fill the form below as best as you can.
-->
### Description of the problem / feature request:
Since Bazel 5.0.0 `--host_cxxopt` and `--cxxopt` are passed to compilers compiling .c files on Windows.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Use the autoconfigure toolchain to build (with -s) a .c file in Windows. Set `--host_cxxopt` and `--cxxopt` in the .bazelrc and see in the compiler call the passed opts from the .bazelrc. Doing the same on Linux show, that the opts here are not passed.
### What operating system are you running Bazel on?
Windows 10 Enterprise (Version 10.0.19042 Build 19042)
### What's the output of `bazel info release`?
release 5.0.0
### Have you found anything relevant by searching the web?
https://github.com/bazelbuild/bazel/pull/14005
https://github.com/bazelbuild/bazel/pull/14131
<!--
Places to look:
- StackOverflow: http://stackoverflow.com/questions/tagged/bazel
- GitHub issues: https://github.com/bazelbuild/bazel/issues
- email threads on https://groups.google.com/forum/#!forum/bazel-discuss
-->
### Any other information, logs, or outputs that you want to share?
This commit https://github.com/bazelbuild/bazel/commit/861584ca049b1b2f3474c3977c4a54d1901f9458 introduced case insensity for files types on Windows
https://github.com/bazelbuild/bazel/blob/88499f615bc03d1b6a3e4e38f2890a4e987a954d/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java#L28
The change also leads to .c files under Windows match to C_SOURCE (.c extension) and CPP_SOURCE (.C extension)
https://github.com/bazelbuild/bazel/blob/88499f615bc03d1b6a3e4e38f2890a4e987a954d/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java#L33-L34
Which results in passing cxxopt for .c files
https://github.com/bazelbuild/bazel/blob/88499f615bc03d1b6a3e4e38f2890a4e987a954d/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationHelper.java#L1605-L1610
<!-- If the files are large, upload as attachment or provide link. -->
| [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/cpp/CppFileTypesTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java
index d525d0be65d8e5..c55cf90028708f 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java
@@ -30,9 +30,44 @@ public final class CppFileTypes {
// .cu and .cl are CUDA and OpenCL source extensions, respectively. They are expected to only be
// supported with clang. Bazel is not officially supporting these targets, and the extensions are
// listed only as long as they work with the existing C++ actions.
+ // FileType is extended to use case-sensitive comparison also on Windows
public static final FileType CPP_SOURCE =
- FileType.of(".cc", ".cpp", ".cxx", ".c++", ".C", ".cu", ".cl");
- public static final FileType C_SOURCE = FileType.of(".c");
+ new FileType() {
+ final ImmutableList<String> extensions =
+ ImmutableList.of(".cc", ".cpp", ".cxx", ".c++", ".C", ".cu", ".cl");
+
+ @Override
+ public boolean apply(String path) {
+ for (String ext : extensions) {
+ if (path.endsWith(ext)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public ImmutableList<String> getExtensions() {
+ return extensions;
+ }
+ };
+
+ // FileType is extended to use case-sensitive comparison also on Windows
+ public static final FileType C_SOURCE =
+ new FileType() {
+ final String ext = ".c";
+
+ @Override
+ public boolean apply(String path) {
+ return path.endsWith(ext);
+ }
+
+ @Override
+ public ImmutableList<String> getExtensions() {
+ return ImmutableList.of(ext);
+ }
+ };
+
public static final FileType OBJC_SOURCE = FileType.of(".m");
public static final FileType OBJCPP_SOURCE = FileType.of(".mm");
public static final FileType CLIF_INPUT_PROTO = FileType.of(".ipb");
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/CppFileTypesTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/CppFileTypesTest.java
index 88aa7ba707292f..4487d6545b8096 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/CppFileTypesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/CppFileTypesTest.java
@@ -77,4 +77,12 @@ public void testNoExtensionLibraries() {
assertThat(Link.ARCHIVE_LIBRARY_FILETYPES.matches("someframework")).isTrue();
assertThat(Link.ARCHIVE_FILETYPES.matches("someframework")).isTrue();
}
+
+ @Test
+ public void testCaseSensitiveCFiles() {
+ assertThat(CppFileTypes.C_SOURCE.matches("foo.c")).isTrue();
+ assertThat(CppFileTypes.CPP_SOURCE.matches("foo.c")).isFalse();
+ assertThat(CppFileTypes.C_SOURCE.matches("foo.C")).isFalse();
+ assertThat(CppFileTypes.CPP_SOURCE.matches("foo.C")).isTrue();
+ }
}
| test | test | 2023-06-08T01:42:56 | "2022-03-18T13:36:25Z" | foxandi | test |
bazelbuild/bazel/18071_18568 | bazelbuild/bazel | bazelbuild/bazel/18071 | bazelbuild/bazel/18568 | [
"keyword_pr_to_issue"
] | 111a53a1811efc86983a6d0147fb5f0d2e2d9714 | c4559295e7122eed14abd15cade54208d495d5ea | [
"the 1s timeout was introduced for #15373",
"I am slightly confused here:\r\n\r\n1. Why is the system under load? Bazel only runs this code upon startup (SandboxModule registration), before any action is executed. So the expectation here is the host system should have enough resources dedicated to running Bazel and downstream actions. Are you suffering from the noisy neighbor problem here? (i.e. running multiple Bazel JVM, isolated by containers without dedicated resources, on the same host?).\r\n\r\n2. If the system does not have adequate resources to execute `/bin/true` inside a `linux-sandbox`, it's a pretty good sign to fail the build right there immediately instead of waiting and letting downstream actions also suffer the same faith?\r\n\r\n3. Do you restart Bazel JVM a lot? Bazel JVM should be long-lived to retain the in-memory analysis cache. Restarting Bazel JVM from cold will make your build slower and increase the chance of this problem happening.\r\n\r\nFrom the point above, I would imagine your current setup is something like this: 1 VM/baremetal host running Bazel in multiple containers. After each build, you are discarding your Bazel container, killing the Bazel JVM inside. You are overfitting the host system to saturate the CPU consumption which resulted in \"noisy neighbor\": builds from a few busier containers are consuming too many CPU, stopping new containers from being spun up successfully.\r\n\r\nIf that's indeed the case, my advice would be: to switch to using a set of \"persistent containers\" and re-use the containers + Bazel JVM inside between runs. Each container should be assigned a fixed set of CPU/RAM, enforced by the container runtime to ensure that they don't use more resources than they should.\r\n\r\nI don't think the mitigation in #18151 will solve your issue at all. You are only delaying the noisy neighbor issue from Bazel's startup phase down to the action execution phase. The 5% failure rate would still retain as all of your action execution will be delayed in scheduling by the same wait time."
] | [] | "2023-06-02T22:46:46Z" | [
"type: bug",
"P2",
"team-Local-Exec"
] | linux-sandbox is not available occasionally since Bazel 6.0.0 | ### Description of the bug:
We noticed that Bazel occasionally (about 5% in our env) fails due to `linux-sandbox` not being available.
```
ERROR: 'linux-sandbox' was requested for default strategies but no strategy with that identifier was registered. Valid values are: [processwrapper-sandbox, standalone, remote, worker, sandboxed, local]
```
It seems that recently a 1s timeout was introduced in checking if `linux-sandbox` available #15414, which might be too tight under load.
In our setup, we disable all other weaker sandboxes for hermeticity, which makes this fail reliably and easy to notice. I suspect this is happening on more environments, but people haven't noticed because of`processwrapper-sandbox` fallback.
CC @meisterT
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
run Bazel >=6.0.0 with `--spawn_strategy=worker,linux-sandbox` under a heavy load many times.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
_No response_
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
index a50f4ba89f48be..cc0219bc340662 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
@@ -34,6 +34,7 @@
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.exec.TreeDeleter;
import com.google.devtools.build.lib.exec.local.LocalEnvProvider;
+import com.google.devtools.build.lib.exec.local.LocalExecutionOptions;
import com.google.devtools.build.lib.exec.local.PosixLocalEnvProvider;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.SilentCloseable;
@@ -94,10 +95,11 @@ public static boolean isSupported(final CommandEnvironment cmdEnv) throws Interr
private static boolean computeIsSupported(CommandEnvironment cmdEnv, Path linuxSandbox)
throws InterruptedException {
+ LocalExecutionOptions options = cmdEnv.getOptions().getOptions(LocalExecutionOptions.class);
ImmutableList<String> linuxSandboxArgv =
LinuxSandboxCommandLineBuilder.commandLineBuilder(
linuxSandbox, ImmutableList.of("/bin/true"))
- .setTimeout(Duration.ofSeconds(1))
+ .setTimeout(options.getLocalSigkillGraceSeconds())
.build();
ImmutableMap<String, String> env = ImmutableMap.of();
Path execRoot = cmdEnv.getExecRoot();
| null | test | test | 2023-06-06T21:07:10 | "2023-04-13T01:17:56Z" | tsawada | test |
bazelbuild/bazel/17289_18649 | bazelbuild/bazel | bazelbuild/bazel/17289 | bazelbuild/bazel/18649 | [
"keyword_pr_to_issue"
] | 7f93a2a33e87ae5f6c5f374b0cff7922cfe72178 | 9310618621a8d431be789b4d780cfad3b5184a54 | [
"This feels to be Working As Intended, since modules specifically have a different way to register toolchains, but I'll leave it for @Wyverald to clarify.",
"I passed this by @Wyverald on Bazel Slack and he asked to create an issue and cc him. Was just trying to find his GitHub handle :)\r\n\r\nIf WORKSPACE files can't register toolchains when bzlmod is enabled then it will be hard to use rulesets that have bzlmod support alongside rulesets that don't (while they all get up to speed) if they both register toolchains.",
"Thank you for contributing to the Bazel repository! This issue has been marked as stale since it has not had any activity in the last 30 days. It will be closed in the next 7 days unless any other activity occurs or one of the following labels is added: \"not stale\", \"awaiting-bazeler\".",
"Not stale. ",
"Ah, I think I figured out what's wrong here. It's that damn `platforms` repo again...\r\n\r\nWhen you don't enable Bzlmod, `@platforms` for everyone is the `@@platforms` repo defined in a WORKSPACE prefix/suffix (don't remember which). All good.\r\n\r\nWhen you enable Bzlmod, `@platforms` is still the `@@platforms` repo defined in a WORKSPACE prefix/suffix for everything that is *not* in the Bzlmod system (i.e. all the WORKSPACE repos including `@@rules_nodejs`). However, for things in the Bzlmod system (i.e. only built-in modules like `bazel_tools` and `local_config_platform` because your MODULE.bazel file is empty), `@platforms` actually refers to `@@platforms~0.0.5`. This is important because when we search for an appropriate execution platform (most likely your host machine), `@local_config_platform//:host` actually uses the platforms defined in `@@platforms~0.0.5`, but `rules_nodejs` defines toolchains for platforms defined in `@@platforms`.\r\n\r\nThe immediate workaround would be to add a single line in your MODULE.bazel file (`bazel_dep(name=\"platforms\", version=\"0.0.5\")`). I'll have to ponder how we could resolve this situation better, if it's even possible.",
"Closing this as things are technically working as intended here. Hopefully the existence of this issue will serve as documentation for whoever's encountering this problem in the future.",
"> Closing this as things are technically working as intended here. Hopefully the existence of this issue will serve as documentation for whoever's encountering this problem in the future.\r\n\r\nUhm, the module system not resolving a dependency, and the user having to manually depend on a specific version of a deep dependency is \"working as intended\"?\r\n\r\nIn my view this completely invalidates bzlmod.\r\n\r\nIt might be working \"as designed\", but definitely not \"as intended\".",
"Agreed, letting the user add a dependency to make it work isn't really a solution to me.\r\nTo anyone that don't want to read the whole thing: \r\nAdd to `MODULE.bazel`:\r\n```\r\nbazel_dep(name=\"platforms\", version=\"0.0.5\")\r\n```",
"if anyone has an idea how to fix this, please leave a suggestion.",
"Maybe making `platforms` v0.0.5 the default on Bazel 7 would be a solution ?"
] | [] | "2023-06-13T00:01:22Z" | [
"type: bug",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | --enable_bzlmod breaks toolchain resolution for toolchains registered in WORKSPACE | ### Description of the bug:
Setting the `--enable_bzlmod` flag (even with an empty `MODULE.bazel` file) breaks toolchain resolution for toolchains registered in the WORKSPACE file.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
https://github.com/gregmagolan/repro-enable_bzlmod_breaks_workspace
### Which operating system are you running Bazel on?
MacOS
### What is the output of `bazel info release`?
```
release 6.0.0
```
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
https://github.com/gregmagolan/repro-enable_bzlmod_breaks_workspace
### Have you found anything relevant by searching the web?
Searched through Bazel issues and didn't see any duplicates.
### Any other information, logs, or outputs that you want to share?
| [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java"
] | [
"src/test/py/bazel/bzlmod/bazel_module_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java
index 50a24292c869f5..5ae1c263366aba 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleKey.java
@@ -39,7 +39,14 @@ public abstract class ModuleKey {
"bazel_tools",
RepositoryName.BAZEL_TOOLS,
"local_config_platform",
- RepositoryName.createUnvalidated("local_config_platform"));
+ RepositoryName.createUnvalidated("local_config_platform"),
+ // Ensures that references to "@platforms" in WORKSPACE files resolve to the repository of
+ // the "platforms" module. Without this, constraints on toolchains registered in WORKSPACE
+ // would reference the "platforms" repository defined in the WORKSPACE suffix, whereas
+ // the host constraints generated by local_config_platform would reference the "platforms"
+ // module repository, resulting in a toolchain resolution mismatch.
+ "platforms",
+ RepositoryName.createUnvalidated("platforms"));
public static final ModuleKey ROOT = create("", Version.EMPTY);
| diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 941823f11fb680..250006526da668 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -557,6 +557,84 @@ def testNativeModuleNameAndVersion(self):
self.assertIn('@@bar~override reporting in: [email protected]', stderr)
self.assertIn('@@quux reporting in: None@None', stderr)
+ def testWorkspaceToolchainRegistrationWithPlatformsConstraint(self):
+ """Regression test for https://github.com/bazelbuild/bazel/issues/17289."""
+ self.ScratchFile('MODULE.bazel')
+ self.ScratchFile(
+ 'WORKSPACE', ['register_toolchains("//:my_toolchain_toolchain")']
+ )
+ os.remove(self.Path('WORKSPACE.bzlmod'))
+
+ self.ScratchFile(
+ 'BUILD.bazel',
+ [
+ 'load(":defs.bzl", "get_host_os", "my_consumer", "my_toolchain")',
+ 'toolchain_type(name = "my_toolchain_type")',
+ 'my_toolchain(',
+ ' name = "my_toolchain",',
+ ' my_value = "Hello, Bzlmod!",',
+ ')',
+ 'toolchain(',
+ ' name = "my_toolchain_toolchain",',
+ ' toolchain = ":my_toolchain",',
+ ' toolchain_type = ":my_toolchain_type",',
+ ' target_compatible_with = [',
+ ' "@platforms//os:" + get_host_os(),',
+ ' ],',
+ ')',
+ 'my_consumer(',
+ ' name = "my_consumer",',
+ ')',
+ ],
+ )
+
+ self.ScratchFile(
+ 'defs.bzl',
+ [
+ (
+ 'load("@local_config_platform//:constraints.bzl",'
+ ' "HOST_CONSTRAINTS")'
+ ),
+ 'def _my_toolchain_impl(ctx):',
+ ' return [',
+ ' platform_common.ToolchainInfo(',
+ ' my_value = ctx.attr.my_value,',
+ ' ),',
+ ' ]',
+ 'my_toolchain = rule(',
+ ' implementation = _my_toolchain_impl,',
+ ' attrs = {',
+ ' "my_value": attr.string(),',
+ ' },',
+ ')',
+ 'def _my_consumer(ctx):',
+ ' my_toolchain_info = ctx.toolchains["//:my_toolchain_type"]',
+ ' out = ctx.actions.declare_file(ctx.attr.name)',
+ (
+ ' ctx.actions.write(out, "my_value ='
+ ' {}".format(my_toolchain_info.my_value))'
+ ),
+ ' return [DefaultInfo(files = depset([out]))]',
+ 'my_consumer = rule(',
+ ' implementation = _my_consumer,',
+ ' attrs = {},',
+ ' toolchains = ["//:my_toolchain_type"],',
+ ')',
+ 'def get_host_os():',
+ ' for constraint in HOST_CONSTRAINTS:',
+ ' if constraint.startswith("@platforms//os:"):',
+ ' return constraint.removeprefix("@platforms//os:")',
+ ],
+ )
+
+ self.RunBazel([
+ 'build',
+ '//:my_consumer',
+ '--toolchain_resolution_debug=//:my_toolchain_type',
+ ])
+ with open(self.Path('bazel-bin/my_consumer'), 'r') as f:
+ self.assertEqual(f.read().strip(), 'my_value = Hello, Bzlmod!')
+
if __name__ == '__main__':
unittest.main()
| test | test | 2023-06-13T02:13:57 | "2023-01-20T21:17:29Z" | gregmagolan | test |
bazelbuild/bazel/18333_18815 | bazelbuild/bazel | bazelbuild/bazel/18333 | bazelbuild/bazel/18815 | [
"keyword_pr_to_issue"
] | 3a8c07699fd33889cd7c27cb0885d480553f4c52 | 14895f0f0493fffa34567c6dcb12c3a8e72326d0 | [
"Fixed by #18815."
] | [] | "2023-06-29T14:00:30Z" | [] | [6.3.0] Ensure outputs are downloaded before sending TargetComplete event via BEP | Forked from #17798 | [
"src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java",
"src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java",
"src/main/java/com/google/devtools/build/lib/vfs/OutputService.java"
] | [
"src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventLocalFileSynchronizer.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java",
"src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java",
"src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java",
"src/main/java/com/google/devtools/build/lib/vfs/OutputService.java"
] | [
"src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java",
"src/test/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransportTest.java",
"src/test/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransportTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
index 4de92bf74c588d..b99dceead675c4 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceModule.java
@@ -38,6 +38,7 @@
import com.google.devtools.build.lib.buildeventservice.client.BuildEventServiceClient;
import com.google.devtools.build.lib.buildeventstream.AnnounceBuildEventTransportsEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.Aborted.AbortReason;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
@@ -90,6 +91,7 @@
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
@@ -753,6 +755,19 @@ private ImmutableSet<BuildEventTransport> createBepTransports(
CountingArtifactGroupNamer artifactGroupNamer)
throws IOException {
ImmutableSet.Builder<BuildEventTransport> bepTransportsBuilder = new ImmutableSet.Builder<>();
+ BuildEventLocalFileSynchronizer synchronizer =
+ localFiles -> {
+ var outputService = cmdEnv.getOutputService();
+ if (outputService == null || localFiles.isEmpty()) {
+ return Futures.immediateVoidFuture();
+ }
+
+ var files =
+ localFiles.stream()
+ .map(localFile -> localFile.path.asFragment())
+ .collect(Collectors.toList());
+ return outputService.waitOutputDownloads(files);
+ };
if (!Strings.isNullOrEmpty(besStreamOptions.buildEventTextFile)) {
try {
@@ -766,7 +781,11 @@ private ImmutableSet<BuildEventTransport> createBepTransports(
: new LocalFilesArtifactUploader();
bepTransportsBuilder.add(
new TextFormatFileTransport(
- bepTextOutputStream, bepOptions, localFileUploader, artifactGroupNamer));
+ bepTextOutputStream,
+ bepOptions,
+ localFileUploader,
+ artifactGroupNamer,
+ synchronizer));
} catch (IOException exception) {
// TODO(b/125216340): Consider making this a warning instead of an error once the
// associated bug has been resolved.
@@ -793,7 +812,11 @@ private ImmutableSet<BuildEventTransport> createBepTransports(
: new LocalFilesArtifactUploader();
bepTransportsBuilder.add(
new BinaryFormatFileTransport(
- bepBinaryOutputStream, bepOptions, localFileUploader, artifactGroupNamer));
+ bepBinaryOutputStream,
+ bepOptions,
+ localFileUploader,
+ artifactGroupNamer,
+ synchronizer));
} catch (IOException exception) {
// TODO(b/125216340): Consider making this a warning instead of an error once the
// associated bug has been resolved.
@@ -819,7 +842,11 @@ private ImmutableSet<BuildEventTransport> createBepTransports(
: new LocalFilesArtifactUploader();
bepTransportsBuilder.add(
new JsonFormatFileTransport(
- bepJsonOutputStream, bepOptions, localFileUploader, artifactGroupNamer));
+ bepJsonOutputStream,
+ bepOptions,
+ localFileUploader,
+ artifactGroupNamer,
+ synchronizer));
} catch (IOException exception) {
// TODO(b/125216340): Consider making this a warning instead of an error once the
// associated bug has been resolved.
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventLocalFileSynchronizer.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventLocalFileSynchronizer.java
new file mode 100644
index 00000000000000..9b693f7cf68dda
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventLocalFileSynchronizer.java
@@ -0,0 +1,29 @@
+// Copyright 2023 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.
+package com.google.devtools.build.lib.buildeventstream;
+
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.devtools.build.lib.buildeventstream.BuildEvent.LocalFile;
+import java.util.Collection;
+
+/**
+ * An interface that is used to wait for downloads of remote outputs before sending out local BEP
+ * events that reference these outputs.
+ */
+public interface BuildEventLocalFileSynchronizer {
+ BuildEventLocalFileSynchronizer NO_OP = localFiles -> Futures.immediateVoidFuture();
+
+ ListenableFuture<Void> waitForLocalFileDownloads(Collection<LocalFile> localFiles);
+}
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java
index c3a83c0a1f8ea8..d1f71a84f381e1 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransport.java
@@ -17,6 +17,7 @@
import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer;
import com.google.devtools.build.lib.buildeventstream.BuildEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
@@ -34,8 +35,9 @@ public BinaryFormatFileTransport(
BufferedOutputStream outputStream,
BuildEventProtocolOptions options,
BuildEventArtifactUploader uploader,
- ArtifactGroupNamer namer) {
- super(outputStream, options, uploader, namer);
+ ArtifactGroupNamer namer,
+ BuildEventLocalFileSynchronizer synchronizer) {
+ super(outputStream, options, uploader, namer, synchronizer);
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java
index 7bc427d7849342..d1473e7ba53cbe 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/FileTransport.java
@@ -28,6 +28,7 @@
import com.google.devtools.build.lib.buildeventstream.BuildEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
@@ -66,6 +67,7 @@ abstract class FileTransport implements BuildEventTransport {
private final BuildEventArtifactUploader uploader;
private final SequentialWriter writer;
private final ArtifactGroupNamer namer;
+ private final BuildEventLocalFileSynchronizer synchronizer;
private final ScheduledExecutorService timeoutExecutor =
MoreExecutors.listeningDecorator(
@@ -76,12 +78,14 @@ abstract class FileTransport implements BuildEventTransport {
BufferedOutputStream outputStream,
BuildEventProtocolOptions options,
BuildEventArtifactUploader uploader,
- ArtifactGroupNamer namer) {
+ ArtifactGroupNamer namer,
+ BuildEventLocalFileSynchronizer synchronizer) {
this.uploader = uploader;
this.options = options;
this.writer =
new SequentialWriter(outputStream, this::serializeEvent, uploader, timeoutExecutor);
this.namer = namer;
+ this.synchronizer = synchronizer;
}
@ThreadSafe
@@ -280,12 +284,14 @@ private ListenableFuture<BuildEventStreamProtos.BuildEvent> asStreamProto(
BuildEvent event, ArtifactGroupNamer namer) {
checkNotNull(event);
+ var localFiles = event.referencedLocalFiles();
+ ListenableFuture<?> localFileDownloads = synchronizer.waitForLocalFileDownloads(localFiles);
ListenableFuture<PathConverter> converterFuture =
- uploader.uploadReferencedLocalFiles(event.referencedLocalFiles());
+ uploader.uploadReferencedLocalFiles(localFiles);
ListenableFuture<?> remoteUploads =
uploader.waitForRemoteUploads(event.remoteUploads(), timeoutExecutor);
return Futures.transform(
- Futures.allAsList(converterFuture, remoteUploads),
+ Futures.allAsList(localFileDownloads, converterFuture, remoteUploads),
results -> {
BuildEventContext context =
new BuildEventContext() {
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java
index a25074164cba7a..dc6bcd9e017e2c 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransport.java
@@ -18,6 +18,7 @@
import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
@@ -34,8 +35,9 @@ public JsonFormatFileTransport(
BufferedOutputStream outputStream,
BuildEventProtocolOptions options,
BuildEventArtifactUploader uploader,
- ArtifactGroupNamer namer) {
- super(outputStream, options, uploader, namer);
+ ArtifactGroupNamer namer,
+ BuildEventLocalFileSynchronizer synchronizer) {
+ super(outputStream, options, uploader, namer, synchronizer);
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java
index 34e26e67c1c33b..f0b88651b7fa1e 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransport.java
@@ -18,6 +18,7 @@
import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
@@ -35,8 +36,9 @@ public TextFormatFileTransport(
BufferedOutputStream outputStream,
BuildEventProtocolOptions options,
BuildEventArtifactUploader uploader,
- ArtifactGroupNamer namer) {
- super(outputStream, options, uploader, namer);
+ ArtifactGroupNamer namer,
+ BuildEventLocalFileSynchronizer synchronizer) {
+ super(outputStream, options, uploader, namer, synchronizer);
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java b/src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java
index a037811a8e70e2..02dae8d8ca4d9a 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/AbstractActionInputPrefetcher.java
@@ -48,6 +48,7 @@
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
import com.google.devtools.build.lib.remote.util.AsyncTaskCache;
+import com.google.devtools.build.lib.remote.util.RxFutures;
import com.google.devtools.build.lib.remote.util.RxUtils.TransferResult;
import com.google.devtools.build.lib.remote.util.TempPathGenerator;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
@@ -60,6 +61,7 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Set;
@@ -67,6 +69,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
@@ -760,6 +763,12 @@ public void flushOutputTree() throws InterruptedException {
downloadCache.awaitInProgressTasks();
}
+ public ListenableFuture<Void> waitDownloads(Collection<PathFragment> files) {
+ var convertedFiles = files.stream().map(file -> execRoot.getFileSystem().getPath(file)).collect(
+ Collectors.toList());
+ return RxFutures.toListenableFuture(downloadCache.waitInProgressTasks(convertedFiles));
+ }
+
public ImmutableSet<ActionInput> getMissingActionInputs() {
return ImmutableSet.copyOf(missingActionInputs);
}
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java
index 7cf03eb399862f..c1b9a6d73b465e 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteOutputService.java
@@ -19,6 +19,8 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.Subscribe;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionInputMap;
@@ -34,10 +36,12 @@
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.OutputService;
+import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import java.io.IOException;
+import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -111,6 +115,13 @@ public void flushOutputTree() throws InterruptedException {
}
}
+ public ListenableFuture<Void> waitOutputDownloads(Collection<PathFragment> files) {
+ if (actionInputFetcher != null) {
+ return actionInputFetcher.waitDownloads(files);
+ }
+ return Futures.immediateVoidFuture();
+ }
+
@Override
public void finalizeBuild(boolean buildSuccessful) {
// Intentionally left empty.
diff --git a/src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java b/src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java
index cd91a72b503226..5d63d2927053c2 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java
@@ -28,6 +28,7 @@
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.subjects.AsyncSubject;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -357,6 +358,32 @@ public void shutdown() {
}
}
+ /**
+ * Returns a {@link Completable} which will completes once the in-progress tasks identified by
+ * {@code keys} are completed. Tasks submitted after the call are not waited.
+ */
+ public Completable waitInProgressTasks(Collection<KeyT> keys) {
+ return Completable.defer(
+ () -> {
+ List<Execution> executions = new ArrayList<>();
+ synchronized (lock) {
+ for (var key : keys) {
+ var execution = inProgress.get(key);
+ if (execution != null) {
+ executions.add(execution);
+ }
+ }
+ }
+ if (executions.isEmpty()) {
+ return Completable.complete();
+ }
+
+ return Completable.fromPublisher(
+ Flowable.fromIterable(executions)
+ .flatMapSingle(e -> Single.fromObservable(e.completion)));
+ });
+ }
+
/**
* Waits for the in-progress tasks to finish. Any tasks that are submitted after the call are not
* waited.
@@ -535,6 +562,14 @@ public void shutdown() {
cache.shutdown();
}
+ /**
+ * Returns a {@link Completable} which will completes once the in-progress tasks identified by
+ * {@code keys} are completed. Tasks submitted after the call are not waited.
+ */
+ public Completable waitInProgressTasks(Collection<KeyT> keys) {
+ return cache.waitInProgressTasks(keys);
+ }
+
/**
* Waits for the in-progress tasks to finish. Any tasks that are submitted after the call are
* not waited.
diff --git a/src/main/java/com/google/devtools/build/lib/vfs/OutputService.java b/src/main/java/com/google/devtools/build/lib/vfs/OutputService.java
index 45ce3d779ea40f..3fb78d67eb008f 100644
--- a/src/main/java/com/google/devtools/build/lib/vfs/OutputService.java
+++ b/src/main/java/com/google/devtools/build/lib/vfs/OutputService.java
@@ -17,6 +17,8 @@
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionInputMap;
@@ -33,6 +35,7 @@
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import java.io.IOException;
+import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -121,6 +124,10 @@ ModifiedFileSet startBuild(EventHandler eventHandler, UUID buildId, boolean fina
/** Flush and wait for in-progress downloads. */
default void flushOutputTree() throws InterruptedException {}
+ default ListenableFuture<Void> waitOutputDownloads(Collection<PathFragment> files) {
+ return Futures.immediateVoidFuture();
+ }
+
/**
* Finish the build.
*
| diff --git a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java
index 527bccebc526ea..5286b50e0cb146 100644
--- a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java
+++ b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java
@@ -32,6 +32,7 @@
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
import com.google.devtools.build.lib.buildeventstream.BuildEventIdUtil;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.BuildEventId;
@@ -107,7 +108,8 @@ public void testCreatesFileAndWritesProtoBinaryFormat() throws Exception {
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
- artifactGroupNamer);
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(buildEvent);
BuildEventStreamProtos.BuildEvent progress =
@@ -157,7 +159,12 @@ public boolean mayBeSlow() {
BufferedOutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));
BinaryFormatFileTransport transport =
- new BinaryFormatFileTransport(outputStream, defaultOpts, uploader, artifactGroupNamer);
+ new BinaryFormatFileTransport(
+ outputStream,
+ defaultOpts,
+ uploader,
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(event1);
ExecutionException expected =
@@ -189,7 +196,8 @@ public void testWriteWhenFileClosed() throws Exception {
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
- artifactGroupNamer);
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.close().get();
@@ -220,7 +228,8 @@ public void testWriteWhenTransportClosed() throws Exception {
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
- artifactGroupNamer);
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(buildEvent);
Future<Void> closeFuture = transport.close();
@@ -267,7 +276,12 @@ public boolean mayBeSlow() {
BufferedOutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));
BinaryFormatFileTransport transport =
- new BinaryFormatFileTransport(outputStream, defaultOpts, uploader, artifactGroupNamer);
+ new BinaryFormatFileTransport(
+ outputStream,
+ defaultOpts,
+ uploader,
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(event1);
transport.sendBuildEvent(event2);
transport.close().get();
@@ -307,7 +321,12 @@ public boolean mayBeSlow() {
BufferedOutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));
BinaryFormatFileTransport transport =
- new BinaryFormatFileTransport(outputStream, defaultOpts, uploader, artifactGroupNamer);
+ new BinaryFormatFileTransport(
+ outputStream,
+ defaultOpts,
+ uploader,
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(event1);
transport.close().get();
@@ -345,7 +364,12 @@ public boolean mayBeSlow() {
BufferedOutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));
BinaryFormatFileTransport transport =
- new BinaryFormatFileTransport(outputStream, defaultOpts, uploader, artifactGroupNamer);
+ new BinaryFormatFileTransport(
+ outputStream,
+ defaultOpts,
+ uploader,
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(event);
ListenableFuture<Void> closeFuture = transport.close();
diff --git a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransportTest.java b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransportTest.java
index 400bdff6d32e68..9229df317f3460 100644
--- a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransportTest.java
+++ b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/JsonFormatFileTransportTest.java
@@ -20,6 +20,7 @@
import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer;
import com.google.devtools.build.lib.buildeventstream.BuildEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.BuildStarted;
@@ -87,7 +88,8 @@ public void testCreatesFileAndWritesProtoJsonFormat() throws Exception {
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
- artifactGroupNamer);
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(buildEvent);
transport.close().get();
@@ -155,7 +157,11 @@ public void testFlushesStreamAfterSmallWrites() throws Exception {
JsonFormatFileTransport transport =
new JsonFormatFileTransport(
- wrappedOutputStream, defaultOpts, new LocalFilesArtifactUploader(), artifactGroupNamer);
+ wrappedOutputStream,
+ defaultOpts,
+ new LocalFilesArtifactUploader(),
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(buildEvent);
Thread.sleep(transport.getFlushInterval().toMillis() * 3);
diff --git a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransportTest.java b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransportTest.java
index a307a129ebc92e..2511852aa8bf6c 100644
--- a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransportTest.java
+++ b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/TextFormatFileTransportTest.java
@@ -22,6 +22,7 @@
import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer;
import com.google.devtools.build.lib.buildeventstream.BuildEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
+import com.google.devtools.build.lib.buildeventstream.BuildEventLocalFileSynchronizer;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.BuildStarted;
@@ -88,7 +89,8 @@ public void testCreatesFileAndWritesProtoTextFormat() throws Exception {
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
- artifactGroupNamer);
+ artifactGroupNamer,
+ BuildEventLocalFileSynchronizer.NO_OP);
transport.sendBuildEvent(buildEvent);
BuildEventStreamProtos.BuildEvent progress =
| train | test | 2023-06-29T10:07:09 | "2023-05-05T15:25:59Z" | bazel-io | test |
bazelbuild/bazel/17884_18846 | bazelbuild/bazel | bazelbuild/bazel/17884 | bazelbuild/bazel/18846 | [
"keyword_pr_to_issue"
] | 601f9090d29b55cdf4f9d8a47f7384d445e9a20b | 6fd3bc199d8d6c9de4c6b602eea00a5db64e96c8 | [
"Note to future self: the minimal repro for https://github.com/bazelbuild/bazel/issues/17911 is also applicable to this issue.",
"@tjgq My usual question 😅 is this cherry-pickable?",
"I don't think it's going to be possible, sorry :( there are way too many other changes that this one depends on.",
"That is unfortunate, as it was working in 5.x, but broke in 6.x, and will only work again in 7.0 ☹️.",
"I will try to work out a dedicated fix for 6.3.",
"@bazel-io fork 6.3.0"
] | [] | "2023-07-05T14:56:33Z" | [
"type: bug",
"P2",
"team-Remote-Exec"
] | --remote_download_toplevel --nozip_undeclared_test_outputs does not download any undeclared test outputs for passing tests | ### Description of the bug:
Prior to upgrading to bazel 6.0.0, on a setup with remote execution, with `bazel test --remote_download_toplevel --nozip_undeclared_test_outputs` I'd see `test.outputs` populated with files.
On bazel 6.0.0, `test.outputs` is always empty on passing tests.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
With remote execution, run `bazel test --remote_download_toplevel --nozip_undeclared_test_outputs`. Observe that test.outputs is empty on passing tests.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
release 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
If I remove `--nozip_undeclared_test_outputs`, I see `test.outputs/outputs.zip` on passing tests too
If I remove `--remote_download_toplevel`, I see the desired files in `test.outputs/*` on passing tests too
Adding `--experimental_remote_download_regex=".*"` didn't help. | [
"src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java"
] | [
"src/test/shell/bazel/remote/build_without_the_bytes_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java b/src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java
index 75ad886bb3d5f2..dc6481f800cb9d 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ToplevelArtifactsDownloader.java
@@ -47,8 +47,10 @@
import com.google.devtools.build.lib.skyframe.TreeArtifactValue;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.Path;
+import com.google.devtools.build.lib.vfs.Symlinks;
import com.google.devtools.build.skyframe.MemoizingEvaluator;
import com.google.devtools.build.skyframe.SkyValue;
+import java.io.IOException;
import java.util.HashMap;
import javax.annotation.Nullable;
@@ -117,6 +119,18 @@ public interface PathToMetadataConverter {
}
private void downloadTestOutput(Path path) {
+ if (path.isDirectory()) {
+ try {
+ var entries = path.readdir(Symlinks.FOLLOW);
+ for (var entry : entries) {
+ downloadTestOutput(path.getRelative(entry.getName()));
+ return;
+ }
+ } catch (IOException e) {
+ logger.atWarning().withCause(e).log("Failed to read dir %s.", path);
+ }
+ }
+
// Since the event is fired within action execution, the skyframe doesn't know the outputs of
// test actions yet, so we can't get their metadata through skyframe. However, the fileSystem
// of the path is an ActionFileSystem, we use it to get the metadata for this file.
| diff --git a/src/test/shell/bazel/remote/build_without_the_bytes_test.sh b/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
index 5cd898753c6f25..5be0b0a05bd238 100755
--- a/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
+++ b/src/test/shell/bazel/remote/build_without_the_bytes_test.sh
@@ -685,6 +685,31 @@ EOF
expect_log "test.outputs_manifest__MANIFEST"
}
+function test_nozip_undeclared_test_outputs() {
+ mkdir -p a
+ cat > a/test.sh << 'EOF'
+#!/bin/sh
+echo foo > "$TEST_UNDECLARED_OUTPUTS_DIR/text.txt"
+EOF
+ chmod +x a/test.sh
+
+ cat > a/BUILD <<'EOF'
+sh_test(
+ name = "foo",
+ srcs = ["test.sh"],
+)
+EOF
+
+ bazel test \
+ --remote_executor=grpc://localhost:${worker_port} \
+ --remote_download_toplevel \
+ --nozip_undeclared_test_outputs \
+ //a:foo || fail "Failed to test //a:foo"
+
+ [[ -e "bazel-testlogs/a/foo/test.outputs/text.txt" ]] || fail "bazel-testlogs/a/foo/test.outputs/text.txt does not exist"
+ assert_contains "foo" "bazel-testlogs/a/foo/test.outputs/text.txt"
+}
+
function test_multiple_test_attempts() {
# Test that test logs of multiple test attempts can be renamed and reported by
# BEP.
| val | test | 2023-07-05T19:04:15 | "2023-03-25T00:24:29Z" | VarunKoyyalagunta | test |
bazelbuild/bazel/16368_18853 | bazelbuild/bazel | bazelbuild/bazel/16368 | bazelbuild/bazel/18853 | [
"keyword_pr_to_issue"
] | 6fd3bc199d8d6c9de4c6b602eea00a5db64e96c8 | 9483bafeef0ab6567389390fcfb74a6c80c1ba58 | [
"@ahumesky ",
"We are also seeing this in our repo using the latest rolling release (6.0.0-pre.20220922.1)",
"@ahumesky can this issue be added to [Bazel 6.1. release blockers](https://github.com/bazelbuild/bazel/milestone/46)? As you noted #16369 does not completely solve it. We are hesitant to upgrade to 6.0 even with that fix since we might run into the same issue with another of synthetic classes at any point.",
"Yes I think we can get the fix in for 6.1.\r\n\r\nBut a question for those of you running into this issue -- we're not seeing this internally, so I'm trying to figure out what differences might be causing this with bazel. Is anyone using the `min_sdk_version` attribute of android_binary (related: https://github.com/bazelbuild/bazel/issues/10556#issuecomment-1425041290), or perhaps modified the [hard coded dexing API level](https://github.com/bazelbuild/bazel/blob/master/src/tools/android/java/com/google/devtools/build/android/r8/CompatDexBuilder.java#L178)?",
"We are not setting either of those. We are setting min API level in the manifest using the uses-sdk tag. For an application that exhibits it, it is happening consistently. However, triggering it doesn't seem to be related to changing build rules. i.e. We have experienced with an application in which the change that triggered this behavior is purely a code change. It's a little hard for me to create a repro, given that it depends on internal code.\r\n\r\nAlso—I don't see this added to 6.1 release blockers. Is that still a possibility?",
"Thanks -- turns out the reason we weren't seeing this internally isn't related to API level exactly, but internally we have other code paths that avoid this problem. We're removing these codepath soon so that the code matches internally and externally, so we'll want the fix for this as well.\r\n\r\nIt's been pretty tricky to get the fix for this working in all cases, and has required reworking the PR for this a fair bit (https://github.com/bazelbuild/bazel/pull/16369#issuecomment-1442802265). I'm rerunning all our tests again to see if anything still fails with the updates to the PR, so I'm a little hesitant now to block 6.1.0 on this if there are more cases that need to be addressed. If we can't get the fix in for 6.1.0 we cherrypick this into 6.2.0.",
"After working through https://github.com/bazelbuild/bazel/pull/16369 and talking with the D8 team, they propose (copied from #16369):\r\n\r\n1. Update CompatDexBuilder to use the D8 DexFilePerClassFile consumer instead of DexIndexed (this should be a no op for the build as the current build there is already doing one dex per class file, but it uses another D8 API such that it can get the synthetic info).\r\n\r\n2. Update the D8 DexFilePerClassFile accept function to also receive the \"synthetic context\" information if the compiled class is a compiler synthesized class.\r\n\r\n3. Update CompatDexBuilder to write the synthetic context information to some build meta info for later access by the DexFileSplitter. Something like this is already done for the desugar dependencies which are written to a proto in META-INF/desugar_deps.\r\n\r\n4. Update DexFileSplitter to use the meta-inf of synthetic classes to group with the right contexts.\r\n\r\nThe D8 team would handle 1 and 2, and the bazel team and/or community could do 3 and 4. This avoids coupling to D8 implementation details and having to parse dex files and hopefully reduces the code complexity a bit.",
"The fix for this should be ready to submit tomorrow, and then I'll cherrypick it into the Bazel 6.3 release.",
"There's still this same issue with the `dex_shards` attribute and DexMapper (which is still used for mobile-install \"classic\" while we open source the starlark replacement). I have an in progress change that applies same fix for DexFileSplitter to DexMapper, which we'll merge into Bazel 6.3 as well.",
"@ahumesky I think we're still seeing this issue on Linux only when filenames contain capital letters. \r\n```\r\n11:49:44 18:49:44 [Bazel] bazel-out/k8-opt-exec-ST-7a15de0b7d6a/bin/external/bazel_tools/tools/android/d8_dexmerger --input bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexsplits/apk/7.shard.zip --output bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexfiles/apk/7.shard.zip '--multidex=given_shard')\r\n11:49:44 18:49:44 [Bazel] # Configuration: 064afe4bfa5b855024151ed67fa23ab997cd53f5f864cf3be12acef0225806a5\r\n11:49:44 18:49:44 [Bazel] # Execution platform: @local_config_platform//:host\r\n11:49:44 18:49:44 [Bazel] Use --sandbox_debug to see verbose messages from the sandbox and retain the sandbox build root for debugging\r\n11:49:44 18:49:44 [Bazel] Error in bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexsplits/apk/7.shard.zip:com/snap/ipc/buffers/IBufferMapper$-CC.class.dex:\r\n11:49:44 18:49:44 [Bazel] Attempt at compiling intermediate artifact without its context\r\n11:49:44 18:49:44 [Bazel] Merge failed: Compilation failed to complete, origin: bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexsplits/apk/7.shard.zip:com/snap/ipc/buffers/IBufferMapper$-CC.class.dex\r\n11:49:44 18:49:44 [Bazel] Exception in thread \"main\" java.lang.RuntimeException: Merge failed: Compilation failed to complete, origin: bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexsplits/apk/7.shard.zip:com/snap/ipc/buffers/IBufferMapper$-CC.class.dex\r\n11:49:44 18:49:44 [Bazel] at com.google.devtools.build.android.r8.DexFileMerger.main(DexFileMerger.java:412)\r\n11:49:44 18:49:44 [Bazel] Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/dexsplits/apk/7.shard.zip:com/snap/ipc/buffers/IBufferMapper$-CC.class.dex\r\n11:49:44 18:49:44 [Bazel] at Version.fakeStackEntry(Version_8.1.51.java:0)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.M.a(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:5)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.utils.R0.a(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:81)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.utils.R0.a(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:32)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.utils.R0.a(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:31)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.utils.R0.b(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:2)\r\n11:49:44 18:49:44 [Bazel] at com.android.tools.r8.D8.run(R8_8.1.51_9b737621870a00577be8badac89ea7485627e0cae5c007fd3c57c275c1a604a9:6)\r\n11:49:44 18:49:44 [Bazel] at com.google.devtools.build.android.r8.DexFileMerger.run(DexFileMerger.java:395)\r\n11:49:44 18:49:44 [Bazel] at com.google.devtools.build.android.r8.DexFileMerger.main(DexFileMerger.java:409)\r\n11:49:44 18:49:44 [Bazel] Caused by: com.android.tools.r8.utils.b: Attempt at compiling intermediate artifact without its context\r\n```",
"nkoroste@ is this a custom R8 build (I can't retrace)?\r\n\r\nIs IBufferMapper.class in any of the shards?"
] | [] | "2023-07-06T19:10:01Z" | [
"type: bug",
"P1",
"team-Android"
] | D8 dex merger fails when a synthetic class is placed on a different shard than its container class | ### Description of the bug:
a desugared lambda is packed in a different shard than the one
from its original class D8 will fail with the following message:
`Attempt at compiling intermediate artifact without its context
`
e.g.
I'm encountering an issue when compiling my app with the following classes:
`org/chromium/base/MemoryPressureListener
``org/chromium/base/MemoryPressureListener$$ExternalSyntheticLambda0`
bazel fails with the following message
```
Error in bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/mirroring-sample-app/dexsplits/apk/9.shard.zip:org/chromium/base/MemoryPressureListener$$ExternalSyntheticLambda0.class.dex:
Attempt at compiling intermediate artifact without its context
Merge failed: Compilation failed to complete, origin: bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/mirroring-sample-app/dexsplits/apk/9.shard.zip:org/chromium/base/MemoryPressureListener$$ExternalSyntheticLambda0.class.dex
Exception in thread "main" com.android.tools.r8.CompilationFailedException: Merge failed: Compilation failed to complete, origin: bazel-out/k8-fastbuild/bin/apps/hermosa/hermosa-services/realtime/mirroring-sample-app/dexsplits/apk/9.shard.zip:org/chromium/base/MemoryPressureListener$$ExternalSyntheticLambda0.class.dex
at com.google.devtools.build.android.r8.DexFileMerger.main(DexFileMerger.java:389)
Target //apps/hermosa/hermosa-services/realtime/mirroring-sample-app:apk failed to build
```
Here the container class is in shard #8 and the lambda class is in shard #9
Running with d8 dexmerger and native multidex.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Its hard to provide a small reproducible example since it needs to be an app large enough to exceed the size of a dex file and the sharding has to result in a lambda class ending up in a different shard than the container class.
### Which operating system are you running Bazel on?
Linux/Mac
### What is the output of `bazel info release`?
Internal build merged with master at commit https://github.com/bazelbuild/bazel/commit/b6803a2a8367e0a6748256d2e1f162ceb5451636
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java",
"src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java",
"tools/android/runtime_deps/BUILD.bazel"
] | [
"src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java",
"src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java",
"tools/android/runtime_deps/BUILD.bazel"
] | [
"src/test/java/com/google/devtools/build/android/ziputils/SplitterTest.java",
"src/test/shell/BUILD",
"src/test/shell/bazel/android/BUILD",
"src/test/shell/bazel/android/DexFileSplitter_synthetic_classes_test.sh",
"src/test/shell/bazel/android/android_sh_test.bzl",
"src/test/shell/testenv.sh.tmpl"
] | diff --git a/src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java b/src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java
index a3b33a042c9a91..8999b9ae269c94 100644
--- a/src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java
+++ b/src/tools/android/java/com/google/devtools/build/android/ziputils/SplitZip.java
@@ -27,9 +27,13 @@
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -39,10 +43,12 @@
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
+import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
@@ -416,12 +422,22 @@ private void checkConfig() throws IOException {
filter = filterFile == null && filterInputStream == null ? null : readPaths(filterFile);
}
- /**
- * Parses the entries and assign each entry to an output file.
- */
- private void split() {
+ /** Parses the entries and assign each entry to an output file. */
+ private void split() throws IOException {
+
+ // A map of class (a "context") to its inner synthetic classes from D8.
+ SetMultimap<String, String> syntheticClassContexts = HashMultimap.create();
+
for (ZipIn in : inputs) {
CentralDirectory cdir = centralDirectories.get(in.getFilename());
+
+ for (DirectoryEntry entry : cdir.list()) {
+ if (entry.getFilename().equals("META-INF/synthetic-contexts.map")) {
+ parseSyntheticContextsMap(in.entryFor(entry).getContent(), syntheticClassContexts);
+ break;
+ }
+ }
+
for (DirectoryEntry entry : cdir.list()) {
String filename = normalizedFilename(entry.getFilename());
if (!inputFilter.apply(filename)) {
@@ -438,17 +454,31 @@ private void split() {
}
}
}
+
Splitter splitter = new Splitter(outputs.size(), classes.size());
+
if (filter != null) {
// Assign files in the filter to the first output file.
- splitter.assign(Sets.filter(filter, inputFilter));
+ splitter.assignAllToCurrentShard(Sets.filter(filter, inputFilter));
splitter.nextShard(); // minimal initial shard
}
+
+ Set<String> allSyntheticClasses = new HashSet<>(syntheticClassContexts.values());
+
for (String path : classes) {
- // Use normalized filename so the filter file doesn't have to change
- int assignment = splitter.assign(path);
- Preconditions.checkState(assignment >= 0 && assignment < zipOuts.length);
- assignments.put(path, zipOuts[assignment]);
+ if (!allSyntheticClasses.contains(path)) {
+
+ // Use normalized filename so the filter file doesn't have to change
+ int assignment = splitter.assign(path);
+ Set<String> syntheticClasses = syntheticClassContexts.get(path);
+ splitter.assignAllToCurrentShard(syntheticClasses);
+ Preconditions.checkState(assignment >= 0 && assignment < zipOuts.length);
+
+ assignments.put(path, zipOuts[assignment]);
+ for (String syntheticClass : syntheticClasses) {
+ assignments.put(syntheticClass, zipOuts[assignment]);
+ }
+ }
}
}
@@ -494,6 +524,23 @@ private String fixPath(String path) {
return path;
}
+ private static void parseSyntheticContextsMap(
+ ByteBuffer byteBuffer, Multimap<String, String> syntheticClassContexts) {
+ // The ByteBuffer returned from the Splitter's zip library is not backed by an accessible array,
+ // so ByteBuffer.array() is not supported, so we must go the long way.
+ byte[] bytes = new byte[byteBuffer.remaining()];
+ byteBuffer.get(bytes);
+ Scanner scanner = new Scanner(new ByteArrayInputStream(bytes), UTF_8);
+ scanner.useDelimiter("[;\n]");
+ while (scanner.hasNext()) {
+ String syntheticClass = scanner.next();
+ String context = scanner.next();
+ // The context map uses class names, whereas SplitZip uses class file names, so add ".class"
+ // here to make it easier to work with the map in the rest of the code.
+ syntheticClassContexts.put(context + ".class", syntheticClass + ".class");
+ }
+ }
+
private void verbose(String msg) {
if (verbose) {
System.out.println(msg);
diff --git a/src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java b/src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java
index 7f1a469f10368d..2c03b74cacac09 100644
--- a/src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java
+++ b/src/tools/android/java/com/google/devtools/build/android/ziputils/Splitter.java
@@ -24,10 +24,10 @@ class Splitter {
private final int numberOfShards;
private final Map<String, Integer> assigned;
- private int size = 0;
- private int shard = 0;
+ private int size = 0; // Number of classes in the current shard
+ private int shard = 0; // Current shard number
private String prevPath = null;
- private int remaining;
+ private int remaining; // Number of classes remaining to be assigned shards
private int idealSize;
private int almostFull;
@@ -51,15 +51,15 @@ public Splitter(int numberOfShards, int expectedSize) {
* remaining entries to process is adjusted, by subtracting the number of as-of-yet unassigned
* entries from the filter.
*/
- public void assign(Collection<String> filter) {
- if (filter != null) {
- for (String s : filter) {
- if (!assigned.containsKey(s)) {
+ public void assignAllToCurrentShard(Collection<String> entries) {
+ if (entries != null) {
+ for (String e : entries) {
+ if (!assigned.containsKey(e)) {
remaining--;
}
- assigned.put(s, shard);
+ assigned.put(e, shard);
}
- size = filter.size();
+ size += entries.size();
}
}
diff --git a/tools/android/runtime_deps/BUILD.bazel b/tools/android/runtime_deps/BUILD.bazel
index 9c50eb42dc2978..b56610231034a7 100644
--- a/tools/android/runtime_deps/BUILD.bazel
+++ b/tools/android/runtime_deps/BUILD.bazel
@@ -4,7 +4,7 @@
# extract all Android rules and tools out of Bazel and into rules_android
# and tools_android.
-load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
+load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
filegroup(
name = "srcs",
@@ -84,5 +84,9 @@ pkg_tar(
"//src/java_tools/import_deps_checker/java/com/google/devtools/build/importdeps:ImportDepsChecker_deploy.jar",
"//src/tools/android/java/com/google/devtools/build/android:all_android_tools_deploy.jar",
],
+ remap_paths = {
+ "src/java_tools/import_deps_checker/java/com/google/devtools/build/importdeps:ImportDepsChecker_deploy.jar": "ImportDepsChecker_deploy.jar",
+ "src/tools/android/java/com/google/devtools/build/android:all_android_tools_deploy.jar": "all_android_tools_deploy.jar",
+ },
visibility = ["//src/test/shell/bazel:__subpackages__"],
)
| diff --git a/src/test/java/com/google/devtools/build/android/ziputils/SplitterTest.java b/src/test/java/com/google/devtools/build/android/ziputils/SplitterTest.java
index 3f24eda65efeaf..568db636ccb0ca 100644
--- a/src/test/java/com/google/devtools/build/android/ziputils/SplitterTest.java
+++ b/src/test/java/com/google/devtools/build/android/ziputils/SplitterTest.java
@@ -51,7 +51,7 @@ public void testAssign() {
filter.add("dir" + i + ARCHIVE_FILE_SEPARATOR + "file" + i + CLASS_SUFFIX);
}
Splitter splitter = new Splitter(size + 1, input.size());
- splitter.assign(filter);
+ splitter.assignAllToCurrentShard(filter);
splitter.nextShard();
output = new LinkedHashMap<>();
for (String path : input) {
diff --git a/src/test/shell/BUILD b/src/test/shell/BUILD
index f3054b8c6c8bf4..6ddf5da707e68f 100644
--- a/src/test/shell/BUILD
+++ b/src/test/shell/BUILD
@@ -29,6 +29,7 @@ gen_workspace_stanza(
"rules_cc",
"rules_java",
"rules_license",
+ "rules_pkg",
"rules_proto",
],
template = "testenv.sh.tmpl",
diff --git a/src/test/shell/bazel/android/BUILD b/src/test/shell/bazel/android/BUILD
index 4a4d14d1f4672b..9921da218dd1f7 100644
--- a/src/test/shell/bazel/android/BUILD
+++ b/src/test/shell/bazel/android/BUILD
@@ -238,11 +238,14 @@ android_sh_test(
name = "DexFileSplitter_synthetic_classes_test",
size = "medium",
srcs = ["DexFileSplitter_synthetic_classes_test.sh"],
+ # Fixes to DexMapper are not released yet.
+ create_test_with_released_tools = False,
data = [
":android_helper",
"//external:android_sdk_for_testing",
"//src/test/shell/bazel:test-deps",
],
+ shard_count = 2,
tags = [
"no_windows",
],
diff --git a/src/test/shell/bazel/android/DexFileSplitter_synthetic_classes_test.sh b/src/test/shell/bazel/android/DexFileSplitter_synthetic_classes_test.sh
index bd70e9f4533437..44c4a00020f2ee 100755
--- a/src/test/shell/bazel/android/DexFileSplitter_synthetic_classes_test.sh
+++ b/src/test/shell/bazel/android/DexFileSplitter_synthetic_classes_test.sh
@@ -26,18 +26,20 @@
# Load the test setup defined in the parent directory
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${CURRENT_DIR}/../../integration_test_setup.sh" \
+ || { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+
source "${CURRENT_DIR}/android_helper.sh" \
|| { echo "android_helper.sh not found!" >&2; exit 1; }
fail_if_no_android_sdk
-source "${CURRENT_DIR}/../../integration_test_setup.sh" \
- || { echo "integration_test_setup.sh not found!" >&2; exit 1; }
-
resolve_android_toolchains "$1"
-function test_DexFileSplitter_synthetic_classes_crossing_dexfiles() {
- create_new_workspace
- setup_android_sdk_support
+function create_test_app() {
+
+ inner_class_count="$1"
+ lambda_count="$2"
+ dex_shard_count="$3"
mkdir -p java/com/testapp
@@ -81,7 +83,7 @@ public class MainActivity extends Activity {
}
EOF
- generate_java_file_with_many_synthetic_classes > java/com/testapp/BigLib.java
+ generate_java_file_with_many_synthetic_classes "$1" "$2" > java/com/testapp/BigLib.java
cat > java/com/testapp/BUILD <<EOF
android_binary(
@@ -90,26 +92,22 @@ android_binary(
"MainActivity.java",
":BigLib.java",
],
+ dex_shards = $dex_shard_count,
manifest = "AndroidManifest.xml",
)
EOF
-
- bazel build java/com/testapp || fail "Test app should have built succesfully"
-
- dex_file_count=$(unzip -l bazel-bin/java/com/testapp/testapp.apk | grep "classes[0-9]*.dex" | wc -l)
- if [[ ! "$dex_file_count" -ge "2" ]]; then
- echo "Expected at least 2 dexes in app, found: $dex_file_count"
- exit 1
- fi
}
-
function generate_java_file_with_many_synthetic_classes() {
+
+ inner_class_count="$1"
+ lambda_count="$2"
+
echo "package com.testapp;"
echo "public class BigLib {"
# First generate enough inner classes to fill up most of the dex
- for (( i = 0; i < 21400; i++ )) do
+ for (( i = 0; i < $inner_class_count; i++ )) do
echo " public static class Bar$i {"
echo " public int bar() {"
@@ -129,7 +127,7 @@ function generate_java_file_with_many_synthetic_classes() {
echo " public IntSupplier[] foo() {"
echo " return new IntSupplier[] {"
- for ((i = 0; i < 6000; i++ )) do
+ for ((i = 0; i < $lambda_count; i++ )) do
echo " () -> $i,"
done
@@ -139,4 +137,42 @@ function generate_java_file_with_many_synthetic_classes() {
echo "}"
}
+function test_DexFileSplitter_synthetic_classes_crossing_dexfiles() {
+ create_new_workspace
+ setup_android_sdk_support
+
+ # dex_shards default is 1
+ create_test_app 21400 6000 1
+
+ bazel build java/com/testapp || fail "Test app should have built succesfully"
+
+ dex_file_count=$(unzip -l bazel-bin/java/com/testapp/testapp.apk | grep "classes[0-9]*.dex" | wc -l)
+ if [[ ! "$dex_file_count" -ge "2" ]]; then
+ echo "Expected at least 2 dexes in app, found: $dex_file_count"
+ exit 1
+ fi
+}
+
+function test_DexMapper_synthetic_classes_crossing_dexfiles() {
+ create_new_workspace
+ setup_android_sdk_support
+
+ # 3 inner classes, 6 lambdas (and thus 6 synthetics from D8) and 5 dex_shards
+ # is one magic combination to repro synthetics being separated from their
+ # context / enclosing classes.
+ create_test_app 3 6 5
+
+ echo here2
+ echo $TEST_TMPDIR/bazelrc
+ cat $TEST_TMPDIR/bazelrc
+
+ bazel build java/com/testapp || fail "Test app should have built succesfully"
+
+ dex_file_count=$(unzip -l bazel-bin/java/com/testapp/testapp.apk | grep "classes[0-9]*.dex" | wc -l)
+ if [[ ! "$dex_file_count" -eq "5" ]]; then
+ echo "Expected 5 dexes in app, found: $dex_file_count"
+ exit 1
+ fi
+}
+
run_suite "Tests for DexFileSplitter with synthetic classes crossing dexfiles"
\ No newline at end of file
diff --git a/src/test/shell/bazel/android/android_sh_test.bzl b/src/test/shell/bazel/android/android_sh_test.bzl
index 40f21648a2f939..8c0bbc626bc40e 100644
--- a/src/test/shell/bazel/android/android_sh_test.bzl
+++ b/src/test/shell/bazel/android/android_sh_test.bzl
@@ -29,20 +29,36 @@ CHECK_FOR_ANDROID_SDK = select(
no_match_error = "This test requires an android SDK, and one isn't present. Make sure to uncomment the android rules in the WORKSPACE.",
)
-def android_sh_test(**kwargs):
+def android_sh_test(create_test_with_released_tools = True, **kwargs):
+ """Creates versions of the test with and without platforms and head android tools.
+
+ Args:
+ create_test_with_released_tools: Whether to create a version of the test with the released
+ android tools, for when the code under test relies on not-yet-released code.
+ **kwargs: Args to sh_test
+ """
name = kwargs.pop("name")
data = kwargs.pop("data")
if not data:
data = []
data = data + CHECK_FOR_ANDROID_SDK
- # Test with released android_tools version.
- native.sh_test(
- name = name,
- args = ["--without_platforms"],
- data = data,
- **kwargs
- )
+ if create_test_with_released_tools:
+ # Test with released android_tools version.
+ native.sh_test(
+ name = name,
+ args = ["--without_platforms"],
+ data = data,
+ **kwargs
+ )
+
+ # Test with platform-based toolchain resolution.
+ native.sh_test(
+ name = name + "_with_platforms",
+ data = data,
+ args = ["--with_platforms"],
+ **kwargs
+ )
# Test with android_tools version that's built at the same revision
# as the test itself.
@@ -54,11 +70,3 @@ def android_sh_test(**kwargs):
],
**kwargs
)
-
- # Test with platform-based toolchain resolution.
- native.sh_test(
- name = name + "_with_platforms",
- data = data,
- args = ["--with_platforms"],
- **kwargs
- )
diff --git a/src/test/shell/testenv.sh.tmpl b/src/test/shell/testenv.sh.tmpl
index 7ee2e772951205..7a9aac74580a1c 100755
--- a/src/test/shell/testenv.sh.tmpl
+++ b/src/test/shell/testenv.sh.tmpl
@@ -330,6 +330,7 @@ EOF
"rules_license"
"rules_proto"
"rules_python"
+ "rules_pkg"
)
for repo in "${repos[@]}"; do
reponame="${repo%"_for_testing"}"
@@ -554,6 +555,14 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
EOF
}
+function add_rules_pkg_to_workspace() {
+ cat >> "$1"<<EOF
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
+{rules_pkg}
+EOF
+}
+
function add_rules_proto_to_workspace() {
cat >> "$1"<<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
@@ -575,6 +584,7 @@ EOF
add_rules_cc_to_workspace "WORKSPACE"
add_rules_java_to_workspace "WORKSPACE"
add_rules_license_to_workspace "WORKSPACE"
+ add_rules_pkg_to_workspace "WORKSPACE"
add_rules_proto_to_workspace "WORKSPACE"
maybe_setup_python_windows_workspace
| train | test | 2023-07-06T10:46:45 | "2022-10-01T00:39:35Z" | mauriciogg | test |
bazelbuild/bazel/19056_19086 | bazelbuild/bazel | bazelbuild/bazel/19056 | bazelbuild/bazel/19086 | [
"keyword_pr_to_issue"
] | bac439336271464c662830c1c0d00dd0f81fc90e | 2e3c5d0acef5f904143126908cc9edafae014636 | [
"cc @oquenchil ",
"Your bisect is likely to land on https://github.com/bazelbuild/bazel/commit/946777ab77ec84223b02b4deb2d7d947a4ab3611, which combines multiple individual commits to master. Could you check whether the issue reproduces with `last_green`?",
"bazelisk --bisect does not work for me, is it supported by Windows bazelisk?\r\n\r\nlast_green gives me a different error:\r\n`Error in fail: Two shared libraries in dependencies link the same library statically. Both @//src/a:liba and @//src/b:libb link statically @//src:include_root\r\n`\r\n\r\nThis diagnostic is correct, but unhelpful; src/include_root is a header-only library and thus has nothing to link.\r\n\r\n",
"CC @meteorcloudy who implemented `--bisect`\r\n\r\n",
"> bazelisk --bisect does not work for me, is it supported by Windows bazelisk?\r\n\r\nYes, it should work for Windows. Can you provide the error messages you get while running bazelisk bisect?",
"@bazel-io fork 6.3.1",
"@bazel-io fork 6.4.0",
"I'm debugging this now. The code was never written to work like this because it discarded pre-compiled dynamic libraries (or at least that was the intention). So it was an accident that it worked for 6.2.\r\n\r\nHowever, the bug report is valid because on Windows the transitive *.libs should be passed to the linker for DLL creation so this needs to be fixed. This doesn't apply on other platforms, for other platforms `b` shouldn't have to appear in the command line of `c`.",
"Actually what I said in my previous comment is completely wrong. This is working at head by the way, I thought you had checked at last_green. This also affects Linux.\r\n\r\nThe issue here is that `cc_import` in 6.x doesn't advertise CcInfo when it should, i.e.: this line https://cs.opensource.google/bazel/bazel/+/master:src/main/starlark/builtins_bzl/common/cc/cc_import.bzl;drc=6ce7a5455640984f69c69d534db61d9c1873a9f0;l=212 is missing",
"Fix is in https://github.com/bazelbuild/bazel/pull/19086/commits",
"@chrisbrown2050 Thank you for reporting this issue.\r\nWe're looking to improve our release process so that we can catch more issues early on in the cycle (before the final release) and would love your input. What can we do to make it easier for you to test _release candidates_ in the future? ",
"@chrisbrown2050 Can you please confirm if this issue has been fixed in 6.3.1rc1?",
"6.3.1rc1 does fix this issue - thank you!\r\n\r\nAs to how we could test _release candidates_, right now I don't track these. But now I know I can test them via bazelisk, it's pretty easy. How would I subscribe to notifications? Or can I set an environment var so my own machine updates to all the release candidates whilst all our production machines stay on official releases?",
"@peakschris Thanks for confirming! Yes, with bazelisk, you can point to the latest rc by setting `USE_BAZEL_VERSION=last_rc`, see https://github.com/bazelbuild/bazelisk#how-does-bazelisk-know-which-bazel-version-to-run\r\n\r\n@keertk It's probably worth advertising this approach ;)"
] | [] | "2023-07-26T13:41:11Z" | [
"type: bug",
"P1",
"team-Rules-CPP"
] | Regression: cc_import not linked to target when added to deps of target | ### Description of the bug:
Since bazelisk moved us to 6.3.0 yesterday, our libraries have not linked. This is a regression in 6.3.0 vs 6.2.0
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
http_archive('a')
cc_import(name='b', interface_library=b.lib, shared_library=b.dll)
cc_library(name='c_base', srcs=[x,y,z], deps=['@a//:b'])
cc_shared_library(name='c', deps=[":c_base"])
6.2.0: c_base links fine, linker params file includes b.lib
6.3.0: c_base not linked, linker params file is missing b.lib
### Which operating system are you running Bazel on?
Windows
### What is the output of `bazel info release`?
release 6.3.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
Between 6.2.0 and 6.3.0, will try to run bisect
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/starlark/builtins_bzl/common/cc/cc_import.bzl"
] | [
"src/main/starlark/builtins_bzl/common/cc/cc_import.bzl"
] | [
"src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test"
] | diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl
index babfb2b40c989e..b7c7ff8df636c7 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl
@@ -220,6 +220,7 @@ cc_import = rule(
),
"_cc_toolchain": attr.label(default = "@" + semantics.get_repo() + "//tools/cpp:current_cc_toolchain"),
},
+ provides = [CcInfo],
toolchains = cc_helper.use_cpp_toolchain(),
fragments = ["cpp"],
incompatible_use_toolchain_transition = True,
| diff --git a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
index 952dea0c426454..196231642e74e2 100644
--- a/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
+++ b/src/main/starlark/tests/builtins_bzl/cc/cc_shared_library/test_cc_shared_library/BUILD.builtin_test
@@ -405,12 +405,10 @@ paths_test(
name = "path_matching_test",
)
-cc_library(
+cc_import(
name = "prebuilt",
hdrs = ["direct_so_file_cc_lib.h"],
- srcs = [
- ":just_main_output",
- ],
+ shared_library = ":just_main_output",
)
filegroup(
| test | test | 2023-07-25T21:51:26 | "2023-07-25T13:54:49Z" | chrisbrown2050 | test |
bazelbuild/bazel/19155_19164 | bazelbuild/bazel | bazelbuild/bazel/19155 | bazelbuild/bazel/19164 | [
"keyword_pr_to_issue"
] | ee918697ea776e03552ed2457421eda75fc5229f | 382dfafa1a77e0eaabe6aa11e92176323e675499 | [
"Can confirm that this is a bug. The two extensions are assigned the prefixes `_main~my_ext~` and `_main~my_ext~2~` now, which is bad since the former is a prefix of the latter.\r\n\r\nI am working on a fix.\r\n\r\nCC @Wyverald ",
"@bazel-io flag",
"@bazel-io fork 6.4.0",
"@iancha1992 This is a regression from Bazel 6.2.0, so unfortunately we may need a 6.3.2 release to cherry-pick this into.",
"> \r\n\r\ncc: @bazelbuild/triage "
] | [] | "2023-08-03T20:27:59Z" | [
"type: bug",
"P1",
"team-ExternalDeps",
"area-Bzlmod"
] | same `module_extension` name in different bzl files could not be resolved while using bzlmod in bazel 6.3.1 | ### Description of the bug:
We're using bzlmod.
This is a part of `MODULE.bazel`, which works fine in bazel 6.2.1.
```
a_ext = use_extension("//path/to/A:A.bzl", "my_ext")
use_repo(a_ext, "abc")
b_ext = use_extension("//path/to/B:B.bzl", "my_ext")
use_repo(b_ext, "xyz")
```
When I updated bazel to 6.3.1, there was an error in analysis phase.
```
ERROR: /my/workspace/library_path/BUILD:4:13: no such package '@_main~my_ext~2~xyz//':
The repository '@_main~my_ext~2~xyz' could not be resolved:
Repository '@_main~my_ext~2~xyz' is not defined and referenced by '//library_path:library_name'
ERROR: Analysis of target '//my_path:my_target' failed; build aborted:
```
It seems that in bazel 6.2.1, if there is a same `module_extension` name in different bzl files, the second one will be named as `@_main~my_ext2~xyz` in external directory. But in bazel 6.3.1, it seems that bazel is tring to find a module named as `@_main~my_ext~2~xyz` (adds a `~` after `ext`) which doesn't actually exist.
### Which category does this issue belong to?
_No response_
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
_No response_
### Which operating system are you running Bazel on?
macOS 13.4.1
### What is the output of `bazel info release`?
release 6.3.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
_No response_
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
index eaf358a011d05b..9e7c0a328e8356 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
@@ -20,6 +20,7 @@
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
@@ -247,39 +248,45 @@ static BzlmodFlagsAndEnvVars getFlagsAndEnvVars(Environment env) throws Interrup
private ImmutableBiMap<String, ModuleExtensionId> calculateUniqueNameForUsedExtensionId(
ImmutableTable<ModuleExtensionId, ModuleKey, ModuleExtensionUsage> extensionUsagesById) {
- // Calculate a unique name for each used extension id.
+ // Calculate a unique name for each used extension id with the following property that is
+ // required for BzlmodRepoRuleFunction to unambiguously identify the extension that generates a
+ // given repo:
+ // After appending a single `~` to each such name, none of the resulting strings is a prefix of
+ // any other such string.
BiMap<String, ModuleExtensionId> extensionUniqueNames = HashBiMap.create();
for (ModuleExtensionId id : extensionUsagesById.rowKeySet()) {
- // Ensure that the resulting extension name (and thus the repository names derived from it) do
- // not start with a tilde.
- RepositoryName repository = id.getBzlFileLabel().getRepository();
- String nonEmptyRepoPart = repository.isMain() ? "_main" : repository.getName();
- // When using a namespace, prefix the extension name with "_" to distinguish the prefix from
- // those generated by non-namespaced extension usages. Extension names are identified by their
- // Starlark identifier, which in the case of an exported symbol cannot start with "_".
- String bestName =
- id.getIsolationKey()
- .map(
- namespace ->
- String.format(
- "%s~_%s~%s~%s~%s",
- nonEmptyRepoPart,
- id.getExtensionName(),
- namespace.getModule().getName(),
- namespace.getModule().getVersion(),
- namespace.getUsageExportedName()))
- .orElse(nonEmptyRepoPart + "~" + id.getExtensionName());
- if (extensionUniqueNames.putIfAbsent(bestName, id) == null) {
- continue;
- }
- int suffix = 2;
- while (extensionUniqueNames.putIfAbsent(bestName + "~" + suffix, id) != null) {
- suffix++;
+ int attempt = 1;
+ while (extensionUniqueNames.putIfAbsent(makeUniqueNameCandidate(id, attempt), id) != null) {
+ attempt++;
}
}
return ImmutableBiMap.copyOf(extensionUniqueNames);
}
+ private static String makeUniqueNameCandidate(ModuleExtensionId id, int attempt) {
+ // Ensure that the resulting extension name (and thus the repository names derived from it) do
+ // not start with a tilde.
+ RepositoryName repository = id.getBzlFileLabel().getRepository();
+ String nonEmptyRepoPart = repository.isMain() ? "_main" : repository.getName();
+ // When using a namespace, prefix the extension name with "_" to distinguish the prefix from
+ // those generated by non-namespaced extension usages. Extension names are identified by their
+ // Starlark identifier, which in the case of an exported symbol cannot start with "_".
+ Preconditions.checkArgument(attempt >= 1);
+ String extensionNameDisambiguator = attempt == 1 ? "" : String.valueOf(attempt);
+ return id.getIsolationKey()
+ .map(
+ namespace ->
+ String.format(
+ "%s~_%s%s~%s~%s~%s",
+ nonEmptyRepoPart,
+ id.getExtensionName(),
+ extensionNameDisambiguator,
+ namespace.getModule().getName(),
+ namespace.getModule().getVersion(),
+ namespace.getUsageExportedName()))
+ .orElse(nonEmptyRepoPart + "~" + id.getExtensionName() + extensionNameDisambiguator);
+ }
+
static class BazelDepGraphFunctionException extends SkyFunctionException {
BazelDepGraphFunctionException(ExternalDepsException e, Transience transience) {
super(e, transience);
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
index fbe92cf779386f..b8602dba90d16e 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
@@ -292,7 +292,7 @@ public void createValue_moduleExtensions() throws Exception {
maven, "rules_jvm_external~1.0~maven",
pip, "rules_python~2.0~pip",
myext, "dep~2.0~myext",
- myext2, "dep~2.0~myext~2");
+ myext2, "dep~2.0~myext2");
assertThat(value.getFullRepoMapping(ModuleKey.ROOT))
.isEqualTo(
@@ -323,7 +323,7 @@ public void createValue_moduleExtensions() throws Exception {
"oneext",
"dep~2.0~myext~myext",
"twoext",
- "dep~2.0~myext~2~myext"));
+ "dep~2.0~myext2~myext"));
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
index 5bd81dac41e5eb..e1e10dfbd92069 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
@@ -419,6 +419,55 @@ public void simpleExtension_nonCanonicalLabel_repoName() throws Exception {
assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("foo:fu bar:ba quz:qu");
}
+ @Test
+ public void multipleExtensions_sameName() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='data_repo', version='1.0')",
+ "first_ext = use_extension('//first_ext:defs.bzl', 'ext')",
+ "first_ext.tag(name='foo', data='first_fu')",
+ "first_ext.tag(name='bar', data='first_ba')",
+ "use_repo(first_ext, first_foo='foo', first_bar='bar')",
+ "second_ext = use_extension('//second_ext:defs.bzl', 'ext')",
+ "second_ext.tag(name='foo', data='second_fu')",
+ "second_ext.tag(name='bar', data='second_ba')",
+ "use_repo(second_ext, second_foo='foo', second_bar='bar')");
+ scratch.file(workspaceRoot.getRelative("first_ext/BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("first_ext/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "tag = tag_class(attrs = {'name':attr.string(),'data':attr.string()})",
+ "def _ext_impl(ctx):",
+ " for mod in ctx.modules:",
+ " for tag in mod.tags.tag:",
+ " data_repo(name=tag.name,data=tag.data)",
+ "ext = module_extension(implementation=_ext_impl, tag_classes={'tag':tag})");
+ scratch.file(workspaceRoot.getRelative("second_ext/BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("second_ext/defs.bzl").getPathString(),
+ "load('//first_ext:defs.bzl', _ext = 'ext')",
+ "ext = _ext");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@first_foo//:data.bzl', first_foo_data='data')",
+ "load('@first_bar//:data.bzl', first_bar_data='data')",
+ "load('@second_foo//:data.bzl', second_foo_data='data')",
+ "load('@second_bar//:data.bzl', second_bar_data='data')",
+ "data = 'first_foo:'+first_foo_data+' first_bar:'+first_bar_data"
+ + "+' second_foo:'+second_foo_data+' second_bar:'+second_bar_data");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ if (result.hasError()) {
+ throw result.getError().getException();
+ }
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo(
+ "first_foo:first_fu first_bar:first_ba second_foo:second_fu " + "second_bar:second_ba");
+ }
+
@Test
public void multipleModules() throws Exception {
scratch.file(
| train | test | 2023-07-31T19:52:45 | "2023-08-03T09:43:23Z" | xiemotongye | test |
bazelbuild/bazel/19155_19167 | bazelbuild/bazel | bazelbuild/bazel/19155 | bazelbuild/bazel/19167 | [
"keyword_pr_to_issue"
] | 283ed362e6ccceb047553c2517a0331afd02db90 | 35e4bbda5357b1a166fa9bbbf6383035650b30dd | [
"Can confirm that this is a bug. The two extensions are assigned the prefixes `_main~my_ext~` and `_main~my_ext~2~` now, which is bad since the former is a prefix of the latter.\r\n\r\nI am working on a fix.\r\n\r\nCC @Wyverald ",
"@bazel-io flag",
"@bazel-io fork 6.4.0",
"@iancha1992 This is a regression from Bazel 6.2.0, so unfortunately we may need a 6.3.2 release to cherry-pick this into.",
"> \r\n\r\ncc: @bazelbuild/triage "
] | [] | "2023-08-03T20:59:21Z" | [
"type: bug",
"P1",
"team-ExternalDeps",
"area-Bzlmod"
] | same `module_extension` name in different bzl files could not be resolved while using bzlmod in bazel 6.3.1 | ### Description of the bug:
We're using bzlmod.
This is a part of `MODULE.bazel`, which works fine in bazel 6.2.1.
```
a_ext = use_extension("//path/to/A:A.bzl", "my_ext")
use_repo(a_ext, "abc")
b_ext = use_extension("//path/to/B:B.bzl", "my_ext")
use_repo(b_ext, "xyz")
```
When I updated bazel to 6.3.1, there was an error in analysis phase.
```
ERROR: /my/workspace/library_path/BUILD:4:13: no such package '@_main~my_ext~2~xyz//':
The repository '@_main~my_ext~2~xyz' could not be resolved:
Repository '@_main~my_ext~2~xyz' is not defined and referenced by '//library_path:library_name'
ERROR: Analysis of target '//my_path:my_target' failed; build aborted:
```
It seems that in bazel 6.2.1, if there is a same `module_extension` name in different bzl files, the second one will be named as `@_main~my_ext2~xyz` in external directory. But in bazel 6.3.1, it seems that bazel is tring to find a module named as `@_main~my_ext~2~xyz` (adds a `~` after `ext`) which doesn't actually exist.
### Which category does this issue belong to?
_No response_
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
_No response_
### Which operating system are you running Bazel on?
macOS 13.4.1
### What is the output of `bazel info release`?
release 6.3.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
_No response_
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
index eaf358a011d05b..9e7c0a328e8356 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunction.java
@@ -20,6 +20,7 @@
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
@@ -247,39 +248,45 @@ static BzlmodFlagsAndEnvVars getFlagsAndEnvVars(Environment env) throws Interrup
private ImmutableBiMap<String, ModuleExtensionId> calculateUniqueNameForUsedExtensionId(
ImmutableTable<ModuleExtensionId, ModuleKey, ModuleExtensionUsage> extensionUsagesById) {
- // Calculate a unique name for each used extension id.
+ // Calculate a unique name for each used extension id with the following property that is
+ // required for BzlmodRepoRuleFunction to unambiguously identify the extension that generates a
+ // given repo:
+ // After appending a single `~` to each such name, none of the resulting strings is a prefix of
+ // any other such string.
BiMap<String, ModuleExtensionId> extensionUniqueNames = HashBiMap.create();
for (ModuleExtensionId id : extensionUsagesById.rowKeySet()) {
- // Ensure that the resulting extension name (and thus the repository names derived from it) do
- // not start with a tilde.
- RepositoryName repository = id.getBzlFileLabel().getRepository();
- String nonEmptyRepoPart = repository.isMain() ? "_main" : repository.getName();
- // When using a namespace, prefix the extension name with "_" to distinguish the prefix from
- // those generated by non-namespaced extension usages. Extension names are identified by their
- // Starlark identifier, which in the case of an exported symbol cannot start with "_".
- String bestName =
- id.getIsolationKey()
- .map(
- namespace ->
- String.format(
- "%s~_%s~%s~%s~%s",
- nonEmptyRepoPart,
- id.getExtensionName(),
- namespace.getModule().getName(),
- namespace.getModule().getVersion(),
- namespace.getUsageExportedName()))
- .orElse(nonEmptyRepoPart + "~" + id.getExtensionName());
- if (extensionUniqueNames.putIfAbsent(bestName, id) == null) {
- continue;
- }
- int suffix = 2;
- while (extensionUniqueNames.putIfAbsent(bestName + "~" + suffix, id) != null) {
- suffix++;
+ int attempt = 1;
+ while (extensionUniqueNames.putIfAbsent(makeUniqueNameCandidate(id, attempt), id) != null) {
+ attempt++;
}
}
return ImmutableBiMap.copyOf(extensionUniqueNames);
}
+ private static String makeUniqueNameCandidate(ModuleExtensionId id, int attempt) {
+ // Ensure that the resulting extension name (and thus the repository names derived from it) do
+ // not start with a tilde.
+ RepositoryName repository = id.getBzlFileLabel().getRepository();
+ String nonEmptyRepoPart = repository.isMain() ? "_main" : repository.getName();
+ // When using a namespace, prefix the extension name with "_" to distinguish the prefix from
+ // those generated by non-namespaced extension usages. Extension names are identified by their
+ // Starlark identifier, which in the case of an exported symbol cannot start with "_".
+ Preconditions.checkArgument(attempt >= 1);
+ String extensionNameDisambiguator = attempt == 1 ? "" : String.valueOf(attempt);
+ return id.getIsolationKey()
+ .map(
+ namespace ->
+ String.format(
+ "%s~_%s%s~%s~%s~%s",
+ nonEmptyRepoPart,
+ id.getExtensionName(),
+ extensionNameDisambiguator,
+ namespace.getModule().getName(),
+ namespace.getModule().getVersion(),
+ namespace.getUsageExportedName()))
+ .orElse(nonEmptyRepoPart + "~" + id.getExtensionName() + extensionNameDisambiguator);
+ }
+
static class BazelDepGraphFunctionException extends SkyFunctionException {
BazelDepGraphFunctionException(ExternalDepsException e, Transience transience) {
super(e, transience);
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
index fbe92cf779386f..b8602dba90d16e 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/BazelDepGraphFunctionTest.java
@@ -292,7 +292,7 @@ public void createValue_moduleExtensions() throws Exception {
maven, "rules_jvm_external~1.0~maven",
pip, "rules_python~2.0~pip",
myext, "dep~2.0~myext",
- myext2, "dep~2.0~myext~2");
+ myext2, "dep~2.0~myext2");
assertThat(value.getFullRepoMapping(ModuleKey.ROOT))
.isEqualTo(
@@ -323,7 +323,7 @@ public void createValue_moduleExtensions() throws Exception {
"oneext",
"dep~2.0~myext~myext",
"twoext",
- "dep~2.0~myext~2~myext"));
+ "dep~2.0~myext2~myext"));
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
index 675a9ce4f7816c..17ad3dca2dc9f3 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/bzlmod/ModuleExtensionResolutionTest.java
@@ -419,6 +419,55 @@ public void simpleExtension_nonCanonicalLabel_repoName() throws Exception {
assertThat(result.get(skyKey).getModule().getGlobal("data")).isEqualTo("foo:fu bar:ba quz:qu");
}
+ @Test
+ public void multipleExtensions_sameName() throws Exception {
+ scratch.file(
+ workspaceRoot.getRelative("MODULE.bazel").getPathString(),
+ "bazel_dep(name='data_repo', version='1.0')",
+ "first_ext = use_extension('//first_ext:defs.bzl', 'ext')",
+ "first_ext.tag(name='foo', data='first_fu')",
+ "first_ext.tag(name='bar', data='first_ba')",
+ "use_repo(first_ext, first_foo='foo', first_bar='bar')",
+ "second_ext = use_extension('//second_ext:defs.bzl', 'ext')",
+ "second_ext.tag(name='foo', data='second_fu')",
+ "second_ext.tag(name='bar', data='second_ba')",
+ "use_repo(second_ext, second_foo='foo', second_bar='bar')");
+ scratch.file(workspaceRoot.getRelative("first_ext/BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("first_ext/defs.bzl").getPathString(),
+ "load('@data_repo//:defs.bzl','data_repo')",
+ "tag = tag_class(attrs = {'name':attr.string(),'data':attr.string()})",
+ "def _ext_impl(ctx):",
+ " for mod in ctx.modules:",
+ " for tag in mod.tags.tag:",
+ " data_repo(name=tag.name,data=tag.data)",
+ "ext = module_extension(implementation=_ext_impl, tag_classes={'tag':tag})");
+ scratch.file(workspaceRoot.getRelative("second_ext/BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("second_ext/defs.bzl").getPathString(),
+ "load('//first_ext:defs.bzl', _ext = 'ext')",
+ "ext = _ext");
+ scratch.file(workspaceRoot.getRelative("BUILD").getPathString());
+ scratch.file(
+ workspaceRoot.getRelative("data.bzl").getPathString(),
+ "load('@first_foo//:data.bzl', first_foo_data='data')",
+ "load('@first_bar//:data.bzl', first_bar_data='data')",
+ "load('@second_foo//:data.bzl', second_foo_data='data')",
+ "load('@second_bar//:data.bzl', second_bar_data='data')",
+ "data = 'first_foo:'+first_foo_data+' first_bar:'+first_bar_data"
+ + "+' second_foo:'+second_foo_data+' second_bar:'+second_bar_data");
+
+ SkyKey skyKey = BzlLoadValue.keyForBuild(Label.parseCanonical("//:data.bzl"));
+ EvaluationResult<BzlLoadValue> result =
+ evaluator.evaluate(ImmutableList.of(skyKey), evaluationContext);
+ if (result.hasError()) {
+ throw result.getError().getException();
+ }
+ assertThat(result.get(skyKey).getModule().getGlobal("data"))
+ .isEqualTo(
+ "first_foo:first_fu first_bar:first_ba second_foo:second_fu " + "second_bar:second_ba");
+ }
+
@Test
public void multipleModules() throws Exception {
scratch.file(
| test | test | 2023-07-31T18:09:22 | "2023-08-03T09:43:23Z" | xiemotongye | test |
bazelbuild/bazel/19126_19197 | bazelbuild/bazel | bazelbuild/bazel/19126 | bazelbuild/bazel/19197 | [
"keyword_pr_to_issue"
] | f6a30b46a7fef82e02e5ef0e4c009f54305bbce3 | 5dd60a64e8d886daad98556e039d14f15087e133 | [
"@bazel-io flag",
"@bazel-io fork 6.4.0",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!",
"I gave 6.4.0rc1 a quick test and confirmed that it does fix the issue in my actual repository, so everything looks good here! 😁"
] | [] | "2023-08-07T19:19:00Z" | [
"type: bug",
"untriaged",
"team-Loading-API"
] | `config_setting` incorrectly treated as implicit dependency by `--incompatible_visibility_private_attributes_at_definition` | ### Description of the bug:
When explicitly depending on a `config_setting` and enabling `--incompatible_visibility_private_attributes_at_definition`, the setting is incorrectly treated as an implicit dependency which must be visible to the dependent's rule definition, which doesn't make logical sense. The full set of conditions from my understanding is:
1. A target which depends on a `config_setting` from a different package through a `select` key.
1. The target is an instance of a rule from a another package which does _not_ have visibility into the `config_setting`.
1. `--incompatible_visibility_private_attributes_at_definition`.
```python
# BUILD.bazel
load("//build_defs:defs.bzl", "my_rule")
my_rule(
name = "my_target",
value = select({
"//config_setting:my_setting": "foo",
"//conditions:default": "bar",
}),
)
```
When all three happen it throws an error like this:
```
$ bazel build //:my_target
ERROR: /home/doug/Source/bazel_visibility/BUILD.bazel:3:8: in my_rule rule //:my_target: target '//config_setting:my_setting' is not visible from target '//build_defs:defs.bzl'. Check the visibility declaration of the former target if you think the dependency is legitimate
ERROR: /home/doug/Source/bazel_visibility/BUILD.bazel:3:8: Analysis of target '//:my_target' failed
ERROR: Analysis of target '//:my_target' failed; build aborted:
INFO: Elapsed time: 0.064s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (2 packages loaded, 2 targets configured)
```
This doesn't make sense: `target '//config_setting:my_setting' is not visible from target '//build_defs:defs.bzl'`. This should not be required, as the config setting is not an implicit dependency.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Minimal reproduction here: https://github.com/dgp1130/bazel-config-setting-visibility-bug/
It does rely on Skylib which probably isn't necessary but I figured that wasn't too significant and I didn't want to try and figure out how to define flags manually.
### Which operating system are you running Bazel on?
Ubuntu on WSL
### What is the output of `bazel info release`?
release 6.3.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
$ git remote get-url origin; git rev-parse main; git rev-parse HEAD
[email protected]:dgp1130/bazel-config-setting-visibility-bug
d86833d09fb3bcb3eb0429d74eb80364db7e684a
d86833d09fb3bcb3eb0429d74eb80364db7e684a
```
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
I don't know, however I initially reproduced on version 6.0.0 before upgrading to 6.3.0 to confirm it was still present on latest. The bug is at least that old.
### Have you found anything relevant by searching the web?
https://github.com/bazelbuild/bazel/issues/12932 feels like it might be relevant, however I found that `--incompatible_enforce_config_setting_visibility` had no effect, so it could be nothing.
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/VisibilityTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java b/src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java
index cd47434d8b63fb..b5721702e1c3b5 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/CommonPrerequisiteValidator.java
@@ -26,6 +26,7 @@
import com.google.devtools.build.lib.packages.RawAttributeMapper;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Target;
+import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData;
@@ -89,6 +90,7 @@ private void validateDirectPrerequisiteVisibility(
if (!toolCheckAtDefinition
|| !attribute.isImplicit()
+ || attribute.getName().equals(RuleClass.CONFIG_SETTING_DEPS_ATTRIBUTE)
|| rule.getRuleClassObject().getRuleDefinitionEnvironmentLabel() == null) {
// Default check: The attribute must be visible from the target.
if (!context.isVisible(prerequisite.getConfiguredTarget())) {
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/VisibilityTest.java b/src/test/java/com/google/devtools/build/lib/analysis/VisibilityTest.java
index de19e50790cfc0..3a3e377974de0d 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/VisibilityTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/VisibilityTest.java
@@ -166,6 +166,42 @@ public void testDataVisibilityPrivateCheckPrivateAtUse() throws Exception {
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
+ @Test
+ public void testConfigSettingVisibilityAlwaysCheckedAtUse() throws Exception {
+ scratch.file(
+ "BUILD",
+ "load('//build_defs:defs.bzl', 'my_rule')",
+ "my_rule(",
+ " name = 'my_target',",
+ " value = select({",
+ " '//config_setting:my_setting': 'foo',",
+ " '//conditions:default': 'bar',",
+ " }),",
+ ")");
+ scratch.file("build_defs/BUILD");
+ scratch.file(
+ "build_defs/defs.bzl",
+ "def _my_rule_impl(ctx):",
+ " pass",
+ "my_rule = rule(",
+ " implementation = _my_rule_impl,",
+ " attrs = {",
+ " 'value': attr.string(mandatory = True),",
+ " },",
+ ")");
+ scratch.file(
+ "config_setting/BUILD",
+ "config_setting(",
+ " name = 'my_setting',",
+ " values = {'cpu': 'does_not_matter'},",
+ " visibility = ['//:__pkg__'],",
+ ")");
+ useConfiguration("--incompatible_visibility_private_attributes_at_definition");
+
+ update("//:my_target");
+ assertThat(hasErrors(getConfiguredTarget("//:my_target"))).isFalse();
+ }
+
void setupFilesScenario(String wantRead) throws Exception {
scratch.file("src/source.txt", "source");
scratch.file("src/BUILD", "exports_files(['source.txt'], visibility=['//pkg:__pkg__'])");
| train | test | 2023-08-07T21:08:41 | "2023-07-29T05:13:14Z" | dgp1130 | test |
bazelbuild/bazel/17483_19229 | bazelbuild/bazel | bazelbuild/bazel/17483 | bazelbuild/bazel/19229 | [
"keyword_pr_to_issue"
] | b2054d66ff3b5dd1183974642c38f5963374f4f4 | 443cbcb641e17f7337ccfdecdfa5e69bc16cae55 | [
"I think it's acceptable to change str representation of Starlark rules to return label of .bzl file and rule name.\r\n\r\nOn the other hand, you probably shouldn't depend on this string. Can you expand you use-case further, provide an example macro? I find it weird you'd need rule kind in a macro, as they are usually written for specific rules.",
"> On the other hand, you probably shouldn't depend on this string. Can you expand you use-case further, provide an example macro? I find it weird you'd need rule kind in a macro, as they are usually written for specific rules.\r\n\r\nWe have a macro which works in tandem with a few repository rules to allow someone doing a build to choose which generation of CUDA and TensorFlow-related libraries they want to use so we can upgrade subsets of the repository to new TF versions incrementally. It looks similar to this:\r\n\r\n```\r\nmlinfra_platform_target(\r\n cc_library,\r\n name = \"foo\",\r\n ...,\r\n)\r\n```\r\n\r\nThis macro wraps arbitrary rules, stubs them out when the build isn't compatible with them, and applies tags based on a generic notion of the rules' categories (binary, library, test, etc.) so we can track the progress of these upgrades using queries. The `repr` representation of these rules is the only thing this macro has at its disposal to do this categorization; rule functions have no other means of introspection. Apart from this tagging, there simply is no need to have different macros for different rules, so we opted to simplify and not deal with proliferating nearly-identical macros.",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-08-10T22:21:05Z" | [
"type: bug",
"P3",
"team-Rules-API"
] | `repr` representation of starlarkified rules is too generic | ### Description of the bug:
Running `str` on a built-in rule function written in java, such as `py_library`, returns strings like `<built-in rule py_library>`, while for one whose implementation has been rewritten in starlark, such as `cc_library`, it merely returns `<rule>`. Upgrading from Bazel 4 to 6 broke some of our macros which take those functions as inputs and make decisions based on what rules they correspond to. Given such a function, there no longer seems to be a way to determine the name of the rule to which it corresponds. One can work around it by explicitly comparing things against `native.cc_library` and so on, but the difference in output seems like an unintended regression. Preferably, the string representations of internal starlarkified rules should somehow expose the rules' names, but another generic means of determining the names of arbitrary rules would suffice instead.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Compare the outputs of `str(cc_library)` and `str(py_library)` using Bazel 6, which are `<rule>` and `<built-in rule py_binary>` respectively.
### Which operating system are you running Bazel on?
Ubuntu
### What is the output of `bazel info release`?
release 6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java"
] | [
"src/test/java/com/google/devtools/build/lib/starlark/StarlarkStringRepresentationsTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java
index 2ae33deca51935..b0ab97ac757f2f 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java
@@ -977,7 +977,11 @@ public boolean isExported() {
@Override
public void repr(Printer printer) {
- printer.append("<rule>");
+ if (isExported()) {
+ printer.append("<rule ").append(getRuleClass().getName()).append(">");
+ } else {
+ printer.append("<rule>");
+ }
}
@Override
| diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkStringRepresentationsTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkStringRepresentationsTest.java
index 35c1f6515d149a..e3b651271c4443 100644
--- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkStringRepresentationsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkStringRepresentationsTest.java
@@ -268,7 +268,7 @@ public void testStringRepresentations_functions() throws Exception {
@Test
public void testStringRepresentations_rules() throws Exception {
setBuildLanguageOptions("--experimental_builtins_injection_override=+cc_library");
- assertStringRepresentation("native.cc_library", "<rule>");
+ assertStringRepresentation("native.cc_library", "<rule cc_library>");
assertStringRepresentation("def f(): pass", "rule(implementation=f)", "<rule>");
}
| val | test | 2023-08-19T00:19:19 | "2023-02-13T23:35:58Z" | gholms | test |
bazelbuild/bazel/17375_19283 | bazelbuild/bazel | bazelbuild/bazel/17375 | bazelbuild/bazel/19283 | [
"keyword_pr_to_issue"
] | 91bfb53419bbbd0742de41cd3bd86ca44f0dd8e0 | b2054d66ff3b5dd1183974642c38f5963374f4f4 | [
"@fmeum Is this already fixed?",
"@meteorcloudy Yes, it was fixed in https://github.com/bazelbuild/bazel/pull/19274.",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-08-18T17:07:04Z" | [
"type: feature request",
"P2",
"team-ExternalDeps",
"area-Bzlmod"
] | Allow module extensions to fail on a tag | ### Description of the feature request:
Module extensions should be able to fail on a particular module extension tag so that the emitted stack trace points to the location at which the particular tag was created by the user.
### What underlying problem are you trying to solve with this feature?
When a user specifies an invalid module extension tag in their `MODULE.bazel` file (e.g. a version of a dependency that isn't valid) and the module extensions `fail`s due to that, the stack trace starts with the module extension implementation function. There is no way to reference the particular tag that caused the failure, which makes it unnecessarily difficult for the user to fix the issue.
### Which operating system are you running Bazel on?
Any
### What is the output of `bazel info release`?
6.0.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/net/starlark/java/eval/MethodLibrary.java"
] | [
"src/main/java/net/starlark/java/eval/MethodLibrary.java"
] | [] | diff --git a/src/main/java/net/starlark/java/eval/MethodLibrary.java b/src/main/java/net/starlark/java/eval/MethodLibrary.java
index 5610061162982a..be5cf11651363b 100644
--- a/src/main/java/net/starlark/java/eval/MethodLibrary.java
+++ b/src/main/java/net/starlark/java/eval/MethodLibrary.java
@@ -15,13 +15,10 @@
package net.starlark.java.eval;
import com.google.common.base.Ascii;
-import com.google.common.base.Joiner;
import com.google.common.collect.Ordering;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
-import java.util.List;
import java.util.NoSuchElementException;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.ParamType;
@@ -679,24 +676,33 @@ public StarlarkList<?> dir(Object object, StarlarkThread thread) throws EvalExce
@Param(
name = "args",
doc =
- "A list of values, formatted with str and joined with spaces, that appear in the"
- + " error message."),
+ "A list of values, formatted with debugPrint (which is equivalent to str by"
+ + " default) and joined with spaces, that appear in the error message."),
useStarlarkThread = true)
public void fail(Object msg, Object attr, Tuple args, StarlarkThread thread)
throws EvalException {
- List<String> elems = new ArrayList<>();
+ Printer printer = new Printer();
+ boolean needSeparator = false;
+ if (attr != Starlark.NONE) {
+ printer.append("attribute ").append((String) attr).append(":");
+ needSeparator = true;
+ }
// msg acts like a leading element of args.
if (msg != Starlark.NONE) {
- elems.add(Starlark.str(msg, thread.getSemantics()));
+ if (needSeparator) {
+ printer.append(" ");
+ }
+ printer.debugPrint(msg, thread.getSemantics());
+ needSeparator = true;
}
for (Object arg : args) {
- elems.add(Starlark.str(arg, thread.getSemantics()));
- }
- String str = Joiner.on(" ").join(elems);
- if (attr != Starlark.NONE) {
- str = String.format("attribute %s: %s", attr, str);
+ if (needSeparator) {
+ printer.append(" ");
+ }
+ printer.debugPrint(arg, thread.getSemantics());
+ needSeparator = true;
}
- throw Starlark.errorf("%s", str);
+ throw Starlark.errorf("%s", printer.toString());
}
@StarlarkMethod(
| null | train | test | 2023-08-18T19:24:23 | "2023-02-01T08:30:59Z" | fmeum | test |
bazelbuild/bazel/12049_19319 | bazelbuild/bazel | bazelbuild/bazel/12049 | bazelbuild/bazel/19319 | [
"keyword_pr_to_issue"
] | cb187a08e6735a42be9aecf53a143144e4cc9a49 | 6052b8bbbf74e1b2c3112fe74663a5d1b5f6b9e8 | [
"@gregestren is this something you'd be able to advise on?",
"Actually, this may be an Apple Rules issue, not an --action_env issue. @googlewalt , is this in your wheelhouse?",
"I think there are two issues:\r\n1. AFAICT, based on code inspection, action_env does not work on bazel. @keith do you know of instances where it works?\r\n2. bazel does not set a default PATH for actions.\r\n\r\nIn both cases, the issue seems to be that `BazelRulesModule` does not have some setup code we have internally, that does both (1) and (2).",
"Sorry. I found the setup code in `BazelRulesModule`.",
"Have you tried `--incompatible_strict_action_env`?",
"I have tried that flag, AFAICT that flag is only read here:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/84834db3a0d5ac2b1c71c5706f259e7dff4a4f0e/src/main/java/com/google/devtools/build/lib/bazel/rules/BazelRuleClassProvider.java#L187-L201\r\n\r\nand IIRC this codepath isn't even hit, otherwise action_env would work as well:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/84834db3a0d5ac2b1c71c5706f259e7dff4a4f0e/src/main/java/com/google/devtools/build/lib/bazel/rules/BazelRuleClassProvider.java#L202-L207",
"[edit: this is wrong, see below]\r\n\r\nI verified that this behavior is not specific to apple rules, and it has been this way since at least bazel 1.0. I would have expected the SHELL_ACTION_ENV to be applied to all the rules that run a shell, but I'm not familiar with exactly how that logic works. The most recent non-trivial refactoring of this code was done in commit 8626623106fc0f9f83781990f7c235074926d196. Perhaps someone more familiar with this code can comment?\r\n",
"cc @lberki (author of that commit)",
"I'm certainly not that \"someone familiar with this code\" :( The commit https://github.com/bazelbuild/bazel/commit/8626623106fc0f9f83781990f7c235074926d196 was meant to be a refactoring without user-visible effects; do you have a reason to believe that this is what caused the behavior change?\r\n\r\nLooking at https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/bazel/rules/BazelRuleClassProvider.java#L205 , it looks like the variables set in `--action_env` should be applied no matter what, which contrary to the statement in the description of this bug. Are you... sure? Or maybe this is something that's specific to Apple rules (I'm even less familiar with those than I am with the computing of the action environment...)\r\n",
"Apologies for the red herring. My statements from previous post was wrong (user error).\r\n\r\n`--action_env` and `--incompatible_strict_action_env` seem to generally work for bazel. I tested it for `cc_library`, and it also works for me for Apple wrapped clang invocation for Objc compile and linking:\r\n\r\n```\r\nbazel build --action_env PATH=/my_special_path:$PATH -s examples/macos/HelloWorld:HelloWorld\r\n...\r\n exec env - \\\r\n APPLE_SDK_PLATFORM=MacOSX \\\r\n APPLE_SDK_VERSION_OVERRIDE=10.15 \\\r\n PATH=/my_special_path//usr/local/git/current/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/Library/Apple/usr/bin \\\r\n XCODE_VERSION_OVERRIDE=11.6.0.11E708 \\\r\n external/local_config_cc/wrapped_clang ...\r\n```\r\n\r\nBut some other Apple actions don't appear to be have default PATHs, or be hooked up to those flags: StoreboardCompile, AssetCatalogCompile, CompileRootInfoPlist, Processing and signing.",
"No worries! Unfortunately, I won't be able to help further then :(",
"No actions in rules_apple seems to employ `use_default_shell_env`, which means `--action_env` will be ignored for them.",
"Are you suggesting all actions should set that? Is that the right switch for this? It surprises me a bit that that would be the way to make this work. Because that means that all non-native rules would need to set that to `True` (and when would you want to set that to `False` given this issue?)\r\n\r\nSomewhat related I guess:\r\n\r\nhttps://github.com/bazelbuild/rules_go/blob/b4c392fcfc0a44f2cc5ee3dbb884121dd2ab6957/proto/compiler.bzl#L126-L130",
"> Are you suggesting all actions should set that? Is that the right switch for this?\r\n\r\nThe [documentation recommends](https://cs.opensource.google/bazel/bazel/+/4c0febc02fab5e9fda3f40532a62854fb1c45631:src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java;l=946) all actions set it.\r\n\r\n> It surprises me a bit that that would be the way to make this work. Because that means that all non-native rules would need to set that to `True`\r\n\r\nNative rules must also opt in, but some effort was historically put into fixing them (#3320).\r\n\r\n> (and when would you want to set that to `False` given this issue?)\r\n\r\nThe `env` parameter to `actions.run(_shell)` is ignored under `use_default_shell_env=True`.",
"It looks like this is mutually exclusive with setting `env` on these, which doesn't work for Apple actions since they use env to propagate Xcode version info. I guess we might not be able to have it both ways?",
"Example of the failures caused by this in the Apple toolchain https://github.com/bazelbuild/rules_swift/pull/497\r\n\r\n```\r\n\r\n(18:30:51) ERROR: /Users/buildkite/builds/bk-imacpro-16/bazel/rules-swift-swift/examples/xplatform/c_from_swift/BUILD:25:14: Compiling Swift module Counter failed: Worker process did not return a WorkResponse:\r\n--\r\n | \r\n | ---8<---8<--- Start of log, file at /private/var/tmp/_bazel_buildkite/022c118cf0acc0d6f57f13796cd5f4e4/bazel-workers/worker-3-SwiftCompile.log ---8<---8<---\r\n | Error: DEVELOPER_DIR not set.\r\n\r\n```",
"Yeah, it sounds like it might make sense to go back to your first suggestion, to set a conservative default PATH for Apple-related actions. We do need the environment that's set for Apple rules, but it's ok to add to it.",
"Using `aquery` (assuming that's a fair way to determine this) here's a quick list of mnemonics in our iOS build that don't have a PATH set even when I pass `--action_env=PATH=something`\r\n\r\nAction\r\nAssetCatalogCompile\r\nBundleApp\r\nBundleResources\r\nCcStrip\r\nCompileRootInfoPlist\r\nCppCompile\r\nCppLink\r\nCppModuleMap\r\nExecutableSymlink\r\nExtractFromProvisioningProfile\r\nFileWrite\r\nGenProtoDescriptorSet\r\nGenrule\r\nImportedDynamicFrameworkProcessor\r\nMiddleman\r\nObjcCompile\r\nObjcLink\r\nProcessAndSign\r\nProcessEntitlementsFiles\r\nPythonZipper\r\nSolibSymlink\r\nSourceSymlinkManifest\r\nStoryboardCompile\r\nStoryboardLink\r\nSwiftArchive\r\nSwiftStdlibCopy\r\nSymlink\r\nSymlinkTree\r\nTemplateExpand\r\nXibCompile\r\n\r\nI'm surprised by some here looking briefly at the code:\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/ecab72e74fa5e922dc18a5b0d059141d81bacdf8/src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java#L726-L740",
"Thinking about this more I kinda thing we should make action_env apply to all actions instead. I think that makes sense from a user perspective and it would solve more issues than just the PATH one. Maybe we would also provide a default PATH though. Thoughts?",
"So there was some confusion with the list above, the problem is that some actions don't print their env with aquery. I'll try to submit a follow up for some of those. This fixes some of my use case https://github.com/bazelbuild/rules_swift/pull/502\r\n\r\nbut it's not perfect. Firstly piping `ctx.configuration.default_shell_env` through everywhere can be cumbersome. But more importantly that doesn't include everything we actually want. This only includes the \"fixed\" environment variables, like those passed with `--action_env=FOO=BAR`, not the \"variable\" environment variables which are attempted to be passed through with `--action_env=FOO`\r\n\r\nhttps://github.com/bazelbuild/bazel/blob/080547f7af998dd45c14f05d426e7c8f60a68a2f/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java#L486-L500\r\n\r\nThere doesn't seem to be a way to get any of the other variables from starlark, but I might be missing something?",
"The CppLinkAction is one of the ones where its environment doesn't show up in aquery because it doesn't implement SpawnAction",
"Ran into a variant of this, switching over to an Apple Silicon machine.\r\n\r\nIt's worth noting that on Apple Silicon, Homebrew no longer installs into the default PATH but rather to /opt/homebrew/bin.\r\n\r\nThat said, if we do get into this and change defaults, I think it might well make sense to include Homebrew installs in the strict_action_env default. I get the hermeticity concerns, but it's also probably a good idea to default to the tools the user is more likely to expect, rather than, e.g., use the 2007 era bash, old python, and other os-bundled binaries that I think most users replace with those installed from brew. Always possible to make it more restrictive with --action_env, ofc.",
"@Keith, what are your thoughts these days on the desirability of having homebrew tools on the action path?\r\n(Sounded negative above, but also now needed to conveniently get e.g. python3 and a version of bash that's newer than the system's ~2007 vintage.) ",
"At least with python3 macOS has been keeping relatively up to date so I'm happy to be using that version since it's the same for everyone (assuming you only maintain 1 Xcode version). For the bash thing we just deal with the old one. I think the downside we saw before we started excluding the brew path was just people's brew states could be all over the place depending on when things were last updated, so it added a lot of variance.",
"Got it. Thanks, @Keith.\r\n(We have a brew-update thing+use a bunch of add'l tools in scripts that are more easily installed that way. I think that flips the personal calculus but good to know & I therefore won't try to upstream or anything.)",
"I also believe that since brew has thousands of formulae in their core repo alone, and most developers are probably using at least _some_ binaries provided by brew (but can be widely-varying and selected according to personal habits), that including it by default opens the door to a ton of subtle variances. I think a lot of developers who are just \"using\" Bazel as their build system because it's what their projects use, can then easily run into issues that may be hard to debug.\n\nThe GNU bash on macOS is old, yes, but since macOS has also shipped with an immutable zsh since 2015 there's now also opportunity for Darwin-specific wrapper scripts to use /bin/zsh if there's a desire for more modern shell scripting language features.",
"So what's the conclusion here?\r\n\r\nMaking copious PRs to rule sets to set `use_default_shell_env = True`? Any reason that isn't a good idea?",
"https://github.com/bazelbuild/bazel/pull/18235 would be the best of both worlds I think. In my case right now we can't get it to work 100% because values like `--action_env=FOO` (where the value should be passed through) isn't something we can fetch in starlark.",
"If possible definitely set `use_default_shell_env = True` and move on though",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!",
"for others note that the change is only if you enable `--incompatible_merge_fixed_and_default_shell_env` and make some patches to rules_apple / rules_swift / apple_support, with bazel 7.x+ this will be the default"
] | [] | "2023-08-24T08:16:30Z" | [
"type: bug",
"P3",
"team-Rules-CPP"
] | `PATH` not propagated to many darwin actions | This is a wider reaching version of https://github.com/bazelbuild/bazel/issues/8425
In the linked issue I did some investigation around default PATH variables for actions that at the time I thought only affected `py_*` targets but it turns out that many other actions on darwin do not inherit any `PATH` and therefore fallback to macOS's default shell env of `/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.` which can allow leakage of `/usr/local/*` binaries (which is specifically an issue because of homebrew).
While the default PATH may be ok for some use cases, if you actually try to restrict it using `--action_env=PATH=something` or by executing bazel with `env -i PATH=something bazel ...`, neither of these are applied to these actions.
For example any action that is executed in the context of Xcode is executed with these environment variables:
```
exec env - \
APPLE_SDK_PLATFORM=MacOSX \
APPLE_SDK_VERSION_OVERRIDE=10.15 \
XCODE_VERSION_OVERRIDE=11.5.0.11E608c \
external/local_config_cc/wrapped_clang ...
```
Some actions that don't require Xcode are executed with no environment variables:
```
exec env - \
bazel-out/host/bin/external/build_bazel_rules_apple/tools/bundletool/bundletool ...
```
This is not the behavior of some other rules like `genrule` where if you build this target with `--action_env=/usr/bin:/bin` it hits the "Valid path":
```bzl
genrule(
name = "foo",
outs = ["foo.txt"],
cmd = """
if [[ "$$PATH" != "/usr/bin:/bin" ]]; then
echo "error: path not propagated: $$PATH"
exit 1
else
echo "Valid path! $$PATH"
exit 1
fi
""",
)
```
I think that either all actions should get a very conservative default PATH like `/usr/bin:/bin`, or the flags like `--action_env` should be able to add env vars to these actions (I believe the latter is likely the more flexible path, but I'm not sure about the implementation implications).
For native actions it seems that this can be resolved by adding:
```java
.setInheritedEnvironment(ImmutableSet.of("PATH"));
```
to this logic https://github.com/bazelbuild/bazel/blob/8f678923ebea788fc1e03ba8c6359b51edafe0df/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcRuleClasses.java#L140-L144
But for starlark actions they inherit this environment:
https://github.com/bazelbuild/bazel/blob/8f678923ebea788fc1e03ba8c6359b51edafe0df/tools/osx/crosstool/cc_toolchain_config.bzl#L4546-L4557
When accessing the environment variables for an action with the [`cc_common` api](https://docs.bazel.build/versions/master/skylark/lib/cc_common.html#get_environment_variables). There doesn't seem to be a way to craft an `env_entry` that doesn't impose a value. So I could add `/usr/bin:/bin` there, but it wouldn't allow overrides via `--action_env=PATH=foo`
I'm happy to make a change here but I'm hoping for some guidance on the right path!
### What operating system are you running Bazel on?
macOS
### Bazel version?
8f678923ebea788fc1e03ba8c6359b51edafe0df | [
"src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java",
"src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java",
"src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java",
"src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java"
] | [
"src/test/shell/integration/action_env_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java b/src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java
index 43d34f565f99ff..c2c1cfe9b46736 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/actions/SpawnAction.java
@@ -28,6 +28,7 @@
import com.google.common.collect.Interner;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionContinuationOrResult;
import com.google.devtools.build.lib.actions.ActionEnvironment;
@@ -683,7 +684,6 @@ public static class Builder {
private final List<Artifact> outputs = new ArrayList<>();
private final List<RunfilesSupplier> inputRunfilesSuppliers = new ArrayList<>();
private ResourceSetOrBuilder resourceSetOrBuilder = AbstractAction.DEFAULT_RESOURCE_SET;
- private ActionEnvironment actionEnvironment = null;
private ImmutableMap<String, String> environment = ImmutableMap.of();
private ImmutableSet<String> inheritedEnvironment = ImmutableSet.of();
private ImmutableMap<String, String> executionInfo = ImmutableMap.of();
@@ -717,7 +717,6 @@ public Builder(Builder other) {
this.outputs.addAll(other.outputs);
this.inputRunfilesSuppliers.addAll(other.inputRunfilesSuppliers);
this.resourceSetOrBuilder = other.resourceSetOrBuilder;
- this.actionEnvironment = other.actionEnvironment;
this.environment = other.environment;
this.executionInfo = other.executionInfo;
this.isShellCommand = other.isShellCommand;
@@ -762,12 +761,31 @@ public SpawnAction build(ActionOwner owner, BuildConfigurationValue configuratio
result.addCommandLine(pair);
}
CommandLines commandLines = result.build();
- ActionEnvironment env =
- actionEnvironment != null
- ? actionEnvironment
- : useDefaultShellEnvironment
- ? configuration.getActionEnvironment()
- : ActionEnvironment.create(environment, inheritedEnvironment);
+ ActionEnvironment env;
+ if (useDefaultShellEnvironment && environment != null) {
+ // Inherited variables override fixed variables in ActionEnvironment. Since we want the
+ // fixed part of the action-provided environment to override the inherited part of the
+ // user-provided environment, we have to explicitly filter the inherited part.
+ var userFilteredInheritedEnv =
+ ImmutableSet.copyOf(
+ Sets.difference(
+ configuration.getActionEnvironment().getInheritedEnv(), environment.keySet()));
+ // Do not create a new ActionEnvironment in the common case where no vars have been filtered
+ // out.
+ if (userFilteredInheritedEnv.equals(
+ configuration.getActionEnvironment().getInheritedEnv())) {
+ env = configuration.getActionEnvironment();
+ } else {
+ env =
+ ActionEnvironment.create(
+ configuration.getActionEnvironment().getFixedEnv(), userFilteredInheritedEnv);
+ }
+ env = env.withAdditionalFixedVariables(environment);
+ } else if (useDefaultShellEnvironment) {
+ env = configuration.getActionEnvironment();
+ } else {
+ env = ActionEnvironment.create(environment, inheritedEnvironment);
+ }
return buildSpawnAction(
owner, commandLines, configuration.getCommandLineLimits(), configuration, env);
}
@@ -984,13 +1002,6 @@ public Builder setResources(ResourceSetOrBuilder resourceSetOrBuilder) {
return this;
}
- /** Sets the action environment. */
- @CanIgnoreReturnValue
- public Builder setEnvironment(ActionEnvironment actionEnvironment) {
- this.actionEnvironment = actionEnvironment;
- return this;
- }
-
/**
* Sets the map of environment variables. Do not use! This makes the builder ignore the 'default
* shell environment', which is computed from the --action_env command line option.
@@ -1075,6 +1086,18 @@ public Builder executeUnconditionally() {
return this;
}
+ /**
+ * Same as {@link #useDefaultShellEnvironment()}, but additionally sets the provided fixed
+ * environment variables, which take precedence over the variables contained in the default
+ * shell environment.
+ */
+ @CanIgnoreReturnValue
+ public Builder useDefaultShellEnvironmentWithOverrides(Map<String, String> environment) {
+ this.environment = ImmutableMap.copyOf(environment);
+ this.useDefaultShellEnvironment = true;
+ return this;
+ }
+
/**
* Sets the executable path; the path is interpreted relative to the execution root, unless it's
* a bare file name.
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
index ca8d46a9ce1671..b6058da30c971b 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
@@ -671,15 +671,24 @@ private void registerStarlarkAction(
} catch (IllegalArgumentException e) {
throw Starlark.errorf("%s", e.getMessage());
}
- if (envUnchecked != Starlark.NONE) {
- builder.setEnvironment(
- ImmutableMap.copyOf(Dict.cast(envUnchecked, String.class, String.class, "env")));
- }
if (progressMessage != Starlark.NONE) {
builder.setProgressMessageFromStarlark((String) progressMessage);
}
+
+ ImmutableMap<String, String> env = null;
+ if (envUnchecked != Starlark.NONE) {
+ env = ImmutableMap.copyOf(Dict.cast(envUnchecked, String.class, String.class, "env"));
+ }
if (Starlark.truth(useDefaultShellEnv)) {
- builder.useDefaultShellEnvironment();
+ if (env != null
+ && getSemantics()
+ .getBool(BuildLanguageOptions.INCOMPATIBLE_MERGE_FIXED_AND_DEFAULT_SHELL_ENV)) {
+ builder.useDefaultShellEnvironmentWithOverrides(env);
+ } else {
+ builder.useDefaultShellEnvironment();
+ }
+ } else if (env != null) {
+ builder.setEnvironment(env);
}
RuleContext ruleContext = getRuleContext();
diff --git a/src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java b/src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java
index 2259ab5a68e7d5..469427b6f32856 100644
--- a/src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/packages/semantics/BuildLanguageOptions.java
@@ -662,6 +662,19 @@ public final class BuildLanguageOptions extends OptionsBase {
help = "If enabled, targets that have unknown attributes set to None fail.")
public boolean incompatibleFailOnUnknownAttributes;
+ @Option(
+ name = "incompatible_merge_fixed_and_default_shell_env",
+ defaultValue = "false",
+ documentationCategory = OptionDocumentationCategory.STARLARK_SEMANTICS,
+ effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
+ metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
+ help =
+ "If enabled, actions registered with ctx.actions.run and ctx.actions.run_shell with both"
+ + " 'env' and 'use_default_shell_env = True' specified will use an environment"
+ + " obtained from the default shell environment by overriding with the values passed"
+ + " in to 'env'. If disabled, the value of 'env' is completely ignored in this case.")
+ public boolean incompatibleMergeFixedAndDefaultShellEnv;
+
@Option(
name = "incompatible_disable_objc_library_transition",
defaultValue = "false",
@@ -765,6 +778,9 @@ public StarlarkSemantics toStarlarkSemantics() {
EXPERIMENTAL_GET_FIXED_CONFIGURED_ACTION_ENV,
experimentalGetFixedConfiguredEnvironment)
.setBool(INCOMPATIBLE_FAIL_ON_UNKNOWN_ATTRIBUTES, incompatibleFailOnUnknownAttributes)
+ .setBool(
+ INCOMPATIBLE_MERGE_FIXED_AND_DEFAULT_SHELL_ENV,
+ incompatibleMergeFixedAndDefaultShellEnv)
.setBool(
INCOMPATIBLE_DISABLE_OBJC_LIBRARY_TRANSITION,
incompatibleDisableObjcLibraryTransition)
@@ -858,6 +874,8 @@ public StarlarkSemantics toStarlarkSemantics() {
"-experimental_get_fixed_configured_action_env";
public static final String INCOMPATIBLE_FAIL_ON_UNKNOWN_ATTRIBUTES =
"-incompatible_fail_on_unknown_attributes";
+ public static final String INCOMPATIBLE_MERGE_FIXED_AND_DEFAULT_SHELL_ENV =
+ "-experimental_merge_fixed_and_default_shell_env";
public static final String INCOMPATIBLE_DISABLE_OBJC_LIBRARY_TRANSITION =
"-incompatible_disable_objc_library_transition";
| diff --git a/src/test/shell/integration/action_env_test.sh b/src/test/shell/integration/action_env_test.sh
index 08af2abd059630..6feaf075740bb0 100755
--- a/src/test/shell/integration/action_env_test.sh
+++ b/src/test/shell/integration/action_env_test.sh
@@ -39,6 +39,15 @@ load("//pkg:build.bzl", "environ")
environ(name = "no_default_env", env = 0)
environ(name = "with_default_env", env = 1)
+environ(
+ name = "with_default_and_fixed_env",
+ env = 1,
+ fixed_env = {
+ "ACTION_FIXED": "action",
+ "ACTION_AND_CLIENT_FIXED": "action",
+ "ACTION_AND_CLIENT_INHERITED": "action",
+ },
+)
sh_test(
name = "test_env_foo",
@@ -72,12 +81,16 @@ def _impl(ctx):
ctx.actions.run_shell(
inputs=[],
outputs=[output],
+ env = ctx.attr.fixed_env,
use_default_shell_env = ctx.attr.env,
command="env > %s" % output.path)
environ = rule(
implementation=_impl,
- attrs={"env": attr.bool(default=True)},
+ attrs={
+ "env": attr.bool(default=True),
+ "fixed_env": attr.string_dict(),
+ },
outputs={"out": "%{name}.env"},
)
EOF
@@ -222,6 +235,52 @@ function test_use_default_shell_env {
&& fail "dynamic action_env used, even though requested not to") || true
}
+function test_use_default_shell_env_and_fixed_env {
+ ACTION_AND_CLIENT_INHERITED=client CLIENT_INHERITED=client \
+ bazel build \
+ --noincompatible_merge_fixed_and_default_shell_env \
+ --action_env=ACTION_AND_CLIENT_FIXED=client \
+ --action_env=ACTION_AND_CLIENT_INHERITED \
+ --action_env=CLIENT_FIXED=client \
+ --action_env=CLIENT_INHERITED \
+ //pkg:with_default_and_fixed_env
+ echo
+ cat bazel-bin/pkg/with_default_and_fixed_env.env
+ echo
+ grep -q ACTION_AND_CLIENT_FIXED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "static action environment not honored"
+ grep -q ACTION_AND_CLIENT_INHERITED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "dynamic action environment not honored"
+ grep -q ACTION_FIXED bazel-bin/pkg/with_default_and_fixed_env.env \
+ && fail "fixed env provided by action should have been ignored"
+ grep -q CLIENT_FIXED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "static action environment not honored"
+ grep -q CLIENT_INHERITED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "dynamic action environment not honored"
+
+ ACTION_AND_CLIENT_INHERITED=client CLIENT_INHERITED=client \
+ bazel build \
+ --incompatible_merge_fixed_and_default_shell_env \
+ --action_env=ACTION_AND_CLIENT_FIXED=client \
+ --action_env=ACTION_AND_CLIENT_INHERITED \
+ --action_env=CLIENT_FIXED=client \
+ --action_env=CLIENT_INHERITED \
+ //pkg:with_default_and_fixed_env
+ echo
+ cat bazel-bin/pkg/with_default_and_fixed_env.env
+ echo
+ grep -q ACTION_AND_CLIENT_FIXED=action bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "action-provided env should have overridden static --action_env"
+ grep -q ACTION_AND_CLIENT_INHERITED=action bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "action-provided env should have overridden dynamic --action_env"
+ grep -q ACTION_FIXED=action bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "action-provided env should have been honored"
+ grep -q CLIENT_FIXED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "static action environment not honored"
+ grep -q CLIENT_INHERITED=client bazel-bin/pkg/with_default_and_fixed_env.env \
+ || fail "dynamic action environment not honored"
+}
+
function test_action_env_changes_honored {
# Verify that changes to the explicitly specified action_env in honored in
# tests. Regression test for #3265.
| train | test | 2023-09-08T23:07:17 | "2020-09-04T17:36:59Z" | keith | test |
bazelbuild/bazel/19380_19443 | bazelbuild/bazel | bazelbuild/bazel/19380 | bazelbuild/bazel/19443 | [
"keyword_pr_to_issue"
] | fb4cc46da593c009e9e0153ac0c384f3fc3b90df | bc8bb956c735b339dec50078142c290cde2de7f9 | [
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-09-07T14:16:33Z" | [
"type: feature request",
"untriaged",
"team-Starlark-Interpreter",
"team-Starlark-Integration"
] | Empty depsets should be optimized out of structs the same as they are optimized out of providers | ### Description of the feature request:
Empty depsets are optimized out of providers, but not structs. This can lead to increased memory usage for some code patterns.
### Which category does this issue belong to?
Starlark Integration, Starlark Interpreter
### What underlying problem are you trying to solve with this feature?
In rules_xcodeproj we marshal a lot of data collected in aspects down the dependency tree. When doing Starlark memory profiling we noticed that creating new empty `depset` instances would drastically increase our memory usage. So instead we create frozen instances of empty values and use them when possible: https://github.com/MobileNativeFoundation/rules_xcodeproj/blob/31a9e114dac0e20625fb7d9119fe5a117ecb3608/xcodeproj/internal/memory_efficiency.bzl, which helped us reduce our memory usage.
### Which operating system are you running Bazel on?
macOS 13.4.1 (c)
### What is the output of `bazel info release`?
release 6.3.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
https://bazelbuild.slack.com/archives/CA31HN1T3/p1693484609534579 where @fmeum requested I open this issue. | [
"src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java",
"src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java"
] | [
"src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java",
"src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java"
] | [
"src/test/java/com/google/devtools/build/lib/collect/nestedset/DepsetTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java b/src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java
index b013822bdf49e6..332092a04e0b39 100644
--- a/src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java
+++ b/src/main/java/com/google/devtools/build/lib/collect/nestedset/Depset.java
@@ -95,7 +95,7 @@ public final class Depset implements StarlarkValue, Debug.ValueWithDebugAttribut
private final ElementType elemType;
private final NestedSet<?> set;
- private Depset(ElementType elemType, NestedSet<?> set) {
+ Depset(ElementType elemType, NestedSet<?> set) {
this.elemType = Preconditions.checkNotNull(elemType, "element type cannot be null");
this.set = set;
}
@@ -189,6 +189,9 @@ private static void checkElement(Object x, boolean strict) throws EvalException
// two arguments: of(Class<T> elemType, NestedSet<T> set). We could also avoid the allocations
// done by ElementType.of().
public static <T> Depset of(ElementType elemType, NestedSet<T> set) {
+ if (set.isEmpty()) {
+ return set.getOrder().emptyDepset();
+ }
return new Depset(elemType, set);
}
@@ -280,15 +283,11 @@ public static <T> NestedSet<T> cast(Object x, Class<T> type, String what) throws
public static <T> NestedSet<T> noneableCast(Object x, Class<T> type, String what)
throws EvalException {
if (x == Starlark.NONE) {
- @SuppressWarnings("unchecked")
- NestedSet<T> empty = (NestedSet<T>) EMPTY;
- return empty;
+ return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
return cast(x, type, what);
}
- private static final NestedSet<?> EMPTY = NestedSetBuilder.<Object>emptySet(Order.STABLE_ORDER);
-
public boolean isEmpty() {
return set.isEmpty();
}
@@ -390,6 +389,9 @@ static Depset fromDirectAndTransitive(
}
}
+ if (builder.isEmpty()) {
+ return builder.getOrder().emptyDepset();
+ }
return new Depset(type, builder.build());
}
diff --git a/src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java b/src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java
index 1a62d054fba06c..3f0ea09422ad4c 100644
--- a/src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java
+++ b/src/main/java/com/google/devtools/build/lib/collect/nestedset/Order.java
@@ -112,10 +112,12 @@ public enum Order {
private final String starlarkName;
private final NestedSet<?> emptySet;
+ private final Depset emptyDepset;
- private Order(String starlarkName) {
+ Order(String starlarkName) {
this.starlarkName = starlarkName;
this.emptySet = new NestedSet<>(this);
+ this.emptyDepset = new Depset(Depset.ElementType.EMPTY, this.emptySet);
}
@SerializationConstant @AutoCodec.VisibleForSerialization
@@ -150,6 +152,11 @@ <E> NestedSet<E> emptySet() {
return (NestedSet<E>) emptySet;
}
+ /** Returns an empty depset of the given ordering. */
+ Depset emptyDepset() {
+ return emptyDepset;
+ }
+
public String getStarlarkName() {
return starlarkName;
}
| diff --git a/src/test/java/com/google/devtools/build/lib/collect/nestedset/DepsetTest.java b/src/test/java/com/google/devtools/build/lib/collect/nestedset/DepsetTest.java
index cc6d597833fdd0..a2139858beb8f6 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/nestedset/DepsetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/nestedset/DepsetTest.java
@@ -404,4 +404,17 @@ ev.new Scenario()
+ " NoneType'",
"depset(direct='hello')");
}
+
+ @Test
+ public void testEmptyDepsetInternedPerOrder() throws Exception {
+ ev.exec(
+ "stable1 = depset()",
+ "stable2 = depset()",
+ "preorder1 = depset(order = 'preorder')",
+ "preorder2 = depset(order = 'preorder')");
+ assertThat(ev.lookup("stable1")).isSameInstanceAs(ev.lookup("stable2"));
+ assertThat(ev.lookup("preorder1")).isSameInstanceAs(ev.lookup("preorder2"));
+ assertThat(ev.lookup("stable1")).isNotSameInstanceAs(ev.lookup("preorder1"));
+ assertThat(ev.lookup("stable2")).isNotSameInstanceAs(ev.lookup("preorder2"));
+ }
}
| val | test | 2023-09-11T22:40:36 | "2023-08-31T15:13:54Z" | brentleyjones | test |
bazelbuild/bazel/19480_19491 | bazelbuild/bazel | bazelbuild/bazel/19480 | bazelbuild/bazel/19491 | [
"keyword_pr_to_issue"
] | 0d70b76f37d19ecf3b77df0c1595ef16ca327050 | 75db6b1bbb3d6663b6557555cf79d65ba1a0aa2b | [
"This is part of the logic that generates a separate jar file as a way to configure classpath that are too long to pass on the command line.\r\n\r\n@rsalvador I'm curious which JDK you're using, is it newer than JDK 8? The long term plan here is to replace this logic in the stub template with an `@argument` file: https://github.com/bazelbuild/bazel/issues/6354\r\n\r\n(I'm also not sure why the stub template generates this every time it's executed, instead of having Bazel create a separate action that generates the separate jar file once; that came up in https://github.com/bazelbuild/bazel/issues/19036.)",
"> @rsalvador I'm curious which JDK you're using, is it newer than JDK 8? The long term plan here is to replace this logic in the stub template with an `@argument` file: #6354\r\n\r\n@cushon using JDK 11: OpenJDK 64-Bit Server VM (build 11.0.19+7-LTS, mixed mode) by Azul Systems, Inc.",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!",
"@iancha1992 verified that the generated test script executables include the fix and that the test execution is faster than with 6.3.2 for a sample test (35 seconds with 6.3.2 vs 12 seconds with 6.4.0rc1)\r\n\r\n"
] | [] | "2023-09-11T20:56:17Z" | [
"type: bug",
"team-Performance",
"untriaged"
] | Long runtime classpaths slow down unit test execution | ### Description of the bug:
The classpath pre-processing loop in `java_stub_template.txt` is inefficient for very long classpaths and slows down unit test execution. The slowdown is in this loop in java_stub_template.txt: https://github.com/bazelbuild/bazel/blob/fcfcb929366dd3faac9643302b19c88bcf871ec6/src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt#L309 for classpaths with ~250,000 and ~700,000 entries the loop takes 28 and 50 seconds, respectively, on an intel MacBook.
### Which category does this issue belong to?
Performance
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Run a unit test with a very long runtime classpath.
### Which operating system are you running Bazel on?
OSX
### What is the output of `bazel info release`?
release 6.1.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
Performance regression seems to have been introduced in https://github.com/bazelbuild/bazel/commit/d0ee889fca77e36f2c76ac07de3048055b8428c9
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt
index b3f5070751dfd1..16129cc14dc1b2 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt
@@ -306,21 +306,24 @@ function create_and_run_classpath_jar() {
OLDIFS="$IFS"
IFS="${CLASSPATH_SEPARATOR}" # Use a custom separator for the loop.
+ current_dir=$(pwd)
for path in ${CLASSPATH}; do
# Loop through the characters of the path and convert characters that are
# not alphanumeric nor -_.~/ to their 2-digit hexadecimal representation
- local i c buff
- local converted_path=""
-
- for ((i=0; i<${#path}; i++)); do
- c=${path:$i:1}
- case ${c} in
- [-_.~/a-zA-Z0-9] ) buff=${c} ;;
- * ) printf -v buff '%%%02x' "'$c'"
- esac
- converted_path+="${buff}"
- done
- path=${converted_path}
+ if [[ ! $path =~ ^[-_.~/a-zA-Z0-9]*$ ]]; then
+ local i c buff
+ local converted_path=""
+
+ for ((i=0; i<${#path}; i++)); do
+ c=${path:$i:1}
+ case ${c} in
+ [-_.~/a-zA-Z0-9] ) buff=${c} ;;
+ * ) printf -v buff '%%%02x' "'$c'"
+ esac
+ converted_path+="${buff}"
+ done
+ path=${converted_path}
+ fi
if is_windows; then
path="file:/${path}" # e.g. "file:/C:/temp/foo.jar"
@@ -328,7 +331,7 @@ function create_and_run_classpath_jar() {
# If not absolute, qualify the path
case "${path}" in
/*) ;; # Already an absolute path
- *) path="$(pwd)/${path}";; # Now qualified
+ *) path="${current_dir}/${path}";; # Now qualified
esac
path="file:${path}" # e.g. "file:/usr/local/foo.jar"
fi
| null | test | test | 2023-09-12T11:55:19 | "2023-09-11T08:59:50Z" | rsalvador | test |
bazelbuild/bazel/18685_19505 | bazelbuild/bazel | bazelbuild/bazel/18685 | bazelbuild/bazel/19505 | [
"keyword_pr_to_issue"
] | 970b9dda7cd215a29d73a53871500bc4e2dc6142 | 2ebbfeb021dfada318e757a54a5c851a9425cdb4 | [
"Additional context: this is necessary to help migrate existing AOSP users using a custom `atest` tool which prints the results of all test cases, even for passing tests, to use bazel as the test runner and results reporter. \r\n\r\n",
"@lberki thoughts about printing passing test cases in `--test_summary=detailed`? The flag already prints failing tests, but I think we can expand it to also print passing test cases too.\r\n\r\nSomething like this:\r\n\r\n<img width=\"717\" alt=\"Screenshot 2023-06-14 at 8 30 22 PM\" src=\"https://github.com/bazelbuild/bazel/assets/347918/a7554f59-97af-4623-9df4-f49f1cfab93e\">\r\n\r\n\r\n\r\n",
"That sounds like a very reasonable approach.",
"@NelsonLi0701 do you want to try implementing this and contribute to Bazel? ",
"Sounds good to me.",
"Thanks, assigning it to you. When you have the pull request ready, send it to me and @lberki.\r\n\r\nLet me know if you need pointers on setting up the Bazel project for development.",
"I tried to build bazel but it failed.\r\nCould you help me to see how to fix it?\r\ncommand: `bazel build //src:bazel`\r\n```\r\nbazel build //src:bazel\r\nStarting local Bazel server and connecting to it...\r\nINFO: Analyzed target //src:bazel (469 packages loaded, 10864 targets configured).\r\nINFO: Found 1 target...\r\nINFO: From Compiling src/google/protobuf/message_lite.cc [for tool]:\r\nIn file included from /usr/include/string.h:535,\r\n from external/com_google_protobuf/src/google/protobuf/stubs/port.h:39,\r\n from external/com_google_protobuf/src/google/protobuf/stubs/common.h:48,\r\n from external/com_google_protobuf/src/google/protobuf/message_lite.h:46,\r\n from external/com_google_protobuf/src/google/protobuf/message_lite.cc:36:\r\nIn function 'void* memcpy(void*, const void*, size_t)',\r\n inlined from 'uint8_t* google::protobuf::io::EpsCopyOutputStream::WriteRaw(const void*, int, uint8_t*)' at external/com_google_protobuf/src/google/protobuf/io/coded_stream.h:684:16,\r\n inlined from 'virtual uint8_t* google::protobuf::internal::ImplicitWeakMessage::_InternalSerialize(uint8_t*, google::protobuf::io::EpsCopyOutputStream*) const' at external/com_google_protobuf/src/google/protobuf/implicit_weak_message.h:103:28,\r\n inlined from 'bool google::protobuf::MessageLite::SerializePartialToZeroCopyStream(google::protobuf::io::ZeroCopyOutputStream*) const' at external/com_google_protobuf/src/google/protobuf/message_lite.cc:411:30:\r\n/usr/include/x86_64-linux-gnu/bits/string_fortified.h:29:33: warning: 'void* __builtin___memcpy_chk(void*, const void*, long unsigned int, long unsigned int)' specified size between 18446744071562067968 and 18446744073709551615 exceeds maximum object size 9223372036854775807 [-Wstringop-overflow=]\r\n 29 | return __builtin___memcpy_chk (__dest, __src, __len,\r\n | ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~\r\n 30 | __glibc_objsize0 (__dest));\r\n | ~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nERROR: /usr/local/google/home/nelsonli/.cache/bazel/_bazel_nelsonli/71aeaef0e77795df4c8339df20bc2a13/external/maven/BUILD:3552:11: Creating compile jar for @maven//:org_tukaani_xz failed: (Aborted): AddJarManifestEntry failed: error executing command (from target @maven//:org_tukaani_xz) bazel-out/k8-opt-exec-EDC14992/bin/external/rules_jvm_external/private/tools/java/com/github/bazelbuild/rules_jvm_external/jar/AddJarManifestEntry --source ... (remaining 6 arguments skipped)\r\n\r\nUse --sandbox_debug to see verbose messages from the sandbox and retain the sandbox build root for debugging\r\n#\r\n# A fatal error has been detected by the Java Runtime Environment:\r\n#\r\n# SIGBUS (0x7) at pc=0x00007fb964e21a39, pid=2, tid=6\r\n#\r\n# JRE version: (11.0.15+10) (build )\r\n# Java VM: OpenJDK 64-Bit Server VM (11.0.15+10-LTS, mixed mode, sharing, tiered, compressed oops, g1 gc, linux-amd64)\r\n# Problematic frame:\r\n# V [libjvm.so+0xc21a39] PerfMemory::alloc(unsigned long)+0x59\r\n#\r\n# No core dump will be written. Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again\r\n#\r\n# An error report file with more information is saved as:\r\n# /usr/local/google/home/nelsonli/.cache/bazel/_bazel_nelsonli/71aeaef0e77795df4c8339df20bc2a13/sandbox/linux-sandbox/1075/execroot/io_bazel/hs_err_pid2.log\r\n#\r\n#\r\nTarget //src:bazel failed to build\r\nUse --verbose_failures to see the command lines of failed build steps.\r\nERROR: /usr/local/google/home/nelsonli/github_projects/bazel/src/main/java/com/google/devtools/build/lib/bazel/rules/BUILD:24:13 Building src/main/java/com/google/devtools/build/lib/bazel/rules/librules-class.jar (11 source files) and running annotation processors (OptionProcessor) failed: (Aborted): AddJarManifestEntry failed: error executing command (from target @maven//:org_tukaani_xz) bazel-out/k8-opt-exec-EDC14992/bin/external/rules_jvm_external/private/tools/java/com/github/bazelbuild/rules_jvm_external/jar/AddJarManifestEntry --source ... (remaining 6 arguments skipped)\r\n\r\nUse --sandbox_debug to see verbose messages from the sandbox and retain the sandbox build root for debugging\r\nINFO: Elapsed time: 57.065s, Critical Path: 19.22s\r\nINFO: 1220 processes: 159 internal, 1009 linux-sandbox, 3 local, 49 worker.\r\nFAILED: Build did NOT complete successfully\r\n```",
"@meteorcloudy have you seen this before?",
"Looks like an issue with JDK17 - passing `export JAVA_HOME=/path/to/jdk11/` works.",
"This is a known non-deterministic failure of Java compilation with (most) JDKs: https://github.com/bazelbuild/bazel/issues/3236\r\n\r\nI will send a PR to flip the flag that fixes this for Bazel.",
"Thanks, I used JDK11 and the problem be solved.\r\ncommand:\r\n`export JAVA_HOME=/usr/local/buildtools/java/jdk11/` && bazel build //src:bazel",
"I tried to run the unitest for `TerminalTestResultNotifier`. \r\nBut it failed without any modification.\r\nDid I do something wrong?\r\n\r\ncommand:\r\nexport JAVA_HOME=/usr/local/buildtools/java/jdk11/ && bazel test `//src/test/java/com/google/devtools/build/lib:runtime-tests` --test_summary=detailed\r\n\r\n```\r\nINFO: Analyzed target //src/test/java/com/google/devtools/build/lib:runtime-tests (0 packages loaded, 0 targets configured).\r\nINFO: Found 1 test target...\r\nFAIL: //src/test/java/com/google/devtools/build/lib:runtime-tests (see /usr/local/google/home/nelsonli/.cache/bazel/_bazel_nelsonli/71aeaef0e77795df4c8339df20bc2a13/execroot/io_bazel/bazel-out/k8-fastbuild/testlogs/src/test/java/com/google/devtools/build/lib/runtime-tests/test.log)\r\nTarget //src/test/java/com/google/devtools/build/lib:runtime-tests up-to-date:\r\n bazel-bin/src/test/java/com/google/devtools/build/lib/runtime-tests.jar\r\n bazel-bin/src/test/java/com/google/devtools/build/lib/runtime-tests\r\nINFO: Elapsed time: 27.970s, Critical Path: 27.43s\r\nINFO: 2 processes: 1 internal, 1 linux-sandbox.\r\nINFO: Build completed, 1 test FAILED, 2 total actions\r\n//src/test/java/com/google/devtools/build/lib:runtime-tests FAILED in 27.2s\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withSameOutputs (0.1s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testOneSpawn (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithDiscoverInputs (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_ignoresSecondSpawnForDependencies (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_recordsBothSpawnsWithRetry (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.actionDepsWithThreeSpawns (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithNullOwnerLabel (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_ENABLED] (0.1s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_DISABLED] (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withDifferentOutputs (0.0s)\r\nTest cases: finished with 510 passing and 10 failing out of 520 test cases\r\n```",
"Can you also print the test logs with `--test_output=errors`?",
"Sure, this is the error message: \r\n\r\nCommand: \r\nexport JAVA_HOME=/usr/local/buildtools/java/jdk11/ && bazel test `//src/test/java/com/google/devtools/build/lib:runtime-tests` --test_summary=detailed `--test_output=errors`\r\n\r\nError Message:\r\n```\r\n==================== Test output for //src/test/java/com/google/devtools/build/lib:runtime-tests:\r\nJUnit4 Test Runner\r\n....Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.util.DebugLoggerConfigurator setupLogging\r\nINFO: Log level: INFO\r\n.......Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime cleanUpForCrash\r\nINFO: Cleaning up in crash: DetailedExitCode{exitCode=OOM_ERROR, failureDetail=message: \"crash oom message\"\r\ncrash {\r\n code: CRASH_OOM\r\n}\r\n}\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down modules on crash: [, , DummyMetricsModule]\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down on crash\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down on crash\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=OOM_ERROR, failureDetail=message: \"crash oom message\"\r\ncrash {\r\n code: CRASH_OOM\r\n}\r\n}\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down DummyMetricsModule on crash\r\n......Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=BUILD_FAILURE, failureDetail=spawn {\r\n code: NON_ZERO_EXIT\r\n}\r\n}\r\n...Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=BUILD_FAILURE, failureDetail=spawn {\r\n code: NON_ZERO_EXIT\r\n}\r\n}\r\n..Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher execExclusively\r\nSEVERE: Shutting down due to exception\r\njava.lang.OutOfMemoryError: oom message\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.lambda$testExecReportsHardCrashStatus$0(BlazeCommandDispatcherTest.java:256)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest$CommandCompleteRecordingCommand.exec(BlazeCommandDispatcherTest.java:727)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:650)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testExecReportsHardCrashStatus(BlazeCommandDispatcherTest.java:263)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.bugreport.BugReport handleCrash\r\nSEVERE: Handling crash with CrashContext{haltJvm=false, args=[testcommand], sendBugReport=true, extraOomInfo=, eventHandler=com.google.devtools.build.lib.events.Reporter@27ea7c8f}\r\njava.lang.OutOfMemoryError: oom message\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.lambda$testExecReportsHardCrashStatus$0(BlazeCommandDispatcherTest.java:256)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest$CommandCompleteRecordingCommand.exec(BlazeCommandDispatcherTest.java:727)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:650)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testExecReportsHardCrashStatus(BlazeCommandDispatcherTest.java:263)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.bugreport.BugReport emitExitData\r\nWARNING: Did not write failure detail file; check stderr for errors.\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime cleanUpForCrash\r\nINFO: Cleaning up in crash: DetailedExitCode{exitCode=OOM_ERROR, failureDetail=message: \"Crashed: (java.lang.OutOfMemoryError) oom message\"\r\ncrash {\r\n code: CRASH_OOM\r\n causes {\r\n throwable_class: \"java.lang.OutOfMemoryError\"\r\n message: \"oom message\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.lambda$testExecReportsHardCrashStatus$0(BlazeCommandDispatcherTest.java:256)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest$CommandCompleteRecordingCommand.exec(BlazeCommandDispatcherTest.java:727)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:650)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testExecReportsHardCrashStatus(BlazeCommandDispatcherTest.java:263)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\"\r\n stack_trace: \"java.base/java.lang.reflect.Method.invoke(Method.java:566)\"\r\n stack_trace: \"org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\"\r\n stack_trace: \"org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\"\r\n stack_trace: \"org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\"\r\n stack_trace: \"org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\"\r\n stack_trace: \"org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\"\r\n stack_trace: \"org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.run(ParentRunner.java:413)\"\r\n stack_trace: \"org.junit.runners.Suite.runChild(Suite.java:128)\"\r\n stack_trace: \"org.junit.runners.Suite.runChild(Suite.java:27)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.run(ParentRunner.java:413)\"\r\n stack_trace: \"com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\"\r\n stack_trace: \"org.junit.runner.JUnitCore.run(JUnitCore.java:137)\"\r\n stack_trace: \"org.junit.runner.JUnitCore.run(JUnitCore.java:115)\"\r\n stack_trace: \"com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\"\r\n stack_trace: \"com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\"\r\n stack_trace: \"com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\"\r\n }\r\n}\r\n}\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down modules on crash: [, DummyMetricsModule]\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down on crash\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down DummyMetricsModule on crash\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.bugreport.BugReport emitExitData\r\nINFO: Cleaned up runtime.\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=OOM_ERROR, failureDetail=message: \"Crashed: (java.lang.OutOfMemoryError) oom message\"\r\ncrash {\r\n code: CRASH_OOM\r\n causes {\r\n throwable_class: \"java.lang.OutOfMemoryError\"\r\n message: \"oom message\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.lambda$testExecReportsHardCrashStatus$0(BlazeCommandDispatcherTest.java:256)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest$CommandCompleteRecordingCommand.exec(BlazeCommandDispatcherTest.java:727)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:650)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\"\r\n stack_trace: \"com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testExecReportsHardCrashStatus(BlazeCommandDispatcherTest.java:263)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\"\r\n stack_trace: \"java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\"\r\n stack_trace: \"java.base/java.lang.reflect.Method.invoke(Method.java:566)\"\r\n stack_trace: \"org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\"\r\n stack_trace: \"org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\"\r\n stack_trace: \"org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\"\r\n stack_trace: \"org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\"\r\n stack_trace: \"org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\"\r\n stack_trace: \"org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\"\r\n stack_trace: \"org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.run(ParentRunner.java:413)\"\r\n stack_trace: \"org.junit.runners.Suite.runChild(Suite.java:128)\"\r\n stack_trace: \"org.junit.runners.Suite.runChild(Suite.java:27)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\"\r\n stack_trace: \"org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\"\r\n stack_trace: \"org.junit.runners.ParentRunner.run(ParentRunner.java:413)\"\r\n stack_trace: \"com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\"\r\n stack_trace: \"org.junit.runner.JUnitCore.run(JUnitCore.java:137)\"\r\n stack_trace: \"org.junit.runner.JUnitCore.run(JUnitCore.java:115)\"\r\n stack_trace: \"com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\"\r\n stack_trace: \"com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\"\r\n stack_trace: \"com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\"\r\n }\r\n}\r\n}\r\n.Jul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeRuntime afterCommand\r\nWARNING: While running afterCommand() on \r\ncom.google.devtools.build.lib.util.AbruptExitException: afterCommandError\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testAfterCommandCanModifyExitStatus(BlazeCommandDispatcherTest.java:412)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\nJul 18, 2023 7:25:19 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=PUBLISH_ERROR, failureDetail=message: \"afterCommandError\"\r\nbuild_progress {\r\n code: BES_UPLOAD_LOCAL_FILE_ERROR\r\n}\r\n}\r\n...Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=BUILD_FAILURE, failureDetail=spawn {\r\n code: NON_ZERO_EXIT\r\n}\r\n}\r\n.Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: --not_a_valid_option\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:327)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testIllegalOptions(BlazeCommandDispatcherTest.java:575)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\nJul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher execExclusively\r\nWARNING: afterCommand yielded different result: BlazeCommandResult{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --not_a_valid_option\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n, execDescription=null, shutdown=false} BlazeCommandResult{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --not_a_valid_option\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n, execDescription=null, shutdown=false}\r\nJul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --not_a_valid_option\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n}\r\n..Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: --invalid\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:327)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:245)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:290)\r\n\tat com.google.devtools.build.lib.runtime.BlazeCommandDispatcherTest.testDetectsInvalidCommandLineOptions(BlazeCommandDispatcherTest.java:507)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\nJul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher execExclusively\r\nWARNING: afterCommand yielded different result: BlazeCommandResult{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --invalid\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n, execDescription=null, shutdown=false} BlazeCommandResult{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --invalid\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n, execDescription=null, shutdown=false}\r\nJul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=COMMAND_LINE_ERROR, failureDetail=message: \"Error parsing options: Unrecognized option: --invalid\"\r\ncommand {\r\n code: OPTIONS_PARSE_FAILURE\r\n}\r\n}\r\n......Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: In file /somewhere/.blazerc, the definition of config conf expands to another config that either has no value or is not in the form --config=value. For recursive config definitions, please do not provide the value in a separate token, such as in the form '--config value'.\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:246)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:182)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.expandConfigOptions(ConfigExpander.java:112)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.expandConfigOptions(BlazeOptionHandler.java:520)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:321)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandlerTest.testParseOptions_recursiveConfigWithDifferentTokens(BlazeOptionHandlerTest.java:721)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n..........................Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Config expansion has a cycle: config value foo expands to itself, see inheritance chain [foo]\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:258)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:182)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.expandConfigOptions(ConfigExpander.java:112)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.expandConfigOptions(BlazeOptionHandler.java:520)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:321)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandlerTest.testParseOptions_configCycleLength1(BlazeOptionHandlerTest.java:884)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n.Jul 18, 2023 7:25:20 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Config expansion has a cycle: config value foo expands to itself, see inheritance chain [foo, bar]\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:258)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:269)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.getExpansion(ConfigExpander.java:182)\r\n\tat com.google.devtools.build.lib.runtime.ConfigExpander.expandConfigOptions(ConfigExpander.java:112)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.expandConfigOptions(BlazeOptionHandler.java:520)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:321)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandlerTest.testParseOptions_configCycleLength2(BlazeOptionHandlerTest.java:903)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n..............OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended\r\n..Jul 18, 2023 7:25:22 AM com.google.devtools.build.lib.runtime.BlazeRuntime cleanUpForCrash\r\nINFO: Cleaning up in crash: DetailedExitCode{exitCode=OOM_ERROR, failureDetail=crash {\r\n code: CRASH_OOM\r\n}\r\n}\r\nJul 18, 2023 7:25:22 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down modules on crash: [DummyMetricsModule]\r\nJul 18, 2023 7:25:22 AM com.google.devtools.build.lib.runtime.BlazeRuntime shutDownModulesOnCrash\r\nINFO: Shutting down DummyMetricsModule on crash\r\n.......................................................Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=NO_TESTS_FOUND, failureDetail=test_command {\r\n code: NO_TEST_TARGETS\r\n}\r\n}\r\n.Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=NO_TESTS_FOUND, failureDetail=test_command {\r\n code: NO_TEST_TARGETS\r\n}\r\n}\r\n...Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=INTERRUPTED, failureDetail=message: \"unexpected interruption\"\r\ninterrupted {\r\n}\r\n}\r\n...Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=INTERRUPTED, failureDetail=message: \"unexpected interruption\"\r\ninterrupted {\r\n}\r\n}\r\n.Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeCommandDispatcher exec\r\nINFO: Exit status was DetailedExitCode{exitCode=BLAZE_INTERNAL_ERROR, failureDetail=message: \"crash\"\r\ncrash {\r\n}\r\n}\r\n..........................Exception in thread \"action-graph-writer\" java.lang.UnsatisfiedLinkError: /usr/local/google/home/nelsonli/.cache/bazel/_bazel_nelsonli/71aeaef0e77795df4c8339df20bc2a13/sandbox/linux-sandbox/93/execroot/io_bazel/_tmp/53a941e5e8d4dac3443b57eddd867750/libzstd-jni-1.5.2-33248079624470795952.so: libstdc++.so.6: cannot open shared object file: No such file or directory\r\nno zstd-jni-1.5.2-3 in java.library.path: [/usr/java/packages/lib, /usr/lib64, /lib64, /lib, /usr/lib]\r\nUnsupported OS/arch, cannot find /linux/amd64/libzstd-jni-1.5.2-3.so or load zstd-jni-1.5.2-3 from system libraries. Please try building from source the jar or providing libzstd-jni-1.5.2-3 in your system.\r\n\tat java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2675)\r\n\tat java.base/java.lang.Runtime.loadLibrary0(Runtime.java:831)\r\n\tat java.base/java.lang.System.loadLibrary(System.java:1876)\r\n\tat com.github.luben.zstd.util.Native.load(Native.java:124)\r\n\tat com.github.luben.zstd.util.Native.load(Native.java:55)\r\n\tat com.github.luben.zstd.ZstdOutputStreamNoFinalizer.<clinit>(ZstdOutputStreamNoFinalizer.java:18)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$FailingOutputStreamFactory$1$1.<init>(ExecutionGraphModuleTest.java:272)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$FailingOutputStreamFactory$1.get(ExecutionGraphModuleTest.java:272)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$1.createCompressingOutputStream(ExecutionGraphModuleTest.java:315)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\n.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$FailingOutputStreamFactory$2$1.<init>(ExecutionGraphModuleTest.java:284)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$FailingOutputStreamFactory$2.get(ExecutionGraphModuleTest.java:284)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest$1.createCompressingOutputStream(ExecutionGraphModuleTest.java:315)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\n.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE..Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Exception in thread \"action-graph-writer\" java.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdOutputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:75)\r\n\tat com.github.luben.zstd.ZstdOutputStream.<init>(ZstdOutputStream.java:55)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.createCompressingOutputStream(ExecutionGraphModule.java:774)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModule$ActionDumpWriter.run(ExecutionGraphModule.java:787)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\nE.Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: While parsing option --flag_alias=foo=//bar=7: --flag_alias does not support flag value assignment.\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:185)\r\n\tat com.google.devtools.common.options.OptionValueDescription$RepeatableOptionValueDescription.addOptionInstance(OptionValueDescription.java:350)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.setOptionValue(OptionsParserImpl.java:691)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.handleNewParsedOption(OptionsParserImpl.java:651)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:548)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasWithValueAssignment(FlagAliasTest.java:73)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\nCaused by: com.google.devtools.common.options.OptionsParsingException: --flag_alias does not support flag value assignment.\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:565)\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:549)\r\n\tat com.google.devtools.common.options.Converter$Contextless.convert(Converter.java:49)\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:181)\r\n\t... 45 more\r\n\r\n...Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: --foo=7\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasBeforeSettingOnCommandLine(FlagAliasTest.java:213)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n..Jul 18, 2023 7:25:23 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: -=\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.aliasLogicSkipsNonDoubleDashArgs(FlagAliasTest.java:190)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n..Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: While parsing option --flag_alias=bad$foo=//bar: bad$foo should only consist of word characters to be a valid alias name.\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:185)\r\n\tat com.google.devtools.common.options.OptionValueDescription$RepeatableOptionValueDescription.addOptionInstance(OptionValueDescription.java:350)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.setOptionValue(OptionsParserImpl.java:691)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.handleNewParsedOption(OptionsParserImpl.java:651)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:548)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasWithInvalidName(FlagAliasTest.java:85)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\nCaused by: com.google.devtools.common.options.OptionsParsingException: bad$foo should only consist of word characters to be a valid alias name.\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:560)\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:549)\r\n\tat com.google.devtools.common.options.Converter$Contextless.convert(Converter.java:49)\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:181)\r\n\t... 45 more\r\n\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: While parsing option --flag_alias=foo: Variable definitions must be in the form of a 'name=value' assignment\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:185)\r\n\tat com.google.devtools.common.options.OptionValueDescription$RepeatableOptionValueDescription.addOptionInstance(OptionValueDescription.java:350)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.setOptionValue(OptionsParserImpl.java:691)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.handleNewParsedOption(OptionsParserImpl.java:651)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:548)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasWithoutEqualsInValue(FlagAliasTest.java:97)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\nCaused by: com.google.devtools.common.options.OptionsParsingException: Variable definitions must be in the form of a 'name=value' assignment\r\n\tat com.google.devtools.common.options.Converters$AssignmentConverter.convert(Converters.java:513)\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:553)\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:549)\r\n\tat com.google.devtools.common.options.Converter$Contextless.convert(Converter.java:49)\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:181)\r\n\t... 45 more\r\n\r\n..Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: --nofoo\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasWithNoBooleanSyntax(FlagAliasTest.java:130)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n..Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: While parsing option --flag_alias=foo=bar: --flag_alias only supports Starlark build settings.\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:185)\r\n\tat com.google.devtools.common.options.OptionValueDescription$RepeatableOptionValueDescription.addOptionInstance(OptionValueDescription.java:350)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.setOptionValue(OptionsParserImpl.java:691)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.handleNewParsedOption(OptionsParserImpl.java:651)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:548)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:304)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.useAliasWithNonStarlarkFlag(FlagAliasTest.java:61)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\nCaused by: com.google.devtools.common.options.OptionsParsingException: --flag_alias only supports Starlark build settings.\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:572)\r\n\tat com.google.devtools.common.options.Converters$FlagAliasConverter.convert(Converters.java:549)\r\n\tat com.google.devtools.common.options.Converter$Contextless.convert(Converter.java:49)\r\n\tat com.google.devtools.common.options.ParsedOptionDescription.getConvertedValue(ParsedOptionDescription.java:181)\r\n\t... 45 more\r\n\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.BlazeOptionHandler parseOptions\r\nINFO: Error parsing options\r\ncom.google.devtools.common.options.OptionsParsingException: Unrecognized option: --foo=7\r\n\tat com.google.devtools.common.options.OptionsParserImpl.identifyOptionAndPossibleArgument(OptionsParserImpl.java:795)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:536)\r\n\tat com.google.devtools.common.options.OptionsParserImpl.parse(OptionsParserImpl.java:457)\r\n\tat com.google.devtools.common.options.OptionsParser.parseWithSourceFunction(OptionsParser.java:746)\r\n\tat com.google.devtools.common.options.OptionsParser.parse(OptionsParser.java:712)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseRcOptions(BlazeOptionHandler.java:253)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseArgsAndConfigs(BlazeOptionHandler.java:301)\r\n\tat com.google.devtools.build.lib.runtime.BlazeOptionHandler.parseOptions(BlazeOptionHandler.java:450)\r\n\tat com.google.devtools.build.lib.runtime.FlagAliasTest.setAliasOnCommandLine_useInRcFile(FlagAliasTest.java:203)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)\r\n\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:128)\r\n\tat org.junit.runners.Suite.runChild(Suite.java:27)\r\n\tat org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)\r\n\tat org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)\r\n\tat org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:413)\r\n\tat com.google.testing.junit.runner.internal.junit4.CancellableRequestFactory$CancellableRunner.run(CancellableRequestFactory.java:108)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat com.google.testing.junit.runner.junit4.JUnit4Runner.run(JUnit4Runner.java:116)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.runTestsInSuite(BazelTestRunner.java:145)\r\n\tat com.google.testing.junit.runner.BazelTestRunner.main(BazelTestRunner.java:76)\r\n\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.GcThrashingDetector$SingleLimitTracker overThresholdGc\r\nINFO: Calling handleCrash\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.GcThrashingDetector$SingleLimitTracker overThresholdGc\r\nINFO: Calling handleCrash\r\n....Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.GcThrashingDetector$SingleLimitTracker overThresholdGc\r\nINFO: Calling handleCrash\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.GcThrashingDetector$SingleLimitTracker overThresholdGc\r\nINFO: Calling handleCrash\r\n........Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption$LoadingPhaseThreadCountConverter checkAndLimit\r\nINFO: Running under a test; loading_phase_threads capped at 20\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption$LoadingPhaseThreadCountConverter checkAndLimit\r\nINFO: Running under a test; loading_phase_threads capped at 0\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption$LoadingPhaseThreadCountConverter checkAndLimit\r\nINFO: Running under a test; loading_phase_threads capped at 20\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption$LoadingPhaseThreadCountConverter checkAndLimit\r\nINFO: Running under a test; loading_phase_threads capped at 7\r\n.........Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Ignoring manual GC from other source\r\n....Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (99% of tenured space after minor GC)\r\nJul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Calling handleCrash\r\n....Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Calling handleCrash\r\n.Jul 18, 2023 7:25:24 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x2 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x3 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x4 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x5 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x6 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x2 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x3 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x4 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x5 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x6 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x7 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x8 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x2 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x3 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x4 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x5 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x6 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x7 (91% of tenured space after full GC) because of recently triggered GC\r\n.Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Calling handleCrash\r\n.Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Ignoring manual GC from other source\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Ignoring manual GC from other source\r\n.Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing (91% of tenured space after minor GC) because of recently triggered GC\r\n..Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Calling handleCrash\r\n..Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Ignoring possible GC thrashing x1 (91% of tenured space after full GC) because of recently triggered GC\r\n.Jul 18, 2023 7:25:25 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\n.Jul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Ignoring manual GC from other source\r\n.Jul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nWARNING: Observed a GCLocker initiated GC without observing a manual GC since the last call to System.gc(), cancelling timeout to permit a retry\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after minor GC)\r\n.Jul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (100% of tenured space after full GC)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\n.Jul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (99% of tenured space after full GC)\r\n..Jul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Back under threshold (89% of tenured space)\r\nJul 18, 2023 7:25:26 AM com.google.devtools.build.lib.runtime.RetainedHeapLimiter handle\r\nINFO: Triggering a full GC (91% of tenured space after full GC)\r\n.................................Jul 18, 2023 7:25:27 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 12 milliseconds doing invalidation of 13 nodes\r\nJul 18, 2023 7:25:27 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 10 milliseconds doing invalidation of 13 nodes\r\nJul 18, 2023 7:25:27 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\nJul 18, 2023 7:25:27 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 15 milliseconds doing invalidation of 2 nodes\r\n.Jul 18, 2023 7:25:28 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:28 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:28 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:28 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n..I.......................................................................................................................................................................................................................Jul 18, 2023 7:25:33 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor runInternal\r\nINFO: Spent 10 milliseconds doing invalidation enqueuing\r\nJul 18, 2023 7:25:33 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 12 milliseconds doing invalidation of 13 nodes\r\nJul 18, 2023 7:25:33 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\nJul 18, 2023 7:25:33 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor runInternal\r\nINFO: Spent 11 milliseconds doing invalidation enqueuing\r\nJul 18, 2023 7:25:33 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 12 milliseconds doing invalidation of 13 nodes\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 10 milliseconds doing invalidation of 13 nodes\r\nJul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\nJul 18, 2023 7:25:34 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 10 milliseconds doing invalidation of 13 nodes\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor runInternal\r\nINFO: Spent 16 milliseconds doing invalidation enqueuing\r\nJul 18, 2023 7:25:34 AM com.google.devtools.build.skyframe.InvalidatingNodeVisitor run\r\nINFO: Spent 17 milliseconds doing invalidation of 13 nodes\r\nJul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:34 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:35 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:35 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:35 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n.Jul 18, 2023 7:25:35 AM com.google.devtools.build.lib.skyframe.SkyframeExecutor handleAnalysisInvalidatingChange\r\nINFO: Dropping configured target data\r\n...........\r\nTime: 17.413\r\nThere were 10 failures:\r\n1) spawnAndAction_withSameOutputs(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.UnsatisfiedLinkError: /usr/local/google/home/nelsonli/.cache/bazel/_bazel_nelsonli/71aeaef0e77795df4c8339df20bc2a13/sandbox/linux-sandbox/93/execroot/io_bazel/_tmp/53a941e5e8d4dac3443b57eddd867750/libzstd-jni-1.5.2-34505731243935472564.so: libstdc++.so.6: cannot open shared object file: No such file or directory\r\nno zstd-jni-1.5.2-3 in java.library.path: [/usr/java/packages/lib, /usr/lib64, /lib64, /lib, /usr/lib]\r\nUnsupported OS/arch, cannot find /linux/amd64/libzstd-jni-1.5.2-3.so or load zstd-jni-1.5.2-3 from system libraries. Please try building from source the jar or providing libzstd-jni-1.5.2-3 in your system.\r\n\tat java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2675)\r\n\tat java.base/java.lang.Runtime.loadLibrary0(Runtime.java:831)\r\n\tat java.base/java.lang.System.loadLibrary(System.java:1876)\r\n\tat com.github.luben.zstd.util.Native.load(Native.java:124)\r\n\tat com.github.luben.zstd.util.Native.load(Native.java:55)\r\n\tat com.github.luben.zstd.ZstdInputStreamNoFinalizer.<clinit>(ZstdInputStreamNoFinalizer.java:23)\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withSameOutputs(ExecutionGraphModuleTest.java:423)\r\n2) testOneSpawn(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testOneSpawn(ExecutionGraphModuleTest.java:135)\r\n3) testSpawnWithDiscoverInputs(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithDiscoverInputs(ExecutionGraphModuleTest.java:186)\r\n4) multipleSpawnsWithSameOutput_overlapping_ignoresSecondSpawnForDependencies(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_ignoresSecondSpawnForDependencies(ExecutionGraphModuleTest.java:615)\r\n5) multipleSpawnsWithSameOutput_recordsBothSpawnsWithRetry(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_recordsBothSpawnsWithRetry(ExecutionGraphModuleTest.java:487)\r\n6) actionDepsWithThreeSpawns(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.actionDepsWithThreeSpawns(ExecutionGraphModuleTest.java:255)\r\n7) testSpawnWithNullOwnerLabel(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithNullOwnerLabel(ExecutionGraphModuleTest.java:400)\r\n8) multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_ENABLED](com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry(ExecutionGraphModuleTest.java:561)\r\n9) multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_DISABLED](com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry(ExecutionGraphModuleTest.java:561)\r\n10) spawnAndAction_withDifferentOutputs(com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest)\r\njava.lang.NoClassDefFoundError: Could not initialize class com.github.luben.zstd.ZstdInputStreamNoFinalizer\r\n\tat com.github.luben.zstd.ZstdInputStream.<init>(ZstdInputStream.java:24)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.parse(ExecutionGraphModuleTest.java:93)\r\n\tat com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withDifferentOutputs(ExecutionGraphModuleTest.java:455)\r\n\r\nFAILURES!!!\r\nTests run: 519, Failures: 10\r\n\r\n\r\nBazelTestRunner exiting with a return value of 1\r\nJVM shutdown hooks (if any) will run now.\r\nThe JVM will exit once they complete.\r\n\r\n-- JVM shutdown starting at 2023-07-18 07:25:36 --\r\n\r\n================================================================================\r\nTarget //src/test/java/com/google/devtools/build/lib:runtime-tests up-to-date:\r\n bazel-bin/src/test/java/com/google/devtools/build/lib/runtime-tests.jar\r\n bazel-bin/src/test/java/com/google/devtools/build/lib/runtime-tests\r\nINFO: Elapsed time: 21.257s, Critical Path: 20.97s\r\nINFO: 2 processes: 1 internal, 1 linux-sandbox.\r\nINFO: Build completed, 1 test FAILED, 2 total actions\r\n//src/test/java/com/google/devtools/build/lib:runtime-tests FAILED in 20.8s\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withSameOutputs (0.1s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testOneSpawn (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithDiscoverInputs (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_ignoresSecondSpawnForDependencies (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_recordsBothSpawnsWithRetry (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.actionDepsWithThreeSpawns (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.testSpawnWithNullOwnerLabel (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_ENABLED] (0.1s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.multipleSpawnsWithSameOutput_overlapping_recordsBothSpawnsWithoutRetry[LOCAL_LOCK_FREE_OUTPUT_DISABLED] (0.0s)\r\n FAILED com.google.devtools.build.lib.runtime.ExecutionGraphModuleTest.spawnAndAction_withDifferentOutputs (0.0s)\r\nTest cases: finished with 510 passing and 10 failing out of 520 test cases\r\n\r\nExecuted 1 out of 1 test: 1 fails locally.\r\n```",
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-09-13T00:40:53Z" | [
"type: feature request",
"untriaged",
"team-Core"
] | Print successful test methods when running `bazel test --test_summary=detailed` | ### Description of the feature request:
Print the results of each test method when running the test module.
e.g.
zipalign_tests (6 Tests)
[1/6] Align#Unaligned: PASSED (0ms)
[2/6] Align#DoubleAligment: PASSED (0ms)
[3/6] Align#Holes: PASSED (0ms)
[4/6] Align#DifferenteOrders: PASSED (0ms)
[5/6] Align#DirectoryEntryDoNotRequireAlignment: PASSED (0ms)
[6/6] Align#DirectoryEntry: PASSED (0ms)
### What underlying problem are you trying to solve with this feature?
Currently, regardless of any options (--test_summary, --test_output), Bazel's output does not print the passed test methods.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
release 6.2.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
```text
92619b01fa7bbaf14ea1ceab3c48033e58d83eb3
```
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
Reproduce steps:
In https://github.com/bazelbuild/examples/tree/main/third-party-dependencies
Run bazel test :gtest_test
```
//:gtest_test PASSED in 0.0s
```
Cant not show any passed test methods.
expects:
```
//:gtest_test PASSED in 0.0s
[PASSED] SumbNegativeValues (0.0s)
[PASSED] SumPositiveValues (0.0s)
```
| [
"src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java",
"src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java",
"src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java"
] | [
"src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java",
"src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java",
"src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java"
] | [
"src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java",
"src/test/shell/bazel/bazel_test_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java b/src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java
index add22ee33df4f6..4445624970cf42 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/TerminalTestResultNotifier.java
@@ -142,13 +142,13 @@ private boolean duplicateLabels(Set<TestSummary> summaries) {
* @param summaries summaries of tests {@link TestSummary}
* @param showAllTests if true, print information about each test regardless of its status
* @param showNoStatusTests if true, print information about not executed tests (no status tests)
- * @param printFailedTestCases if true, print details about which test cases in a test failed
+ * @param showAllTestCases if true, print all test cases status and detailed information
*/
private void printSummary(
Set<TestSummary> summaries,
boolean showAllTests,
boolean showNoStatusTests,
- boolean printFailedTestCases) {
+ boolean showAllTestCases) {
boolean withConfig = duplicateLabels(summaries);
int numFailedToBuildReported = 0;
for (TestSummary summary : summaries) {
@@ -171,7 +171,7 @@ private void printSummary(
printer,
testLogPathFormatter,
summaryOptions.verboseSummary,
- printFailedTestCases,
+ showAllTestCases,
withConfig);
}
}
@@ -243,9 +243,9 @@ public void notify(Set<TestSummary> summaries, int numberOfExecutedTargets) {
case DETAILED:
printSummary(
summaries,
- /* showAllTests= */ false,
+ /* showAllTests= */ true,
/* showNoStatusTests= */ true,
- /* printFailedTestCases= */ true);
+ /* showAllTestCases= */ true);
break;
case SHORT:
@@ -253,7 +253,7 @@ public void notify(Set<TestSummary> summaries, int numberOfExecutedTargets) {
summaries,
/* showAllTests= */ true,
/* showNoStatusTests= */ false,
- /* printFailedTestCases= */ false);
+ /* showAllTestCases= */ false);
break;
case TERSE:
@@ -261,7 +261,7 @@ public void notify(Set<TestSummary> summaries, int numberOfExecutedTargets) {
summaries,
/* showAllTests= */ false,
/* showNoStatusTests= */ false,
- /* printFailedTestCases= */ false);
+ /* showAllTestCases= */ false);
break;
case TESTCASE:
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java b/src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java
index 2ddd38e349c164..baf19688611c89 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/TestSummary.java
@@ -41,6 +41,7 @@
import com.google.devtools.build.lib.view.test.TestStatus.BlazeTestStatus;
import com.google.devtools.build.lib.view.test.TestStatus.FailedTestCasesStatus;
import com.google.devtools.build.lib.view.test.TestStatus.TestCase;
+import com.google.devtools.build.lib.view.test.TestStatus.TestCase.Status;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.util.Durations;
import com.google.protobuf.util.Timestamps;
@@ -218,9 +219,20 @@ private int traverseTestCases(TestCase testCase) {
if (testCase.getStatus() != TestCase.Status.PASSED) {
this.summary.failedTestCases.add(testCase);
}
+
+ if (testCase.getStatus() == Status.PASSED) {
+ this.summary.passedTestCases.add(testCase);
+ }
+
return 1;
}
+ public Builder addPassedTestCases(List<TestCase> testCases) {
+ checkMutation(testCases);
+ summary.passedTestCases.addAll(testCases);
+ return this;
+ }
+
@CanIgnoreReturnValue
public Builder addFailedTestCases(List<TestCase> testCases, FailedTestCasesStatus status) {
checkMutation(status);
@@ -396,6 +408,7 @@ private void makeSummaryImmutable() {
private boolean ranRemotely;
private boolean wasUnreportedWrongSize;
private List<TestCase> failedTestCases = new ArrayList<>();
+ private final List<TestCase> passedTestCases = new ArrayList<>();
private List<Path> passedLogs = new ArrayList<>();
private List<Path> failedLogs = new ArrayList<>();
private List<String> warnings = new ArrayList<>();
@@ -507,6 +520,10 @@ public List<TestCase> getFailedTestCases() {
return failedTestCases;
}
+ public List<TestCase> getPassedTestCases() {
+ return passedTestCases;
+ }
+
public List<Path> getCoverageFiles() {
return coverageFiles;
}
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java b/src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java
index eb76c11b951c75..8ee42143bd0ef1 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/TestSummaryPrinter.java
@@ -24,6 +24,7 @@
import com.google.devtools.build.lib.view.test.TestStatus.BlazeTestStatus;
import com.google.devtools.build.lib.view.test.TestStatus.FailedTestCasesStatus;
import com.google.devtools.build.lib.view.test.TestStatus.TestCase;
+import com.google.devtools.build.lib.view.test.TestStatus.TestCase.Status;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -117,18 +118,13 @@ public static void print(
AnsiTerminalPrinter terminalPrinter,
TestLogPathFormatter testLogPathFormatter,
boolean verboseSummary,
- boolean printFailedTestCases) {
- print(
- summary,
- terminalPrinter,
- testLogPathFormatter,
- verboseSummary,
- printFailedTestCases,
- false);
+ boolean showAllTestCases) {
+ print(summary, terminalPrinter, testLogPathFormatter, verboseSummary, showAllTestCases, false);
}
/**
* Prints summary status for a single test.
+ *
* @param terminalPrinter The printer to print to
*/
public static void print(
@@ -136,7 +132,7 @@ public static void print(
AnsiTerminalPrinter terminalPrinter,
TestLogPathFormatter testLogPathFormatter,
boolean verboseSummary,
- boolean printFailedTestCases,
+ boolean showAllTestCases,
boolean withConfigurationName) {
BlazeTestStatus status = summary.getStatus();
// Skip output for tests that failed to build.
@@ -158,29 +154,35 @@ public static void print(
+ (verboseSummary ? getAttemptSummary(summary) + getTimeSummary(summary) : "")
+ "\n");
- if (printFailedTestCases && summary.getStatus() == BlazeTestStatus.FAILED) {
- if (summary.getFailedTestCasesStatus() == FailedTestCasesStatus.NOT_AVAILABLE) {
- terminalPrinter.print(
- Mode.WARNING + " (individual test case information not available) "
- + Mode.DEFAULT + "\n");
- } else {
- for (TestCase testCase : summary.getFailedTestCases()) {
- if (testCase.getStatus() != TestCase.Status.PASSED) {
- TestSummaryPrinter.printTestCase(terminalPrinter, testCase);
- }
- }
+ if (showAllTestCases) {
+ for (TestCase testCase : summary.getPassedTestCases()) {
+ TestSummaryPrinter.printTestCase(terminalPrinter, testCase);
+ }
- if (summary.getFailedTestCasesStatus() != FailedTestCasesStatus.FULL) {
+ if (summary.getStatus() == BlazeTestStatus.FAILED) {
+ if (summary.getFailedTestCasesStatus() == FailedTestCasesStatus.NOT_AVAILABLE) {
terminalPrinter.print(
Mode.WARNING
- + " (some shards did not report details, list of failed test"
- + " cases incomplete)\n"
- + Mode.DEFAULT);
+ + " (individual test case information not available) "
+ + Mode.DEFAULT
+ + "\n");
+ } else {
+ for (TestCase testCase : summary.getFailedTestCases()) {
+ if (testCase.getStatus() != TestCase.Status.PASSED) {
+ TestSummaryPrinter.printTestCase(terminalPrinter, testCase);
+ }
+ }
+
+ if (summary.getFailedTestCasesStatus() != FailedTestCasesStatus.FULL) {
+ terminalPrinter.print(
+ Mode.WARNING
+ + " (some shards did not report details, list of failed test"
+ + " cases incomplete)\n"
+ + Mode.DEFAULT);
+ }
}
}
- }
-
- if (!printFailedTestCases) {
+ } else {
for (String warning : summary.getWarnings()) {
terminalPrinter.print(" " + AnsiTerminalPrinter.Mode.WARNING + "WARNING: "
+ AnsiTerminalPrinter.Mode.DEFAULT + warning + "\n");
@@ -205,12 +207,8 @@ public static void print(
}
}
- /**
- * Prints the result of an individual test case. It is assumed not to have
- * passed, since passed test cases are not reported.
- */
- static void printTestCase(
- AnsiTerminalPrinter terminalPrinter, TestCase testCase) {
+ /** Prints the result of an individual test case. */
+ static void printTestCase(AnsiTerminalPrinter terminalPrinter, TestCase testCase) {
String timeSummary;
if (testCase.hasRunDurationMillis()) {
timeSummary = " ("
@@ -220,16 +218,17 @@ static void printTestCase(
timeSummary = "";
}
+ Mode mode = (testCase.getStatus() == Status.PASSED) ? Mode.INFO : Mode.ERROR;
terminalPrinter.print(
" "
- + Mode.ERROR
- + Strings.padEnd(testCase.getStatus().toString(), 8, ' ')
- + Mode.DEFAULT
- + testCase.getClassName()
- + "."
- + testCase.getName()
- + timeSummary
- + "\n");
+ + mode
+ + Strings.padEnd(testCase.getStatus().toString(), 8, ' ')
+ + Mode.DEFAULT
+ + testCase.getClassName()
+ + "."
+ + testCase.getName()
+ + timeSummary
+ + "\n");
}
/**
| diff --git a/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java b/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
index 2bb030773ab723..a82242ae56bb29 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
@@ -445,6 +445,30 @@ public void testTestCaseNamesShownWhenNeeded() throws Exception {
verify(printerFailed).print(find("FAILED.*orange *\\(1\\.5"));
}
+ @Test
+ public void testShowTestCaseNames() throws Exception {
+ TestCase detailPassed = newDetail("strawberry", TestCase.Status.PASSED, 1000L);
+ TestCase detailFailed = newDetail("orange", TestCase.Status.FAILED, 1500L);
+
+ TestSummary summaryPassed =
+ createPassedTestSummary(BlazeTestStatus.PASSED, Arrays.asList(detailPassed));
+
+ TestSummary summaryFailed =
+ createTestSummaryWithDetails(
+ BlazeTestStatus.FAILED, Arrays.asList(detailPassed, detailFailed));
+ assertThat(summaryFailed.getStatus()).isEqualTo(BlazeTestStatus.FAILED);
+
+ AnsiTerminalPrinter printerPassed = Mockito.mock(AnsiTerminalPrinter.class);
+ TestSummaryPrinter.print(summaryPassed, printerPassed, Path::getPathString, true, true);
+ verify(printerPassed).print(contains("//package:name"));
+ verify(printerPassed).print(find("PASSED.*strawberry *\\(1\\.0"));
+
+ AnsiTerminalPrinter printerFailed = Mockito.mock(AnsiTerminalPrinter.class);
+ TestSummaryPrinter.print(summaryFailed, printerFailed, Path::getPathString, true, true);
+ verify(printerFailed).print(contains("//package:name"));
+ verify(printerFailed).print(find("FAILED.*orange *\\(1\\.5"));
+ }
+
@Test
public void testTestCaseNamesOrdered() throws Exception {
TestCase[] details = {
@@ -500,13 +524,13 @@ public void testCachedResultsFirstInSort() throws Exception {
@Test
public void testCollectingFailedDetails() throws Exception {
- TestCase rootCase = TestCase.newBuilder()
- .setName("tests")
- .setRunDurationMillis(5000L)
- .addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
- .addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
- .addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
- .build();
+ TestCase rootCase =
+ TestCase.newBuilder()
+ .setName("tests")
+ .setRunDurationMillis(5000L)
+ .addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
+ .addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
+ .build();
TestSummary summary =
getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.FAILED).build();
@@ -518,6 +542,46 @@ public void testCollectingFailedDetails() throws Exception {
verify(printer).print(find("ERROR.*cherry"));
}
+ @Test
+ public void testCollectingAllDetails() throws Exception {
+ TestCase rootCase =
+ TestCase.newBuilder()
+ .setName("tests")
+ .setRunDurationMillis(5000L)
+ .addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
+ .addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
+ .addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
+ .build();
+
+ TestSummary summary =
+ getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.FAILED).build();
+
+ AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
+ TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
+ verify(printer).print(contains("//package:name"));
+ verify(printer).print(find("FAILED.*apple"));
+ verify(printer).print(find("PASSED.*banana"));
+ verify(printer).print(find("ERROR.*cherry"));
+ }
+
+ @Test
+ public void testCollectingPassedDetails() throws Exception {
+ TestCase rootCase =
+ TestCase.newBuilder()
+ .setName("tests")
+ .setRunDurationMillis(5000L)
+ .addChild(newDetail("apple", TestCase.Status.PASSED, 1000L))
+ .build();
+
+ TestSummary summary =
+ getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.PASSED).build();
+
+ AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
+ TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
+ verify(printer).print(contains("//package:name"));
+ verify(printer).print(find("PASSED.*apple"));
+ }
+
@Test
public void countTotalTestCases() throws Exception {
TestCase rootCase =
@@ -605,6 +669,10 @@ private ConfiguredTarget stubTarget() throws Exception {
return target(PATH, TARGET_NAME);
}
+ private TestSummary createPassedTestSummary(BlazeTestStatus status, List<TestCase> details) {
+ return getTemplateBuilder().setStatus(status).addPassedTestCases(details).build();
+ }
+
private TestSummary createTestSummaryWithDetails(BlazeTestStatus status,
List<TestCase> details) {
TestSummary summary = getTemplateBuilder()
diff --git a/src/test/shell/bazel/bazel_test_test.sh b/src/test/shell/bazel/bazel_test_test.sh
index 4bee9e4a4178c4..b87b0a3f9f6457 100755
--- a/src/test/shell/bazel/bazel_test_test.sh
+++ b/src/test/shell/bazel/bazel_test_test.sh
@@ -645,7 +645,7 @@ EOF
expect_log "name=\"dir/fail\""
}
-function test_detailed_test_summary() {
+function test_detailed_test_summary_for_failed_test() {
copy_examples
create_workspace_with_default_repos WORKSPACE
setup_javatest_support
@@ -658,6 +658,19 @@ function test_detailed_test_summary() {
expect_log 'FAILED.*com\.example\.myproject\.Fail\.testFail'
}
+function test_detailed_test_summary_for_passed_test() {
+ copy_examples
+ create_workspace_with_default_repos WORKSPACE
+ setup_javatest_support
+
+ local java_native_tests=//examples/java-native/src/test/java/com/example/myproject
+
+ bazel test --test_summary=detailed "${java_native_tests}:hello" >& $TEST_log \
+ || fail "expected success"
+ expect_log 'PASSED.*com\.example\.myproject\.TestHello\.testNoArgument'
+ expect_log 'PASSED.*com\.example\.myproject\.TestHello\.testWithArgument'
+}
+
# This test uses "--ignore_all_rc_files" since outside .bazelrc files can pollute
# this environment. Just "--bazelrc=/dev/null" is not sufficient to fix.
function test_flaky_test() {
| val | test | 2023-09-13T15:07:07 | "2023-06-15T06:34:47Z" | NelsonLi0701 | test |
bazelbuild/bazel/19450_19534 | bazelbuild/bazel | bazelbuild/bazel/19450 | bazelbuild/bazel/19534 | [
"keyword_pr_to_issue"
] | 42c6755ba9bbf0e3c9f03ae3d54166f29d991539 | 49886f3666075c52af7f0d7b9d2c0393aee30b07 | [
"A fix for this issue has been included in [Bazel 6.4.0 RC1](https://releases.bazel.build/6.4.0/rc1/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!",
"Fix is from the PR: https://github.com/bazelbuild/bazel/pull/19534",
"I confirmed that this issue is fixed in `6.4.0 rc1`.\r\nThank you!"
] | [] | "2023-09-15T09:17:08Z" | [
"type: bug",
"team-Rules-CPP",
"untriaged"
] | Backport bugfixes for "cc_proto_library not linked to target" to 6.x | ### Description of the bug:
Related to: #17091, #19056 , 590ee17
Similar to #19056, objects from protocol buffer are not linked properly after upgrading from 6.2.1 to 6.3.2,.
This seems to have been fixed in 590ee17, but the fix is not included in `release-6.4.0` branch yet.
When a shared object is generated with bazel, some of the symbols from protobuf are not linked.
```
> nm -C -D bazel-bin/libtest.so
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
00000000000009c9 T test()
U mozc::commands::Config::Config(google::protobuf::Arena*, bool)
0000000000000a40 W mozc::commands::Config::Config()
0000000000000a40 W mozc::commands::Config::Config()
0000000000000a1a W mozc::commands::Config::~Config()
00000000000009ec W mozc::commands::Config::~Config()
00000000000009ec W mozc::commands::Config::~Config()
U google::protobuf::internal::ZeroFieldsBase::~ZeroFieldsBase()
U std::ios_base_library_init()@GLIBCXX_3.4.32
U vtable for mozc::commands::Config
U operator delete(void*)@GLIBCXX_3.4
0000000000002008 D __bss_start
w __cxa_finalize@GLIBC_2.2.5
w __gmon_start__
0000000000002008 D _edata
0000000000002009 D _end
```
Applying the following patch seems to fix the issue.
```patch
diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
index 55036600f8..fa7f896264 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
@@ -282,4 +282,5 @@ cc_proto_library = rule(
allow_files = False,
),
},
+ provides = [CcInfo],
)
```
### Which category does this issue belong to?
C++/Objective-C Rules
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Add BUILD.bazel
```bazel
proto_library(
name = "commands_proto",
srcs = [
"commands.proto",
],
deps = [],
)
cc_proto_library(
name = "commands_cc_proto",
deps = [":commands_proto"],
)
cc_library(
name = "test_lib",
srcs = ["test.cc"],
deps = [
":commands_cc_proto",
],
)
cc_shared_library(
name = "test",
roots = ["test_lib"],
)
```
2. Add commands.proto
```protobuf
syntax = "proto2";
package mozc.commands;
message Config {
}
```
3. Add test.cc
```c++
#include "commands.pb.h"
void test(void) {
mozc::commands::Config b;
}
```
4. Build
`bazel build //:test --experimental_cc_shared_library`
5. Check the generated shared library with nm
`nm -C -D bazel-bin/libtest.so`
### Which operating system are you running Bazel on?
Linux 6.1.49-1-MANJARO #1 SMP PREEMPT_DYNAMIC Sun Aug 27 23:08:04 UTC 2023 x86_64 GNU/Linux
### What is the output of `bazel info release`?
release 6.3.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
_No response_
### Have you found anything relevant by searching the web?
590ee17 may have fixed this issue, but I could not confirm it on master branch due to an unrelated error.
### Any other information, logs, or outputs that you want to share?
Bazel 6.3.2 generates following result:
```
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
00000000000009c9 T test()
U mozc::commands::Config::Config(google::protobuf::Arena*, bool)
0000000000000a40 W mozc::commands::Config::Config()
0000000000000a40 W mozc::commands::Config::Config()
0000000000000a1a W mozc::commands::Config::~Config()
00000000000009ec W mozc::commands::Config::~Config()
00000000000009ec W mozc::commands::Config::~Config()
U google::protobuf::internal::ZeroFieldsBase::~ZeroFieldsBase()
U std::ios_base_library_init()@GLIBCXX_3.4.32
U vtable for mozc::commands::Config
U operator delete(void*)@GLIBCXX_3.4
0000000000002008 D __bss_start
w __cxa_finalize@GLIBC_2.2.5
w __gmon_start__
0000000000002008 D _edata
0000000000002009 D _end
```
Bazel 6.2.1 generates following result:
```
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
U _Unwind_Resume@GCC_3.0
0000000000004f86 W descriptor_table_commands_2eproto_getter()
0000000000004ee9 T test()
00000000000062e0 R TableStruct_commands_2eproto::offsets
00000000000058ba W mozc::commands::ConfigDefaultTypeInternal::~ConfigDefaultTypeInternal()
00000000000058ba W mozc::commands::ConfigDefaultTypeInternal::~ConfigDefaultTypeInternal()
0000000000009020 D mozc::commands::_Config_default_instance_
0000000000008970 D mozc::commands::Config::_class_data_
0000000000004f94 T mozc::commands::Config::Config(google::protobuf::Arena*, bool)
0000000000004fd6 T mozc::commands::Config::Config(mozc::commands::Config const&)
0000000000004f60 W mozc::commands::Config::Config()
0000000000004f94 T mozc::commands::Config::Config(google::protobuf::Arena*, bool)
0000000000004fd6 T mozc::commands::Config::Config(mozc::commands::Config const&)
0000000000004f60 W mozc::commands::Config::Config()
0000000000004f3a W mozc::commands::Config::~Config()
0000000000004f0c W mozc::commands::Config::~Config()
0000000000004f0c W mozc::commands::Config::~Config()
0000000000005aa8 W mozc::commands::Config* google::protobuf::MessageLite::CreateMaybeMessage<mozc::commands::Config>(google::protobuf::Arena*)
(reducted as the output is long)
``` | [
"src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl"
] | [
"src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl"
] | [] | diff --git a/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl b/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
index 55036600f8ebbf..fa7f896264c386 100644
--- a/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
+++ b/src/main/starlark/builtins_bzl/common/cc/cc_proto_library.bzl
@@ -282,4 +282,5 @@ cc_proto_library = rule(
allow_files = False,
),
},
+ provides = [CcInfo],
)
| null | val | test | 2023-09-15T17:12:58 | "2023-09-08T02:01:38Z" | femshima | test |
bazelbuild/bazel/19438_19591 | bazelbuild/bazel | bazelbuild/bazel/19438 | bazelbuild/bazel/19591 | [
"keyword_pr_to_issue"
] | d5f678323bf2c151d6fb0014455c63282fcf0327 | 671f0b3dd7ffa84c8bc8c54a3113af0faad56a27 | [
"how can i submit the changes?",
"> how can i submit the changes?\n\nIf it's really just this line, you could use GitHub's web interface to edit the file and create a Pull Request from that.",
"Feel free to send a PR, we are happy to review it!"
] | [] | "2023-09-22T09:27:52Z" | [
"type: bug",
"P3",
"team-Local-Exec",
"help wanted"
] | No writable permission for /tmp if /tmp is symbolic link | ### Description of the bug:
Hi,
In some cases there is no enough space for /tmp to build big project, usually we will set /tmp as a symbolic link to local path (ex, /tmp -> /home/xxx/tmp)
For bazel build we will have no writable permission for /tmp
Use --sandbox_debug to see verbose messages from the sandbox and retain the sandbox build root for debugging
clang-17: error: unable to make temporary file: Read-only file system
From the sandbox_debug log we can see the canonical path is remounted as read only.
src/main/tools/linux-sandbox-pid1.cc:311: writable: /tmp
src/main/tools/linux-sandbox-pid1.cc:405: remount ro: /home/xxx/tmp
https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
430 writableDirs.add(fs.getPath("/tmp"));
So it could be a bug for linux sandbox spaw runner. it can be changed as below
430 writableDirs.add(fs.getPath("/tmp").resolveSymbolicLinks());
Thanks
### Which category does this issue belong to?
Java Rules
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
set /tmp as a symbolic link and build kernel modules with bazel which need to write files into /tmp directory
### Which operating system are you running Bazel on?
linux
### What is the output of `bazel info release`?
bazel 7.0.0 all pre release
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
bazel 7.0.0 all preversion dist
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
no
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [
"src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
index 3b2582f8647abc..29d342e14b08b6 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java
@@ -427,7 +427,7 @@ protected ImmutableSet<Path> getWritableDirs(
}
FileSystem fs = sandboxExecRoot.getFileSystem();
writableDirs.add(fs.getPath("/dev/shm").resolveSymbolicLinks());
- writableDirs.add(fs.getPath("/tmp"));
+ writableDirs.add(fs.getPath("/tmp").resolveSymbolicLinks());
return writableDirs.build();
}
| null | test | test | 2023-09-13T16:48:28 | "2023-09-07T07:27:44Z" | harveydevloper | test |
bazelbuild/bazel/17571_19606 | bazelbuild/bazel | bazelbuild/bazel/17571 | bazelbuild/bazel/19606 | [
"keyword_pr_to_issue"
] | fc43994f0065f19728c2c0b3a2e3dcd8cd49b48c | 65e5c378b56fbb70575ef7ab9d6cf6ea7c35450c | [
"The list of variables potentially affecting runfiles libraries further includes `JAVA_RUNFILES`, `PYTHON_RUNFILES` and `RUNFILES_MANIFEST_ONLY`.\n\n@meteorcloudy @Wyverald What do you think, could `bazel run` drop these variables from the environment? Not doing so potentially breaks the runfiles library \"promise\" to \"just work\" with `bazel run`.",
"In general, I think it makes sense, but I wonder under what circumstances, users would set those env vars before running `bazel run`? And what if the user just runs the binary directly, it could still be a problem, right?",
"I'll defer to @linzhp for the first question.\n\nRunning a binary directly already has some notable differences from running it via `bazel run`, e.g. `args` an `env` aren't honored. I don't think users would expect everything to just work if they do that, but they should probably be able to assume that `bazel run` makes it so.",
"> users would set those env vars before running bazel run? \r\n\r\nThis is just a way to reproduce the issue. In the real scenario, they set `RUNFILES_DIR` in their `$HOME/.zshrc` file when they were debugging something else in the past and forgot to remove it. When we enable Python Gazelle extension, which uses the runfiles library to locate Python parser, they found Gazelle no longer work for them.\r\n\r\n> And what if the user just runs the binary directly, it could still be a problem, right?\r\nIn such scenario, it's users responsibility to set `RUNFILES_DIR` correctly, or pass the files via command line arguments.\r\n\r\n",
"I see, thanks for the context! I'm happy to review a PR to address this issue ;)",
"A fix for this issue has been included in [Bazel 6.4.0 RC2](https://releases.bazel.build/6.4.0/rc2/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-09-23T06:08:21Z" | [
"type: bug",
"P2",
"team-ExternalDeps",
"help wanted"
] | bazel run should not inherit RUNFILES_DIR from OS | ### Description of the bug:
Runfile libraries such as [github.com/bazelbuild/rules_go/go/runfiles](https://github.com/bazelbuild/rules_go/blob/948f9587d27821afacfb5fb632fda0eb28ffd2ff/go/runfiles/runfiles.go#L48) relies on the environment variables `RUNFILES_DIR` and `RUNFILES_MANIFEST_FILE` to work correctly. These two variables are set by Bazel during `bazel run`. However, if they are set in OS, Bazel would inherit them and not set them anymore, leading to machine dependent behaviors.
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Create a repo like this:
```
-- WORKSPACE --
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_go",
sha256 = "56d8c5a5c91e1af73eca71a6fab2ced959b67c86d12ba37feedb0a2dfea441a6",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.37.0/rules_go-v0.37.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.37.0/rules_go-v0.37.0.zip",
],
)
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
go_rules_dependencies()
go_register_toolchains(version = "1.19.3")
-- BUILD.bazel --
load("@io_bazel_rules_go//go:def.bzl", "go_binary")
go_binary(
name = "runfiles",
srcs = ["main.go"],
data = ["@go_sdk//:tools"],
deps = ["@io_bazel_rules_go//go/runfiles"],
)
-- main.go --
package main
import (
"fmt"
"log"
"github.com/bazelbuild/rules_go/go/runfiles"
)
func main() {
loc, err := runfiles.Rlocation("go_sdk/bin/gofmt")
if err != nil {
log.Fatal(err)
}
fmt.Println(loc)
}
```
2. Run:
```bash
RUNFILES_DIR=/tmp bazel run //:runfiles
```
It outputs `/tmp/go_sdk/bin/gofmt`, but Bazel should ignore `RUNFILES_DIR=/tmp`, and output something like `/private/var/tmp/_bazel_zplin/a20570cf42c983bd18597126a6b3c06e/external/go_sdk/bin/gofmt` instead.
### Which operating system are you running Bazel on?
macOS
### What is the output of `bazel info release`?
release 6.0.0-homebrew
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/cpp/blaze.cc",
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java",
"src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java",
"src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java",
"src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java",
"src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java",
"src/main/protobuf/command_server.proto"
] | [
"src/main/cpp/blaze.cc",
"src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java",
"src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java",
"src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java",
"src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java",
"src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java",
"src/main/protobuf/command_server.proto"
] | [
"src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java",
"src/test/shell/bazel/run_test.sh"
] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 459dd524c62dc8..1ef38f81344bbe 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -2151,6 +2151,12 @@ unsigned int BlazeServer::Communicate(
return blaze_exit_code::INTERNAL_ERROR;
}
+ // Clear environment variables before setting the requested ones so that
+ // users can still explicitly override the clearing.
+ for (const auto &variable_name : request.environment_variable_to_clear()) {
+ UnsetEnv(variable_name);
+ }
+
vector<string> argv(request.argv().begin(), request.argv().end());
for (const auto &variable : request.environment_variable()) {
SetEnv(variable.name(), variable.value());
diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java
index ce283b1accbc75..ce3c12352611c2 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java
+++ b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionContext.java
@@ -339,6 +339,7 @@ public void maybeReportSubcommand(Spawn spawn) {
showSubcommands.prettyPrintArgs,
spawn.getArguments(),
spawn.getEnvironment(),
+ /* environmentVariablesToClear= */ null,
getExecRoot().getPathString(),
spawn.getConfigurationChecksum(),
spawn.getExecutionPlatformLabelString());
diff --git a/src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java b/src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java
index 6e954351a0709c..b0c97f6e7e276d 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/aquery/ActionGraphTextOutputFormatterCallback.java
@@ -280,6 +280,7 @@ private void writeAction(ActionAnalysisMetadata action, PrintStream printStream)
.map(a -> escapeBytestringUtf8(a))
.collect(toImmutableList()),
/* environment= */ null,
+ /* environmentVariablesToClear= */ null,
/* cwd= */ null,
action.getOwner().getConfigurationChecksum(),
action.getExecutionPlatform() == null
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java
index 13069d4bd5aac0..045b641efc5501 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/RunCommand.java
@@ -15,6 +15,9 @@
package com.google.devtools.build.lib.runtime.commands;
import com.google.common.annotations.VisibleForTesting;
+import static com.google.common.collect.ImmutableList.toImmutableList;
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
@@ -147,7 +150,7 @@ private static final class NoShellFoundException extends Exception {}
public static final String MULTIPLE_TESTS_MESSAGE =
"'run' only works with tests with one shard ('--test_sharding_strategy=disabled' is okay) "
- + "and without --runs_per_test";
+ + "and without --runs_per_test";
// The test policy to determine the environment variables from when running tests
private final TestPolicy testPolicy;
@@ -157,11 +160,22 @@ private static final class NoShellFoundException extends Exception {}
private static final FileType RUNFILES_MANIFEST = FileType.of(".runfiles_manifest");
+ private static final ImmutableList<String> ENV_VARIABLES_TO_CLEAR =
+ ImmutableList.of(
+ // These variables are all used by runfiles libraries to locate the runfiles directory or
+ // manifest and can cause incorrect behavior when set for the top-level binary run with
+ // bazel run.
+ "JAVA_RUNFILES",
+ "RUNFILES_DIR",
+ "RUNFILES_MANIFEST_FILE",
+ "RUNFILES_MANIFEST_ONLY",
+ "TEST_SRCDIR");
+
public RunCommand(TestPolicy testPolicy) {
this.testPolicy = testPolicy;
}
- @VisibleForTesting // productionVisibility = Visibility.PRIVATE
+ @VisibleForTesting // productionVisibility = Visibility.PRIVATE
protected BuildResult processRequest(final CommandEnvironment env, BuildRequest request) {
List<String> targetPatternStrings = request.getTargets();
return new BuildTool(env)
@@ -542,6 +556,7 @@ public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult opti
/* prettyPrintArgs= */ false,
cmdLine,
runEnvironment,
+ ENV_VARIABLES_TO_CLEAR,
workingDir.getPathString(),
configuration.checksum(),
/* executionPlatformAsLabelString= */ null);
@@ -629,6 +644,10 @@ public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult opti
.setValue(ByteString.copyFrom(variable.getValue(), StandardCharsets.ISO_8859_1))
.build());
}
+ execDescription.addAllEnvironmentVariableToClear(
+ ENV_VARIABLES_TO_CLEAR.stream()
+ .map(s -> ByteString.copyFrom(s, ISO_8859_1))
+ .collect(toImmutableList()));
return BlazeCommandResult.execute(execDescription.build());
}
diff --git a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
index 8e7a4a91383242..a3e7d15bd9c765 100644
--- a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
+++ b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
@@ -22,6 +22,7 @@
import java.io.File;
import java.util.Collection;
import java.util.Comparator;
+import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
@@ -41,6 +42,8 @@ private interface DescribeCommandImpl {
void describeCommandCwd(String cwd, StringBuilder message);
void describeCommandEnvPrefix(StringBuilder message, boolean isolated);
void describeCommandEnvVar(StringBuilder message, Map.Entry<String, String> entry);
+
+ void describeCommandUnsetEnvVar(StringBuilder message, String name);
/**
* Formats the command element and adds it to the message.
*
@@ -83,6 +86,12 @@ public void describeCommandEnvVar(StringBuilder message, Map.Entry<String, Strin
.append(ShellEscaper.escapeString(entry.getValue())).append(" \\\n ");
}
+ @Override
+ public void describeCommandUnsetEnvVar(StringBuilder message, String name) {
+ // Only the short form of --unset is supported on macOS.
+ message.append("-u ").append(ShellEscaper.escapeString(name)).append(" \\\n ");
+ }
+
@Override
public void describeCommandElement(
StringBuilder message, String commandElement, boolean isBinary) {
@@ -123,6 +132,11 @@ public void describeCommandEnvVar(StringBuilder message, Map.Entry<String, Strin
.append(entry.getValue()).append("\n ");
}
+ @Override
+ public void describeCommandUnsetEnvVar(StringBuilder message, String name) {
+ message.append("SET ").append(name).append('=').append("\n ");
+ }
+
@Override
public void describeCommandElement(
StringBuilder message, String commandElement, boolean isBinary) {
@@ -156,6 +170,7 @@ public static String describeCommand(
boolean prettyPrintArgs,
Collection<String> commandLineElements,
@Nullable Map<String, String> environment,
+ @Nullable List<String> environmentVariablesToClear,
@Nullable String cwd,
@Nullable String configurationChecksum,
@Nullable String executionPlatformAsLabelString) {
@@ -205,6 +220,12 @@ public static String describeCommand(
if (environment != null) {
describeCommandImpl.describeCommandEnvPrefix(
message, form != CommandDescriptionForm.COMPLETE_UNISOLATED);
+ if (environmentVariablesToClear != null) {
+ for (String name : Ordering.natural().sortedCopy(environmentVariablesToClear)) {
+ message.append(" ");
+ describeCommandImpl.describeCommandUnsetEnvVar(message, name);
+ }
+ }
// A map can never have two keys with the same value, so we only need to compare the keys.
Comparator<Map.Entry<String, String>> mapEntryComparator = comparingByKey();
for (Map.Entry<String, String> entry :
@@ -291,6 +312,7 @@ static String describeCommandFailure(
/* prettyPrintArgs= */ false,
commandLineElements,
env,
+ null,
cwd,
configurationChecksum,
executionPlatformAsLabelString));
diff --git a/src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java b/src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java
index 2ffacc9824b522..3c781a8a2f2f89 100644
--- a/src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java
+++ b/src/main/java/com/google/devtools/build/lib/worker/WorkerKey.java
@@ -211,11 +211,12 @@ public String toString() {
// debugging.
return CommandFailureUtils.describeCommand(
CommandDescriptionForm.COMPLETE,
- /*prettyPrintArgs=*/ false,
+ /* prettyPrintArgs= */ false,
args,
env,
+ /* environmentVariablesToClear= */ null,
execRoot.getPathString(),
- /*configurationChecksum=*/ null,
- /*executionPlatformAsLabelString=*/ null);
+ /* configurationChecksum= */ null,
+ /* executionPlatformAsLabelString= */ null);
}
}
diff --git a/src/main/protobuf/command_server.proto b/src/main/protobuf/command_server.proto
index 5a1155df007f99..e2987492327383 100644
--- a/src/main/protobuf/command_server.proto
+++ b/src/main/protobuf/command_server.proto
@@ -92,6 +92,7 @@ message ExecRequest {
bytes working_directory = 1;
repeated bytes argv = 2;
repeated EnvironmentVariable environment_variable = 3;
+ repeated bytes environment_variable_to_clear = 4;
}
// Contains metadata and result data for a command execution.
| diff --git a/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java b/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
index fdc9027f09891c..44b8badbb9c24b 100644
--- a/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
@@ -15,6 +15,7 @@
import static com.google.common.truth.Truth.assertThat;
+import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.cmdline.Label;
import java.util.Arrays;
@@ -210,6 +211,8 @@ public void describeCommandPrettyPrintArgs() throws Exception {
env.put("FOO", "foo");
env.put("PATH", "/usr/bin:/bin:/sbin");
+ ImmutableList<String> envToClear = ImmutableList.of("CLEAR", "THIS");
+
String cwd = "/my/working/directory";
PlatformInfo executionPlatform =
PlatformInfo.builder().setLabel(Label.parseAbsoluteUnchecked("//platform:exec")).build();
@@ -219,6 +222,7 @@ public void describeCommandPrettyPrintArgs() throws Exception {
true,
Arrays.asList(args),
env,
+ envToClear,
cwd,
"cfg12345",
executionPlatform.label().toString());
@@ -227,6 +231,8 @@ public void describeCommandPrettyPrintArgs() throws Exception {
.isEqualTo(
"(cd /my/working/directory && \\\n"
+ " exec env - \\\n"
+ + " -u CLEAR \\\n"
+ + " -u THIS \\\n"
+ " FOO=foo \\\n"
+ " PATH=/usr/bin:/bin:/sbin \\\n"
+ " some_command \\\n"
diff --git a/src/test/shell/bazel/run_test.sh b/src/test/shell/bazel/run_test.sh
index fd6c3c0de5d53e..82a987446306a2 100755
--- a/src/test/shell/bazel/run_test.sh
+++ b/src/test/shell/bazel/run_test.sh
@@ -164,4 +164,51 @@ EOF
true
}
+function test_run_with_runfiles_env() {
+ mkdir -p b
+ cat > b/BUILD <<'EOF'
+sh_binary(
+ name = "binary",
+ srcs = ["binary.sh"],
+ deps = ["@bazel_tools//tools/bash/runfiles"],
+)
+EOF
+ cat > b/binary.sh <<'EOF'
+#!/usr/bin/env bash
+# --- begin runfiles.bash initialization v3 ---
+# Copy-pasted from the Bazel Bash runfiles library v3.
+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 v3 ---
+
+own_path=$(rlocation main/b/binary.sh)
+echo "own path: $own_path"
+test -f "$own_path"
+EOF
+ chmod +x b/binary.sh
+
+ bazel run //b:binary --script_path=script.bat &>"$TEST_log" \
+ || fail "Script generation should succeed"
+
+ cat ./script.bat &>"$TEST_log"
+
+ # Make it so that the runfiles variables point to an incorrect but valid
+ # runfiles directory/manifest, simulating a left over one from a different
+ # test to which RUNFILES_DIR and RUNFILES_MANIFEST_FILE point in the client
+ # env.
+ BOGUS_RUNFILES_DIR="$(pwd)/bogus_runfiles/bazel_tools/tools/bash/runfiles"
+ mkdir -p "$BOGUS_RUNFILES_DIR"
+ touch "$BOGUS_RUNFILES_DIR/runfiles.bash"
+ BOGUS_RUNFILES_MANIFEST_FILE="$(pwd)/bogus_manifest"
+ echo "bazel_tools/tools/bash/runfiles/runfiles.bash bogus/path" > "$BOGUS_RUNFILES_MANIFEST_FILE"
+
+ RUNFILES_DIR="$BOGUS_RUNFILES_DIR" RUNFILES_MANIFEST_FILE="$BOGUS_RUNFILES_MANIFEST_FILE" \
+ ./script.bat || fail "Run should succeed"
+}
+
run_suite "run_under_tests"
| val | test | 2023-09-21T19:46:55 | "2023-02-23T23:18:53Z" | linzhp | test |
bazelbuild/bazel/19680_19735 | bazelbuild/bazel | bazelbuild/bazel/19680 | bazelbuild/bazel/19735 | [
"connected"
] | ef72058c79a4343f2688f7b1e426cb0b3f29bb83 | b5987978c323c39c1000141ace68569ff9c6ebe8 | [
"https://github.com/bazelbuild/bazel/pull/19735"
] | [] | "2023-10-05T07:11:44Z" | [] | [6.4.0] Issue with Java header compilation | Forked from #19598 | [
"tools/jdk/DumpPlatformClassPath.java"
] | [
"tools/jdk/DumpPlatformClassPath.java"
] | [] | diff --git a/tools/jdk/DumpPlatformClassPath.java b/tools/jdk/DumpPlatformClassPath.java
index 083285350ba379..b4e69ffbd5d950 100644
--- a/tools/jdk/DumpPlatformClassPath.java
+++ b/tools/jdk/DumpPlatformClassPath.java
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-import com.sun.tools.javac.api.JavacTool;
-import com.sun.tools.javac.util.Context;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -21,13 +19,19 @@
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.Method;
+import java.net.URI;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.EnumSet;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
@@ -38,16 +42,11 @@
import java.util.jar.JarOutputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
-import javax.tools.JavaFileManager;
-import javax.tools.JavaFileObject;
-import javax.tools.JavaFileObject.Kind;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.StandardLocation;
/**
* Output a jar file containing all classes on the platform classpath of the given JDK release.
*
- * <p>usage: DumpPlatformClassPath <release version> <output jar> <path to target JDK>?
+ * <p>usage: {@code DumpPlatformClassPath <output jar> <path to target JDK>}
*/
public class DumpPlatformClassPath {
@@ -90,7 +89,7 @@ static boolean dumpJDK9AndNewerBootClassPath(
// * --release takes a language level (e.g. '9') and uses the API information baked in to
// the host JDK (in lib/ct.sym).
- // Since --system only supports JDK >= 9, first check of the target JDK defines a JDK 8
+ // Since --system only supports JDK >= 9, first check if the target JDK defines a JDK 8
// bootclasspath.
List<Path> bootClassPathJars = getBootClassPathJars(targetJavabase);
if (!bootClassPathJars.isEmpty()) {
@@ -98,50 +97,35 @@ static boolean dumpJDK9AndNewerBootClassPath(
return true;
}
- // Initialize a FileManager to process the --system argument, and then read the
- // initialized bootclasspath data back out.
-
- Context context = new Context();
- try {
- JavacTool.create()
- .getTask(
- /* out = */ null,
- /* fileManager = */ null,
- /* diagnosticListener = */ null,
- /* options = */ Arrays.asList("--system", String.valueOf(targetJavabase)),
- /* classes = */ null,
- /* compilationUnits = */ null,
- context);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException(
- String.format(
- "Failed to collect system class path. Please ensure that the configured Java runtime"
- + " ('%s') is a complete JDK. There are known issues with Homebrew versions of"
- + " the Java runtime.",
- targetJavabase.toRealPath()),
- e);
- }
- StandardJavaFileManager fileManager =
- (StandardJavaFileManager) context.get(JavaFileManager.class);
-
- SortedMap<String, InputStream> entries = new TreeMap<>();
- for (JavaFileObject fileObject :
- fileManager.list(
- StandardLocation.PLATFORM_CLASS_PATH,
- "",
- EnumSet.of(Kind.CLASS),
- /* recurse= */ true)) {
- String binaryName =
- fileManager.inferBinaryName(StandardLocation.PLATFORM_CLASS_PATH, fileObject);
- entries.put(binaryName.replace('.', '/') + ".class", fileObject.openInputStream());
+ // Read the bootclasspath data using the JRT filesystem
+ Map<String, byte[]> entries = new TreeMap<>();
+ Map<String, String> env = new TreeMap<>();
+ env.put("java.home", String.valueOf(targetJavabase));
+ try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), env)) {
+ Path modules = fileSystem.getPath("/modules");
+ try (DirectoryStream<Path> ms = Files.newDirectoryStream(modules)) {
+ for (Path m : ms) {
+ Files.walkFileTree(
+ m,
+ new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+ throws IOException {
+ if (file.getFileName().toString().endsWith(".class")) {
+ entries.put(m.relativize(file).toString(), Files.readAllBytes(file));
+ }
+ return super.visitFile(file, attrs);
+ }
+ });
+ }
+ }
+ writeEntries(output, entries);
}
- writeEntries(output, entries);
return true;
}
/** Writes the given entry names and data to a jar archive at the given path. */
- private static void writeEntries(Path output, Map<String, InputStream> entries)
- throws IOException {
+ private static void writeEntries(Path output, Map<String, byte[]> entries) throws IOException {
if (!entries.containsKey("java/lang/Object.class")) {
throw new AssertionError(
"\nCould not find java.lang.Object on bootclasspath; something has gone terribly wrong.\n"
@@ -168,14 +152,14 @@ private static void writeClassPathJars(Path output, Collection<Path> paths) thro
for (Path path : paths) {
jars.add(new JarFile(path.toFile()));
}
- SortedMap<String, InputStream> entries = new TreeMap<>();
+ SortedMap<String, byte[]> entries = new TreeMap<>();
for (JarFile jar : jars) {
jar.stream()
.filter(p -> p.getName().endsWith(".class"))
.forEachOrdered(
entry -> {
try {
- entries.put(entry.getName(), jar.getInputStream(entry));
+ entries.put(entry.getName(), toByteArray(jar.getInputStream(entry)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
@@ -214,12 +198,10 @@ private static List<Path> getBootClassPathJars(Path javaHome) throws IOException
* Add a jar entry to the given {@link JarOutputStream}, normalizing the entry timestamps to
* ensure deterministic build output.
*/
- private static void addEntry(JarOutputStream jos, String name, InputStream input)
- throws IOException {
+ private static void addEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
JarEntry je = new JarEntry(name);
je.setTime(FIXED_TIMESTAMP);
je.setMethod(ZipEntry.STORED);
- byte[] bytes = toByteArray(input);
// When targeting JDK >= 10, patch the major version so it will be accepted by javac 9
// TODO(cushon): remove this after updating javac
if (bytes[7] > 53) {
| null | train | test | 2023-10-05T15:17:47 | "2023-09-29T16:49:13Z" | bazel-io | test |
bazelbuild/bazel/19624_19745 | bazelbuild/bazel | bazelbuild/bazel/19624 | bazelbuild/bazel/19745 | [
"keyword_pr_to_issue"
] | 7e600bd0af2dd11d80a314ede823ce1f1f90701f | ddc3e5217d6ce211866caf75adee2b8222f396ba | [
"A fix for this issue has been included in [Bazel 6.4.0 RC2](https://releases.bazel.build/6.4.0/rc2/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-10-06T07:07:40Z" | [
"type: feature request",
"untriaged",
"team-Core"
] | Aspects: Merge validation output group | ### Description of the feature request:
If I have a rule that returns the special [_validation](https://bazel.build/extending/rules#validation_actions) output group, it's not possible for an aspect also return the `_validation` output group. This results in a `Output group _validation provided twice` error.
According to the [aspect documentation](https://bazel.build/extending/aspects):
> It is an error if a target and an aspect that is applied to it each provide a provider with the same type, with the exceptions of [OutputGroupInfo](https://bazel.build/rules/lib/providers/OutputGroupInfo) (which is merged, so long as the rule and aspect specify different output groups)
It would be nice to extend this allow merging the `_validation` output group.
### Which category does this issue belong to?
Core
### What underlying problem are you trying to solve with this feature?
Allow multiple aspects to declare their own validations.
### Which operating system are you running Bazel on?
Linux
### What is the output of `bazel info release`?
6.2.0
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
https://groups.google.com/g/bazel-discuss/c/TCo0msh1My4 was used as an inspiration to add validations via aspects.
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java"
] | [
"src/test/shell/integration/validation_actions_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java b/src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java
index 44720d8c8d9352..f98b8e49853a54 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/OutputGroupInfo.java
@@ -189,7 +189,8 @@ public NestedSet<Artifact> getOutputGroup(String outputGroupName) {
}
/**
- * Merges output groups from two output providers. The set of output groups must be disjoint.
+ * Merges output groups from two output providers. The set of output groups must be disjoint,
+ * except for the special validation output group, which is always merged.
*
* @param providers providers to merge {@code this} with.
*/
@@ -207,6 +208,9 @@ public static OutputGroupInfo merge(List<OutputGroupInfo> providers)
Set<String> seenGroups = new HashSet<>();
for (OutputGroupInfo provider : providers) {
for (String outputGroup : provider.outputGroups.keySet()) {
+ if (outputGroup.equals(VALIDATION)) {
+ continue;
+ }
if (!seenGroups.add(outputGroup)) {
throw new DuplicateException(
"Output group " + outputGroup + " provided twice");
@@ -215,6 +219,17 @@ public static OutputGroupInfo merge(List<OutputGroupInfo> providers)
resultBuilder.put(outputGroup, provider.getOutputGroup(outputGroup));
}
}
+ // Allow both an aspect and the rule to use validation actions.
+ NestedSetBuilder<Artifact> validationOutputs = NestedSetBuilder.stableOrder();
+ for (OutputGroupInfo provider : providers) {
+ try {
+ validationOutputs.addTransitive(provider.getOutputGroup(VALIDATION));
+ } catch (IllegalArgumentException e) {
+ // Thrown if nested set orders aren't compatible.
+ throw new DuplicateException(
+ "Output group " + VALIDATION + " provided twice with incompatible depset orders");
+ }
+ }
return new OutputGroupInfo(resultBuilder.buildOrThrow());
}
| diff --git a/src/test/shell/integration/validation_actions_test.sh b/src/test/shell/integration/validation_actions_test.sh
index 6145c1f2b284a6..0790c9161fe4bb 100755
--- a/src/test/shell/integration/validation_actions_test.sh
+++ b/src/test/shell/integration/validation_actions_test.sh
@@ -508,4 +508,54 @@ function test_validation_actions_flags() {
expect_log "Target //validation_actions:foo0 up-to-date:"
}
+function test_validation_actions_in_rule_and_aspect() {
+ setup_test_project
+
+ mkdir -p aspect
+ cat > aspect/BUILD <<'EOF'
+exports_files(["aspect_validation_tool"])
+EOF
+ cat > aspect/def.bzl <<'EOF'
+def _validation_aspect_impl(target, ctx):
+ validation_output = ctx.actions.declare_file(ctx.rule.attr.name + ".aspect_validation")
+ ctx.actions.run(
+ outputs = [validation_output],
+ executable = ctx.executable._validation_tool,
+ arguments = [validation_output.path])
+ return [
+ OutputGroupInfo(_validation = depset([validation_output])),
+ ]
+
+validation_aspect = aspect(
+ implementation = _validation_aspect_impl,
+ attrs = {
+ "_validation_tool": attr.label(
+ allow_single_file = True,
+ default = Label(":aspect_validation_tool"),
+ executable = True,
+ cfg = "exec"),
+ },
+)
+EOF
+ cat > aspect/aspect_validation_tool <<'EOF'
+#!/bin/bash
+echo "aspect validation output" > $1
+EOF
+ chmod +x aspect/aspect_validation_tool
+ setup_passing_validation_action
+
+ bazel build --run_validations --aspects=//aspect:def.bzl%validation_aspect \
+ //validation_actions:foo0 >& "$TEST_log" || fail "Expected build to succeed"
+
+ cat > aspect/aspect_validation_tool <<'EOF'
+#!/bin/bash
+echo "aspect validation failed!"
+exit 1
+EOF
+
+ bazel build --run_validations --aspects=//aspect:def.bzl%validation_aspect \
+ //validation_actions:foo0 >& "$TEST_log" && fail "Expected build to fail"
+ expect_log "aspect validation failed!"
+}
+
run_suite "Validation actions integration tests"
| train | test | 2023-10-06T18:02:13 | "2023-09-25T19:38:48Z" | ismell | test |
bazelbuild/bazel/19632_19764 | bazelbuild/bazel | bazelbuild/bazel/19632 | bazelbuild/bazel/19764 | [
"keyword_pr_to_issue"
] | b90ab8baf507178853942e961450561475719f8e | d3d2dd20b9f6046cbb0a14fb4401da758556ab49 | [
"A fix for this issue has been included in [Bazel 6.4.0 RC2](https://releases.bazel.build/6.4.0/rc2/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-10-09T08:27:14Z" | [
"type: bug",
"team-Configurability",
"untriaged"
] | Unrecoverable error using bzlmod | ### Description of the bug:
While making rules_dotnet bzlmod compatible I encountered an Bazel crash:
```
FATAL: bazel crashed due to an internal error. Printing stack trace:
java.lang.RuntimeException: Unrecoverable error while evaluating node 'ConfiguredTargetKey{label=//dotnet/private/tests/warning_settings:csharp_treat_warnings_as_errors_config_test, config=BuildConfigurationKey[0cfe0dbd956d9b571c331623c346c60b3b866c9f5bcd256de36fa22c2b46c2b8]}' (requested by nodes )
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:633)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:365)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.scan(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: com.google.devtools.build.lib.cmdline.LabelSyntaxException: invalid repository name '@[unknown repo '' requested from @bazel_skylib~1.4.2]': repo names may contain only A-Z, a-z, 0-9, '-', '_', '.' and '~' and must not start with '~'
at com.google.devtools.build.lib.cmdline.Label.parseAbsoluteUnchecked(Label.java:240)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
at java.base/java.util.HashMap$KeySpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.collect(Unknown Source)
at com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.getRelevantStarlarkSettingsFromTransition(StarlarkTransition.java:393)
at com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.lambda$getAllStarlarkBuildSettings$0(StarlarkTransition.java:123)
at com.google.devtools.build.lib.analysis.starlark.StarlarkTransition$StarlarkTransitionVisitor.accept(StarlarkTransition.java:430)
at com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition.visit(ConfigurationTransition.java:101)
at com.google.devtools.build.lib.analysis.config.transitions.ComposingTransition.visit(ComposingTransition.java:99)
at com.google.devtools.build.lib.analysis.config.transitions.ComposingTransition.visit(ComposingTransition.java:99)
at com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.getAllStarlarkBuildSettings(StarlarkTransition.java:119)
at com.google.devtools.build.lib.analysis.config.ConfigurationResolver.getStarlarkBuildSettingsDetailsValue(ConfigurationResolver.java:407)
at com.google.devtools.build.lib.analysis.config.ConfigurationResolver.applyTransitionWithSkyframe(ConfigurationResolver.java:388)
at com.google.devtools.build.lib.analysis.config.ConfigurationResolver.resolveGenericTransition(ConfigurationResolver.java:233)
at com.google.devtools.build.lib.analysis.config.ConfigurationResolver.resolveConfiguration(ConfigurationResolver.java:192)
at com.google.devtools.build.lib.analysis.config.ConfigurationResolver.resolveConfigurations(ConfigurationResolver.java:151)
at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.computeDependencies(ConfiguredTargetFunction.java:869)
at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.compute(ConfiguredTargetFunction.java:371)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:562)
... 7 more
Caused by: com.google.devtools.build.lib.cmdline.LabelSyntaxException: invalid repository name '@[unknown repo '' requested from @bazel_skylib~1.4.2]': repo names may contain only A-Z, a-z, 0-9, '-', '_', '.' and '~' and must not start with '~'
at com.google.devtools.build.lib.cmdline.LabelParser.syntaxErrorf(LabelParser.java:208)
at com.google.devtools.build.lib.cmdline.RepositoryName.validate(RepositoryName.java:160)
at com.google.devtools.build.lib.cmdline.LabelParser$Parts.validateRepoName(LabelParser.java:180)
at com.google.devtools.build.lib.cmdline.LabelParser$Parts.validateAndCreate(LabelParser.java:72)
at com.google.devtools.build.lib.cmdline.LabelParser$Parts.parse(LabelParser.java:164)
at com.google.devtools.build.lib.cmdline.Label.parseCanonical(Label.java:123)
at com.google.devtools.build.lib.cmdline.Label.parseAbsoluteUnchecked(Label.java:238)
... 30 more
```
Reproduction is available at https://github.com/bazelbuild/rules_dotnet/pull/387 by running `bazel test //... --enable_bzlmod`
cc @fmeum
### Which category does this issue belong to?
_No response_
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
_No response_
### Which operating system are you running Bazel on?
Linux Fedora 38
### What is the output of `bazel info release`?
release 6.3.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/LabelBuildSettingTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java
index 19bb09104c6938..861504ed602906 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java
@@ -21,6 +21,7 @@
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition.Settings;
import com.google.devtools.build.lib.cmdline.BazelModuleContext;
import com.google.devtools.build.lib.cmdline.Label;
+import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigGlobalLibraryApi;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigurationTransitionApi;
import java.util.HashSet;
@@ -53,10 +54,10 @@ public ConfigurationTransitionApi transition(
StarlarkSemantics semantics = thread.getSemantics();
List<String> inputsList = Sequence.cast(inputs, String.class, "inputs");
List<String> outputsList = Sequence.cast(outputs, String.class, "outputs");
- validateBuildSettingKeys(inputsList, Settings.INPUTS);
- validateBuildSettingKeys(outputsList, Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
+ validateBuildSettingKeys(inputsList, Settings.INPUTS, moduleContext.packageContext());
+ validateBuildSettingKeys(outputsList, Settings.OUTPUTS, moduleContext.packageContext());
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newRegularTransition(
implementation,
@@ -76,15 +77,17 @@ public ConfigurationTransitionApi analysisTestTransition(
throws EvalException {
Map<String, Object> changedSettingsMap =
Dict.cast(changedSettings, String.class, Object.class, "changed_settings dict");
- validateBuildSettingKeys(changedSettingsMap.keySet(), Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
+ validateBuildSettingKeys(
+ changedSettingsMap.keySet(), Settings.OUTPUTS, moduleContext.packageContext());
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newAnalysisTestTransition(
changedSettingsMap, moduleContext.repoMapping(), moduleContext.label(), location);
}
- private void validateBuildSettingKeys(Iterable<String> optionKeys, Settings keyErrorDescriptor)
+ private void validateBuildSettingKeys(
+ Iterable<String> optionKeys, Settings keyErrorDescriptor, Label.PackageContext packageContext)
throws EvalException {
HashSet<String> processedOptions = Sets.newHashSet();
@@ -93,8 +96,16 @@ private void validateBuildSettingKeys(Iterable<String> optionKeys, Settings keyE
for (String optionKey : optionKeys) {
if (!optionKey.startsWith(COMMAND_LINE_OPTION_PREFIX)) {
try {
- Label.parseAbsoluteUnchecked(optionKey);
- } catch (IllegalArgumentException e) {
+ Label label = Label.parseWithRepoContext(optionKey, packageContext);
+ if (!label.getRepository().isVisible()) {
+ throw Starlark.errorf(
+ "invalid transition %s '%s': no repo visible as @%s from %s",
+ singularErrorDescriptor,
+ label,
+ label.getRepository().getName(),
+ label.getRepository().getOwnerRepoDisplayString());
+ }
+ } catch (LabelSyntaxException e) {
throw Starlark.errorf(
"invalid transition %s '%s'. If this is intended as a native option, "
+ "it must begin with //command_line_option: %s",
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/LabelBuildSettingTest.java b/src/test/java/com/google/devtools/build/lib/rules/LabelBuildSettingTest.java
index 24fcfd5962afa1..2b1caf109e6cca 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/LabelBuildSettingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/LabelBuildSettingTest.java
@@ -339,4 +339,48 @@ public void transitionOutput_otherRepo() throws Exception {
assertThat(getConfiguredTarget("//test:buildme")).isNotNull();
assertNoEvents();
}
+
+ @Test
+ public void testInvisibleRepoInLabelResultsInEarlyError() throws Exception {
+ setBuildLanguageOptions("--enable_bzlmod");
+
+ scratch.file("MODULE.bazel");
+ scratch.file(
+ "test/defs.bzl",
+ "def _setting_impl(ctx):",
+ " return []",
+ "string_flag = rule(",
+ " implementation = _setting_impl,",
+ " build_setting = config.string(flag=True),",
+ ")",
+ "def _transition_impl(settings, attr):",
+ " return {'//test:formation': 'mesa'}",
+ "formation_transition = transition(",
+ " implementation = _transition_impl,",
+ " inputs = ['@foobar//test:formation'],", // invalid repo name
+ " outputs = ['//test:formation'],",
+ ")",
+ "def _impl(ctx):",
+ " return []",
+ "state = rule(",
+ " implementation = _impl,",
+ " cfg = formation_transition,",
+ " attrs = {",
+ " '_allowlist_function_transition': attr.label(",
+ " default = '//tools/allowlists/function_transition_allowlist',",
+ " ),",
+ " })");
+ scratch.file(
+ "test/BUILD",
+ "load('//test:defs.bzl', 'state', 'string_flag')",
+ "state(name = 'arizona')",
+ "string_flag(name = 'formation', build_setting_default = 'canyon')");
+
+ reporter.removeHandler(failFastHandler);
+ getConfiguredTarget("//test:arizona");
+
+ assertContainsEvent(
+ "Error in transition: invalid transition input '@[unknown repo 'foobar' requested from @]"
+ + "//test:formation': no repo visible as @foobar from main repository");
+ }
}
| train | test | 2023-10-09T11:29:07 | "2023-09-26T11:07:09Z" | purkhusid | test |
bazelbuild/bazel/12986_19765 | bazelbuild/bazel | bazelbuild/bazel/12986 | bazelbuild/bazel/19765 | [
"keyword_pr_to_issue"
] | ddc3e5217d6ce211866caf75adee2b8222f396ba | b90ab8baf507178853942e961450561475719f8e | [
"I happened to do some debugging of this yesterday - the probematic call chain is that https://github.com/bazelbuild/bazel/blob/2910d3d860044ef5fb0989306bafebc1c5545e42/src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java#L104 ends up calling into https://github.com/bazelbuild/bazel/blob/2910d3d860044ef5fb0989306bafebc1c5545e42/src/main/native/unix_jni.cc#L1045-L1058\r\n\r\nIdeally we could use the raw buffer of bytes from the tar header to pass to `open`, rather than round-tripping via a String, but I'm not sure how to holistically go about that...",
"cc @tetromino This is a nice summary of the MacOS file handling strangeness I was talking about.",
"Addressing the unicode handling situation for strings (replacing latin-1 with utf-8) is on the schedule for this year, perhaps in Q2.",
"hi! Here is [a victim](https://github.com/envoyproxy/envoy/issues/16065) of this bug (I'm using Ubuntu 20.04 with ZFS and, seems like, it was set up with an `utf8only` flag, according to the original description). \r\nI tried to investigate the problem yesterday and copy some parts of Bazel's `CompressedTarFunction.java` to a small snippet. And, probably, I've found a workaround for this issue with just replacing `filePath.getOutputStream()` to `new FileOutputStream(filePath.getPathFile())`\r\nSo this code works for me https://gist.github.com/QIvan/bf88d152c31a35eccf162845ce05c455",
"@QIvan per my understanding this breaks other cases in which an archive contains a filename as a string of non-UTF-8 compatible bytes and the destination filesystem will accept it. #7757 has more context.",
"Update: We haven't had bandwidth to work on eliminating the latin-1 hack, but may reconsider after 2023 Q1.",
"I started a playground to observe some actual behaviors. We'll need to know how macos behaves when it sees NFC style names.\r\nhttps://github.com/aiuto/bazel_samples/tree/main/utf8",
"A fix for this issue has been included in [Bazel 6.4.0 RC2](https://releases.bazel.build/6.4.0/rc2/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-10-09T09:02:46Z" | [
"type: bug",
"P4",
"platform: apple",
"help wanted",
"team-Starlark-Integration"
] | Repo rules fail to extract unicode archives due to latin-1 hack | ### Description of the problem / feature request:
`rules_go` currently [fails on some machines](https://github.com/bazelbuild/rules_go/issues/2771) due to some [unicode characters](https://github.com/golang/go/tree/master/test/fixedbugs/issue27836.dir) included in filenames within the Go source archive - specifically the character [Ä](https://www.compart.com/en/unicode/U+00C4). For Linux and macOS, Go archives are distributed as [`tar.gz`](https://golang.org/dl/) files with [pax headers](https://en.wikipedia.org/wiki/Tar_(computing)#POSIX.1-2001/pax) in the tar files.
Affected systems include:
* ZFS volumes with the `utf8only` option. This is Ubuntu's default when choosing ZFS at install time.
* macOS (HFS+ and APFS require UTF-8 filenames)
Bazel uses Apache Commons Compress to extract tar archives. For most tar files, Commons Compress defers to the encoding specified by the JVM's `-Dfile.encoding` param, or the platform default. With ISO-8859-1 - Bazel's preference - UTF-8 encoded filename bytes in tar files basically pass through verbatim when extracted and everything works.
But when the tar entry has a pax `path` header, the path name is [always decoded as UTF-8](https://github.com/apache/commons-compress/blob/rel/1.19/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java#L516-L517).
The character Ä in its [composed](https://en.wikipedia.org/wiki/Unicode_equivalence) form is unicode character `U+00C4`. In Java's internal UTF-16, it's simply represented as `0xC4`. But encoded as UTF-8 it becomes the multi-byte sequence `0xC3 0x84` since `0xC4` as a single byte is not a valid UTF-8 value.
When Commons Compress parses a pax-formatted tar file with a filename containing Ä as the `0xC3 0x84` UTF-8 string, the resulting Java string contains the value `0xC4` after decoding. But this value is never re-encoded as UTF-8 when creating the file on the filesystem. Instead, Bazel uses the Java char values [verbatim as long as they're < 0xff](https://github.com/bazelbuild/bazel/blob/master/src/main/native/latin1_jni_path.cc#L84). An attempt to create a filename containing `0xC4` on a filesystem that requires UTF-8 filenames will fail.
But `rules_go` doesn't currently fail on macOS systems despite them also requiring UTF-8 filenames. This is because the `darwin` archives use decomposed representations of unicode characters. OS X has a history of preferring the decomposed forms over composed.
So instead of Ä being `U+00C4` ("Latin Capital Letter A with Diaeresis"), it's `U+0041` (just capital A) followed by `U+0308` ("Combining Diaeresis"). Encoded in UTF-8 as seen in the macOS golang tarballs, the byte string is `0x41 0xCC 0x88`. Decoded to a Java string (16-bit chars) it's `0x0041 0x0308`. Coincidentally I presume, Bazel is able to extract this decomposed form on UTF-8 filesystems because it [ignores](https://github.com/bazelbuild/bazel/blob/master/src/main/native/latin1_jni_path.cc#L84) the diaeresis and replaces it with a literal `'?'` character. So instead of `Äfoo.go` as is contained in the Go source archive, Bazel writes `A?foo.go` on macOS.
Like Linux on ZFS, Bazel fails to extract the linux archive on macOS as reported [here](https://github.com/bazelbuild/rules_go/issues/2773).
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
`test.bzl`
```python
def _tar_round_trip_impl(ctx):
ctx.file("Äfoo.txt", "boo!\n")
ctx.execute(["tar", "--format=" + ctx.attr.format, "-czvf", "file.tar.gz", "Äfoo.txt"])
ctx.extract("file.tar.gz", "out")
ctx.file("BUILD.bazel", 'exports_files(["Äfoo.txt", "out/Äfoo.txt", "file.tar.gz"])', legacy_utf8=False)
tar_round_trip = repository_rule(
implementation = _tar_round_trip_impl,
attrs = {
"format": attr.string(
mandatory = True,
),
},
)
```
`WORKSPACE`
```python
load("//:test.bzl", "tar_round_trip")
tar_round_trip(
name = "non_pax",
format = "ustar", # supported by both macos BSD tar and linux GNU tar
)
tar_round_trip(
name = "pax",
format = "pax",
)
```
`BUILD`
```python
genrule(
name = "non_pax_test",
srcs = ["@non_pax//:out/Äfoo.txt"],
outs = ["non_pax.txt"],
cmd = """
cp $(location @non_pax//:out/Äfoo.txt) "$@"
""",
)
genrule(
name = "pax_test",
srcs = ["@pax//:out/Äfoo.txt"],
outs = ["pax.txt"],
cmd = """
cp $(location @pax//:out/Äfoo.txt) "$@"
""",
)
```
```shell
# Works
bazel build //:non_pax_test
# Fails, either due to not being able to write the file (utf8 filesystem),
# or because the written filename is mangled.
bazel build //:pax_test
```
### What operating system are you running Bazel on?
Mac OS 10.15.7
Ubuntu 20.04 with a ZFS root partition with `utf8only` enabled (the default for Ubuntu's ZFS support).
### What's the output of `bazel info release`?
`release 4.0.0`
### Have you found anything relevant by searching the web?
https://github.com/bazelbuild/rules_go/issues/2771
https://github.com/bazelbuild/bazel/issues/374 - pretty generic issue regarding filename characters.
https://github.com/bazelbuild/bazel/issues/7055 - an issue with the same problematic file in the Go archive, but targeted at Darwin only. | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD",
"src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java",
"src/test/shell/bazel/bazel_workspaces_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD b/src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD
index 32f958012df068..fdffb6a517709d 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/BUILD
@@ -49,6 +49,7 @@ java_library(
"//src/main/java/com/google/devtools/common/options",
"//src/main/java/net/starlark/java/eval",
"//third_party:apache_commons_compress",
+ "//third_party:auto_service",
"//third_party:auto_value",
"//third_party:flogger",
"//third_party:guava",
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java
index f38e7d56894ac2..c32a423940e0a1 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/CompressedTarFunction.java
@@ -15,8 +15,10 @@
package com.google.devtools.build.lib.bazel.repository;
import static com.google.devtools.build.lib.bazel.repository.StripPrefixedPath.maybeDeprefixSymlink;
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+import static java.nio.charset.StandardCharsets.UTF_8;
-import com.google.common.base.Optional;
+import com.google.auto.service.AutoService;
import com.google.common.io.ByteStreams;
import com.google.devtools.build.lib.bazel.repository.DecompressorValue.Decompressor;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
@@ -25,16 +27,33 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.spi.CharsetProvider;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
+import java.util.UUID;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
/**
* Common code for unarchiving a compressed TAR file.
+ *
+ * <p>TAR file entries commonly use one of two formats: PAX, which uses UTF-8 encoding for all
+ * strings, and USTAR, which does not specify an encoding. This class interprets USTAR headers as
+ * latin-1, thus preserving the original bytes of the header without enforcing any particular
+ * encoding. Internally, for file system operations, all strings are converted into Bazel's internal
+ * representation of raw bytes stored as latin-1 strings.
*/
public abstract class CompressedTarFunction implements Decompressor {
protected abstract InputStream getDecompressorStream(DecompressorDescriptor descriptor)
@@ -54,20 +73,23 @@ public Path decompress(DecompressorDescriptor descriptor)
Map<Path, PathFragment> symlinks = new HashMap<>();
try (InputStream decompressorStream = getDecompressorStream(descriptor)) {
- TarArchiveInputStream tarStream = new TarArchiveInputStream(decompressorStream);
+ // USTAR tar headers use an unspecified encoding whereas PAX tar headers always use UTF-8.
+ // We can specify the encoding to use for USTAR headers, but the Charset used for PAX headers
+ // is fixed to UTF-8. We thus specify a custom Charset for the former so that we can
+ // distinguish between the two.
+ TarArchiveInputStream tarStream =
+ new TarArchiveInputStream(decompressorStream, MarkedIso88591Charset.NAME);
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
- String entryName = entry.getName();
+ String entryName = toRawBytesString(entry.getName());
entryName = renameFiles.getOrDefault(entryName, entryName);
- StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entryName, prefix);
+ StripPrefixedPath entryPath =
+ StripPrefixedPath.maybeDeprefix(entryName.getBytes(ISO_8859_1), prefix);
foundPrefix = foundPrefix || entryPath.foundPrefix();
if (prefix.isPresent() && !foundPrefix) {
- Optional<String> suggestion =
- CouldNotFindPrefixException.maybeMakePrefixSuggestion(entryPath.getPathFragment());
- if (suggestion.isPresent()) {
- availablePrefixes.add(suggestion.get());
- }
+ CouldNotFindPrefixException.maybeMakePrefixSuggestion(entryPath.getPathFragment())
+ .ifPresent(availablePrefixes::add);
}
if (entryPath.skip()) {
@@ -80,8 +102,11 @@ public Path decompress(DecompressorDescriptor descriptor)
filePath.createDirectoryAndParents();
} else {
if (entry.isSymbolicLink() || entry.isLink()) {
- PathFragment targetName = PathFragment.create(entry.getLinkName());
- targetName = maybeDeprefixSymlink(targetName, prefix, descriptor.destinationPath());
+ PathFragment targetName =
+ maybeDeprefixSymlink(
+ toRawBytesString(entry.getLinkName()).getBytes(ISO_8859_1),
+ prefix,
+ descriptor.destinationPath());
if (entry.isSymbolicLink()) {
symlinks.put(filePath, targetName);
} else {
@@ -135,4 +160,100 @@ public Path decompress(DecompressorDescriptor descriptor)
return descriptor.destinationPath();
}
+
+ /**
+ * Returns a string that contains the raw bytes of the given string encoded in ISO-8859-1,
+ * assuming that the given string was encoded with either UTF-8 or the special {@link
+ * MarkedIso88591Charset}.
+ */
+ private static String toRawBytesString(String name) {
+ // Marked strings are already encoded in ISO-8859-1. Other strings originate from PAX headers
+ // and are thus encoded in UTF-8, which we decode to the raw bytes and then re-encode trivially
+ // in ISO-8859-1.
+ return MarkedIso88591Charset.getRawBytesStringIfMarked(name)
+ .orElseGet(() -> new String(name.getBytes(UTF_8), ISO_8859_1));
+ }
+
+ /** A provider of {@link MarkedIso88591Charset}s. */
+ @AutoService(CharsetProvider.class)
+ public static class MarkedIso88591CharsetProvider extends CharsetProvider {
+ private static final Charset CHARSET = new MarkedIso88591Charset();
+
+ @Override
+ public Iterator<Charset> charsets() {
+ // This charset is only meant for internal use within CompressedTarFunction and thus should
+ // not be discoverable.
+ return Collections.emptyIterator();
+ }
+
+ @Override
+ public Charset charsetForName(String charsetName) {
+ return MarkedIso88591Charset.NAME.equals(charsetName) ? CHARSET : null;
+ }
+ }
+
+ /**
+ * A charset that decodes ISO-8859-1, i.e., produces a String that contains the raw decoded bytes,
+ * and appends a marker to the end of the string to indicate that it was decoded with this
+ * charset.
+ */
+ private static class MarkedIso88591Charset extends Charset {
+ // The name
+ // * must not collide with the name of any other charset.
+ // * must not appear in archive entry names by chance.
+ // * is internal to CompressedTarFunction.
+ // This is best served by a cryptographically random UUID, generated at startup.
+ private static final String NAME = UUID.randomUUID().toString();
+
+ private MarkedIso88591Charset() {
+ super(NAME, new String[0]);
+ }
+
+ public static Optional<String> getRawBytesStringIfMarked(String s) {
+ // Check for the marker in all positions as TarArchiveInputStream manipulates the raw name in
+ // certain cases (for example, appending a '/' to directory names).
+ if (s.contains(NAME)) {
+ return Optional.of(s.replaceAll(NAME, ""));
+ }
+ return Optional.empty();
+ }
+
+ @Override
+ public CharsetDecoder newDecoder() {
+ return new CharsetDecoder(this, 1, 1) {
+ @Override
+ protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
+ // A simple unoptimized ISO-8859-1 decoder.
+ while (in.hasRemaining()) {
+ if (!out.hasRemaining()) {
+ return CoderResult.OVERFLOW;
+ }
+ out.put((char) (in.get() & 0xFF));
+ }
+ return CoderResult.UNDERFLOW;
+ }
+
+ @Override
+ protected CoderResult implFlush(CharBuffer out) {
+ // Append the marker to the end of the buffer to indicate that it was decoded with this
+ // charset.
+ if (out.remaining() < NAME.length()) {
+ return CoderResult.OVERFLOW;
+ }
+ out.put(NAME);
+ return CoderResult.UNDERFLOW;
+ }
+ };
+ }
+
+ @Override
+ public CharsetEncoder newEncoder() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean contains(Charset cs) {
+ return false;
+ }
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java
index 2676fdba14d091..c40d5ab35f38da 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorDescriptor.java
@@ -15,10 +15,10 @@
package com.google.devtools.build.lib.bazel.repository;
import com.google.auto.value.AutoValue;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.vfs.Path;
import java.util.Map;
+import java.util.Optional;
/** Description of an archive to be decompressed. */
@AutoValue
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java
index 82e3dcf747f21b..02cab611ae162e 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/DecompressorValue.java
@@ -14,14 +14,17 @@
package com.google.devtools.build.lib.bazel.repository;
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import com.google.devtools.build.skyframe.SkyValue;
import java.io.IOException;
+import java.util.Optional;
import java.util.Set;
import net.starlark.java.eval.Starlark;
@@ -59,9 +62,14 @@ private static String prepareErrorMessage(String prefix, Set<String> availablePr
}
public static Optional<String> maybeMakePrefixSuggestion(PathFragment pathFragment) {
- return pathFragment.isMultiSegment()
- ? Optional.of(pathFragment.getSegment(0))
- : Optional.absent();
+ if (!pathFragment.isMultiSegment()) {
+ return Optional.empty();
+ }
+ String rawFirstSegment = pathFragment.getSegment(0);
+ // Users can only specify prefixes from Starlark, which is planned to use UTF-8 for all
+ // strings, but currently still collects the raw bytes in a latin-1 string. We thus
+ // optimistically decode the raw bytes with UTF-8 here for display purposes.
+ return Optional.of(new String(rawFirstSegment.getBytes(ISO_8859_1), UTF_8));
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java
index 77c5815e79a50d..5852b4d0ea5303 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPath.java
@@ -14,11 +14,13 @@
package com.google.devtools.build.lib.bazel.repository;
-import com.google.common.base.Optional;
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.concurrent.ThreadSafety;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
+import java.util.Optional;
/**
* Utility class for removing a prefix from an archive's path.
@@ -36,17 +38,19 @@ public final class StripPrefixedPath {
* could cause collisions, if a zip file had one entry for bin/some-binary and another entry for
* /bin/some-binary.
*
- * Note that the prefix is stripped to move the files up one level, so if you have an entry
+ * <p>Note that the prefix is stripped to move the files up one level, so if you have an entry
* "foo/../bar" and a prefix of "foo", the result will be "bar" not "../bar".
*/
- public static StripPrefixedPath maybeDeprefix(String entry, Optional<String> prefix) {
+ public static StripPrefixedPath maybeDeprefix(byte[] entry, Optional<String> prefix) {
Preconditions.checkNotNull(entry);
PathFragment entryPath = relativize(entry);
- if (!prefix.isPresent()) {
+ if (prefix.isEmpty()) {
return new StripPrefixedPath(entryPath, false, false);
}
- PathFragment prefixPath = relativize(prefix.get());
+ // Bazel parses Starlark files, which are the ultimate source of prefixes, as Latin-1
+ // (ISO-8859-1).
+ PathFragment prefixPath = relativize(prefix.get().getBytes(ISO_8859_1));
boolean found = false;
boolean skip = false;
if (entryPath.startsWith(prefixPath)) {
@@ -64,8 +68,8 @@ public static StripPrefixedPath maybeDeprefix(String entry, Optional<String> pre
/**
* Normalize the path and, if it is absolute, make it relative (e.g., /foo/bar becomes foo/bar).
*/
- private static PathFragment relativize(String path) {
- PathFragment entryPath = PathFragment.create(path);
+ private static PathFragment relativize(byte[] path) {
+ PathFragment entryPath = createPathFragment(path);
if (entryPath.isAbsolute()) {
entryPath = entryPath.toRelative();
}
@@ -79,10 +83,10 @@ private StripPrefixedPath(PathFragment pathFragment, boolean found, boolean skip
}
public static PathFragment maybeDeprefixSymlink(
- PathFragment linkPathFragment, Optional<String> prefix, Path root) {
- boolean wasAbsolute = linkPathFragment.isAbsolute();
+ byte[] rawTarget, Optional<String> prefix, Path root) {
+ boolean wasAbsolute = createPathFragment(rawTarget).isAbsolute();
// Strip the prefix from the link path if set.
- linkPathFragment = maybeDeprefix(linkPathFragment.getPathString(), prefix).getPathFragment();
+ PathFragment linkPathFragment = maybeDeprefix(rawTarget, prefix).getPathFragment();
if (wasAbsolute) {
// Recover the path to an absolute path as maybeDeprefix() relativize the path
// even if the prefix is not set
@@ -103,4 +107,10 @@ public boolean skip() {
return skip;
}
+ static PathFragment createPathFragment(byte[] rawBytes) {
+ // Bazel internally represents paths as raw bytes by using the Latin-1 encoding, which has the
+ // property that (new String(bytes, ISO_8859_1)).getBytes(ISO_8859_1)) equals bytes for every
+ // byte array bytes.
+ return PathFragment.create(new String(rawBytes, ISO_8859_1));
+ }
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java
index 8990e7c4c08e64..4a8f7709a5798b 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/ZipDecompressor.java
@@ -15,9 +15,9 @@
package com.google.devtools.build.lib.bazel.repository;
import static com.google.devtools.build.lib.bazel.repository.StripPrefixedPath.maybeDeprefixSymlink;
+import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import com.google.devtools.build.lib.bazel.repository.DecompressorValue.Decompressor;
@@ -29,11 +29,11 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
@@ -89,7 +89,8 @@ public Path decompress(DecompressorDescriptor descriptor)
for (ZipFileEntry entry : entries) {
String entryName = entry.getName();
entryName = renameFiles.getOrDefault(entryName, entryName);
- StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entryName, prefix);
+ StripPrefixedPath entryPath =
+ StripPrefixedPath.maybeDeprefix(entryName.getBytes(UTF_8), prefix);
foundPrefix = foundPrefix || entryPath.foundPrefix();
if (entryPath.skip()) {
continue;
@@ -102,12 +103,9 @@ public Path decompress(DecompressorDescriptor descriptor)
Set<String> prefixes = new HashSet<>();
for (ZipFileEntry entry : entries) {
StripPrefixedPath entryPath =
- StripPrefixedPath.maybeDeprefix(entry.getName(), Optional.absent());
- Optional<String> suggestion =
- CouldNotFindPrefixException.maybeMakePrefixSuggestion(entryPath.getPathFragment());
- if (suggestion.isPresent()) {
- prefixes.add(suggestion.get());
- }
+ StripPrefixedPath.maybeDeprefix(entry.getName().getBytes(UTF_8), Optional.empty());
+ CouldNotFindPrefixException.maybeMakePrefixSuggestion(entryPath.getPathFragment())
+ .ifPresent(prefixes::add);
}
throw new CouldNotFindPrefixException(prefix.get(), prefixes);
}
@@ -146,17 +144,22 @@ private static void extractZipEntry(
// For symlinks, the "compressed data" is actually the target name.
int read = reader.getInputStream(entry).read(buffer);
Preconditions.checkState(read == buffer.length);
- PathFragment target = PathFragment.create(new String(buffer, Charset.defaultCharset()));
+
+ PathFragment target = StripPrefixedPath.createPathFragment(buffer);
if (target.containsUplevelReferences()) {
PathFragment pointsTo = strippedRelativePath.getParentDirectory().getRelative(target);
if (pointsTo.containsUplevelReferences()) {
- throw new IOException("Zip entries cannot refer to files outside of their directory: "
- + reader.getFilename() + " has a symlink " + strippedRelativePath + " pointing to "
- + target);
+ throw new IOException(
+ "Zip entries cannot refer to files outside of their directory: "
+ + reader.getFilename()
+ + " has a symlink "
+ + strippedRelativePath
+ + " pointing to "
+ + new String(buffer, UTF_8));
}
}
- target = maybeDeprefixSymlink(target, prefix, destinationDirectory);
- symlinks.put(outputPath, target);
+
+ symlinks.put(outputPath, maybeDeprefixSymlink(buffer, prefix, destinationDirectory));
} else {
try (InputStream input = reader.getInputStream(entry);
OutputStream output = outputPath.getOutputStream()) {
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
index df1ea4db0fb19f..784b16348e0580 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
@@ -15,13 +15,14 @@
package com.google.devtools.build.lib.bazel.repository;
import static com.google.common.truth.Truth.assertThat;
+import static java.nio.charset.StandardCharsets.UTF_8;
-import com.google.common.base.Optional;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
+import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -33,31 +34,32 @@
public class StripPrefixedPathTest {
@Test
public void testStrip() {
- StripPrefixedPath result = StripPrefixedPath.maybeDeprefix("foo/bar", Optional.of("foo"));
+ StripPrefixedPath result =
+ StripPrefixedPath.maybeDeprefix("foo/bar".getBytes(UTF_8), Optional.of("foo"));
assertThat(PathFragment.create("bar")).isEqualTo(result.getPathFragment());
assertThat(result.foundPrefix()).isTrue();
assertThat(result.skip()).isFalse();
- result = StripPrefixedPath.maybeDeprefix("foo", Optional.of("foo"));
+ result = StripPrefixedPath.maybeDeprefix("foo".getBytes(UTF_8), Optional.of("foo"));
assertThat(result.skip()).isTrue();
- result = StripPrefixedPath.maybeDeprefix("bar/baz", Optional.of("foo"));
+ result = StripPrefixedPath.maybeDeprefix("bar/baz".getBytes(UTF_8), Optional.of("foo"));
assertThat(result.foundPrefix()).isFalse();
- result = StripPrefixedPath.maybeDeprefix("foof/bar", Optional.of("foo"));
+ result = StripPrefixedPath.maybeDeprefix("foof/bar".getBytes(UTF_8), Optional.of("foo"));
assertThat(result.foundPrefix()).isFalse();
}
@Test
public void testAbsolute() {
- StripPrefixedPath result = StripPrefixedPath.maybeDeprefix(
- "/foo/bar", Optional.<String>absent());
+ StripPrefixedPath result =
+ StripPrefixedPath.maybeDeprefix("/foo/bar".getBytes(UTF_8), Optional.empty());
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar"));
- result = StripPrefixedPath.maybeDeprefix("///foo/bar/baz", Optional.<String>absent());
+ result = StripPrefixedPath.maybeDeprefix("///foo/bar/baz".getBytes(UTF_8), Optional.empty());
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar/baz"));
- result = StripPrefixedPath.maybeDeprefix("/foo/bar/baz", Optional.of("/foo"));
+ result = StripPrefixedPath.maybeDeprefix("/foo/bar/baz".getBytes(UTF_8), Optional.of("/foo"));
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("bar/baz"));
}
@@ -66,21 +68,21 @@ public void testWindowsAbsolute() {
if (OS.getCurrent() != OS.WINDOWS) {
return;
}
- StripPrefixedPath result = StripPrefixedPath.maybeDeprefix(
- "c:/foo/bar", Optional.<String>absent());
+ StripPrefixedPath result =
+ StripPrefixedPath.maybeDeprefix("c:/foo/bar".getBytes(UTF_8), Optional.empty());
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar"));
}
@Test
public void testNormalize() {
- StripPrefixedPath result = StripPrefixedPath.maybeDeprefix(
- "../bar", Optional.<String>absent());
+ StripPrefixedPath result =
+ StripPrefixedPath.maybeDeprefix("../bar".getBytes(UTF_8), Optional.empty());
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("../bar"));
- result = StripPrefixedPath.maybeDeprefix("foo/../baz", Optional.<String>absent());
+ result = StripPrefixedPath.maybeDeprefix("foo/../baz".getBytes(UTF_8), Optional.empty());
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("baz"));
- result = StripPrefixedPath.maybeDeprefix("foo/../baz", Optional.of("foo"));
+ result = StripPrefixedPath.maybeDeprefix("foo/../baz".getBytes(UTF_8), Optional.of("foo"));
assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("baz"));
}
@@ -91,23 +93,23 @@ public void testDeprefixSymlink() {
PathFragment relativeNoPrefix =
StripPrefixedPath.maybeDeprefixSymlink(
- PathFragment.create("a/b"), Optional.absent(), fileSystem.getPath("/usr"));
+ "a/b".getBytes(UTF_8), Optional.empty(), fileSystem.getPath("/usr"));
// there is no attempt to get absolute path for the relative symlinks target path
assertThat(relativeNoPrefix).isEqualTo(PathFragment.create("a/b"));
PathFragment absoluteNoPrefix =
StripPrefixedPath.maybeDeprefixSymlink(
- PathFragment.create("/a/b"), Optional.absent(), fileSystem.getPath("/usr"));
+ "/a/b".getBytes(UTF_8), Optional.empty(), fileSystem.getPath("/usr"));
assertThat(absoluteNoPrefix).isEqualTo(PathFragment.create("/usr/a/b"));
PathFragment absolutePrefix =
StripPrefixedPath.maybeDeprefixSymlink(
- PathFragment.create("/root/a/b"), Optional.of("root"), fileSystem.getPath("/usr"));
+ "/root/a/b".getBytes(UTF_8), Optional.of("root"), fileSystem.getPath("/usr"));
assertThat(absolutePrefix).isEqualTo(PathFragment.create("/usr/a/b"));
PathFragment relativePrefix =
StripPrefixedPath.maybeDeprefixSymlink(
- PathFragment.create("root/a/b"), Optional.of("root"), fileSystem.getPath("/usr"));
+ "root/a/b".getBytes(UTF_8), Optional.of("root"), fileSystem.getPath("/usr"));
// there is no attempt to get absolute path for the relative symlinks target path
assertThat(relativePrefix).isEqualTo(PathFragment.create("a/b"));
}
diff --git a/src/test/shell/bazel/bazel_workspaces_test.sh b/src/test/shell/bazel/bazel_workspaces_test.sh
index a0669133572c25..df185e7f2cb326 100755
--- a/src/test/shell/bazel/bazel_workspaces_test.sh
+++ b/src/test/shell/bazel/bazel_workspaces_test.sh
@@ -449,6 +449,102 @@ function test_extract_rename_files() {
ensure_output_contains_exactly_once "external/repo/out_dir/renamed-A.txt" "Second file: A"
}
+# Regression test for https://github.com/bazelbuild/bazel/issues/12986
+# Verifies that tar entries with PAX headers, which are always encoded in UTF-8, are extracted
+# correctly.
+function test_extract_pax_tar_non_ascii_utf8_file_names() {
+ local archive_tar="${TEST_TMPDIR}/pax.tar"
+
+ pushd "${TEST_TMPDIR}"
+ mkdir "Ä_pax_∅"
+ echo "bar" > "Ä_pax_∅/Ä_foo_∅.txt"
+ tar --format=pax -cvf pax.tar "Ä_pax_∅"
+ popd
+
+ set_workspace_command "
+ repository_ctx.extract('${archive_tar}', 'out_dir', 'Ä_pax_∅/')"
+
+ build_and_process_log --exclude_rule "repository @local_config_cc"
+
+ ensure_contains_exactly 'location: .*repos.bzl:3:25' 1
+ ensure_contains_atleast 'context: "repository @repo"' 2
+ ensure_contains_exactly 'extract_event' 1
+
+ ensure_output_contains_exactly_once "external/repo/out_dir/Ä_foo_∅.txt" "bar"
+}
+
+# Verifies that tar entries with USTAR headers, for which an encoding isn't specified, are extracted
+# correctly if that encoding happens to be UTF-8.
+function test_extract_ustar_tar_non_ascii_utf8_file_names() {
+ local archive_tar="${TEST_TMPDIR}/ustar.tar"
+
+ pushd "${TEST_TMPDIR}"
+ mkdir "Ä_ustar_∅"
+ echo "bar" > "Ä_ustar_∅/Ä_foo_∅.txt"
+ tar --format=ustar -cvf ustar.tar "Ä_ustar_∅"
+ popd
+
+ set_workspace_command "
+ repository_ctx.extract('${archive_tar}', 'out_dir', 'Ä_ustar_∅/')"
+
+ build_and_process_log --exclude_rule "repository @local_config_cc"
+
+ ensure_contains_exactly 'location: .*repos.bzl:3:25' 1
+ ensure_contains_atleast 'context: "repository @repo"' 2
+ ensure_contains_exactly 'extract_event' 1
+
+ ensure_output_contains_exactly_once "external/repo/out_dir/Ä_foo_∅.txt" "bar"
+}
+
+# Verifies that tar entries with USTAR headers, for which an encoding isn't specified, are extracted
+# correctly if that encoding is not UTF-8.
+function test_extract_ustar_tar_non_ascii_non_utf8_file_names() {
+ if is_darwin; then
+ echo "Skipping test on macOS due to lack of support for non-UTF-8 filenames"
+ return
+ fi
+
+ local archive_tar="${TEST_TMPDIR}/ustar.tar"
+
+ pushd "${TEST_TMPDIR}"
+ mkdir "Ä_ustar_latin1_∅"
+ echo "bar" > "$(echo -e 'Ä_ustar_latin1_∅/\xC4_foo_latin1_\xD6.txt')"
+ tar --format=ustar -cvf ustar.tar "Ä_ustar_latin1_∅"
+ popd
+
+ set_workspace_command "
+ repository_ctx.extract('${archive_tar}', 'out_dir', 'Ä_ustar_latin1_∅/')"
+
+ build_and_process_log --exclude_rule "repository @local_config_cc"
+
+ ensure_contains_exactly 'location: .*repos.bzl:3:25' 1
+ ensure_contains_atleast 'context: "repository @repo"' 2
+ ensure_contains_exactly 'extract_event' 1
+
+ ensure_output_contains_exactly_once "$(echo -e 'external/repo/out_dir/\xC4_foo_latin1_\xD6.txt')" "bar"
+}
+
+function test_extract_default_zip_non_ascii_utf8_file_names() {
+ local archive_tar="${TEST_TMPDIR}/default.zip"
+
+ pushd "${TEST_TMPDIR}"
+ mkdir "Ä_default_∅"
+ echo "bar" > "Ä_default_∅/Ä_foo_∅.txt"
+ zip default.zip -r "Ä_default_∅"
+ popd
+
+ set_workspace_command "
+ repository_ctx.extract('${archive_tar}', 'out_dir', 'Ä_default_∅/')"
+
+ build_and_process_log --exclude_rule "repository @local_config_cc"
+
+ ensure_contains_exactly 'location: .*repos.bzl:3:25' 1
+ ensure_contains_atleast 'context: "repository @repo"' 2
+ ensure_contains_exactly 'extract_event' 1
+
+ ensure_output_contains_exactly_once "external/repo/out_dir/Ä_foo_∅.txt" "bar"
+}
+
function test_file() {
set_workspace_command 'repository_ctx.file("filefile.sh", "echo filefile", True)'
| train | test | 2023-10-06T18:32:16 | "2021-02-10T06:41:05Z" | jvolkman | test |
bazelbuild/bazel/19244_19827 | bazelbuild/bazel | bazelbuild/bazel/19244 | bazelbuild/bazel/19827 | [
"keyword_pr_to_issue"
] | ceb4f2dd29ad7c8d8d921d20697a77ec04072e3c | ddeea51a96143528802ae172a295be3563101aa6 | [
"Before 6.3.2 this was not an error; Bazel would silently consume the duplicate env variables. 6.3.2 made this a failure mode which presents itself in an not so user friendly manner.",
"A fix for this issue has been included in [Bazel 6.4.0 RC4](https://releases.bazel.build/6.4.0/rc4/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-10-16T13:21:25Z" | [
"type: feature request",
"team-ExternalDeps"
] | Graceful failure on duplicate environ keys in repository_rules | ### Description of the feature request:
https://github.com/bazelbuild/bazel/commit/9cd182e446f9f334930091540a58e131a9d58540#diff-5652706121f964f38ee7253331b650d61975116b50127fece8f2d30882003b61 introduces checking of duplicate keys in the environment. This fails with a stack trace if duplicates exist in the definition e.g. with `PATH` duplicated in environ I see the following backtrace:
```
(15:06:19) FATAL: bazel crashed due to an internal error. Printing stack trace:
java.lang.RuntimeException: Unrecoverable error while evaluating node 'REPOSITORY_DIRECTORY:@zenotech_cc_toolchain' (requested by nodes 'IGNORED_PACKAGE_PREFIXES:@zenotech_cc_toolchain')
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:633)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:365)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.scan(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Multiple entries with same key: PATH=/home/james.sharpe/.nvm/versions/node/v18.16.0/bin:/home/james.sharpe/.local/bin:/opt/intel/oneapi/vtune/2022.0.0/bin64:/opt/intel/oneapi/vpl/2022.0.0/bin:/opt/intel/oneapi/mpi/2021.5.0//libfabric/bin:/opt/intel/oneapi/mpi/2021.5.0//bin:/opt/intel/oneapi/mkl/2022.0.1/bin/intel64:/opt/intel/oneapi/itac/2021.5.0/bin:/opt/intel/oneapi/intelpython/latest/bin:/opt/intel/oneapi/intelpython/latest/condabin:/opt/intel/oneapi/inspector/2022.0.0/bin64:/opt/intel/oneapi/dev-utilities/2021.5.1/bin:/opt/intel/oneapi/debugger/2021.5.0/gdb/intel64/bin:/opt/intel/oneapi/compiler/2022.0.1/linux/lib/oclfpga/bin:/opt/intel/oneapi/compiler/2022.0.1/linux/bin/intel64:/opt/intel/oneapi/compiler/2022.0.1/linux/bin:/opt/intel/oneapi/clck/2021.5.0/bin/intel64:/opt/intel/oneapi/advisor/2022.0.0/bin64:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/cuda/bin and PATH=/home/james.sharpe/.nvm/versions/node/v18.16.0/bin:/home/james.sharpe/.local/bin:/opt/intel/oneapi/vtune/2022.0.0/bin64:/opt/intel/oneapi/vpl/2022.0.0/bin:/opt/intel/oneapi/mpi/2021.5.0//libfabric/bin:/opt/intel/oneapi/mpi/2021.5.0//bin:/opt/intel/oneapi/mkl/2022.0.1/bin/intel64:/opt/intel/oneapi/itac/2021.5.0/bin:/opt/intel/oneapi/intelpython/latest/bin:/opt/intel/oneapi/intelpython/latest/condabin:/opt/intel/oneapi/inspector/2022.0.0/bin64:/opt/intel/oneapi/dev-utilities/2021.5.1/bin:/opt/intel/oneapi/debugger/2021.5.0/gdb/intel64/bin:/opt/intel/oneapi/compiler/2022.0.1/linux/lib/oclfpga/bin:/opt/intel/oneapi/compiler/2022.0.1/linux/bin/intel64:/opt/intel/oneapi/compiler/2022.0.1/linux/bin:/opt/intel/oneapi/clck/2021.5.0/bin/intel64:/opt/intel/oneapi/advisor/2022.0.0/bin64:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/cuda/bin
at com.google.common.collect.ImmutableMap.conflictException(ImmutableMap.java:377)
at com.google.common.collect.ImmutableMap.checkNoConflict(ImmutableMap.java:371)
at com.google.common.collect.RegularImmutableMap.checkNoConflictInKeyBucket(RegularImmutableMap.java:241)
at com.google.common.collect.RegularImmutableMap.fromEntryArrayCheckingBucketOverflow(RegularImmutableMap.java:132)
at com.google.common.collect.RegularImmutableMap.fromEntryArray(RegularImmutableMap.java:94)
at com.google.common.collect.ImmutableMap$Builder.build(ImmutableMap.java:573)
at com.google.common.collect.ImmutableMap$Builder.buildOrThrow(ImmutableMap.java:601)
at com.google.devtools.build.lib.skyframe.ActionEnvironmentFunction.getEnvironmentView(ActionEnvironmentFunction.java:105)
at com.google.devtools.build.lib.rules.repository.RepositoryFunction.getEnvVarValues(RepositoryFunction.java:305)
at com.google.devtools.build.lib.rules.repository.RepositoryFunction.declareEnvironmentDependencies(RepositoryFunction.java:293)
at com.google.devtools.build.lib.bazel.repository.starlark.StarlarkRepositoryFunction.fetch(StarlarkRepositoryFunction.java:123)
at com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction.fetchRepository(RepositoryDelegatorFunction.java:411)
at com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction.compute(RepositoryDelegatorFunction.java:342)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:562)
... 7 more
```
### Which category does this issue belong to?
Rules API
### What underlying problem are you trying to solve with this feature?
Bazel should fail gracefully when duplicate keys are present and not present the user with a stacktrace.
### Which operating system are you running Bazel on?
Ubuntu linux
### What is the output of `bazel info release`?
6.3.2
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
_No response_ | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java"
] | [
"src/test/shell/bazel/starlark_repository_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
index 748735a88288e2..4d00ea10c18a3e 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/SingleExtensionEvalFunction.java
@@ -159,7 +159,7 @@ public SkyValue compute(SkyKey skyKey, Environment env)
ModuleExtension extension = ((ModuleExtension) exported);
ImmutableMap<String, String> extensionEnvVars =
- RepositoryFunction.getEnvVarValues(env, extension.getEnvVariables());
+ RepositoryFunction.getEnvVarValues(env, ImmutableSet.copyOf(extension.getEnvVariables()));
if (extensionEnvVars == null) {
return null;
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
index 140697445739bb..fc2c43d1a1b276 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryFunction.java
@@ -285,8 +285,8 @@ public RepositoryDirectoryValue.Builder fetch(
}
@SuppressWarnings("unchecked")
- private static Iterable<String> getEnviron(Rule rule) {
- return (Iterable<String>) rule.getAttr("$environ");
+ private static ImmutableSet<String> getEnviron(Rule rule) {
+ return ImmutableSet.copyOf((Iterable<String>) rule.getAttr("$environ"));
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
index d6bfd2d4d0f420..934fa82e1b4ccd 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
@@ -18,6 +18,7 @@
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
@@ -71,7 +72,7 @@ public class AndroidNdkRepositoryFunction extends AndroidRepositoryFunction {
private static final String PATH_ENV_VAR = "ANDROID_NDK_HOME";
private static final PathFragment PLATFORMS_DIR = PathFragment.create("platforms");
- private static final ImmutableList<String> PATH_ENV_VAR_AS_LIST = ImmutableList.of(PATH_ENV_VAR);
+ private static final ImmutableSet<String> PATH_ENV_VAR_AS_SET = ImmutableSet.of(PATH_ENV_VAR);
private static String getDefaultCrosstool(Integer majorRevision) {
// From NDK 17, libc++ replaces gnu-libstdc++ as the default STL.
@@ -262,7 +263,7 @@ public boolean verifyMarkerData(Rule rule, Map<String, String> markerData, Envir
if (attributes.isAttributeValueExplicitlySpecified("path")) {
return true;
}
- return super.verifyEnvironMarkerData(markerData, env, PATH_ENV_VAR_AS_LIST);
+ return super.verifyEnvironMarkerData(markerData, env, PATH_ENV_VAR_AS_SET);
}
@Override
@@ -276,7 +277,7 @@ public RepositoryDirectoryValue.Builder fetch(
SkyKey key)
throws InterruptedException, RepositoryFunctionException {
Map<String, String> environ =
- declareEnvironmentDependencies(markerData, env, PATH_ENV_VAR_AS_LIST);
+ declareEnvironmentDependencies(markerData, env, PATH_ENV_VAR_AS_SET);
if (environ == null) {
return null;
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java
index 5875814a248c8e..e52dbb6303f011 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java
@@ -19,6 +19,7 @@
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
@@ -163,7 +164,7 @@ public String toString() {
private static final PathFragment SYSTEM_IMAGES_DIR = PathFragment.create("system-images");
private static final AndroidRevision MIN_BUILD_TOOLS_REVISION = AndroidRevision.parse("30.0.0");
private static final String PATH_ENV_VAR = "ANDROID_HOME";
- private static final ImmutableList<String> PATH_ENV_VAR_AS_LIST = ImmutableList.of(PATH_ENV_VAR);
+ private static final ImmutableSet<String> PATH_ENV_VAR_AS_SET = ImmutableSet.of(PATH_ENV_VAR);
private static final ImmutableList<String> LOCAL_MAVEN_REPOSITORIES =
ImmutableList.of(
"extras/android/m2repository", "extras/google/m2repository", "extras/m2repository");
@@ -180,7 +181,7 @@ public boolean verifyMarkerData(Rule rule, Map<String, String> markerData, Envir
if (attributes.isAttributeValueExplicitlySpecified("path")) {
return true;
}
- return super.verifyEnvironMarkerData(markerData, env, PATH_ENV_VAR_AS_LIST);
+ return super.verifyEnvironMarkerData(markerData, env, PATH_ENV_VAR_AS_SET);
}
@Override
@@ -194,7 +195,7 @@ public RepositoryDirectoryValue.Builder fetch(
SkyKey key)
throws RepositoryFunctionException, InterruptedException {
Map<String, String> environ =
- declareEnvironmentDependencies(markerData, env, PATH_ENV_VAR_AS_LIST);
+ declareEnvironmentDependencies(markerData, env, PATH_ENV_VAR_AS_SET);
if (environ == null) {
return null;
}
diff --git a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
index 26d04ae28c2288..2ac13825d39ce8 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
@@ -19,8 +19,8 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.common.io.BaseEncoding;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
@@ -55,6 +55,7 @@
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Starlark;
@@ -172,11 +173,11 @@ public abstract RepositoryDirectoryValue.Builder fetch(
throws InterruptedException, RepositoryFunctionException;
@SuppressWarnings("unchecked")
- private static Collection<String> getEnviron(Rule rule) {
+ private static ImmutableSet<String> getEnviron(Rule rule) {
if (rule.isAttrDefined("$environ", Type.STRING_LIST)) {
- return (Collection<String>) rule.getAttr("$environ");
+ return ImmutableSet.copyOf((Collection<String>) rule.getAttr("$environ"));
}
- return ImmutableList.of();
+ return ImmutableSet.of();
}
/**
@@ -288,7 +289,7 @@ public static RootedPath getRootedPathFromLabel(Label label, Environment env)
*/
@Nullable
protected Map<String, String> declareEnvironmentDependencies(
- Map<String, String> markerData, Environment env, Iterable<String> keys)
+ Map<String, String> markerData, Environment env, Set<String> keys)
throws InterruptedException {
ImmutableMap<String, String> envDep = getEnvVarValues(env, keys);
if (envDep == null) {
@@ -300,7 +301,7 @@ protected Map<String, String> declareEnvironmentDependencies(
}
@Nullable
- public static ImmutableMap<String, String> getEnvVarValues(Environment env, Iterable<String> keys)
+ public static ImmutableMap<String, String> getEnvVarValues(Environment env, Set<String> keys)
throws InterruptedException {
ImmutableMap<String, String> environ = ActionEnvironmentFunction.getEnvironmentView(env, keys);
if (environ == null) {
@@ -329,7 +330,7 @@ public static ImmutableMap<String, String> getEnvVarValues(Environment env, Iter
* Environment)} function to verify the values for environment variables.
*/
protected boolean verifyEnvironMarkerData(
- Map<String, String> markerData, Environment env, Collection<String> keys)
+ Map<String, String> markerData, Environment env, Set<String> keys)
throws InterruptedException {
ImmutableMap<String, String> environ = ActionEnvironmentFunction.getEnvironmentView(env, keys);
if (env.valuesMissing()) {
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java
index 4edf0fb1b31078..2a8cd3f8c80963 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ActionEnvironmentFunction.java
@@ -14,7 +14,8 @@
package com.google.devtools.build.lib.skyframe;
-import com.google.common.collect.ImmutableList;
+import static com.google.common.collect.ImmutableSet.toImmutableSet;
+
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Interner;
import com.google.devtools.build.lib.bugreport.BugReport;
@@ -27,6 +28,7 @@
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.SkyframeLookupResult;
import java.util.Map;
+import java.util.Set;
import javax.annotation.Nullable;
/**
@@ -77,13 +79,9 @@ public SkyFunctionName functionName() {
* if and only if some dependencies from Skyframe still need to be resolved.
*/
@Nullable
- public static ImmutableMap<String, String> getEnvironmentView(
- Environment env, Iterable<String> keys) throws InterruptedException {
- ImmutableList.Builder<SkyKey> skyframeKeysBuilder = ImmutableList.builder();
- for (String key : keys) {
- skyframeKeysBuilder.add(key(key));
- }
- ImmutableList<SkyKey> skyframeKeys = skyframeKeysBuilder.build();
+ public static ImmutableMap<String, String> getEnvironmentView(Environment env, Set<String> keys)
+ throws InterruptedException {
+ var skyframeKeys = keys.stream().map(ActionEnvironmentFunction::key).collect(toImmutableSet());
SkyframeLookupResult values = env.getValuesAndExceptions(skyframeKeys);
if (env.valuesMissing()) {
return null;
| diff --git a/src/test/shell/bazel/starlark_repository_test.sh b/src/test/shell/bazel/starlark_repository_test.sh
index 5569735b30d612..4ded3acfc5bb0d 100755
--- a/src/test/shell/bazel/starlark_repository_test.sh
+++ b/src/test/shell/bazel/starlark_repository_test.sh
@@ -2356,4 +2356,26 @@ EOF
bazel build --experimental_repository_disable_download //:it || fail "Failed to build"
}
+function test_duplicate_value_in_environ() {
+ cat >> WORKSPACE <<EOF
+load('//:def.bzl', 'repo')
+repo(name='foo')
+EOF
+
+ touch BUILD
+ cat > def.bzl <<'EOF'
+def _impl(repository_ctx):
+ repository_ctx.file("WORKSPACE")
+ repository_ctx.file("BUILD", """filegroup(name="bar",srcs=[])""")
+
+repo = repository_rule(
+ implementation=_impl,
+ environ=["FOO", "FOO"],
+)
+EOF
+
+ FOO=bar bazel build @foo//:bar >& $TEST_log \
+ || fail "Expected build to succeed"
+}
+
run_suite "local repository tests"
| train | test | 2023-10-12T17:18:57 | "2023-08-14T15:44:48Z" | jsharpe | test |
bazelbuild/bazel/19823_19848 | bazelbuild/bazel | bazelbuild/bazel/19823 | bazelbuild/bazel/19848 | [
"keyword_pr_to_issue"
] | 17998862e28b6aa012b7689dd3d0ced04546bb17 | 48892ae099581d4c9ad9bab785add2c0bb17e6be | [
"/cc @gregestren ",
"/cc @katre ",
"As @fmeum mentioned at https://github.com/bazelbuild/bazel/pull/19785#issuecomment-1761368842, you can also demonstrate this with `$ bazel config`. But this specific error is about cquery's `config()` function, which is technically different. Updated the title accordingly.",
"@fmeum I'm not recreating the failure you described in https://github.com/bazelbuild/bazel/pull/19785#issuecomment-1761368842 at the command line.\r\n\r\nI can reproduce the test failure.\r\n\r\nBut a direct i cquery / config invocation with bazel@head with `--enable_bzlmod` works for me. What are you doing differently?\r\n\r\n```\r\n$ b/bazel cquery \"deps(//$pkg:demo)\" --enable_bzlmod\r\n<results snipped>\r\n\r\n$ b/bazel config --enable_bzlmod\r\nAvailable configurations:\r\n0c35974bbc4114fb6b2aaa97afc0fa05325df6498995fc5ab8048c6e904ce99c k8-fastbuild\r\nf3e09891a52a118ada4747b9fed7d209ab6049a7786710934f5f50e1d0f82f2a fastbuild-noconfig\r\nf60fa7f4f050ef3d0bbd3e9a847759d104c0983e4613406726e82cfac3fc0db1 k8-opt-exec-ST-fad1763555eb (exec)\r\nfb7cccd5d9f2742c9ccf42571051eb647e8f01b2cf7be93309af5916222f86e2 k8-fastbuild\r\n```",
"With this setup:\r\n\r\n```starlark\r\n# MODULE.bazel (empty)\r\n# WORKSPACE (empty)\r\n# pkg/BUILD\r\nload(\"//pkg:rule.bzl\", \"demo_rule\")\r\n\r\nsh_binary(name = \"tool\", srcs = [\"tool.sh\"])\r\n\r\ndemo_rule(\r\n name = 'demo',\r\n binary = \":tool\",\r\n)\r\n# pkg/rule.bzl\r\ndef _impl(ctx):\r\n pass\r\n\r\ndemo_rule = rule(\r\n implementation = _impl,\r\n attrs = {\r\n \"binary\": attr.label(cfg = \"exec\"),\r\n },\r\n)\r\n# pkg/tool.sh\r\necho \"Hello\"\r\nexit 0\r\n```\r\n\r\nI get:\r\n```shell\r\n$ USE_BAZEL_VERSION=2ddacab80af1dca3c04e74809827c47ec4bc8498 bazel --nohome_rc --nosystem_rc cquery \"deps(//pkg:demo)\"\r\n//pkg:demo (cb4f3cc)\r\n@local_config_platform//:host (f3e0989)\r\n//pkg:tool (bac8967)\r\n...\r\n$ USE_BAZEL_VERSION=2ddacab80af1dca3c04e74809827c47ec4bc8498 bazel --nohome_rc --nosystem_rc config\r\nAvailable configurations:\r\n$ USE_BAZEL_VERSION=2ddacab80af1dca3c04e74809827c47ec4bc8498 bazel --nohome_rc --nosystem_rc cquery \"deps(//pkg:demo)\" --noenable_bzlmod\r\n//pkg:demo (cb4f3cc)\r\n@local_config_platform//:host (f3e0989)\r\n//pkg:tool (bac8967)\r\n...\r\n$ USE_BAZEL_VERSION=2ddacab80af1dca3c04e74809827c47ec4bc8498 bazel --nohome_rc --nosystem_rc config --noenable_bzlmod\r\nAvailable configurations:\r\nbac89673cb6a316d6814d09db69e2300dd9796229313c36bc7c06680a1c4d8ec k8-opt-exec-ST-e846b08c7501 (exec)\r\ncb4f3ccb516213afb57b51cb2aba480bc44b184b701bcc30e6dd090e8540af2b k8-fastbuild\r\nf3e09891a52a118ada4747b9fed7d209ab6049a7786710934f5f50e1d0f82f2a fastbuild-noconfig\r\n```",
"It seems likely that this is also the cause of https://github.com/bazelbuild/rules_go/issues/3597#issuecomment-1765905567.",
"I will submit a fix shortly.",
"@bazel-io flag",
"I submitted https://github.com/bazelbuild/bazel/pull/19842.",
"@bazel-io fork 6.4.0",
"A fix for this issue has been included in [Bazel 6.4.0 RC5](https://releases.bazel.build/6.4.0/rc5/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!",
"@bazel-io fork 7.0.0"
] | [] | "2023-10-17T16:51:49Z" | [
"type: bug",
"P1",
"team-Configurability"
] | cquery's config function doesn't work with Bzlmod | ### Description of the bug:
When Bzlmod is enabled, `//src/test/shell/integration:configured_query_test` fails with
```
** test_config_function ********************************************************
-- Test log: -----------------------------------------------------------
$TEST_TMPDIR defined: output root default is '/b/f/w/_tmp/7db115b6dfb285ceb10442ec6acaf9d3' and max_idle_secs default is '15'.
Computing main repo mapping:
Loading:
Loading: 0 packages loaded
Analyzing: target //test_config_function:tool (0 packages loaded, 0 targets configured)
INFO: Analyzed target //test_config_function:tool (0 packages loaded, 1 target configured).
INFO: Found 1 target...
ERROR: Error doing post analysis query: Evaluation failed: No target (in) //test_config_function:tool could be found in the configuration with checksum '50265a7'
INFO: Elapsed time: 0.333s, Critical Path: 0.00s
INFO: 0 processes.
ERROR: Build did NOT complete successfully
```
see https://github.com/bazelbuild/bazel/pull/19785#issuecomment-1761368842
### Which category does this issue belong to?
Configurability
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
To reproduce:
- Remove `disable_bzlmod` from `src/test/shell/integration/configured_query_test.sh`
- `bazel test //src/test/shell/integration:configured_query_test --test_filter test_config_function`
### Which operating system are you running Bazel on?
_No response_
### What is the output of `bazel info release`?
_No response_
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Is this a regression? If yes, please try to identify the Bazel commit where the bug was introduced.
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
It's very likely `//src/test/java/com/google/devtools/build/lib/runtime:ConfigCommandTest` is failing with the same reason when enabling Bzlmod. | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java
index a664ae3437b5c2..4036eb3b994f42 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BazelLockFileModule.java
@@ -106,8 +106,13 @@ public void afterCommand() throws AbruptExitException {
combineModuleExtensions(lockfile.getModuleExtensions(), oldExtensionUsages))
.build();
- // Write the new value to the file
- updateLockfile(lockfilePath, lockfile);
+ // Write the new value to the file, but only if needed. This is not just a performance
+ // optimization: whenever the lockfile is updated, most Skyframe nodes will be marked as dirty
+ // on the next build, which breaks commands such as `bazel config` that rely on
+ // com.google.devtools.build.skyframe.MemoizingEvaluator#getDoneValues.
+ if (!lockfile.equals(oldLockfile)) {
+ updateLockfile(lockfilePath, lockfile);
+ }
this.moduleResolutionEvent = null;
this.extensionResolutionEventsMap.clear();
}
| null | val | test | 2023-10-16T20:58:33 | "2023-10-16T09:48:04Z" | meteorcloudy | test |
bazelbuild/bazel/18265_19900 | bazelbuild/bazel | bazelbuild/bazel/18265 | bazelbuild/bazel/19900 | [
"keyword_pr_to_issue"
] | 9e8ae1aaac2409824aab7c7204858d12fabb60a1 | 2cb3159aed5b73eb13a866d8fe63953d388cd30b | [
"My attempt at a fix at https://github.com/bazelbuild/bazel/pull/18262 results in a cycle being reported - I don't know why.",
"We need to wait for Bazel 6.4.0 to see if #18262 fixes this.",
"A fix for this issue has been included in [Bazel 7.0.0 RC2](https://releases.bazel.build/7.0.0/rc2/index.html). Please test out the release candidate and report any issues as soon as possible. Thanks!"
] | [] | "2023-10-19T17:36:30Z" | [
"type: bug",
"P2",
"team-Rules-Java",
"next_month"
] | Bazel treats local_jdk as a "can run anywhere" toolchain | ### Description of the bug:
I have a shell test which tries to run Java, and fetches it by adding `"@bazel_tools//tools/jdk:current_java_runtime"` to both `toolchains` and `data`.
If I have not configured any Java toolchains, and try to run this test from my host (which is a Mac) remotely on an Linux remote execution worker (exec=target=linux), rather than failing because no toolchain could be located, it brings along the `local_jdk` toolchain, which is a Mac toolchain.
This appears to be because the `local_java_repository` doesn't constraint the `toolchain` target it generates at all: https://cs.opensource.google/bazel/bazel/+/e8cedf459936895f939906474d9f9878a8a45edc:tools/jdk/local_java_repository.bzl;l=91-96
### What's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
BUILD file:
```starlark
sh_test(
name = "list_test",
srcs = ["list_test.sh"],
env = {
"JAVA": "$(JAVA)",
},
toolchains = ["@bazel_tools//tools/jdk:current_java_runtime"],
data = ["@bazel_tools//tools/jdk:current_java_runtime"],
)
```
list_test.sh:
```
#!/bin/bash -eux
if [[ "${JAVA}" == external/* ]]; then
JAVA="${JAVA:9}"
fi
"${RUNFILES_DIR}/${JAVA}"
```
Command run on a Mac:
```console
% bazel test :list_test --platforms=@some_linux_platform --extra_execution_platforms=@some_linux_platform --remote_executor=grpcs://linux-remote-execution-server
```
If I run locally on my Mac, I get the output of java help printed, if I run remotely, I get:
```
==================== Test output for //:list_test:
+ [[ external/local_jdk/bin/java == external/* ]]
+ JAVA=local_jdk/bin/java
+ /runner/build/4fde3789d4c6a2f3/root/bazel-out/darwin-fastbuild/bin/list_test.runfiles/local_jdk/bin/java
/runner/build/4fde3789d4c6a2f3/root/bazel-out/darwin-fastbuild/bin/list_test.runfiles/__main__/list_test: line 6: /runner/build/4fde3789d4c6a2f3/root/bazel-out/darwin-fastbuild/bin/list_test.runfiles/local_jdk/bin/java: cannot execute binary file: Exec format error
```
### Which operating system are you running Bazel on?
macOS
### What is the output of `bazel info release`?
release 6.1.1
### If `bazel info release` returns `development version` or `(@non-git)`, tell us how you built Bazel.
_No response_
### What's the output of `git remote get-url origin; git rev-parse master; git rev-parse HEAD` ?
_No response_
### Have you found anything relevant by searching the web?
_No response_
### Any other information, logs, or outputs that you want to share?
/cc @fmeum who was helping me debug, and has https://github.com/bazelbuild/bazel/pull/18262 as a possible solution | [
".bazelrc",
"BUILD",
"MODULE.bazel",
"MODULE.bazel.lock",
"distdir_deps.bzl",
"src/BUILD",
"src/MODULE.tools",
"tools/jdk/local_java_repository.bzl",
"tools/jdk/remote_java_repository.bzl"
] | [
".bazelrc",
"BUILD",
"MODULE.bazel",
"MODULE.bazel.lock",
"distdir_deps.bzl",
"src/BUILD",
"src/MODULE.tools",
"tools/jdk/local_java_repository.bzl",
"tools/jdk/remote_java_repository.bzl"
] | [
"src/test/java/com/google/devtools/build/android/dexer/BUILD",
"src/test/py/bazel/test_base.py",
"src/test/shell/bazel/bazel_java17_test.sh",
"src/test/shell/bazel/bazel_java_test_defaults.sh",
"src/test/shell/bazel/bazel_with_jdk_test.sh",
"src/test/shell/integration/bazel_java_test.sh",
"src/test/shell/testenv.sh.tmpl",
"src/test/tools/bzlmod/MODULE.bazel.lock"
] | diff --git a/.bazelrc b/.bazelrc
index 9fbb5ece42fe72..d6be9f065df2f0 100644
--- a/.bazelrc
+++ b/.bazelrc
@@ -14,6 +14,9 @@ build:remote_shared --tool_java_runtime_version=rbe_jdk
build:remote_shared --noexperimental_check_desugar_deps
# Configuration to build and test Bazel on RBE on Ubuntu 18.04 with Java 11
+# Workaround for https://github.com/bazelbuild/bazel/issues/19837.
+# TODO(bazel-team): Remove this toolchain when .bazelversion is 7.0.0rc2 or later.
+build:ubuntu2004_java11 --extra_toolchains=//:bazel_rbe_java_toolchain_definition
build:ubuntu2004_java11 --extra_toolchains=@rbe_ubuntu2004_java11//java:all
build:ubuntu2004_java11 --crosstool_top=@rbe_ubuntu2004_java11//cc:toolchain
build:ubuntu2004_java11 --extra_toolchains=@rbe_ubuntu2004_java11//config:cc-toolchain
@@ -34,6 +37,9 @@ build:windows --extra_toolchains=@bazel_tools//tools/python:autodetecting_toolch
build:windows_arm64 --platforms=//:windows_arm64
build:windows_arm64 --extra_toolchains=@local_config_cc//:cc-toolchain-arm64_windows
+# When cross-compiling, the local Java runtime, which is used by default, will not be compatible
+# with the target.
+build:windows_arm64 --java_runtime_version=remotejdk_11
# Enable Bzlmod
common:bzlmod --enable_bzlmod
diff --git a/BUILD b/BUILD
index 56b79c87eac07d..07eb0bc076c0a1 100644
--- a/BUILD
+++ b/BUILD
@@ -1,6 +1,7 @@
# Bazel - Google's Build System
load("@bazel_skylib//rules:write_file.bzl", "write_file")
+load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain")
load("@rules_license//rules:license.bzl", "license")
load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
load("@rules_python//python:defs.bzl", "py_binary")
@@ -293,3 +294,19 @@ REMOTE_PLATFORMS = ("rbe_ubuntu2004_java11",)
)
for platform_name in REMOTE_PLATFORMS
]
+
+# Workaround for https://github.com/bazelbuild/bazel/issues/19837.
+# TODO(bazel-team): Remove these two targets when .bazelversion is 7.0.0rc2 or later.
+default_java_toolchain(
+ name = "bazel_java_toolchain",
+ bootclasspath = ["@rules_java//toolchains:platformclasspath"],
+ source_version = "11",
+ tags = ["manual"],
+ target_version = "11",
+)
+
+default_java_toolchain(
+ name = "bazel_rbe_java_toolchain",
+ source_version = "11",
+ target_version = "11",
+)
diff --git a/MODULE.bazel b/MODULE.bazel
index e39f58d2909469..d04304e6a043be 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
@@ -24,7 +24,7 @@ bazel_dep(name = "zstd-jni", version = "1.5.2-3.bcr.1")
bazel_dep(name = "blake3", version = "1.3.3.bcr.1")
bazel_dep(name = "zlib", version = "1.3")
bazel_dep(name = "rules_cc", version = "0.0.9")
-bazel_dep(name = "rules_java", version = "6.3.1")
+bazel_dep(name = "rules_java", version = "7.0.6")
bazel_dep(name = "rules_proto", version = "5.3.0-21.7")
bazel_dep(name = "rules_jvm_external", version = "5.2")
bazel_dep(name = "rules_python", version = "0.24.0")
@@ -231,10 +231,10 @@ use_repo(
"remotejdk17_macos_aarch64",
"remotejdk17_win",
"remotejdk17_win_arm64",
- "remotejdk20_linux",
- "remotejdk20_macos",
- "remotejdk20_macos_aarch64",
- "remotejdk20_win",
+ "remotejdk21_linux",
+ "remotejdk21_macos",
+ "remotejdk21_macos_aarch64",
+ "remotejdk21_win",
)
# =========================================
@@ -309,6 +309,10 @@ register_toolchains("@local_config_winsdk//:all")
register_toolchains("//src/main/res:empty_rc_toolchain")
+# Workaround for https://github.com/bazelbuild/bazel/issues/19837.
+# TODO(bazel-team): Remove when .bazelversion is 7.0.0rc2 or later.
+register_toolchains("//:bazel_java_toolchain_definition")
+
# =========================================
# Android tools dependencies
# =========================================
diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock
index dee726962f0a5a..01f1f68a99e5ab 100644
--- a/MODULE.bazel.lock
+++ b/MODULE.bazel.lock
@@ -1,6 +1,6 @@
{
"lockFileVersion": 3,
- "moduleFileHash": "50de843d4bf36021313d6db4e8f2656ed1d2aadbcc3d26791537d366111eb6be",
+ "moduleFileHash": "9ee47c2efef5f33f69b8cf617fba1fb6e38fb35e79345ce524924bee781cb72e",
"flags": {
"cmdRegistries": [
"https://bcr.bazel.build/"
@@ -29,7 +29,8 @@
"toolchainsToRegister": [
"@bazel_tools//tools/python:autodetecting_toolchain",
"@local_config_winsdk//:all",
- "//src/main/res:empty_rc_toolchain"
+ "//src/main/res:empty_rc_toolchain",
+ "//:bazel_java_toolchain_definition"
],
"extensionUsages": [
{
@@ -329,7 +330,7 @@
"devDependency": false,
"location": {
"file": "@@//:MODULE.bazel",
- "line": 317,
+ "line": 321,
"column": 22
}
}
@@ -367,10 +368,10 @@
"remotejdk17_macos_aarch64": "remotejdk17_macos_aarch64",
"remotejdk17_win": "remotejdk17_win",
"remotejdk17_win_arm64": "remotejdk17_win_arm64",
- "remotejdk20_linux": "remotejdk20_linux",
- "remotejdk20_macos": "remotejdk20_macos",
- "remotejdk20_macos_aarch64": "remotejdk20_macos_aarch64",
- "remotejdk20_win": "remotejdk20_win"
+ "remotejdk21_linux": "remotejdk21_linux",
+ "remotejdk21_macos": "remotejdk21_macos",
+ "remotejdk21_macos_aarch64": "remotejdk21_macos_aarch64",
+ "remotejdk21_win": "remotejdk21_win"
},
"devImports": [],
"tags": [],
@@ -543,7 +544,7 @@
"usingModule": "<root>",
"location": {
"file": "@@//:MODULE.bazel",
- "line": 339,
+ "line": 343,
"column": 35
},
"imports": {
@@ -560,7 +561,7 @@
"usingModule": "<root>",
"location": {
"file": "@@//:MODULE.bazel",
- "line": 342,
+ "line": 346,
"column": 42
},
"imports": {
@@ -585,7 +586,7 @@
"blake3": "[email protected]",
"zlib": "[email protected]",
"rules_cc": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_proto": "[email protected]",
"rules_jvm_external": "[email protected]",
"rules_python": "[email protected]",
@@ -715,7 +716,7 @@
"rules_python": "[email protected]",
"rules_cc": "[email protected]",
"rules_proto": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_pkg": "[email protected]",
"com_google_abseil": "[email protected]",
"zlib": "[email protected]",
@@ -801,7 +802,7 @@
"rules_proto": "[email protected]",
"upb": "[email protected]",
"zlib": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"io_bazel_rules_go": "[email protected]",
"bazel_tools": "bazel_tools@_",
"local_config_platform": "local_config_platform@_"
@@ -891,7 +892,7 @@
"extensionUsages": [],
"deps": {
"bazel_skylib": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"bazel_tools": "bazel_tools@_",
"local_config_platform": "local_config_platform@_"
},
@@ -1056,45 +1057,46 @@
}
}
},
- "[email protected]": {
+ "[email protected]": {
"name": "rules_java",
- "version": "6.3.1",
- "key": "[email protected]",
+ "version": "7.0.6",
+ "key": "[email protected]",
"repoName": "rules_java",
"executionPlatformsToRegister": [],
"toolchainsToRegister": [
"//toolchains:all",
"@local_jdk//:runtime_toolchain_definition",
- "@remotejdk11_linux_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_ppc64le_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_s390x_toolchain_config_repo//:toolchain",
- "@remotejdk11_macos_toolchain_config_repo//:toolchain",
- "@remotejdk11_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk11_win_toolchain_config_repo//:toolchain",
- "@remotejdk11_win_arm64_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_ppc64le_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_s390x_toolchain_config_repo//:toolchain",
- "@remotejdk17_macos_toolchain_config_repo//:toolchain",
- "@remotejdk17_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk17_win_toolchain_config_repo//:toolchain",
- "@remotejdk17_win_arm64_toolchain_config_repo//:toolchain",
- "@remotejdk20_linux_toolchain_config_repo//:toolchain",
- "@remotejdk20_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk20_macos_toolchain_config_repo//:toolchain",
- "@remotejdk20_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk20_win_toolchain_config_repo//:toolchain"
+ "@local_jdk//:bootstrap_runtime_toolchain_definition",
+ "@remotejdk11_linux_toolchain_config_repo//:all",
+ "@remotejdk11_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk11_linux_ppc64le_toolchain_config_repo//:all",
+ "@remotejdk11_linux_s390x_toolchain_config_repo//:all",
+ "@remotejdk11_macos_toolchain_config_repo//:all",
+ "@remotejdk11_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk11_win_toolchain_config_repo//:all",
+ "@remotejdk11_win_arm64_toolchain_config_repo//:all",
+ "@remotejdk17_linux_toolchain_config_repo//:all",
+ "@remotejdk17_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk17_linux_ppc64le_toolchain_config_repo//:all",
+ "@remotejdk17_linux_s390x_toolchain_config_repo//:all",
+ "@remotejdk17_macos_toolchain_config_repo//:all",
+ "@remotejdk17_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk17_win_toolchain_config_repo//:all",
+ "@remotejdk17_win_arm64_toolchain_config_repo//:all",
+ "@remotejdk21_linux_toolchain_config_repo//:all",
+ "@remotejdk21_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk21_macos_toolchain_config_repo//:all",
+ "@remotejdk21_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk21_win_toolchain_config_repo//:all"
],
"extensionUsages": [
{
"extensionBzlFile": "@rules_java//java:extensions.bzl",
"extensionName": "toolchains",
- "usingModule": "[email protected]",
+ "usingModule": "[email protected]",
"location": {
- "file": "https://bcr.bazel.build/modules/rules_java/6.3.1/MODULE.bazel",
- "line": 17,
+ "file": "https://bcr.bazel.build/modules/rules_java/7.0.6/MODULE.bazel",
+ "line": 18,
"column": 27
},
"imports": {
@@ -1120,11 +1122,11 @@
"remotejdk17_macos_aarch64_toolchain_config_repo": "remotejdk17_macos_aarch64_toolchain_config_repo",
"remotejdk17_win_toolchain_config_repo": "remotejdk17_win_toolchain_config_repo",
"remotejdk17_win_arm64_toolchain_config_repo": "remotejdk17_win_arm64_toolchain_config_repo",
- "remotejdk20_linux_toolchain_config_repo": "remotejdk20_linux_toolchain_config_repo",
- "remotejdk20_linux_aarch64_toolchain_config_repo": "remotejdk20_linux_aarch64_toolchain_config_repo",
- "remotejdk20_macos_toolchain_config_repo": "remotejdk20_macos_toolchain_config_repo",
- "remotejdk20_macos_aarch64_toolchain_config_repo": "remotejdk20_macos_aarch64_toolchain_config_repo",
- "remotejdk20_win_toolchain_config_repo": "remotejdk20_win_toolchain_config_repo"
+ "remotejdk21_linux_toolchain_config_repo": "remotejdk21_linux_toolchain_config_repo",
+ "remotejdk21_linux_aarch64_toolchain_config_repo": "remotejdk21_linux_aarch64_toolchain_config_repo",
+ "remotejdk21_macos_toolchain_config_repo": "remotejdk21_macos_toolchain_config_repo",
+ "remotejdk21_macos_aarch64_toolchain_config_repo": "remotejdk21_macos_aarch64_toolchain_config_repo",
+ "remotejdk21_win_toolchain_config_repo": "remotejdk21_win_toolchain_config_repo"
},
"devImports": [],
"tags": [],
@@ -1145,11 +1147,11 @@
"bzlFile": "@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1",
+ "name": "rules_java~7.0.6",
"urls": [
- "https://github.com/bazelbuild/rules_java/releases/download/6.3.1/rules_java-6.3.1.tar.gz"
+ "https://github.com/bazelbuild/rules_java/releases/download/7.0.6/rules_java-7.0.6.tar.gz"
],
- "integrity": "sha256-EXoSJ82vgTogobunip8tj7MIQQAMM+Ly0qZAvSJMkoI=",
+ "integrity": "sha256-6B6d6q4NnZnvPdX2wbMjOER/4W1VZBVVMepOt+84hUs=",
"strip_prefix": "",
"remote_patches": {},
"remote_patch_strip": 0
@@ -1461,7 +1463,7 @@
"toolchainsToRegister": [],
"extensionUsages": [],
"deps": {
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_proto": "[email protected]",
"com_google_protobuf": "[email protected]",
"googleapis": "googleapis@_",
@@ -1480,7 +1482,7 @@
"extensionUsages": [],
"deps": {
"rules_license": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_proto": "[email protected]",
"com_google_protobuf": "[email protected]",
"io_bazel": "<root>",
@@ -1894,7 +1896,7 @@
],
"deps": {
"rules_cc": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_license": "[email protected]",
"rules_proto": "[email protected]",
"rules_python": "[email protected]",
@@ -2104,7 +2106,7 @@
"moduleExtensions": {
"//:extensions.bzl%bazel_android_deps": {
"general": {
- "bzlTransitiveDigest": "yseV59Gli/QtNiWYztGw/BCEfbZOAJ97MKMy8mbTpbg=",
+ "bzlTransitiveDigest": "n3Rv2PmmDuw7aJr+nz1ckn3VyB5UDfB7IIh1wMuc+4s=",
"accumulatedFileDigests": {},
"envVariables": {},
"generatedRepoSpecs": {
@@ -2129,9 +2131,9 @@
},
"//:extensions.bzl%bazel_build_deps": {
"general": {
- "bzlTransitiveDigest": "yseV59Gli/QtNiWYztGw/BCEfbZOAJ97MKMy8mbTpbg=",
+ "bzlTransitiveDigest": "n3Rv2PmmDuw7aJr+nz1ckn3VyB5UDfB7IIh1wMuc+4s=",
"accumulatedFileDigests": {
- "@@//src/test/tools/bzlmod:MODULE.bazel.lock": "e321d417e120f584c05c82bc03b878d62887d36f65809ecfd343b00f75778d6d"
+ "@@//src/test/tools/bzlmod:MODULE.bazel.lock": "3690079fb96225220955f4e04363ba87470cb4cfb0f2b6deddd9929822ecc3ad"
},
"envVariables": {},
"generatedRepoSpecs": {
@@ -2155,7 +2157,7 @@
"name": "_main~bazel_build_deps~bazel_tools_repo_cache",
"repos": [
"rules_cc~0.0.9",
- "rules_java~6.3.1",
+ "rules_java~7.0.6",
"rules_license~0.0.7",
"rules_proto~4.0.0",
"rules_python~0.4.0",
@@ -2231,7 +2233,7 @@
"platforms",
"rules_cc~0.0.9",
"rules_go~0.39.1",
- "rules_java~6.3.1",
+ "rules_java~7.0.6",
"rules_jvm_external~5.2",
"rules_license~0.0.7",
"rules_pkg~0.9.1",
@@ -2345,7 +2347,7 @@
},
"//:extensions.bzl%bazel_test_deps": {
"general": {
- "bzlTransitiveDigest": "yseV59Gli/QtNiWYztGw/BCEfbZOAJ97MKMy8mbTpbg=",
+ "bzlTransitiveDigest": "n3Rv2PmmDuw7aJr+nz1ckn3VyB5UDfB7IIh1wMuc+4s=",
"accumulatedFileDigests": {},
"envVariables": {},
"generatedRepoSpecs": {
@@ -3593,64 +3595,80 @@
}
}
},
- "@rules_java~6.3.1//java:extensions.bzl%toolchains": {
+ "@rules_java~7.0.6//java:extensions.bzl%toolchains": {
"general": {
- "bzlTransitiveDigest": "Rz6TuBbGewHQwuehc1H9tRP+L5ORZKpeG+bcabQWP1c=",
+ "bzlTransitiveDigest": "S4ACUNQWaXa0wT3rT0IlpEuyljTfb611fi6lw+/WX3M=",
"accumulatedFileDigests": {},
"envVariables": {},
"generatedRepoSpecs": {
- "remotejdk20_linux": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
+ "remotejdk21_linux_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "0386418db7f23ae677d05045d30224094fc13423593ce9cd087d455069893bac",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-linux_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_x64.tar.gz"
- ]
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux//:jdk\",\n)\n"
}
},
"remotejdk17_linux_s390x_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_s390x_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_s390x_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\n"
}
},
"remotejdk17_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_macos_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos_aarch64//:jdk\",\n)\n"
}
},
"remotejdk17_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_macos_aarch64": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "2a7a99a3ea263dbd8d32a67d1e6e363ba8b25c645c826f5e167a02bbafaff1fa",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-macosx_aarch64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_aarch64.tar.gz"
+ ]
}
},
"remotejdk17_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\n"
}
},
"remotejdk17_macos_aarch64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "515dd56ec99bb5ae8966621a2088aadfbe72631818ffbba6e4387b7ee292ab09",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-macosx_aarch64",
"urls": [
@@ -3663,11 +3681,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_windows",
- "sha256": "bae6a03b5aeead5804ba7bcdcc8b14ec3ed05b37f3db5519f788ab060bc53b05",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_windows",
+ "sha256": "0224bb368b98f14d97afb749f3f956a177b60f753213b6c57db16deb2706c5dc",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_windows-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_windows-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_windows-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_windows-v13.0.zip"
]
}
},
@@ -3675,49 +3693,35 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "a106c77389a63b6bd963a087d5f01171bd32aa3ee7377ecef87531390dcb9050",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-win_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "43408193ce2fa0862819495b5ae8541085b95660153f2adcf91a52d3a1710e83",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-win_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-win_x64.zip",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-win_x64.zip"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-win_x64.zip",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-win_x64.zip"
]
}
},
"remotejdk11_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\n"
- }
- },
- "remotejdk20_win": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "ac5f6a7d84dbbb0bb4d376feb331cc4c49a9920562f2a5e85b7a6b4863b10e1e",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-win_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-win_x64.zip",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-win_x64.zip"
- ]
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\n"
}
},
"remotejdk11_linux_aarch64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "fc7c41a0005180d4ca471c90d01e049469e0614cf774566d4cf383caa29d1a97",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-linux_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "54174439f2b3fddd11f1048c397fe7bb45d4c9d66d452d6889b013d04d21c4de",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-linux_aarch64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu-embedded/bin/zulu11.56.19-ca-jdk11.0.15-linux_aarch64.tar.gz",
- "https://cdn.azul.com/zulu-embedded/bin/zulu11.56.19-ca-jdk11.0.15-linux_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_aarch64.tar.gz"
]
}
},
@@ -3725,8 +3729,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "20c91a922eec795f3181eaa70def8b99d8eac56047c9a14bfb257c85b991df1b",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-linux_x64",
"urls": [
@@ -3736,40 +3740,32 @@
}
},
"remotejdk11_linux_s390x_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_s390x_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\n"
- }
- },
- "remotejdk20_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_s390x_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\n"
}
},
"remotejdk11_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\n"
}
},
"remotejdk11_macos": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "2614e5c5de8e989d4d81759de4c333aa5b867b17ab9ee78754309ba65c7f6f55",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-macosx_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "bcaab11cfe586fae7583c6d9d311c64384354fb2638eb9a012eca4c3f1a1d9fd",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-macosx_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_x64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_x64.tar.gz"
]
}
},
@@ -3777,8 +3773,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_arm64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_arm64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "b8a28e6e767d90acf793ea6f5bed0bb595ba0ba5ebdf8b99f395266161e53ec2",
"strip_prefix": "jdk-11.0.13+8",
"urls": [
@@ -3790,8 +3786,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "e6317cee4d40995f0da5b702af3f04a6af2bbd55febf67927696987d11113b53",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-macosx_x64",
"urls": [
@@ -3800,34 +3796,42 @@
]
}
},
- "remotejdk17_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos_aarch64": {
+ "remotejdk21_macos": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "a2eff6a940c2df3a2352278027e83f5959f34dcfc8663034fe92be0f1b91ce6f",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-macosx_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "9639b87db586d0c89f7a9892ae47f421e442c64b97baebdff31788fbe23265bd",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-macosx_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_x64.tar.gz"
]
}
},
+ "remotejdk21_macos_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk17_macos_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\n"
+ }
+ },
"remotejdk17_win": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "9972c5b62a61b45785d3d956c559e079d9e91f144ec46225f5deeda214d48f27",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-win_x64",
"urls": [
@@ -3837,47 +3841,89 @@
}
},
"remotejdk11_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_linux_ppc64le_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_ppc64le_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_ppc64le_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_linux": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "0c0eadfbdc47a7ca64aeab51b9c061f71b6e4d25d2d87674512e9b6387e9e3a6",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-linux_x64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_x64.tar.gz"
+ ]
}
},
"remote_java_tools_linux": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_linux",
- "sha256": "a346b9a291b6db1bb06f7955f267e47522d99963fe14e337da1d75d125a8599f",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_linux",
+ "sha256": "f950ecc09cbc2ca110016095fe2a46e661925115975c84039f4370db1e70fe27",
+ "urls": [
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_linux-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_linux-v13.0.zip"
+ ]
+ }
+ },
+ "remotejdk21_win": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "e9959d500a0d9a7694ac243baf657761479da132f0f94720cbffd092150bd802",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-win_x64",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_linux-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_linux-v12.7.zip"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-win_x64.zip",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-win_x64.zip"
+ ]
+ }
+ },
+ "remotejdk21_linux_aarch64": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "1fb64b8036c5d463d8ab59af06bf5b6b006811e6012e3b0eb6bccf57f1c55835",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-linux_aarch64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_aarch64.tar.gz"
]
}
},
"remotejdk11_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_linux_s390x": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_s390x",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_s390x",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "a58fc0361966af0a5d5a31a2d8a208e3c9bb0f54f345596fd80b99ea9a39788b",
"strip_prefix": "jdk-11.0.15+10",
"urls": [
@@ -3890,8 +3936,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "dbc6ae9163e7ff469a9ab1f342cd1bc1f4c1fb78afc3c4f2228ee3b32c4f3e43",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-linux_aarch64",
"urls": [
@@ -3901,49 +3947,49 @@
}
},
"remotejdk17_win_arm64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_arm64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_arm64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\n"
}
},
"remotejdk11_linux": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "e064b61d93304012351242bf0823c6a2e41d9e28add7ea7f05378b7243d34247",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-linux_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "a34b404f87a08a61148b38e1416d837189e1df7a040d949e743633daf4695a3c",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-linux_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-linux_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-linux_x64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_x64.tar.gz"
]
}
},
"remotejdk11_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\n"
}
},
"remotejdk17_linux_ppc64le_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_ppc64le_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_ppc64le_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\n"
}
},
"remotejdk17_win_arm64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_arm64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_arm64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "bc3476f2161bf99bc9a243ff535b8fc033b34ce9a2fa4b62fb8d79b6bfdc427f",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-win_aarch64",
"urls": [
@@ -3956,11 +4002,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_darwin_arm64",
- "sha256": "ecedf6305768dfd51751d0ad732898af092bd7710d497c6c6c3214af7e49395f",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_darwin_arm64",
+ "sha256": "1ecd91bf870b4f246960c11445218798113b766762e26a3de09cfcf3e9b4c646",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_darwin_arm64-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_darwin_arm64-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_darwin_arm64-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_darwin_arm64-v13.0.zip"
]
}
},
@@ -3968,8 +4014,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_ppc64le",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_ppc64le",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "cbedd0a1428b3058d156e99e8e9bc8769e0d633736d6776a4c4d9136648f2fd1",
"strip_prefix": "jdk-17.0.4.1+1",
"urls": [
@@ -3978,93 +4024,41 @@
]
}
},
- "remotejdk20_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_macos//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "remotejdk21_linux_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_macos_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_win//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_win_arm64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_arm64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_arm64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\n"
}
},
"local_jdk": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:local_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:local_java_repository.bzl",
"ruleClassName": "_local_java_repository_rule",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~local_jdk",
+ "name": "rules_java~7.0.6~toolchains~local_jdk",
"java_home": "",
"version": "",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = {RUNTIME_VERSION},\n)\n"
- }
- },
- "remotejdk20_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_linux_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "fde6cc17a194ea0d9b0c6c0cb6178199d8edfc282d649eec2c86a9796e843f86",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-macosx_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_x64.tar.gz"
- ]
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = {RUNTIME_VERSION},\n)\n"
}
},
"remote_java_tools_darwin_x86_64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_darwin_x86_64",
- "sha256": "e116c649c0355ab57ffcc870ce1139e5e1528cabac458bd50263d2b84ea4ffb2",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_darwin_x86_64",
+ "sha256": "3edf102f683bfece8651f206aee864628825b4f6e614d183154e6bdf98b8c494",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_darwin_x86_64-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_darwin_x86_64-v12.7.zip"
- ]
- }
- },
- "remotejdk20_linux_aarch64": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "47ce58ead9a05d5d53b96706ff6fa0eb2e46755ee67e2b416925e28f5b55038a",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-linux_aarch64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_aarch64.tar.gz"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_darwin_x86_64-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_darwin_x86_64-v13.0.zip"
]
}
},
@@ -4072,11 +4066,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools",
- "sha256": "aa11ecd5fc0af2769f0f2bdd25e2f4de7c1291ed24326fb23fa69bdd5dcae2b5",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools",
+ "sha256": "610e40b1a89c9941638e33c56cf1be58f2d9d24cf9ac5a34b63270e08bb7000a",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools-v13.0.zip"
]
}
},
@@ -4084,8 +4078,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_s390x",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_s390x",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "fdc82f4b06c880762503b0cb40e25f46cf8190d06011b3b768f4091d3334ef7f",
"strip_prefix": "jdk-17.0.4.1+1",
"urls": [
@@ -4095,19 +4089,19 @@
}
},
"remotejdk17_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\n"
}
},
"remotejdk11_linux_ppc64le": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_ppc64le",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_ppc64le",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "a8fba686f6eb8ae1d1a9566821dbd5a85a1108b96ad857fdbac5c1e4649fc56f",
"strip_prefix": "jdk-11.0.15+10",
"urls": [
@@ -4120,15 +4114,23 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "6bb0d2c6e8a29dcd9c577bbb2986352ba12481a9549ac2c0bcfd00ed60e538d2",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-macosx_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "7632bc29f8a4b7d492b93f3bc75a7b61630894db85d136456035ab2a24d38885",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-macosx_aarch64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_aarch64.tar.gz"
]
}
+ },
+ "remotejdk21_win_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_win//:jdk\",\n)\n"
+ }
}
}
}
@@ -7919,7 +7921,7 @@
},
"@rules_python~0.24.0//python/extensions:pip.bzl%pip": {
"general": {
- "bzlTransitiveDigest": "Ft3hTgShxX/7p6AciATaTUQJgVShv/1SJ64filkse6c=",
+ "bzlTransitiveDigest": "TEllPVzarB4s4TpELB3gWHqo8xpekIiVpXI5FLmg+CQ=",
"accumulatedFileDigests": {
"@@//:requirements.txt": "ff12967a755bb8e9b4c92524f6471a99e14c30474a3d428547c55745ec8f23a0"
},
@@ -7954,7 +7956,7 @@
"repo": "bazel_pip_dev_deps_38",
"repo_prefix": "bazel_pip_dev_deps_38_",
"python_interpreter": "",
- "python_interpreter_target": "@@rules_python~0.24.0~python~python_3_8_x86_64-unknown-linux-gnu//:bin/python3",
+ "python_interpreter_target": "@@rules_python~0.24.0~python~python_3_8_aarch64-apple-darwin//:bin/python3",
"quiet": true,
"timeout": 600,
"isolated": true,
diff --git a/distdir_deps.bzl b/distdir_deps.bzl
index 8c2f8e20c78ebc..7eeaf24ad8b424 100644
--- a/distdir_deps.bzl
+++ b/distdir_deps.bzl
@@ -106,9 +106,9 @@ DIST_DEPS = {
"rules_java_builtin",
"rules_java_builtin_for_testing",
],
- "archive": "rules_java-6.3.1.tar.gz",
- "sha256": "117a1227cdaf813a20a1bba78a9f2d8fb30841000c33e2f2d2a640bd224c9282",
- "urls": ["https://github.com/bazelbuild/rules_java/releases/download/6.3.1/rules_java-6.3.1.tar.gz"],
+ "archive": "rules_java-7.0.6.tar.gz",
+ "sha256": "e81e9deaae0d9d99ef3dd5f6c1b32338447fe16d5564155531ea4eb7ef38854b",
+ "urls": ["https://github.com/bazelbuild/rules_java/releases/download/7.0.6/rules_java-7.0.6.tar.gz"],
"workspace_file_content": "",
"used_in": [
"additional_distfiles",
@@ -116,7 +116,7 @@ DIST_DEPS = {
"license_kinds": [
"@rules_license//licenses/spdx:Apache-2.0",
],
- "package_version": "6.1.1",
+ "package_version": "7.0.6",
},
# Used in src/test/java/com/google/devtools/build/lib/blackbox/framework/blackbox.WORKSAPCE
"rules_proto": {
diff --git a/src/BUILD b/src/BUILD
index eee29967ce96f8..8f70304152da0c 100644
--- a/src/BUILD
+++ b/src/BUILD
@@ -585,7 +585,7 @@ filegroup(
"@rules_testing//:LICENSE",
] + [
"@remotejdk%s_%s//:WORKSPACE" % (version, os)
- for version in ("17", "20")
+ for version in ("17", "21")
for os in ("macos", "macos_aarch64", "linux", "win")
] + ["@bazel_tools_repo_cache//:files"],
)
diff --git a/src/MODULE.tools b/src/MODULE.tools
index 33993075290286..c134770a2ba2d9 100644
--- a/src/MODULE.tools
+++ b/src/MODULE.tools
@@ -1,10 +1,11 @@
# NOTE: When editing this file, also update the lockfile.
# bazel run //src/test/tools/bzlmod:update_default_lock_file
+# bazel mod deps --lockfile_mode=update
module(name = "bazel_tools")
bazel_dep(name = "rules_cc", version = "0.0.9")
-bazel_dep(name = "rules_java", version = "6.3.1")
+bazel_dep(name = "rules_java", version = "7.0.6")
bazel_dep(name = "rules_license", version = "0.0.3")
bazel_dep(name = "rules_proto", version = "4.0.0")
bazel_dep(name = "rules_python", version = "0.4.0")
diff --git a/tools/jdk/local_java_repository.bzl b/tools/jdk/local_java_repository.bzl
index 416db4a1541a8f..f8554a1ac6310f 100644
--- a/tools/jdk/local_java_repository.bzl
+++ b/tools/jdk/local_java_repository.bzl
@@ -19,5 +19,6 @@ load("@rules_java//toolchains:local_java_repository.bzl", _local_java_repository
def local_java_repository(name, **kwargs):
_local_java_repository(name, **kwargs)
native.register_toolchains("@" + name + "//:runtime_toolchain_definition")
+ native.register_toolchains("@" + name + "//:bootstrap_runtime_toolchain_definition")
local_java_runtime = _local_java_runtime
diff --git a/tools/jdk/remote_java_repository.bzl b/tools/jdk/remote_java_repository.bzl
index b4ab1da279330b..32f4c1fdacb351 100644
--- a/tools/jdk/remote_java_repository.bzl
+++ b/tools/jdk/remote_java_repository.bzl
@@ -18,4 +18,4 @@ load("@rules_java//toolchains:remote_java_repository.bzl", _remote_java_reposito
def remote_java_repository(name, **kwargs):
_remote_java_repository(name, **kwargs)
- native.register_toolchains("@" + name + "_toolchain_config_repo//:toolchain")
+ native.register_toolchains("@" + name + "_toolchain_config_repo//:all")
| diff --git a/src/test/java/com/google/devtools/build/android/dexer/BUILD b/src/test/java/com/google/devtools/build/android/dexer/BUILD
index 9a29e00b6e149f..ac14ee2489ec0d 100644
--- a/src/test/java/com/google/devtools/build/android/dexer/BUILD
+++ b/src/test/java/com/google/devtools/build/android/dexer/BUILD
@@ -28,7 +28,7 @@ java_library(
),
"//conditions:default": ["NoAndroidSdkStubTest.java"],
}),
- javacopts = ["-source 7 -target 7"], # we run this through dx for testing, so no lambdas!
+ javacopts = ["-source 8 -target 8"],
resources = ["testresource.txt"],
deps = [
"//src/test/java/com/google/devtools/build/lib/testutil",
diff --git a/src/test/py/bazel/test_base.py b/src/test/py/bazel/test_base.py
index 33a37092b279a3..b7459b50939a6d 100644
--- a/src/test/py/bazel/test_base.py
+++ b/src/test/py/bazel/test_base.py
@@ -89,11 +89,11 @@ class TestBase(absltest.TestCase):
'remotejdk17_macos_aarch64',
'remotejdk17_win',
'remotejdk17_win_arm64',
- 'remotejdk20_linux',
- 'remotejdk20_macos',
- 'remotejdk20_macos_aarch64',
- 'remotejdk20_win',
- 'remotejdk20_win_arm64',
+ 'remotejdk21_linux',
+ 'remotejdk21_macos',
+ 'remotejdk21_macos_aarch64',
+ 'remotejdk21_win',
+ 'remotejdk21_win_arm64',
'rules_cc',
'rules_java',
'rules_java_builtin_for_testing',
diff --git a/src/test/shell/bazel/bazel_java17_test.sh b/src/test/shell/bazel/bazel_java17_test.sh
index 3507d089d271b8..a977927e608fb9 100755
--- a/src/test/shell/bazel/bazel_java17_test.sh
+++ b/src/test/shell/bazel/bazel_java17_test.sh
@@ -173,11 +173,11 @@ EOF
bazel build //pkg:Main \
--extra_toolchains=//pkg:java_toolchain_definition \
--java_language_version=17 \
- --java_runtime_version=remotejdk_20 \
+ --java_runtime_version=remotejdk_21 \
&>"${TEST_log}" && fail "Expected build to fail"
expect_log "error: \[BazelJavaConfiguration\] The Java 17 runtime used to run javac is not " \
- "recent enough to compile for the Java 20 runtime in external/remotejdk20_[a-z0-9]*\. Either " \
+ "recent enough to compile for the Java 21 runtime in external/remotejdk21_[a-z0-9]*\. Either " \
"register a Java toolchain with a newer java_runtime or specify a lower " \
"--java_runtime_version\."
}
@@ -220,11 +220,11 @@ EOF
bazel build //pkg:gen \
--extra_toolchains=//pkg:java_toolchain_definition \
--tool_java_language_version=17 \
- --tool_java_runtime_version=remotejdk_20 \
+ --tool_java_runtime_version=remotejdk_21 \
&>"${TEST_log}" && fail "Expected build to fail"
expect_log "error: \[BazelJavaConfiguration\] The Java 17 runtime used to run javac is not " \
- "recent enough to compile for the Java 20 runtime in external/remotejdk20_[a-z0-9]*\. Either " \
+ "recent enough to compile for the Java 21 runtime in external/remotejdk21_[a-z0-9]*\. Either " \
"register a Java toolchain with a newer java_runtime or specify a lower " \
"--tool_java_runtime_version\."
}
diff --git a/src/test/shell/bazel/bazel_java_test_defaults.sh b/src/test/shell/bazel/bazel_java_test_defaults.sh
index 3b91929031a2d7..c97b040aa16466 100755
--- a/src/test/shell/bazel/bazel_java_test_defaults.sh
+++ b/src/test/shell/bazel/bazel_java_test_defaults.sh
@@ -306,6 +306,52 @@ EOF
//pkg:foo_deploy.jar &>"$TEST_log" || fail "Build should succeed"
}
+function test_java_library_compiles_for_any_platform_with_local_jdk() {
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+platform(name = "exotic_platform")
+java_library(
+ name = "foo",
+ srcs = ["Foo.java"],
+)
+EOF
+
+ cat > pkg/Foo.java <<'EOF'
+package com.example;
+public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
+EOF
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=local_jdk \
+ //pkg:foo &>"$TEST_log" || fail "Build should succeed"
+}
+
+function test_java_library_compiles_for_any_platform_with_remote_jdk() {
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+platform(name = "exotic_platform")
+java_library(
+ name = "foo",
+ srcs = ["Foo.java"],
+)
+EOF
+
+ cat > pkg/Foo.java <<'EOF'
+package com.example;
+public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
+EOF
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=remotejdk_11 \
+ //pkg:foo &>"$TEST_log" || fail "Build should succeed"
+}
+
function test_non_executable_java_binary_compiles_for_any_platform_with_local_jdk() {
mkdir -p pkg
cat > pkg/BUILD.bazel <<'EOF'
@@ -332,4 +378,89 @@ EOF
//pkg:foo_deploy.jar &>"$TEST_log" || fail "Build should succeed"
}
+function test_non_executable_java_binary_compiles_for_any_platform_with_remote_jdk() {
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+platform(name = "exotic_platform")
+java_binary(
+ name = "foo",
+ srcs = ["Foo.java"],
+ create_executable = False,
+)
+EOF
+
+ cat > pkg/Foo.java <<'EOF'
+package com.example;
+public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
+EOF
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=remotejdk_11 \
+ //pkg:foo &>"$TEST_log" || fail "Build should succeed"
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=remotejdk_11 \
+ //pkg:foo_deploy.jar &>"$TEST_log" || fail "Build should succeed"
+}
+
+function test_executable_java_binary_fails_without_runtime_with_local_jdk() {
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+platform(name = "exotic_platform")
+java_binary(
+ name = "foo",
+ srcs = ["Foo.java"],
+ main_class = "com.example.Foo",
+)
+EOF
+
+ cat > pkg/Foo.java <<'EOF'
+package com.example;
+public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
+EOF
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=local_jdk \
+ //pkg:foo &>"$TEST_log" && fail "Build should fail"
+ expect_log "While resolving toolchains for target //pkg:foo ([0-9a-f]*): No matching toolchains found for types @bazel_tools//tools/jdk:runtime_toolchain_type"
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=local_jdk \
+ //pkg:foo_deploy.jar &>"$TEST_log" && fail "Build should fail"
+ expect_log "While resolving toolchains for target //pkg:foo_deployjars_internal_rule ([0-9a-f]*): No matching toolchains found for types @bazel_tools//tools/jdk:runtime_toolchain_type"
+}
+
+function test_executable_java_binary_fails_without_runtime_with_remote_jdk() {
+ mkdir -p pkg
+ cat > pkg/BUILD.bazel <<'EOF'
+platform(name = "exotic_platform")
+java_binary(
+ name = "foo",
+ srcs = ["Foo.java"],
+ main_class = "com.example.Foo",
+)
+EOF
+
+ cat > pkg/Foo.java <<'EOF'
+package com.example;
+public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
+EOF
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=remotejdk_11 \
+ //pkg:foo &>"$TEST_log" && fail "Build should fail"
+ expect_log "While resolving toolchains for target //pkg:foo ([0-9a-f]*): No matching toolchains found for types @bazel_tools//tools/jdk:runtime_toolchain_type"
+
+ bazel build --platforms=//pkg:exotic_platform --java_runtime_version=remotejdk_11 \
+ //pkg:foo_deploy.jar &>"$TEST_log" && fail "Build should fail"
+ expect_log "While resolving toolchains for target //pkg:foo_deployjars_internal_rule ([0-9a-f]*): No matching toolchains found for types @bazel_tools//tools/jdk:runtime_toolchain_type"
+}
+
run_suite "Java toolchains tests, configured using flags or the default_java_toolchain macro."
diff --git a/src/test/shell/bazel/bazel_with_jdk_test.sh b/src/test/shell/bazel/bazel_with_jdk_test.sh
index 6d1e83a698be5f..bbc44423f9f54d 100755
--- a/src/test/shell/bazel/bazel_with_jdk_test.sh
+++ b/src/test/shell/bazel/bazel_with_jdk_test.sh
@@ -92,9 +92,10 @@ function set_up() {
mkdir -p java/main
cat >java/main/BUILD <<EOF
-java_library(
+java_binary(
name = 'JavaExample',
srcs = ['JavaExample.java'],
+ main_class = 'JavaExample',
)
EOF
diff --git a/src/test/shell/integration/bazel_java_test.sh b/src/test/shell/integration/bazel_java_test.sh
index 3ac75a97a9ed02..c72e2b58fa8e4f 100755
--- a/src/test/shell/integration/bazel_java_test.sh
+++ b/src/test/shell/integration/bazel_java_test.sh
@@ -21,6 +21,10 @@ CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CURRENT_DIR}/../integration_test_setup.sh" \
|| { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+# should match the java_runtime in `_BASE_TOOLCHAIN_CONFIGURATION` in
+# `@rules_java//toolchains/default_java_toolchain.bzl`
+DEFAULT_JAVA_RUNTIME_VERSION="remotejdk21"
+
function test_server_javabase() {
mkdir -p test_server_javabase/bin
MAGIC="the cake is a lie"
@@ -71,16 +75,16 @@ EOF
# We expect the given host_javabase does not appear in the command line of
# java_library actions.
bazel aquery --output=text --tool_java_runtime_version='host_javabase' //java:javalib >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
expect_not_log "exec external/host_javabase/bin/java"
# If we don't specify anything, we expect the remote JDK to be used.
bazel aquery --output=text //java:javalib >& $TEST_log
expect_not_log "exec external/embedded_jdk/bin/java"
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
bazel aquery --output=text --java_runtime_version='host_javabase' //java:javalib >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
expect_not_log "exec external/host_javabase/bin/java"
}
@@ -102,13 +106,13 @@ EOF
touch foobar/bin/java
bazel aquery --output=text --java_language_version=8 //java:javalib >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
bazel aquery --output=text --java_language_version=11 //java:javalib >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
bazel aquery --output=text --java_language_version=17 //java:javalib >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
}
# Javabuilder shall be executed using JDK defined in java_toolchain's java_runtime attribute, not tool_java_runtime.
@@ -155,21 +159,21 @@ EOF
# We expect the given host_javabase does not appear in the command line of
# java_library actions.
bazel aquery --output=text --tool_java_runtime_version='host_javabase' 'deps(//java:sample,1)' >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
expect_not_log "exec external/host_javabase/bin/java"
# If we don't specify anything, we expect the remote JDK to be used.
# Note that this will change in the future but is the current state.
bazel aquery --output=text 'deps(//java:sample,1)' >& $TEST_log
expect_not_log "exec external/embedded_jdk/bin/java"
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
bazel aquery --output=text --tool_java_runtime_version='host_javabase' 'deps(//java:sample,1)' >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
expect_not_log "exec external/host_javabase/bin/java"
bazel aquery --output=text --tool_java_language_version=17 --tool_java_runtime_version='host_javabase' 'deps(//java:sample,1)' >& $TEST_log
- expect_log "exec external/rules_java~.*~toolchains~remotejdk17_.*/bin/java"
+ expect_log "exec external/rules_java~.*~toolchains~${DEFAULT_JAVA_RUNTIME_VERSION}_.*/bin/java"
expect_not_log "exec external/host_javabase/bin/java"
}
diff --git a/src/test/shell/testenv.sh.tmpl b/src/test/shell/testenv.sh.tmpl
index c887367d89ec0e..e7795aa3657ce4 100755
--- a/src/test/shell/testenv.sh.tmpl
+++ b/src/test/shell/testenv.sh.tmpl
@@ -304,11 +304,11 @@ EOF
"remotejdk17_macos_aarch64"
"remotejdk17_win"
"remotejdk17_win_arm64"
- "remotejdk20_linux"
- "remotejdk20_macos"
- "remotejdk20_macos_aarch64"
- "remotejdk20_win"
- "remotejdk20_win_arm64"
+ "remotejdk21_linux"
+ "remotejdk21_macos"
+ "remotejdk21_macos_aarch64"
+ "remotejdk21_win"
+ "remotejdk21_win_arm64"
"rules_cc"
"rules_java"
"rules_java_builtin_for_testing"
diff --git a/src/test/tools/bzlmod/MODULE.bazel.lock b/src/test/tools/bzlmod/MODULE.bazel.lock
index c396712279610b..237766b0ae6590 100644
--- a/src/test/tools/bzlmod/MODULE.bazel.lock
+++ b/src/test/tools/bzlmod/MODULE.bazel.lock
@@ -13,7 +13,7 @@
"compatibilityMode": "ERROR"
},
"localOverrideHashes": {
- "bazel_tools": "32c7d903c5371feba2a1ab3f89f649918e55c40be0cff0c1aed01741a613938e"
+ "bazel_tools": "18ffd442cf258c9048798a0d9bc49bbb06aba5ccb141dd357ce0c13c56f1ae78"
},
"moduleDepGraph": {
"<root>": {
@@ -46,7 +46,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 16,
+ "line": 17,
"column": 29
},
"imports": {
@@ -64,7 +64,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 20,
+ "line": 21,
"column": 32
},
"imports": {
@@ -81,7 +81,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 23,
+ "line": 24,
"column": 32
},
"imports": {
@@ -103,7 +103,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 34,
+ "line": 35,
"column": 39
},
"imports": {
@@ -120,7 +120,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 38,
+ "line": 39,
"column": 48
},
"imports": {
@@ -137,7 +137,7 @@
"usingModule": "bazel_tools@_",
"location": {
"file": "@@bazel_tools//:MODULE.bazel",
- "line": 41,
+ "line": 42,
"column": 42
},
"imports": {
@@ -152,7 +152,7 @@
],
"deps": {
"rules_cc": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"rules_license": "[email protected]",
"rules_proto": "[email protected]",
"rules_python": "[email protected]",
@@ -226,45 +226,46 @@
}
}
},
- "[email protected]": {
+ "[email protected]": {
"name": "rules_java",
- "version": "6.3.1",
- "key": "[email protected]",
+ "version": "7.0.6",
+ "key": "[email protected]",
"repoName": "rules_java",
"executionPlatformsToRegister": [],
"toolchainsToRegister": [
"//toolchains:all",
"@local_jdk//:runtime_toolchain_definition",
- "@remotejdk11_linux_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_ppc64le_toolchain_config_repo//:toolchain",
- "@remotejdk11_linux_s390x_toolchain_config_repo//:toolchain",
- "@remotejdk11_macos_toolchain_config_repo//:toolchain",
- "@remotejdk11_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk11_win_toolchain_config_repo//:toolchain",
- "@remotejdk11_win_arm64_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_ppc64le_toolchain_config_repo//:toolchain",
- "@remotejdk17_linux_s390x_toolchain_config_repo//:toolchain",
- "@remotejdk17_macos_toolchain_config_repo//:toolchain",
- "@remotejdk17_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk17_win_toolchain_config_repo//:toolchain",
- "@remotejdk17_win_arm64_toolchain_config_repo//:toolchain",
- "@remotejdk20_linux_toolchain_config_repo//:toolchain",
- "@remotejdk20_linux_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk20_macos_toolchain_config_repo//:toolchain",
- "@remotejdk20_macos_aarch64_toolchain_config_repo//:toolchain",
- "@remotejdk20_win_toolchain_config_repo//:toolchain"
+ "@local_jdk//:bootstrap_runtime_toolchain_definition",
+ "@remotejdk11_linux_toolchain_config_repo//:all",
+ "@remotejdk11_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk11_linux_ppc64le_toolchain_config_repo//:all",
+ "@remotejdk11_linux_s390x_toolchain_config_repo//:all",
+ "@remotejdk11_macos_toolchain_config_repo//:all",
+ "@remotejdk11_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk11_win_toolchain_config_repo//:all",
+ "@remotejdk11_win_arm64_toolchain_config_repo//:all",
+ "@remotejdk17_linux_toolchain_config_repo//:all",
+ "@remotejdk17_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk17_linux_ppc64le_toolchain_config_repo//:all",
+ "@remotejdk17_linux_s390x_toolchain_config_repo//:all",
+ "@remotejdk17_macos_toolchain_config_repo//:all",
+ "@remotejdk17_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk17_win_toolchain_config_repo//:all",
+ "@remotejdk17_win_arm64_toolchain_config_repo//:all",
+ "@remotejdk21_linux_toolchain_config_repo//:all",
+ "@remotejdk21_linux_aarch64_toolchain_config_repo//:all",
+ "@remotejdk21_macos_toolchain_config_repo//:all",
+ "@remotejdk21_macos_aarch64_toolchain_config_repo//:all",
+ "@remotejdk21_win_toolchain_config_repo//:all"
],
"extensionUsages": [
{
"extensionBzlFile": "@rules_java//java:extensions.bzl",
"extensionName": "toolchains",
- "usingModule": "[email protected]",
+ "usingModule": "[email protected]",
"location": {
- "file": "https://bcr.bazel.build/modules/rules_java/6.3.1/MODULE.bazel",
- "line": 17,
+ "file": "https://bcr.bazel.build/modules/rules_java/7.0.6/MODULE.bazel",
+ "line": 18,
"column": 27
},
"imports": {
@@ -290,11 +291,11 @@
"remotejdk17_macos_aarch64_toolchain_config_repo": "remotejdk17_macos_aarch64_toolchain_config_repo",
"remotejdk17_win_toolchain_config_repo": "remotejdk17_win_toolchain_config_repo",
"remotejdk17_win_arm64_toolchain_config_repo": "remotejdk17_win_arm64_toolchain_config_repo",
- "remotejdk20_linux_toolchain_config_repo": "remotejdk20_linux_toolchain_config_repo",
- "remotejdk20_linux_aarch64_toolchain_config_repo": "remotejdk20_linux_aarch64_toolchain_config_repo",
- "remotejdk20_macos_toolchain_config_repo": "remotejdk20_macos_toolchain_config_repo",
- "remotejdk20_macos_aarch64_toolchain_config_repo": "remotejdk20_macos_aarch64_toolchain_config_repo",
- "remotejdk20_win_toolchain_config_repo": "remotejdk20_win_toolchain_config_repo"
+ "remotejdk21_linux_toolchain_config_repo": "remotejdk21_linux_toolchain_config_repo",
+ "remotejdk21_linux_aarch64_toolchain_config_repo": "remotejdk21_linux_aarch64_toolchain_config_repo",
+ "remotejdk21_macos_toolchain_config_repo": "remotejdk21_macos_toolchain_config_repo",
+ "remotejdk21_macos_aarch64_toolchain_config_repo": "remotejdk21_macos_aarch64_toolchain_config_repo",
+ "remotejdk21_win_toolchain_config_repo": "remotejdk21_win_toolchain_config_repo"
},
"devImports": [],
"tags": [],
@@ -315,11 +316,11 @@
"bzlFile": "@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1",
+ "name": "rules_java~7.0.6",
"urls": [
- "https://github.com/bazelbuild/rules_java/releases/download/6.3.1/rules_java-6.3.1.tar.gz"
+ "https://github.com/bazelbuild/rules_java/releases/download/7.0.6/rules_java-7.0.6.tar.gz"
],
- "integrity": "sha256-EXoSJ82vgTogobunip8tj7MIQQAMM+Ly0qZAvSJMkoI=",
+ "integrity": "sha256-6B6d6q4NnZnvPdX2wbMjOER/4W1VZBVVMepOt+84hUs=",
"strip_prefix": "",
"remote_patches": {},
"remote_patch_strip": 0
@@ -481,7 +482,7 @@
"rules_python": "[email protected]",
"rules_cc": "[email protected]",
"rules_proto": "[email protected]",
- "rules_java": "[email protected]",
+ "rules_java": "[email protected]",
"bazel_tools": "bazel_tools@_",
"local_config_platform": "local_config_platform@_"
},
@@ -747,64 +748,80 @@
}
}
},
- "@rules_java~6.3.1//java:extensions.bzl%toolchains": {
+ "@rules_java~7.0.6//java:extensions.bzl%toolchains": {
"general": {
- "bzlTransitiveDigest": "42zU2TJ0nDBFOigt11wj3De2m25mcH3K8SRoG0nGgIA=",
+ "bzlTransitiveDigest": "MgCo2BSYmyPA2WdKpPo9jP+FL4/VRknyohG5Q/Vm5hY=",
"accumulatedFileDigests": {},
"envVariables": {},
"generatedRepoSpecs": {
- "remotejdk20_linux": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
+ "remotejdk21_linux_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "0386418db7f23ae677d05045d30224094fc13423593ce9cd087d455069893bac",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-linux_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_x64.tar.gz"
- ]
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux//:jdk\",\n)\n"
}
},
"remotejdk17_linux_s390x_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_s390x_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_s390x_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_s390x//:jdk\",\n)\n"
}
},
"remotejdk17_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_macos_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos_aarch64//:jdk\",\n)\n"
}
},
"remotejdk17_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_aarch64//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_macos_aarch64": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "2a7a99a3ea263dbd8d32a67d1e6e363ba8b25c645c826f5e167a02bbafaff1fa",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-macosx_aarch64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_aarch64.tar.gz"
+ ]
}
},
"remotejdk17_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux//:jdk\",\n)\n"
}
},
"remotejdk17_macos_aarch64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "515dd56ec99bb5ae8966621a2088aadfbe72631818ffbba6e4387b7ee292ab09",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-macosx_aarch64",
"urls": [
@@ -817,11 +834,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_windows",
- "sha256": "bae6a03b5aeead5804ba7bcdcc8b14ec3ed05b37f3db5519f788ab060bc53b05",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_windows",
+ "sha256": "0224bb368b98f14d97afb749f3f956a177b60f753213b6c57db16deb2706c5dc",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_windows-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_windows-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_windows-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_windows-v13.0.zip"
]
}
},
@@ -829,49 +846,35 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "a106c77389a63b6bd963a087d5f01171bd32aa3ee7377ecef87531390dcb9050",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-win_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "43408193ce2fa0862819495b5ae8541085b95660153f2adcf91a52d3a1710e83",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-win_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-win_x64.zip",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-win_x64.zip"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-win_x64.zip",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-win_x64.zip"
]
}
},
"remotejdk11_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\n"
- }
- },
- "remotejdk20_win": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "ac5f6a7d84dbbb0bb4d376feb331cc4c49a9920562f2a5e85b7a6b4863b10e1e",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-win_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-win_x64.zip",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-win_x64.zip"
- ]
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win//:jdk\",\n)\n"
}
},
"remotejdk11_linux_aarch64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "fc7c41a0005180d4ca471c90d01e049469e0614cf774566d4cf383caa29d1a97",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-linux_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "54174439f2b3fddd11f1048c397fe7bb45d4c9d66d452d6889b013d04d21c4de",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-linux_aarch64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu-embedded/bin/zulu11.56.19-ca-jdk11.0.15-linux_aarch64.tar.gz",
- "https://cdn.azul.com/zulu-embedded/bin/zulu11.56.19-ca-jdk11.0.15-linux_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_aarch64.tar.gz"
]
}
},
@@ -879,8 +882,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "20c91a922eec795f3181eaa70def8b99d8eac56047c9a14bfb257c85b991df1b",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-linux_x64",
"urls": [
@@ -890,40 +893,32 @@
}
},
"remotejdk11_linux_s390x_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_s390x_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\n"
- }
- },
- "remotejdk20_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_s390x_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:s390x\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_s390x//:jdk\",\n)\n"
}
},
"remotejdk11_linux_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux//:jdk\",\n)\n"
}
},
"remotejdk11_macos": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "2614e5c5de8e989d4d81759de4c333aa5b867b17ab9ee78754309ba65c7f6f55",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-macosx_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "bcaab11cfe586fae7583c6d9d311c64384354fb2638eb9a012eca4c3f1a1d9fd",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-macosx_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_x64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_x64.tar.gz"
]
}
},
@@ -931,8 +926,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_arm64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_arm64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "b8a28e6e767d90acf793ea6f5bed0bb595ba0ba5ebdf8b99f395266161e53ec2",
"strip_prefix": "jdk-11.0.13+8",
"urls": [
@@ -944,8 +939,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "e6317cee4d40995f0da5b702af3f04a6af2bbd55febf67927696987d11113b53",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-macosx_x64",
"urls": [
@@ -954,34 +949,42 @@
]
}
},
- "remotejdk17_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos_aarch64": {
+ "remotejdk21_macos": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "a2eff6a940c2df3a2352278027e83f5959f34dcfc8663034fe92be0f1b91ce6f",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-macosx_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "9639b87db586d0c89f7a9892ae47f421e442c64b97baebdff31788fbe23265bd",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-macosx_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-macosx_x64.tar.gz"
]
}
},
+ "remotejdk21_macos_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_macos//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk17_macos_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_macos_aarch64//:jdk\",\n)\n"
+ }
+ },
"remotejdk17_win": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "9972c5b62a61b45785d3d956c559e079d9e91f144ec46225f5deeda214d48f27",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-win_x64",
"urls": [
@@ -991,47 +994,89 @@
}
},
"remotejdk11_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_linux_ppc64le_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_ppc64le_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_ppc64le_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_ppc64le//:jdk\",\n)\n"
+ }
+ },
+ "remotejdk21_linux": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "0c0eadfbdc47a7ca64aeab51b9c061f71b6e4d25d2d87674512e9b6387e9e3a6",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-linux_x64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_x64.tar.gz"
+ ]
}
},
"remote_java_tools_linux": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_linux",
- "sha256": "a346b9a291b6db1bb06f7955f267e47522d99963fe14e337da1d75d125a8599f",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_linux",
+ "sha256": "f950ecc09cbc2ca110016095fe2a46e661925115975c84039f4370db1e70fe27",
+ "urls": [
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_linux-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_linux-v13.0.zip"
+ ]
+ }
+ },
+ "remotejdk21_win": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_win",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "e9959d500a0d9a7694ac243baf657761479da132f0f94720cbffd092150bd802",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-win_x64",
+ "urls": [
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-win_x64.zip",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-win_x64.zip"
+ ]
+ }
+ },
+ "remotejdk21_linux_aarch64": {
+ "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
+ "ruleClassName": "http_archive",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 21,\n)\n",
+ "sha256": "1fb64b8036c5d463d8ab59af06bf5b6b006811e6012e3b0eb6bccf57f1c55835",
+ "strip_prefix": "zulu21.28.85-ca-jdk21.0.0-linux_aarch64",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_linux-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_linux-v12.7.zip"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu21.28.85-ca-jdk21.0.0-linux_aarch64.tar.gz"
]
}
},
"remotejdk11_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_linux_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_linux_s390x": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_s390x",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_s390x",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "a58fc0361966af0a5d5a31a2d8a208e3c9bb0f54f345596fd80b99ea9a39788b",
"strip_prefix": "jdk-11.0.15+10",
"urls": [
@@ -1044,8 +1089,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "dbc6ae9163e7ff469a9ab1f342cd1bc1f4c1fb78afc3c4f2228ee3b32c4f3e43",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-linux_aarch64",
"urls": [
@@ -1055,49 +1100,49 @@
}
},
"remotejdk17_win_arm64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_arm64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_arm64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win_arm64//:jdk\",\n)\n"
}
},
"remotejdk11_linux": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "e064b61d93304012351242bf0823c6a2e41d9e28add7ea7f05378b7243d34247",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-linux_x64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "a34b404f87a08a61148b38e1416d837189e1df7a040d949e743633daf4695a3c",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-linux_x64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-linux_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-linux_x64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_x64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-linux_x64.tar.gz"
]
}
},
"remotejdk11_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_macos//:jdk\",\n)\n"
}
},
"remotejdk17_linux_ppc64le_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_ppc64le_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_ppc64le_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:ppc\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_linux_ppc64le//:jdk\",\n)\n"
}
},
"remotejdk17_win_arm64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_arm64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_arm64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "bc3476f2161bf99bc9a243ff535b8fc033b34ce9a2fa4b62fb8d79b6bfdc427f",
"strip_prefix": "zulu17.38.21-ca-jdk17.0.5-win_aarch64",
"urls": [
@@ -1110,11 +1155,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_darwin_arm64",
- "sha256": "ecedf6305768dfd51751d0ad732898af092bd7710d497c6c6c3214af7e49395f",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_darwin_arm64",
+ "sha256": "1ecd91bf870b4f246960c11445218798113b766762e26a3de09cfcf3e9b4c646",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_darwin_arm64-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_darwin_arm64-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_darwin_arm64-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_darwin_arm64-v13.0.zip"
]
}
},
@@ -1122,8 +1167,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_ppc64le",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_ppc64le",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "cbedd0a1428b3058d156e99e8e9bc8769e0d633736d6776a4c4d9136648f2fd1",
"strip_prefix": "jdk-17.0.4.1+1",
"urls": [
@@ -1132,93 +1177,41 @@
]
}
},
- "remotejdk20_macos_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_macos//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "remotejdk21_linux_aarch64_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:macos\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_macos_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_win//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_linux_aarch64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux_aarch64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_linux_aarch64//:jdk\",\n)\n"
}
},
"remotejdk11_win_arm64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_win_arm64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_win_arm64_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_11\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"11\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:arm64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk11_win_arm64//:jdk\",\n)\n"
}
},
"local_jdk": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:local_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:local_java_repository.bzl",
"ruleClassName": "_local_java_repository_rule",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~local_jdk",
+ "name": "rules_java~7.0.6~toolchains~local_jdk",
"java_home": "",
"version": "",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = {RUNTIME_VERSION},\n)\n"
- }
- },
- "remotejdk20_linux_aarch64_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
- "ruleClassName": "_toolchain_config",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_aarch64_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_20\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"20\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:linux\", \"@platforms//cpu:aarch64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk20_linux_aarch64//:jdk\",\n)\n"
- }
- },
- "remotejdk20_macos": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_macos",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "fde6cc17a194ea0d9b0c6c0cb6178199d8edfc282d649eec2c86a9796e843f86",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-macosx_x64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_x64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-macosx_x64.tar.gz"
- ]
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = {RUNTIME_VERSION},\n)\n"
}
},
"remote_java_tools_darwin_x86_64": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools_darwin_x86_64",
- "sha256": "e116c649c0355ab57ffcc870ce1139e5e1528cabac458bd50263d2b84ea4ffb2",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools_darwin_x86_64",
+ "sha256": "3edf102f683bfece8651f206aee864628825b4f6e614d183154e6bdf98b8c494",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools_darwin_x86_64-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools_darwin_x86_64-v12.7.zip"
- ]
- }
- },
- "remotejdk20_linux_aarch64": {
- "bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
- "ruleClassName": "http_archive",
- "attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk20_linux_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 20,\n)\n",
- "sha256": "47ce58ead9a05d5d53b96706ff6fa0eb2e46755ee67e2b416925e28f5b55038a",
- "strip_prefix": "zulu20.28.85-ca-jdk20.0.0-linux_aarch64",
- "urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu20.28.85-ca-jdk20.0.0-linux_aarch64.tar.gz"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools_darwin_x86_64-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools_darwin_x86_64-v13.0.zip"
]
}
},
@@ -1226,11 +1219,11 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remote_java_tools",
- "sha256": "aa11ecd5fc0af2769f0f2bdd25e2f4de7c1291ed24326fb23fa69bdd5dcae2b5",
+ "name": "rules_java~7.0.6~toolchains~remote_java_tools",
+ "sha256": "610e40b1a89c9941638e33c56cf1be58f2d9d24cf9ac5a34b63270e08bb7000a",
"urls": [
- "https://mirror.bazel.build/bazel_java_tools/releases/java/v12.7/java_tools-v12.7.zip",
- "https://github.com/bazelbuild/java_tools/releases/download/java_v12.7/java_tools-v12.7.zip"
+ "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.0/java_tools-v13.0.zip",
+ "https://github.com/bazelbuild/java_tools/releases/download/java_v13.0/java_tools-v13.0.zip"
]
}
},
@@ -1238,8 +1231,8 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_linux_s390x",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 17,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_linux_s390x",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 17,\n)\n",
"sha256": "fdc82f4b06c880762503b0cb40e25f46cf8190d06011b3b768f4091d3334ef7f",
"strip_prefix": "jdk-17.0.4.1+1",
"urls": [
@@ -1249,19 +1242,19 @@
}
},
"remotejdk17_win_toolchain_config_repo": {
- "bzlFile": "@@rules_java~6.3.1//toolchains:remote_java_repository.bzl",
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
"ruleClassName": "_toolchain_config",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk17_win_toolchain_config_repo",
- "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\n"
+ "name": "rules_java~7.0.6~toolchains~remotejdk17_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_17\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"17\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk17_win//:jdk\",\n)\n"
}
},
"remotejdk11_linux_ppc64le": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_linux_ppc64le",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_linux_ppc64le",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
"sha256": "a8fba686f6eb8ae1d1a9566821dbd5a85a1108b96ad857fdbac5c1e4649fc56f",
"strip_prefix": "jdk-11.0.15+10",
"urls": [
@@ -1274,15 +1267,23 @@
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
- "name": "rules_java~6.3.1~toolchains~remotejdk11_macos_aarch64",
- "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n version = 11,\n)\n",
- "sha256": "6bb0d2c6e8a29dcd9c577bbb2986352ba12481a9549ac2c0bcfd00ed60e538d2",
- "strip_prefix": "zulu11.56.19-ca-jdk11.0.15-macosx_aarch64",
+ "name": "rules_java~7.0.6~toolchains~remotejdk11_macos_aarch64",
+ "build_file_content": "load(\"@rules_java//java:defs.bzl\", \"java_runtime\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files([\"WORKSPACE\", \"BUILD.bazel\"])\n\nfilegroup(\n name = \"jre\",\n srcs = glob(\n [\n \"jre/bin/**\",\n \"jre/lib/**\",\n ],\n allow_empty = True,\n # In some configurations, Java browser plugin is considered harmful and\n # common antivirus software blocks access to npjp2.dll interfering with Bazel,\n # so do not include it in JRE on Windows.\n exclude = [\"jre/bin/plugin2/**\"],\n ),\n)\n\nfilegroup(\n name = \"jdk-bin\",\n srcs = glob(\n [\"bin/**\"],\n # The JDK on Windows sometimes contains a directory called\n # \"%systemroot%\", which is not a valid label.\n exclude = [\"**/*%*/**\"],\n ),\n)\n\n# This folder holds security policies.\nfilegroup(\n name = \"jdk-conf\",\n srcs = glob(\n [\"conf/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-include\",\n srcs = glob(\n [\"include/**\"],\n allow_empty = True,\n ),\n)\n\nfilegroup(\n name = \"jdk-lib\",\n srcs = glob(\n [\"lib/**\", \"release\"],\n allow_empty = True,\n exclude = [\n \"lib/missioncontrol/**\",\n \"lib/visualvm/**\",\n ],\n ),\n)\n\njava_runtime(\n name = \"jdk\",\n srcs = [\n \":jdk-bin\",\n \":jdk-conf\",\n \":jdk-include\",\n \":jdk-lib\",\n \":jre\",\n ],\n # Provide the 'java` binary explicitly so that the correct path is used by\n # Bazel even when the host platform differs from the execution platform.\n # Exactly one of the two globs will be empty depending on the host platform.\n # When --incompatible_disallow_empty_glob is enabled, each individual empty\n # glob will fail without allow_empty = True, even if the overall result is\n # non-empty.\n java = glob([\"bin/java.exe\", \"bin/java\"], allow_empty = True)[0],\n version = 11,\n)\n",
+ "sha256": "7632bc29f8a4b7d492b93f3bc75a7b61630894db85d136456035ab2a24d38885",
+ "strip_prefix": "zulu11.66.15-ca-jdk11.0.20-macosx_aarch64",
"urls": [
- "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_aarch64.tar.gz",
- "https://cdn.azul.com/zulu/bin/zulu11.56.19-ca-jdk11.0.15-macosx_aarch64.tar.gz"
+ "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_aarch64.tar.gz",
+ "https://cdn.azul.com/zulu/bin/zulu11.66.15-ca-jdk11.0.20-macosx_aarch64.tar.gz"
]
}
+ },
+ "remotejdk21_win_toolchain_config_repo": {
+ "bzlFile": "@@rules_java~7.0.6//toolchains:remote_java_repository.bzl",
+ "ruleClassName": "_toolchain_config",
+ "attributes": {
+ "name": "rules_java~7.0.6~toolchains~remotejdk21_win_toolchain_config_repo",
+ "build_file": "\nconfig_setting(\n name = \"prefix_version_setting\",\n values = {\"java_runtime_version\": \"remotejdk_21\"},\n visibility = [\"//visibility:private\"],\n)\nconfig_setting(\n name = \"version_setting\",\n values = {\"java_runtime_version\": \"21\"},\n visibility = [\"//visibility:private\"],\n)\nalias(\n name = \"version_or_prefix_version_setting\",\n actual = select({\n \":version_setting\": \":version_setting\",\n \"//conditions:default\": \":prefix_version_setting\",\n }),\n visibility = [\"//visibility:private\"],\n)\ntoolchain(\n name = \"toolchain\",\n target_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:runtime_toolchain_type\",\n toolchain = \"@remotejdk21_win//:jdk\",\n)\ntoolchain(\n name = \"bootstrap_runtime_toolchain\",\n # These constraints are not required for correctness, but prevent fetches of remote JDK for\n # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in\n # the same configuration, this constraint will not result in toolchain resolution failures.\n exec_compatible_with = [\"@platforms//os:windows\", \"@platforms//cpu:x86_64\"],\n target_settings = [\":version_or_prefix_version_setting\"],\n toolchain_type = \"@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type\",\n toolchain = \"@remotejdk21_win//:jdk\",\n)\n"
+ }
}
}
}
| val | test | 2023-10-19T20:44:55 | "2023-04-28T15:12:28Z" | illicitonion | test |
Subsets and Splits