Skip to content

refactor:remove PLR0912 ignore and fix 4 violations update #1979

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 5 commits into
base: main
Choose a base branch
from

Conversation

trucodd
Copy link
Contributor

@trucodd trucodd commented Aug 5, 2025

Proposed change

Resolves #1826

This PR addresses PLR0912 issue 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 August 5, 2025 07:47
Copy link
Contributor

coderabbitai bot commented Aug 5, 2025

Summary by CodeRabbit

  • Refactor

    • Improved clarity and consistency in processing chapter and project content, consolidating logic and introducing helper methods for more maintainable code.
    • Simplified repository synchronization by delegating detailed sync operations to dedicated methods, resulting in a cleaner and more modular workflow.
    • Enhanced modularity and error handling in GitHub repository data processing and synchronization, with new methods for syncing milestones, issues, pull requests, releases, and contributors.
  • Bug Fixes

    • Improved filtering and handling of related URLs and metadata fields to ensure more robust data extraction.
  • Chores

    • Updated linter configuration to enforce the "too-many-branches" rule, promoting cleaner code structure.

Walkthrough

This set of changes refactors several backend modules to address "too-many-branches" (PLR0912) linter violations. Key methods in AI management commands and GitHub repository synchronization are modularized, introducing helper methods and loops to reduce branching complexity. The Ruff linter configuration is updated to enforce PLR0912 by removing it from ignored rules.

Changes

