Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add runCode function to execute temporary scripts in various languages #264

Merged
merged 5 commits into from
Jan 25, 2025

Conversation

hawkeyexl
Copy link
Contributor

@hawkeyexl hawkeyexl commented Jan 21, 2025

Summary by CodeRabbit

  • New Features
    • Added a new module for executing code snippets across different programming languages
    • Supports code validation and execution for Python, JavaScript, and Bash
    • Includes error handling and temporary file management for code execution

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jan 21, 2025
Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (1)
  • rc

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The new src/tests/runCode.js module introduces a comprehensive function runCode designed to execute code snippets across multiple programming languages. This utility handles input validation, temporary script file creation, command verification, and script execution. It supports Python, JavaScript, and Bash languages, with built-in error handling and platform compatibility checks. The module provides a flexible mechanism for running code in a controlled, temporary environment.

Changes

File Change Summary
src/tests/runCode.js Added new module with runCode function for executing code snippets across languages

Sequence Diagram

sequenceDiagram
    participant Caller
    participant RunCode
    participant Validator
    participant TempFileManager
    participant ScriptExecutor

    Caller->>RunCode: Invoke with config and step
    RunCode->>Validator: Validate input
    alt Input Invalid
        Validator-->>RunCode: Validation Failure
        RunCode-->>Caller: Return Error
    else Input Valid
        RunCode->>TempFileManager: Create Temporary Script
        RunCode->>ScriptExecutor: Execute Script
        ScriptExecutor-->>RunCode: Execution Results
        RunCode->>TempFileManager: Delete Temporary Script
        RunCode-->>Caller: Return Execution Results
    end
Loading

Poem

🐰 Code Hopping Rabbit's Delight

In temp files, I dance with might
Python, Bash, JavaScript too
Executing scripts, my magic brew
Validation tight, errors in sight
A coding rabbit's pure delight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

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.

@hawkeyexl hawkeyexl changed the base branch from main to 2.19.0 January 21, 2025 19:05
@hawkeyexl hawkeyexl linked an issue Jan 21, 2025 that may be closed by this pull request
@dosubot dosubot bot added the enhancement New feature or request label Jan 21, 2025
Copy link
Contributor

@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: 2

🧹 Nitpick comments (5)
src/tests/runCode.js (5)

62-69: Synchronize command determination logic

There's duplication in determining the command based on the language in both lines 62-69 and 91-96. To enhance maintainability, consider extracting this logic into a separate function to avoid inconsistencies and make future updates easier.

Apply this diff to extract the logic:

+      function getCommandFromLanguage(language) {
+        const lang = language.toLowerCase();
+        if (lang === "python" || lang === "py") return "python";
+        if (lang === "javascript" || lang === "js" || lang === "node") return "node";
+        if (lang === "bash") return "bash";
+        throw new Error(`Unsupported language: ${language}`);
+      }

       // Determine command if not specified
       if (!step.command) {
-        step.command =
-          step.language.toLowerCase() === "python"
-            ? "python"
-            : step.language.toLowerCase() === "javascript"
-            ? "node"
-            : "bash";
+        step.command = getCommandFromLanguage(step.language);
       }

       // Prepare shell command based on language
       const command = step.command;
+      // Use the same function here
       const shellStep = {
         ...step,
         action: "runShell",
-        command:
-          step.language.toLowerCase() === "python"
-            ? "python"
-            : step.language.toLowerCase() === "javascript"
-            ? "node"
-            : "bash",
+        command: getCommandFromLanguage(step.language),
         args: [scriptPath, ...(step.args || [])],
       };

This refactoring reduces code duplication and centralizes the command determination logic.


98-101: Avoid using the delete operator for better performance

Using the delete operator can negatively impact performance because it forces the JavaScript engine to reoptimize the object structure. Instead of deleting properties, consider setting them to undefined or restructuring your code to avoid the need to remove properties.

Apply this diff to set properties to undefined:

       if (step.code) delete shellStep.code;
       if (step.language) delete shellStep.language;
       if (step.file) delete shellStep.file;
       if (step.group) delete shellStep.group;
+      // Set properties to undefined instead
+      if (step.code) shellStep.code = undefined;
+      if (step.language) shellStep.language = undefined;
+      if (step.file) shellStep.file = undefined;
+      if (step.group) shellStep.group = undefined;

Alternatively, you could create a new object excluding these properties to avoid mutation:

       // Create a new object without certain properties
       const { code, language, file, group, ...shellStep } = step;

This approach prevents side effects and maintains performance.

🧰 Tools
🪛 Biome (1.9.4)

[error] 98-98: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 99-99: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 100-100: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 101-101: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


103-103: Use consistent logging mechanisms

The console.log statement on line 103 might not align with your application's logging strategy. Consider using the log function provided in your utilities for consistent logging practices.

Apply this diff to use the log function:

-    console.log("shellStep", shellStep);
+    log(config, "debug", `shellStep: ${JSON.stringify(shellStep)}`);

This ensures that logging respects the configured log level and format.


80-84: Extend Windows support for Bash scripts

The current implementation restricts running Bash scripts on Windows platforms. Since Windows 10, it's possible to run Bash scripts using environments like Git Bash or the Windows Subsystem for Linux (WSL). Consider detecting these environments to provide broader support.

You might adjust the code to check for available Bash environments:

         if (os.platform() === "win32" && command === "bash") {
-          result.status = "FAIL";
-          result.description = `runCode currently doesn't support bash on Windows. Use a different command, a different language, or a runShell step.`;
-          return result;
+          // Check if Bash is available on Windows
+          const bashAvailable = await spawnCommand("bash", ["--version"]);
+          if (bashAvailable.exitCode !== 0) {
+            result.status = "FAIL";
+            result.description = `Bash is not available on this Windows system. Install Git Bash or WSL, or use a different language.`;
+            return result;
+          }
         }

This enhancement allows users with Bash installed to run scripts on Windows platforms.


15-37: Consider handling more languages and extensions

The createTempScript function currently supports Python, JavaScript, and Bash. If there's a need to support additional languages in the future, it might be useful to design the function to be more extensible.

Consider using a mapping for languages to extensions:

       function createTempScript(code, language) {
-        let extension;
-        switch (language) {
-          case "python":
-          case "py":
-            extension = ".py";
-            break;
-          case "javascript":
-          case "js":
-          case "node":
-            extension = ".js";
-            break;
-          case "bash":
-            extension = ".sh";
-            break;
-          default:
-            extension = "";
-        }
+        const extensionMap = {
+          python: ".py",
+          py: ".py",
+          javascript: ".js",
+          js: ".js",
+          node: ".js",
+          bash: ".sh",
+          sh: ".sh",
+        };
+        const extension = extensionMap[language.toLowerCase()];
+        if (!extension) {
+          throw new Error(`Unsupported language: ${language}`);
+        }
         const tmpDir = os.tmpdir();
         const tmpFile = path.join(tmpDir, `doc-detective-${Date.now()}${extension}`);
         fs.writeFileSync(tmpFile, code);
         return tmpFile;
       }

This refactoring makes it easier to add support for new languages by updating the extensionMap.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2b404 and 54c4010.

📒 Files selected for processing (1)
  • src/tests/runCode.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/tests/runCode.js

[error] 98-98: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 99-99: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 100-100: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 101-101: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test (macos-latest, 20)
  • GitHub Check: test (macos-latest, 18)
  • GitHub Check: test (windows-latest, 20)
  • GitHub Check: test (windows-latest, 18)
  • GitHub Check: test (ubuntu-latest, 20)
  • GitHub Check: test (ubuntu-latest, 18)

: step.language.toLowerCase() === "javascript"
? "node"
: "bash",
args: [scriptPath, ...step.args],
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure step.args is defined before spreading

On line 96, spreading step.args without verifying its existence can lead to errors if step.args is undefined. To prevent this, default step.args to an empty array when it's missing.

Apply this diff to handle step.args safely:

-        args: [scriptPath, ...step.args],
+        args: [scriptPath, ...(step.args || [])],

This change ensures that the spread operator always receives an array, avoiding potential runtime exceptions.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
args: [scriptPath, ...step.args],
args: [scriptPath, ...(step.args || [])],

Comment on lines +91 to +96
step.language.toLowerCase() === "python"
? "python"
: step.language.toLowerCase() === "javascript"
? "node"
: "bash",
args: [scriptPath, ...step.args],
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle unsupported languages more explicitly

Currently, the code defaults to "bash" when the step.language is neither "python" nor "javascript". This could lead to unexpected behavior if an unsupported language is specified. It's better to explicitly handle unsupported languages by throwing an error or returning a meaningful message to the user.

Apply this diff to handle unsupported languages:

       // Prepare shell command based on language
       const shellStep = {
         ...step,
         action: "runShell",
-        command:
-          step.language.toLowerCase() === "python"
-            ? "python"
-            : step.language.toLowerCase() === "javascript"
-            ? "node"
-            : "bash",
+        command: (() => {
+          const lang = step.language.toLowerCase();
+          if (lang === "python" || lang === "py") return "python";
+          if (lang === "javascript" || lang === "js" || lang === "node") return "node";
+          if (lang === "bash") return "bash";
+          throw new Error(`Unsupported language: ${step.language}`);
+        })(),
         args: [scriptPath, ...(step.args || [])],
       };

This change ensures that only supported languages are processed, and provides clear feedback when an unsupported language is encountered.

Committable suggestion skipped: line range outside the PR's diff.

@hawkeyexl hawkeyexl merged commit 2362ddb into 2.19.0 Jan 25, 2025
8 checks passed
@hawkeyexl hawkeyexl deleted the runCode branch February 1, 2025 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

runCode action
1 participant