Skip to content

Conversation

@visz11
Copy link
Collaborator

@visz11 visz11 commented Apr 15, 2025

…port Windows

Summary by CodeRabbit

  • New Features

    • Added support for replacing %bazel_workspace% in environment variable values with the workspace path when configuring repository environments.
  • Documentation

    • Updated help text for repository environment options to clarify %bazel_workspace% substitution.
  • Tests

    • Introduced a new test to verify correct interpolation of %bazel_workspace% in repository environment variables.

@visz11
Copy link
Collaborator Author

visz11 commented Apr 25, 2025

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Apr 25, 2025

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link

coderabbitai bot commented Apr 25, 2025

Walkthrough

This update removes the resourceManager field and its constructor parameter from the CommandEnvironment class, updating the relevant method to use the singleton ResourceManager.instance() instead. The constructor now also replaces %bazel_workspace% placeholders in repository environment variables with the actual workspace path. The help text for the repo_env option in CommonCommandOptions was updated to document this substitution feature. Additionally, a new test was added to verify that %bazel_workspace% interpolation works as intended when setting up repository environments.

Changes

File(s) Change Summary
src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java Removed resourceManager field and constructor parameter; updated method to use singleton; added workspace path interpolation for %bazel_workspace% in repo env variables.
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java Extended help text for repo_env option to document %bazel_workspace% substitution.
src/test/shell/bazel/starlark_repository_test.sh Added new test function test_repo_env_workspace_interpolation to verify workspace path interpolation in repo env.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Bazel
    participant CommandEnvironment
    participant ResourceManager

    User->>Bazel: Runs command with --repo_env containing %bazel_workspace%
    Bazel->>CommandEnvironment: Initializes with workspace and repo env
    CommandEnvironment->>CommandEnvironment: Replace %bazel_workspace% with workspace path in repo env
    CommandEnvironment->>ResourceManager: getLocalResourceManager() via singleton
    Bazel->>User: Executes command with interpolated environment
Loading

Poem

In the warren of code, a change hops through,
No more resourceManager fields in view.
Now workspace paths in envs appear,
With %bazel_workspace% swapped, all clear!
A test ensures the trick is sound,
As bunnies cheer and leap around.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/test/shell/bazel/starlark_repository_test.sh (1)

883-924: Good test implementation for the workspace path interpolation feature.

This test effectively validates the %bazel_workspace% interpolation in repository environment variables by:

  1. Creating a tool in the workspace
  2. Setting up a repo rule that uses the tool via a PATH environment variable with %bazel_workspace%
  3. Correctly handling platform-specific path separators for both Windows and non-Windows
  4. Verifying the tool executes properly with the interpolated path

Consider quoting $PATH in line 923 to prevent word splitting if it contains spaces:

-common --repo_env=PATH="$repo_env_path"
+common --repo_env=PATH="${repo_env_path}"
🧰 Tools
🪛 Shellcheck (0.10.0)

[warning] 923-923: Quote this to prevent word splitting.

(SC2046)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0c98a2 and 8cb1a07.

