Skip to content

refactor:remove PLR0912 ignore and fix 4 violations #1834

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

trucodd
Copy link
Contributor

@trucodd trucodd commented Jul 25, 2025

Proposed change

Resolves #1826

This PR addresses PLR0912 issues by:
Fixing 4 existing cases
Removing PLR0912 from pyproject.toml ignore list

Checklist

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.

@trucodd trucodd requested a review from arkid15r as a code owner July 25, 2025 02:18
Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Summary by CodeRabbit

  • Refactor

    • Streamlined and modularized backend logic for extracting and synchronizing content and metadata, improving maintainability and clarity.
    • Consolidated repetitive code into loops, comprehensions, and helper methods for more efficient data processing.
    • Enhanced modularity in repository synchronization and funding compliance checks.
  • Chores

    • Updated linter configuration to enforce stricter code quality by enabling the "too-many-branches" rule.

Walkthrough

The codebase was refactored to address and eliminate violations of the "too-many-branches" (PLR0912) linter rule. Several large functions were modularized by extracting logic into helper methods, reducing branching complexity. The Ruff linter configuration was updated to remove the PLR0912 rule from the ignore list, enabling enforcement.

Changes

Cohort / File(s) Change Summary
AI content extraction commands
backend/apps/ai/management/commands/ai_create_chapter_chunks.py, backend/apps/ai/management/commands/ai_create_project_chunks.py
Refactored content extraction logic to replace repetitive conditionals with loops and helper methods, improving structure and clarity.
GitHub repository synchronization helpers
backend/apps/github/common.py
Split large repository sync function into multiple private helper functions to modularize milestone, issue, pull request, release, and contributor syncing logic.
GitHub repository model enhancements
backend/apps/github/models/repository.py
Refactored from_github method by extracting commits, contributors, languages, and funding data processing into private helper methods; added incremental sync methods for milestones, issues, pull requests, releases, and contributors.
GitHub funding compliance utility
backend/apps/github/utils.py
Changed funding policy compliance check to handle multiple targets, adding helper for single target compliance check.
Linter configuration update
backend/pyproject.toml
Removed "PLR0912" (too-many-branches) rule from Ruff linter ignore list to enable enforcement of this rule.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Assessment against linked issues