Cohort / File(s) Change Summary
AI Chapter Chunk Extraction Refactor
backend/apps/ai/management/commands/ai_create_chapter_chunks.py
Refactored chapter content extraction logic for clarity and consistency, consolidating field processing into loops and comprehensions without changing method signatures or output.
AI Project Chunk Extraction Refactor
backend/apps/ai/management/commands/ai_create_project_chunks.py
Refactored project content extraction by grouping related fields, introducing helper methods, and modularizing logic to reduce branching and improve structure.
GitHub Repository Sync Refactor
backend/apps/github/common.py
Simplified sync_repository by delegating milestone, issue, PR, release, and contributor sync logic to new repository instance methods, removing inline iteration and error handling.
Repository Model Sync Methods
backend/apps/github/models/repository.py
Refactored from_github to use private helper methods for data processing; added new synchronization methods for milestones, issues, pull requests, releases, and contributors, with improved modularity and logging.
Funding Policy Compliance Logic
backend/apps/github/utils.py
Updated funding policy compliance check to support multiple targets and moved single-target logic into a helper function.
Linter Configuration
backend/pyproject.toml
Removed PLR0912 ("too-many-branches") from Ruff linter ignore list to enforce the rule.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
Refactor code to address all existing PLR0912 ("too-many-branches") violations (Issue #1826)
Remove PLR0912 from the list of ignored rules in pyproject.toml (Issue #1826)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Possibly related PRs

Suggested labels

backend

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ 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.
  • 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.

Support

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

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

sonarqubecloud bot commented Aug 5, 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: 0

🧹 Nitpick comments (4)
backend/apps/github/utils.py (1)

46-67: Consider adding type hints for better clarity.

The helper function implementation is correct. Consider adding type hints to improve code documentation and IDE support.

-def _check_single_funding_policy_compliance(platform, target):
+def _check_single_funding_policy_compliance(platform: str, target: str) -> bool:
backend/apps/ai/management/commands/ai_create_chapter_chunks.py (1)

139-149: Good uniform handling of metadata fields.

The approach correctly handles both string and list types. However, consider extracting the list joining logic for reusability.

You could extract the display value logic into a small helper:

def _format_display_value(value):
    """Format value for display, joining lists with commas."""
    return ", ".join(value) if isinstance(value, list) else value

Then use it in the loop:

-                display_value = ", ".join(value) if isinstance(value, list) else value
+                display_value = _format_display_value(value)
backend/apps/ai/management/commands/ai_create_project_chunks.py (1)

89-91: Consider using type annotations for clarity.

Adding type hints would improve code documentation and IDE support.

-    def extract_project_content(self, project: Project) -> tuple[str, str]:
-        prose_parts: list[str] = []
-        metadata_parts: list[str] = []
+    def extract_project_content(self, project: Project) -> tuple[str, str]:
+        prose_parts: list[str] = []
+        metadata_parts: list[str] = []

Note: The type hints are already present, this is good practice!

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

366-389: Consider adding error handling for milestone sync.

While the UnknownObjectException is caught for labels, consider wrapping the entire milestone update in a try-except to handle potential GitHub API errors gracefully.

     def sync_milestones(self, gh_repository):
         """Sync milestones from GitHub repository."""
         until = (
             self.latest_updated_milestone.updated_at
             if self.latest_updated_milestone
             else timezone.now() - td(days=30)
         )
         for gh_milestone in gh_repository.get_milestones(
             direction="desc", sort="updated", state="all"
         ):
             if gh_milestone.updated_at < until:
                 break
+            try:
                 milestone = Milestone.update_data(
                     gh_milestone,
                     author=User.update_data(gh_milestone.creator),
                     repository=self,
                 )
                 milestone.labels.clear()
                 for gh_milestone_label in gh_milestone.get_labels():
                     try:
                         milestone.labels.add(Label.update_data(gh_milestone_label))
                     except UnknownObjectException:
                         logger.exception("Couldn't get GitHub milestone label %s", milestone.url)
+            except GithubException as e:
+                logger.exception("Failed to sync milestone for repository %s: %s", self.name, str(e))
+                continue
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5fcff2a and 04fe755.

📒 Files selected for processing (6)
  • 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 (1 hunks)
  • backend/apps/github/models/repository.py (4 hunks)
  • backend/apps/github/utils.py (1 hunks)
  • backend/pyproject.toml (0 hunks)
💤 Files with no reviewable changes (1)
  • backend/pyproject.toml
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: adithya-naik
PR: OWASP/Nest#1894
File: frontend/src/components/TopContributorsList.tsx:74-74
Timestamp: 2025-07-28T14:51:14.736Z
Learning: In the OWASP/Nest project, the maintainer adithya-naik prefers not to create separate components for code that's only used in two specific cases, following the YAGNI principle to avoid over-engineering when the duplication is limited and manageable.
🔇 Additional comments (13)
backend/apps/github/utils.py (1)

36-43: LGTM! Clean refactoring to support multiple targets.

The refactoring elegantly handles both single and multiple funding targets while maintaining backward compatibility. The early return pattern for non-compliant targets is efficient.

backend/apps/ai/management/commands/ai_create_chapter_chunks.py (2)

104-111: LGTM! Clean consolidation of prose field processing.

The loop-based approach reduces code duplication and makes it easier to add new prose fields in the future.


125-136: Excellent refactoring of location information processing.

The list comprehension with conditional filtering is elegant and the consolidation into a single "Location Information" entry improves readability of the output.

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

56-63: LGTM! Excellent delegation to repository methods.

The refactoring improves separation of concerns by moving synchronization logic to the Repository model where it belongs. The conditional check for archived repositories is preserved correctly.

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

94-102: Clever use of target list parameter to reduce branching.

The approach of including the target list in the tuple elegantly determines where to append each field without additional conditionals.


125-137: LGTM! Clean statistics aggregation.

The list comprehension with filtering for positive counts is efficient and the single "Project Statistics" entry improves output organization.


157-161: Well-structured helper method.

The _add_list_metadata helper properly encapsulates the repeated logic for processing list-based fields.

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

224-280: Excellent refactoring of the from_github method.

The use of field mapping dictionary and optional data processors significantly reduces branching and improves maintainability. The code is now more modular and easier to extend.


281-288: Good error handling for empty repositories.

The specific handling of the 409 status for empty Git repositories is appropriate.


314-319: Clean implementation of funding compliance check.

The simplified approach using the updated check_funding_policy_compliance function is much cleaner than nested loops.


454-465: LGTM! Good extraction of common logic.

The _update_assignees_and_labels helper method effectively reduces code duplication between issue and pull request synchronization.


467-485: Smart optimization in release synchronization.

The use of existing node IDs to avoid re-processing releases is an efficient approach. The early break when encountering an existing release assumes releases are ordered chronologically, which appears to be the case.


487-495: No changes needed for None handling in sync_contributors
The comprehension’s if (user := User.update_data(…)) clause already filters out any None returns from User.update_data, so only valid User instances reach bulk_save. No additional handling is required.

Likely an incorrect or invalid review comment.

@trucodd trucodd changed the title Feature/fix plr0912 update refactor:remove PLR0912 ignore and fix 4 violations update Aug 5, 2025
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
1 participant