📒 Files selected for processing (3)
  • src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java (3 hunks)
  • src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java (1 hunks)
  • src/test/shell/bazel/starlark_repository_test.sh (1 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
src/test/shell/bazel/starlark_repository_test.sh

[warning] 923-923: Quote this to prevent word splitting.

(SC2046)

🔇 Additional comments (4)
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java (1)

545-547: Good documentation update for the %bazel_workspace% interpolation feature.

The help text addition clearly explains the functionality of replacing %bazel_workspace% with the absolute workspace path. This documentation is important for users to understand how to leverage this feature.

src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java (3)

236-236: Removal of resourceManager parameter from constructor.

The change simplifies the dependency structure by removing the resourceManager parameter, which will be obtained through the singleton instance instead.


358-360: Good implementation of the %bazel_workspace% interpolation feature.

The code properly checks for a non-null workspace before performing the replacement, preventing potential null pointer exceptions. The string replacement is straightforward and effectively implements the desired functionality.


718-718: Migrated to singleton ResourceManager pattern.

The method now uses the singleton ResourceManager.instance() instead of an instance field. This simplifies the API and removes the need for passing the ResourceManager through the constructor.

@visz11
Copy link
Collaborator Author

visz11 commented Apr 28, 2025

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for %bazel_workspace% interpolation in the --repo_env flag, allowing repository rules to access the workspace path. It also attempts to support Windows. The changes include modifications to CommandEnvironment.java, CommonCommandOptions.java, and starlark_repository_test.sh. Overall, the changes seem well-structured and include a new test case to verify the interpolation functionality. However, there are a few areas that could benefit from closer examination and potential improvement.

Summary of Findings

  • Resource Manager Removal: The ResourceManager field and its associated logic have been removed from CommandEnvironment.java. It's important to verify that this removal doesn't introduce any regressions or performance issues, especially concerning resource management during command execution. While the code now uses ResourceManager.instance(), it's crucial to ensure this singleton access pattern is appropriate and doesn't lead to contention or other unforeseen consequences.
  • Windows Support: The pull request description mentions an attempt to support Windows. The test case test_repo_env_workspace_interpolation includes a conditional check for $is_windows. It's important to ensure that the Windows-specific path handling is correct and that the test case adequately covers Windows scenarios. Further investigation may be needed to confirm that the changes are fully compatible with Windows.
  • Error Handling in Starlark Repository Test: In the test_repo_env_workspace_interpolation test, the error message in the fail function could be improved by including the actual PATH variable. This would provide more context when debugging test failures related to environment variable interpolation.

Merge Readiness

The pull request introduces a valuable feature with the %bazel_workspace% interpolation. However, the removal of the ResourceManager and the attempt to support Windows require careful consideration. I recommend addressing the identified issues before merging. I am unable to directly approve this pull request, and other reviewers should examine the code before merging.

Comment on lines +888 to +890
result = ctx.execute(["my_tool"])
if result.return_code != 0:
fail("my_tool failed ({}, PATH = {}): {}".format(result.return_code, ctx.os.environ["PATH"], result.stderr))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider including the actual PATH variable in the error message for better debugging:

fail("my_tool failed ({}, PATH = {}): {}".format(result.return_code, ctx.os.environ["PATH"], result.stderr))
Suggested change
result = ctx.execute(["my_tool"])
if result.return_code != 0:
fail("my_tool failed ({}, PATH = {}): {}".format(result.return_code, ctx.os.environ["PATH"], result.stderr))
fail "my_tool failed ($result.return_code, PATH = ${ctx.os.environ["PATH"]}): $result.stderr"

@visz11
Copy link
Collaborator Author

visz11 commented Sep 19, 2025

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Sep 19, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-test
Copy link

refacto-test bot commented Sep 19, 2025

Code Review: Repository Environment Interpolation

👍 Well Done
Workspace Path Interpolation

Added workspace path interpolation feature enhances repository rule flexibility and reliability.

📌 Files Processed
  • src/test/shell/bazel/starlark_repository_test.sh
  • src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java
  • src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java
📝 Additional Comments
src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java (5)
String Replacement Safety

String.replace() replaces all occurrences without bounds checking. If the replacement path contains special characters, it could cause unexpected behavior in repository rules. Consider validating or escaping the workspace path before interpolation.

Standards:

  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
Resource Manager Singleton

Switching to a singleton pattern for ResourceManager could create contention under high load. Consider evaluating if this change impacts performance when multiple commands execute concurrently, as singletons can become bottlenecks in multi-threaded environments.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Concurrency
  • Resource-Management-Efficiency
Path Sanitization Needed

Path string is directly inserted without sanitization or normalization. Consider normalizing the path and implementing path validation to prevent potential directory traversal attacks when the path is later used in file operations.

Standards:

  • CWE-22
  • OWASP-A03
  • NIST-SSDF-PW.1
Conditional Path Interpolation

The interpolation logic doesn't handle the case where workspace.getWorkspace() is null but the string contains %bazel_workspace%. Consider adding a warning or error message when interpolation is requested but cannot be performed due to null workspace.

Standards:

  • Business-Rule-Input-Validation
  • Logic-Verification-Error-Handling
Constructor Parameter Removal

The resourceManager parameter was removed from the constructor but the field was also removed. This maintains functional correctness but changes initialization pattern. Consider documenting this architectural change for maintainability.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • DbC-Resource-Mgmt
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java (1)
Documentation Update

The documentation update correctly describes the new functionality but uses HTML tags in a context that might not render them correctly. Consider using plain text formatting for consistency across different documentation rendering systems.

Standards:

  • Clean-Code-Documentation
  • Maintainability-Quality-Documentation

Comment on lines +358 to +360
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Path Injection Risk

Direct string replacement of %bazel_workspace% with workspace path without validation creates path injection vulnerability. Malicious repository rules could exploit this to manipulate paths and potentially access files outside intended boundaries. This could lead to unauthorized file access or path traversal attacks.

        if (workspace.getWorkspace() != null) {
          Path workspacePath = workspace.getWorkspace();
          // Normalize path to prevent path traversal attacks
          String normalizedPath = workspacePath.normalize().toAbsolutePath().toString();
          value = value.replace("%bazel_workspace%", normalizedPath);
        } else {
          logger.warning("Cannot interpolate %bazel_workspace% as workspace is null");
        }
Commitable Suggestion
Suggested change
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
}
if (workspace.getWorkspace() != null) {
Path workspacePath = workspace.getWorkspace();
// Normalize path to prevent path traversal attacks
String normalizedPath = workspacePath.normalize().toAbsolutePath().toString();
value = value.replace("%bazel_workspace%", normalizedPath);
} else {
logger.warning("Cannot interpolate %bazel_workspace% as workspace is null");
}
Standards
  • CWE-22
  • CWE-73
  • OWASP-A01

