Skip to content

feat: add RuleOverwrite to rule#1546

Merged
HerringtonDarkholme merged 1 commit intomainfrom
severity-override
Oct 22, 2024
Merged

feat: add RuleOverwrite to rule#1546
HerringtonDarkholme merged 1 commit intomainfrom
severity-override

Conversation

@HerringtonDarkholme
Copy link
Copy Markdown
Member

@HerringtonDarkholme HerringtonDarkholme commented Oct 22, 2024

Summary by CodeRabbit

  • New Features

    • Introduced RuleOverwrite utility for enhanced rule management in configurations.
    • Added functionality to filter rules based on regex patterns.
  • Bug Fixes

    • Updated method calls to improve handling of configuration rules, ensuring default values are utilized.
  • Documentation

    • Enhanced comments to indicate planned future improvements regarding error reporting for rules with different languages.
  • Refactor

    • Streamlined the logic for rule processing and configuration reading, moving towards a more structured approach.
  • Style

    • Improved readability in several functions by refining the handling of Option types.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes involve significant modifications to the configuration handling within the CLI, particularly focusing on the management of rules. The rule_filter parameter has been replaced with rule_overwrite, a new structured type. This refactoring eliminates the regex-based filtering approach, introducing a more complex rule management system. The RuleOverwrite utility has been added, enhancing the ability to process configurations. Various functions have been updated to accommodate these changes, streamlining the control flow while maintaining consistent error handling.

Changes

File Path Change Summary
crates/cli/src/config.rs - Updated find_rules and read_directory_yaml to use rule_overwrite instead of rule_filter.
- Removed filter_rule_by_regex.
crates/cli/src/lsp.rs - Changed call to find_rules from None to Default::default().
crates/cli/src/scan.rs - Introduced RuleOverwrite in ScanWithConfig, modifying how rules are found based on severity and filtering criteria.
crates/cli/src/utils/mod.rs - Added public export for RuleOverwrite.
crates/cli/src/utils/rule_overwrite.rs - Updated RuleOverwrite struct with #[derive(Default)], added rule_filter field, and introduced process_configs method for filtering rules.
crates/cli/src/verify.rs - Updated find_rules call to use Default::default().
- Enhanced readability in apply_snapshot_action function.
crates/config/src/rule_config.rs - Implemented DerefMut trait for RuleConfig<L>, allowing mutable dereferencing of the inner configuration.

Possibly related PRs

🐰 In the fields where rules now play,
A new path blooms, bright as day.
With RuleOverwrite, we refine,
Our configurations, all align.
No more regex, just structured grace,
In our CLI, we find our place! 🌼


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

@codecov
Copy link
Copy Markdown

codecov bot commented Oct 22, 2024

Codecov Report

Attention: Patch coverage is 61.53846% with 10 lines in your changes missing coverage. Please review.

Project coverage is 72.68%. Comparing base (8ad0182) to head (e4f8b07).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
crates/cli/src/utils/rule_overwrite.rs 61.11% 7 Missing ⚠️
crates/config/src/rule_config.rs 0.00% 2 Missing ⚠️
crates/cli/src/lsp.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1546      +/-   ##
==========================================
+ Coverage   72.31%   72.68%   +0.36%     
==========================================
  Files          88       88              
  Lines        6018     6029      +11     
==========================================
+ Hits         4352     4382      +30     
+ Misses       1666     1647      -19     

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

Copy link
Copy Markdown
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: 4

🧹 Outside diff range and nitpick comments (4)
crates/cli/src/verify.rs (1)

60-60: LGTM! Consider adding a comment for clarity.

The change from None to Default::default() aligns with the new RuleOverwrite structure and maintains consistency with similar updates in other files. This modification doesn't affect the overall logic of the function but may impact how rules are processed.

Consider adding a brief comment explaining the purpose of Default::default() in this context, especially if the RuleOverwrite struct has a non-trivial default implementation. This would improve code readability and maintainability.

-  let collections = &find_rules(arg.config.clone(), Default::default())?.0;
+  // Use default RuleOverwrite configuration
+  let collections = &find_rules(arg.config.clone(), Default::default())?.0;
crates/cli/src/utils/rule_overwrite.rs (3)

12-16: Questioning the necessity of deriving Default for RuleOverwrite

The #[derive(Default)] trait is added to the RuleOverwrite struct. Since all fields inside the struct are types that implement Default, this is acceptable. However, if RuleOverwrite is only instantiated via the new method, the Default trait may be unnecessary. Consider removing it unless there is a specific need for default instantiation elsewhere in the codebase.


Line range hint 36-73: Optimize cloning of filter in the new method

In the new method, filter: &Option<Regex> is cloned to initialize rule_filter. Since Regex is internally reference-counted, cloning is cheap. However, to avoid the unnecessary cloning of the Option, you could change the parameter to take ownership: filter: Option<Regex>. This way, you can directly assign rule_filter: filter without cloning.

Apply this diff to modify the parameter and assignment:

-pub fn new(cli: &SeverityArg, filter: &Option<Regex>) -> Result<Self> {
+pub fn new(cli: &SeverityArg, filter: Option<Regex>) -> Result<Self> {

...

    Ok(Self {
      default_severity,
      by_rule_id,
-     rule_filter: filter.clone(),
+     rule_filter: filter,
    })

102-116: Handle empty filter results with a more informative error

In the filter_rule_by_regex function, if no rules match the provided regex filter, an error is returned. Consider providing additional information or suggestions in the error message to help users understand why no rules were matched and how they might adjust their filter.

Apply this diff to enhance the error message:

if selected.is_empty() {
-    Err(anyhow::anyhow!(EC::RuleNotFound(filter.to_string())))
+    Err(anyhow::anyhow!(EC::RuleNotFound(format!(
+        "No rules matched the provided filter: {}. Please check the filter pattern or available rule IDs.",
+        filter
+    ))))
} else {
    Ok(selected)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8ad0182 and e4f8b07.

📒 Files selected for processing (7)
  • crates/cli/src/config.rs (4 hunks)
  • crates/cli/src/lsp.rs (1 hunks)
  • crates/cli/src/scan.rs (2 hunks)
  • crates/cli/src/utils/mod.rs (1 hunks)
  • crates/cli/src/utils/rule_overwrite.rs (4 hunks)
  • crates/cli/src/verify.rs (1 hunks)
  • crates/config/src/rule_config.rs (1 hunks)
🧰 Additional context used
🔇 Additional comments (10)
crates/cli/src/utils/mod.rs (1)

11-11: LGTM. Verify usage of RuleOverwrite in the codebase.

The new public export of RuleOverwrite aligns with the PR objectives. This change makes the RuleOverwrite entity accessible to other parts of the codebase, which is likely intentional for the new rule management system.

To ensure this change is properly integrated, please verify its usage across the codebase:

crates/cli/src/scan.rs (3)

20-20: LGTM: New import added correctly.

The RuleOverwrite import from crate::utils is appropriately placed and grouped with other imports from the same module.


Line range hint 1-424: Overall assessment: Good improvements to rule management.

The changes in this file are focused and align well with the PR objectives. The introduction of RuleOverwrite and its usage in the try_new method of ScanWithConfig represent a positive step towards more structured and flexible rule management. The modifications are consistent with the PR summary and should enhance the overall functionality of the CLI configuration handling.


124-125: LGTM: Improved rule management with RuleOverwrite.

The introduction of RuleOverwrite enhances the structure and potentially the flexibility of rule management. This change aligns well with the refactoring mentioned in the PR summary.

To ensure consistency across the codebase, please run the following script:

crates/config/src/rule_config.rs (1)

211-215: LGTM! Enhances RuleConfig<L> usability.

The implementation of DerefMut for RuleConfig<L> is correct and follows Rust conventions. This addition complements the existing Deref implementation, providing both immutable and mutable access to the inner SerializableRuleConfig<L>. This enhancement improves the usability of RuleConfig<L> by allowing direct mutable access to its inner configuration.

crates/cli/src/config.rs (5)

1-2: Necessary imports added correctly

The imports of RuleOverwrite and RuleTrace are appropriately added to support the new rule management functionality.


90-93: Function call to read_directory_yaml updated correctly

The call to read_directory_yaml now includes the rule_overwrite parameter, aligning with the updated function signature.


Line range hint 155-159: Updated read_directory_yaml function to include rule_overwrite

The function read_directory_yaml now accepts rule_overwrite: RuleOverwrite as a parameter, which reflects the new structured approach to rule management.


184-184: Applying rule_overwrite to process configurations

The invocation of rule_overwrite.process_configs(configs)? correctly integrates the new rule overwriting logic into the configuration processing.


86-89: Verify all calls to find_rules are updated with the new parameter

The function find_rules now includes the rule_overwrite: RuleOverwrite parameter. Please ensure that all calls to this function throughout the codebase are updated to match the new signature.

You can use the following script to locate any calls to find_rules that may not have been updated:

Expected result: No matches should be found. If any matches are found, those calls need to be updated to include the rule_overwrite parameter.

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