Objective Addressed Explanation
Remove "PLR0912" from Ruff linter ignore list and address existing cases (#1826)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

Suggested reviewers

  • arkid15r

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76ac7f6 and f443326.

📒 Files selected for processing (1)
  • backend/apps/ai/management/commands/ai_create_chapter_chunks.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/apps/ai/management/commands/ai_create_chapter_chunks.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate unit tests to generate unit tests for 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.

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
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 (1)
backend/apps/github/models/repository.py (1)

298-303: Consider improving readability of the funding compliance check.

While the comprehension is concise, the nested logic with conditional list handling might be difficult to understand. Consider extracting this to a separate method or using a more explicit loop for better maintainability.

-self.is_funding_policy_compliant = all(
-    check_funding_policy_compliance(platform, target)
-    for platform, targets in self.funding_yml.items()
-    for target in (targets if isinstance(targets, list) else [targets])
-    if target
-)
+self.is_funding_policy_compliant = self._check_all_funding_compliance()

Add this helper method:

def _check_all_funding_compliance(self) -> bool:
    """Check if all funding targets are policy compliant."""
    for platform, targets in self.funding_yml.items():
        # Normalize to list for consistent processing
        target_list = targets if isinstance(targets, list) else [targets]
        for target in target_list:
            if target and not check_funding_policy_compliance(platform, target):
                return False
    return True
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dff9f2e and f4f07c7.

📒 Files selected for processing (5)
  • backend/apps/ai/management/commands/ai_create_chapter_chunks.py (2 hunks)
  • backend/apps/ai/management/commands/ai_create_project_chunks.py (2 hunks)
  • backend/apps/github/common.py (2 hunks)
  • backend/apps/github/models/repository.py (2 hunks)
  • backend/pyproject.toml (0 hunks)
💤 Files with no reviewable changes (1)
  • backend/pyproject.toml
🔇 Additional comments (14)
backend/apps/ai/management/commands/ai_create_chapter_chunks.py (4)

104-108: Good refactoring to reduce code duplication.

The use of getattr with a loop effectively reduces repetitive conditional blocks while maintaining the same functionality.


110-116: Safe repository access with getattr.

Good use of getattr to safely access the owasp_repository attribute, preventing potential AttributeError.


121-132: Elegant consolidation of location fields.

The list comprehension effectively consolidates multiple conditional checks into a single, readable operation while maintaining the same filtering logic.


135-146: Well-structured metadata processing.

The loop-based approach with dynamic type handling for lists effectively reduces code duplication while preserving the original logic.

backend/apps/github/models/repository.py (2)

250-259: Excellent modularization pattern.

The use of a loop with (data, processor) tuples elegantly handles optional data sources and reduces branching complexity.


270-277: Clean extraction of commits processing logic.

The method properly handles the edge case of empty repositories with appropriate exception handling.

backend/apps/ai/management/commands/ai_create_project_chunks.py (4)

93-103: Clever use of target list in tuple pattern.

The inclusion of the target list in the tuple allows for dynamic routing of content to the appropriate list, effectively reducing code duplication.


125-137: Efficient statistics aggregation.

Good use of list comprehension with filtering to create a concise statistics summary, excluding zero values.


157-162: Clean helper method for list metadata.

Simple and effective extraction that reduces code duplication for list-based metadata fields.


163-187: Well-organized additional metadata handling.

The method effectively groups related metadata logic, maintaining clear separation of concerns.

backend/apps/github/common.py (4)

42-70: Excellent modularization of sync_repository.

The refactoring transforms a complex function into a clear, high-level orchestrator that delegates specific sync operations to focused helper functions. This greatly improves code maintainability and readability.


72-98: Well-structured milestone synchronization.

The extracted function maintains the original logic with proper date-based filtering and exception handling.


174-188: Excellent DRY implementation.

The shared helper function effectively eliminates code duplication between issue and pull request processing while maintaining proper error handling.


212-221: Elegant use of walrus operator.

The list comprehension with walrus operator efficiently handles user updates while filtering out None values in a single pass.

@trucodd trucodd marked this pull request as draft July 25, 2025 09:09
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

@trucodd is it still WIP? I saw it ready for review but then it was converted to a draft.

Please let me know when you're done -- I have some ideas on how to refactor it.

@trucodd trucodd marked this pull request as ready for review July 26, 2025 03:28
@trucodd
Copy link
Contributor Author

trucodd commented Jul 26, 2025

@trucodd is it still WIP? I saw it ready for review but then it was converted to a draft.

Please let me know when you're done -- I have some ideas on how to refactor it.

Hey I didnt make any new changes just marked for review again let me know your suggestions

@arkid15r
Copy link
Collaborator

@trucodd is it still WIP? I saw it ready for review but then it was converted to a draft.
Please let me know when you're done -- I have some ideas on how to refactor it.

Hey I didnt make any new changes just marked for review again let me know your suggestions

@trucodd I'm off for today, will review it later. Feel free to join OWASP Slack if you want to discuss anything it DM.

@trucodd trucodd force-pushed the feature/fix-plr0912 branch 2 times, most recently from 845a82c to d6cdb73 Compare July 26, 2025 18:00
@trucodd trucodd force-pushed the feature/fix-plr0912 branch from d6cdb73 to 80fc1e1 Compare July 28, 2025 04:03
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

Sorry, just got to this PR. Here are some suggestions to consider:

if hasattr(chapter, "owasp_repository") and chapter.owasp_repository:
repo = chapter.owasp_repository
# Prose content
for field, label in [("description", "Description"), ("summary", "Summary")]:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Use tuples for immutable containers

Comment on lines 62 to 67
_sync_repository_milestones(gh_repository, repository)
_sync_repository_issues(gh_repository, repository)
_sync_repository_pull_requests(gh_repository, repository)

_sync_repository_releases(gh_repository, repository, is_owasp_site_repository)
_sync_repository_contributors(gh_repository, repository)
Copy link
Collaborator

Choose a reason for hiding this comment

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

It looks like these can be defined as Repository model methods, it's fine to make it fatter.

# FKs.
self.organization = organization
self.owner = user
def _check_all_funding_compliance(self) -> bool:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe it'd be better to refactor check_funding_policy_compliance function to accept an iterable instead of a single target?

@trucodd trucodd requested a review from arkid15r July 28, 2025 07:49
@trucodd trucodd marked this pull request as draft July 28, 2025 12:43
Copy link

@trucodd trucodd marked this pull request as ready for review July 28, 2025 13:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Address PLR0912 ignored cases and remove the code from ignored
2 participants