Comment on lines +358 to +360
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Null Workspace Check

The workspace null check protects against NPE, but there's no handling for the case when workspace is null. Without fallback behavior, repository rules using %bazel_workspace% will receive uninterpolated values, causing potential runtime failures.

        if (workspace.getWorkspace() != null) {
          value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
        } else {
          logger.warning("Cannot interpolate %bazel_workspace% as workspace is null");
          // Leave the placeholder unchanged to avoid silent failures
        }
Commitable Suggestion
Suggested change
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
}
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
} else {
logger.warning("Cannot interpolate %bazel_workspace% as workspace is null");
// Leave the placeholder unchanged to avoid silent failures
}
Standards
  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • SRE-Error-Handling

Comment on lines 717 to +718
public ResourceManager getLocalResourceManager() {
return resourceManager;
return ResourceManager.instance();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ResourceManager Reference Change

Method implementation changed from returning stored resourceManager field to ResourceManager.instance(). This changes from instance-specific to global singleton access pattern, potentially affecting resource isolation and reliability in multi-environment scenarios.

Standards
  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • DbC-Resource-Mgmt


public ResourceManager getLocalResourceManager() {
return resourceManager;
return ResourceManager.instance();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resource Manager Reference

The constructor parameter resourceManager was removed but the getLocalResourceManager method now returns a global singleton instead of the instance-specific reference. This changes the logical behavior from using a command-specific resource manager to a global one, potentially affecting resource management isolation.

Standards
  • Business-Rule-State-Consistency
  • Logic-Verification-Data-Flow

private final RemoteAnalysisCachingEventListener remoteAnalysisCachingEventListener;
private final ImmutableList.Builder<IdleTask> idleTasks = ImmutableList.builder();
private final ResourceManager resourceManager;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary Field Removal

The resourceManager field was removed but its usage pattern was changed to a singleton access. This creates an inconsistent pattern where some dependencies are injected while others use global state, reducing maintainability.

Standards
  • Clean-Code-Consistency
  • Maintainability-Quality-Dependency-Management
  • SOLID-DIP

@Nullable String buildRequestIdOverride,
ConfigFlagDefinitions configFlagDefinitions,
ResourceManager resourceManager) {
ConfigFlagDefinitions configFlagDefinitions) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Constructor Parameter Removal

The resourceManager parameter was removed from the constructor but its usage was changed to a singleton access pattern. This creates inconsistent dependency management where some components are injected while others use global state.

Standards
  • SOLID-DIP
  • Clean-Code-Dependency-Management
  • Design-Pattern-Dependency-Injection

Comment on lines +358 to +360
if (workspace.getWorkspace() != null) {
value = value.replace("%bazel_workspace%", workspace.getWorkspace().getPathString());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String Replacement Logic

String replacement is performed unconditionally without checking if the placeholder exists in the value. This could lead to unnecessary string operations for every environment variable, impacting performance with large environment sets.

Standards
  • Clean-Code-Performance
  • Maintainability-Quality-Optimization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant