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

Fixed eslint_disable_check.py (Fixes #3272) #3273

Conversation

adithyanotfound
Copy link
Contributor

@adithyanotfound adithyanotfound commented Jan 14, 2025

Issue Number:

Fixes #3272

Snapshots/Videos:

Screenshot 2025-01-14 at 1 29 00 PM

Does this PR introduce a breaking change?

No.

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Have you read the contributing guide?

Yes

Summary by CodeRabbit

Summary by CodeRabbit

  • Workflow Updates

    • Added a new job to the GitHub Actions workflow to check for code coverage disablement.
    • Updated workflow structure to ensure the new check runs before application tests.
  • Script Improvements

    • Enhanced regex pattern for detecting eslint-disable comments in TypeScript files.
    • Streamlined error handling in the eslint check script for improved clarity.
    • Simplified file and directory checking mechanism for better readability.

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces a new job named "Check-Code-Coverage-Disable" to the GitHub Actions workflow in .github/workflows/pull-request.yml. This job checks for code coverage disablement by executing a Python script on the changed files. Additionally, the existing "Test-Application" job is updated to depend on this new job. The eslint_disable_check.py script has also been modified to enhance the regex for detecting eslint-disable statements, streamline error handling, and improve overall readability.

Changes

File Change Summary
.github/workflows/pull-request.yml - Added new job: Check-Code-Coverage-Disable
- Updated "Test-Application" job to depend on the new job
.github/workflows/scripts/eslint_disable_check.py - Enhanced regex pattern for eslint-disable detection
- Streamlined error handling
- Consolidated file extension checking
- Updated argument parser help descriptions

Assessment against linked issues

Objective Addressed Explanation
Detect all variants of eslint-disable
Fail PR when eslint-disable is found
Cover eslint configuration options

Possibly related PRs

Suggested reviewers

  • palisadoes
  • varshith257
  • noman2002

Poem

🐰 In the realm of code, a rabbit's delight,
Eslint's whispers now shine so bright!
TypeScript files, filtered with care,
No more linting errors to despair!
A workflow dance, clean and neat,
Our code's quality now complete! 🔍✨


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.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 197092f and 287a983.

📒 Files selected for processing (2)
  • .github/workflows/pull-request.yml (1 hunks)
  • .github/workflows/scripts/eslint_disable_check.py (4 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/pull-request.yml

200-200: workflow command "set-output" was deprecated. use echo "{name}={value}" >> $GITHUB_OUTPUT instead: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions

(deprecated-commands)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Application
🔇 Additional comments (3)
.github/workflows/scripts/eslint_disable_check.py (3)

41-42: LGTM! Robust regex pattern implementation.

The enhanced regex pattern effectively captures all variations of eslint-disable comments including:

  • Single-line comments
  • Block comments
  • Multiline block comments

55-55: LGTM! Consistent error handling.

The streamlined error handling provides consistent behavior across all error cases.


71-74: LGTM! Clean and maintainable implementation.

The file checking logic is well-structured with:

  • Consolidated extension checking
  • Consistent error messages
  • Clear control flow

Also applies to: 81-84

.github/workflows/pull-request.yml Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 14, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.99%. Comparing base (197092f) to head (5bba47b).
Report is 3 commits behind head on develop-postgres.

Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #3273       +/-   ##
=====================================================
+ Coverage              8.49%   89.99%   +81.50%     
=====================================================
  Files                   309      330       +21     
  Lines                  7832     8519      +687     
  Branches               1730     1884      +154     
=====================================================
+ Hits                    665     7667     +7002     
+ Misses                 7093      598     -6495     
- Partials                 74      254      +180     
Flag Coverage Δ
combined 89.99% <ø> (?)
jest 8.56% <ø> (?)
vitest 89.99% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 14, 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 (2)
.github/workflows/scripts/eslint_disable_check.py (2)

71-76: Optimize file checking logic for better readability and performance.

The current implementation could be improved by:

  1. Using early returns to reduce nesting
  2. Extracting the file checking logic into a separate function
  3. Optimizing directory traversal

Consider this refactoring:

+def _check_single_file(file_path):
+    """Check a single file for eslint-disable statements."""
+    if not file_path.endswith((".ts", ".tsx")):
+        return False
+    
+    if has_eslint_disable(file_path):
+        print(f"Error: File {file_path} contains eslint-disable statements.")
+        return True
+    return False

 def check_eslint(files_or_directories):
     eslint_found = False
 
     for item in files_or_directories:
         if os.path.isfile(item):
-            if item.endswith((".ts", ".tsx")) and has_eslint_disable(item):
-                print(
-                    f"Error: File {item} contains eslint-disable statements."
-                )
-                eslint_found = True
+            eslint_found |= _check_single_file(item)
         elif os.path.isdir(item):
             for root, _, files in os.walk(item):
                 if "node_modules" in root:
                     continue
                 for file_name in files:
-                    if file_name.endswith((".ts", ".tsx")):
-                        file_path = os.path.join(root, file_name)
-                        if has_eslint_disable(file_path):
-                            print(
-                                f"Error: File {file_path} contains eslint-disable statements."
-                            )
-                            eslint_found = True
+                    file_path = os.path.join(root, file_name)
+                    eslint_found |= _check_single_file(file_path)
     return eslint_found

Also applies to: 78-89


101-103: Enhance argument parser with validation and detailed help.

While the help messages are more concise, consider:

  1. Adding path validation
  2. Providing more detailed help with examples
  3. Adding type hints for better IDE support

Consider these improvements:

+from typing import List, Optional
+from pathlib import Path

+def validate_path(path: str) -> str:
+    """Validate if path exists."""
+    if not os.path.exists(path):
+        raise argparse.ArgumentTypeError(f"Path does not exist: {path}")
+    return path

 def arg_parser_resolver():
     parser = argparse.ArgumentParser(
-        description="Check TypeScript files for eslint-disable statements."
+        description="Check TypeScript files for eslint-disable statements.",
+        epilog="Example: %(prog)s --files src/foo.ts src/bar.ts --directory src/components"
     )
     parser.add_argument(
         "--files",
-        type=str,
+        type=validate_path,
         nargs="+",
         default=[],
-        help="List of files to check for eslint-disable statements.",
+        help="List of TypeScript files to check (e.g., src/foo.ts).",
     )
     parser.add_argument(
         "--directory",
-        type=str,
+        type=validate_path,
         nargs="+",
         default=[os.getcwd()],
-        help="One or more directories to check for eslint-disable statements.",
+        help="Directories to recursively check (default: current directory).",
     )

Also applies to: 109-109, 116-116

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 287a983 and d765c0a.

📒 Files selected for processing (2)
  • .github/workflows/pull-request.yml (1 hunks)
  • .github/workflows/scripts/eslint_disable_check.py (4 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/pull-request.yml

200-200: shellcheck reported issue in this script: SC2086:info:1:135: Double quote to prevent globbing and word splitting

(shellcheck)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Check Python Code Style
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (2)
.github/workflows/pull-request.yml (1)

205-207: LGTM! Efficient conditional execution.

The conditional execution ensures the script only runs when TypeScript files are present, improving workflow efficiency.

.github/workflows/scripts/eslint_disable_check.py (1)

41-42: Verify regex pattern coverage and performance.

The regex pattern has been enhanced to handle various eslint-disable comment formats. However, consider:

  1. Adding test cases for edge cases (unusual whitespace, nested comments)
  2. Performance implications of the pattern's complexity

Let's verify the pattern coverage with this script:

✅ Verification successful

The regex pattern is well-designed and comprehensive

The pattern effectively handles:

  • Single-line eslint-disable comments with various formats
  • Multi-line block comments with the re.DOTALL flag
  • Case-insensitive matching with re.IGNORECASE
  • Various whitespace patterns and rule specifications
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential eslint-disable patterns that might be missed

# Create a temporary test file
cat << 'EOF' > test_patterns.ts
// eslint-disable
//eslint-disable
// eslint-disable-next-line
/*eslint-disable*/
/* eslint-disable */
/*
  eslint-disable
*/
/**
 * eslint-disable
 */
EOF

# Test the script against these patterns
python .github/workflows/scripts/eslint_disable_check.py --files test_patterns.ts

# Clean up
rm test_patterns.ts

Length of output: 209


Script:

#!/bin/bash
# Create a test file with various eslint-disable patterns
cat << 'EOF' > test_patterns.ts
// eslint-disable
//eslint-disable
// eslint-disable-next-line
/*eslint-disable*/
/* eslint-disable */
/*
  eslint-disable
*/
/**
 * eslint-disable
 */
// ESLINT-DISABLE
/* ESLINT-DISABLE */
//  eslint-disable  some-rule, other-rule
/* eslint-disable
   some-rule,
   other-rule
*/
EOF

# Use ripgrep to test the pattern
echo "Testing eslint-disable pattern matches:"
rg -i "//\s*eslint-disable(?:-next-line|-line)?[^\n]*|/\*\s*eslint-disable[^\*]*\*/|/\*[\s\S]*?eslint-disable[\s\S]*?\*/" test_patterns.ts

# Clean up
rm test_patterns.ts

Length of output: 441


Script:

#!/bin/bash
# Create a test file with various eslint-disable patterns
cat << 'EOF' > test_patterns.ts
// eslint-disable
//eslint-disable
// eslint-disable-next-line
/*eslint-disable*/
/* eslint-disable */
/*
  eslint-disable
*/
/**
 * eslint-disable
 */
// ESLINT-DISABLE
/* ESLINT-DISABLE */
//  eslint-disable  some-rule, other-rule
/* eslint-disable
   some-rule,
   other-rule
*/
EOF

# Use ripgrep with modified pattern to handle multi-line cases
echo "Testing with adjusted pattern:"
rg -i -U "//\s*eslint-disable(?:-next-line|-line)?[^\n]*|/\*(?:[^*]|\*(?!/))*eslint-disable(?:[^*]|\*(?!/))*\*/" test_patterns.ts

# Clean up
rm test_patterns.ts

Length of output: 595

.github/workflows/pull-request.yml Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 14, 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: 1

🧹 Nitpick comments (1)
.github/workflows/pull-request.yml (1)

205-207: Consider adding error handling for the Python script.

The conditional check ensures the script only runs when TypeScript files are present, but there's no explicit error handling if the Python script fails.

Consider adding error handling:

       if: steps.filter-files.outputs.ts_files != ''
       run: |
+          set -e  # Exit on error
           python .github/workflows/scripts/eslint_disable_check.py --files ${{ steps.filter-files.outputs.ts_files }}
+      continue-on-error: false  # Ensure the workflow fails if the script fails
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d765c0a and 8dbff8c.

📒 Files selected for processing (2)
  • .github/workflows/pull-request.yml (1 hunks)
  • .github/workflows/scripts/eslint_disable_check.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/scripts/eslint_disable_check.py
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/pull-request.yml

200-200: shellcheck reported issue in this script: SC2086:info:1:136: Double quote to prevent globbing and word splitting

(shellcheck)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test Application
  • GitHub Check: Check Python Code Style
  • GitHub Check: Analyse Code With CodeQL (javascript)

.github/workflows/pull-request.yml Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 14, 2025
@Cioppolo14 Cioppolo14 removed the request for review from palisadoes January 14, 2025 13:44
@Cioppolo14
Copy link
Contributor

@adithyanotfound Can the failed test on python code style be fixed?

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 14, 2025
@adithyanotfound
Copy link
Contributor Author

adithyanotfound commented Jan 14, 2025

@adithyanotfound Can the failed test on python code style be fixed?

Fixed the failed test

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 14, 2025
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

See comments

.github/workflows/pull-request.yml Outdated Show resolved Hide resolved
.github/workflows/scripts/eslint_disable_check.py Outdated Show resolved Hide resolved
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: 0

🧹 Nitpick comments (2)
.github/workflows/pull-request.yml (2)

Line range hint 207-227: Add error handling and script verification.

While the job implementation follows best practices, consider these improvements for robustness:

       - name: Run Python script
         run: |
+          if [ ! -f .github/workflows/scripts/code_coverage_disable_check.py ]; then
+            echo "Error: code_coverage_disable_check.py script not found"
+            exit 1
+          fi
+          chmod +x .github/workflows/scripts/code_coverage_disable_check.py
           python .github/workflows/scripts/code_coverage_disable_check.py --files ${{ steps.changed-files.outputs.all_changed_files }} 
+        continue-on-error: false

Line range hint 219-221: Align Python versions across jobs.

The workflow uses Python 3.11 in the "Python-Compliance" job but Python 3.9 here. Consider updating to Python 3.11 for consistency:

       - name: Set up Python
         uses: actions/setup-python@v5
         with:
-          python-version: 3.9
+          python-version: 3.11
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 314d235 and 5bba47b.

📒 Files selected for processing (2)
  • .github/workflows/pull-request.yml (1 hunks)
  • .github/workflows/scripts/eslint_disable_check.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/scripts/eslint_disable_check.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (1)
.github/workflows/pull-request.yml (1)

Line range hint 228-228: LGTM! Dependencies are correctly configured.

The addition of "Check-Code-Coverage-Disable" to the needs array ensures proper sequencing of checks before running tests.

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

See comment

@palisadoes palisadoes merged commit 334f0f7 into PalisadoesFoundation:develop-postgres Jan 14, 2025
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants