Skip to content

feat: add severity override#1537

Merged
HerringtonDarkholme merged 3 commits intomainfrom
severity-override
Oct 21, 2024
Merged

feat: add severity override#1537
HerringtonDarkholme merged 3 commits intomainfrom
severity-override

Conversation

@HerringtonDarkholme
Copy link
Copy Markdown
Member

@HerringtonDarkholme HerringtonDarkholme commented Oct 21, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new command-line option for specifying severity levels during the scanning process, enhancing user control over rule evaluations.
    • Added functionality for managing rule severities, allowing users to define default severities and customize severities for specific rules.
  • Documentation

    • Updated documentation for the JSON output parameter to reflect a change in the expected casing for the style parameter.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The pull request introduces a new struct, SeverityArg, to encapsulate command-line arguments for severity levels in the scanning process. It modifies the existing ScanArg struct to include a severity field of type SeverityArg. Additionally, the OutputArgs struct in args.rs is updated to change the documentation and value name for the json field, specifying a new casing requirement for the style parameter. Furthermore, a new module rule_overwrite is added, enhancing the handling of rule severities through a structured approach.

Changes

File Path Change Summary
crates/cli/src/scan.rs Added struct SeverityArg with fields for severity levels; modified ScanArg to include severity.
crates/cli/src/utils/args.rs Updated documentation and value name for json field in OutputArgs to change casing from style to STYLE; added new struct SeverityArg.
crates/cli/src/utils/mod.rs Added new module rule_overwrite; updated public exports to include SeverityArg.
crates/cli/src/utils/rule_overwrite.rs Introduced RuleOverwrite struct for managing rule severities and added associated methods.

Possibly related PRs

  • feat: add tracing to cli argument #1509: Modifications to the OutputArgs struct in run.rs and scan.rs, which includes the addition of a tracing field, enhancing command-line argument handling.
  • feat: support json output #1510: Changes to the consume_items method in scan.rs, adding a parameter to check for JSON output, relevant to the enhancements regarding severity levels and command-line arguments.

Poem

In the garden of code, where bunnies hop,
A new SeverityArg makes the scanning stop.
With options aplenty, for rules we can see,
The CLI now dances, as bright as can be!
So let’s scan with joy, and style that’s just right,
For every little rule, our future is bright! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 079229e and 550d06a.

📒 Files selected for processing (1)
  • crates/cli/src/utils/rule_overwrite.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/cli/src/utils/rule_overwrite.rs

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.

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

🧹 Outside diff range and nitpick comments (3)
crates/cli/src/utils/args.rs (1)

131-131: LGTM: Attribute update improves consistency.

The change from value_name="style" to value_name="STYLE" aligns with the documentation update and ensures consistency in the command-line help output. This improvement enhances the user experience by maintaining a uniform style across documentation and usage.

For complete consistency, consider updating the num_args and require_equals attributes to use the same quotation style as value_name. For example:

-      num_args(0..=1),
-      require_equals = true,
+      num_args = "0..=1",
+      require_equals = "true",

This change would make the attribute styles uniform throughout the struct field.

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

26-38: LGTM! Consider adding documentation comments.

The SeverityArg struct is well-implemented and follows good practices for defining command-line arguments using clap. The structure allows for flexible specification of rule IDs for different severity levels.

Consider adding documentation comments to the struct and its fields to provide more context for users and maintainers. For example:

/// Represents command-line arguments for specifying rule severities
#[derive(Args, Debug)]
struct SeverityArg {
    /// Rule IDs to be treated as errors
    #[clap(long, action = clap::ArgAction::Append, value_name = "RULE_ID", num_args(0..), require_equals = true)]
    pub error: Option<Vec<String>>,
    // ... (add similar comments for other fields)
}

76-78: LGTM! Consider using doc comments for consistency.

The integration of SeverityArg into ScanArg is well-implemented. The use of #[clap(flatten)] is appropriate for incorporating the severity options into the main command-line interface.

For consistency with Rust documentation practices, consider using a doc comment (///) instead of a regular comment for the "severity related options" line:

/// Severity related options
#[clap(flatten)]
severity: SeverityArg,

This change would make the comment style consistent with other documentation in the codebase and allow tools like rustdoc to include this information in generated documentation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c11fd89 and f9ce3be.

📒 Files selected for processing (2)
  • crates/cli/src/scan.rs (3 hunks)
  • crates/cli/src/utils/args.rs (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
crates/cli/src/utils/args.rs (1)

124-124: LGTM: Documentation update improves clarity.

The change from <style> to <STYLE> in the documentation comment aligns with common command-line argument conventions, where placeholder values are typically uppercase. This update enhances clarity and consistency in the documentation.

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

385-391: LGTM! Proper initialization of the new severity field.

The initialization of the severity field in the default_scan_arg function is correct and consistent with the SeverityArg struct definition. Setting all fields to None is appropriate for a default value, indicating that no severity overrides are specified by default.


Line range hint 26-391: Overall, the changes look good and effectively implement the severity override feature.

The introduction of the SeverityArg struct and its integration into the ScanArg struct are well-implemented. The changes follow existing code patterns and make good use of the clap derive macros for defining command-line arguments.

Key points:

  1. The new SeverityArg struct provides a flexible way to specify rule severities.
  2. The integration into ScanArg using #[clap(flatten)] is appropriate.
  3. The default initialization in default_scan_arg is correct.

Minor suggestions for improvement:

  1. Add documentation comments to the SeverityArg struct and its fields.
  2. Use doc comments (///) instead of regular comments for consistency.

These changes enhance the CLI's functionality while maintaining code quality and consistency.

@codecov
Copy link
Copy Markdown

codecov bot commented Oct 21, 2024

Codecov Report

Attention: Patch coverage is 0% with 26 lines in your changes missing coverage. Please review.

Project coverage is 72.24%. Comparing base (b52ae6b) to head (550d06a).
Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
crates/cli/src/utils/rule_overwrite.rs 0.00% 26 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1537      +/-   ##
==========================================
- Coverage   72.55%   72.24%   -0.32%     
==========================================
  Files          87       88       +1     
  Lines        5983     6009      +26     
==========================================
  Hits         4341     4341              
- Misses       1642     1668      +26     

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

🧹 Outside diff range and nitpick comments (10)
crates/cli/src/utils/mod.rs (1)

4-4: LGTM. Consider adding a brief comment.

The addition of the rule_overwrite module aligns with the PR's objective of adding severity override functionality.

Consider adding a brief comment above the module declaration to explain its purpose, e.g.:

// Module for handling rule severity overrides
mod rule_overwrite;
crates/cli/src/utils/args.rs (1)

231-243: LGTM: Well-structured SeverityArg for fine-grained severity control.

The new SeverityArg struct provides a clear and flexible way to override rule severities:

  1. Each severity level (error, warning, info, hint, off) can accept multiple rule IDs.
  2. The use of Option<Vec<String>> allows for easy handling of cases where no rules are specified for a level.
  3. The require_equals = true attribute enforces clear syntax for specifying values.

Consider adding a brief doc comment to the SeverityArg struct explaining its purpose and usage. This would improve the self-documentation of the code. For example:

/// Represents command-line arguments for overriding rule severities.
/// Each field corresponds to a severity level and can accept multiple rule IDs.
#[derive(Args, Debug)]
pub struct SeverityArg {
    // ... existing fields ...
}
crates/cli/src/scan.rs (3)

62-64: LGTM: SeverityArg integration looks good

The addition of the severity field of type SeverityArg to the ScanArg struct is a good enhancement. The use of #[clap(flatten)] is appropriate for organizing related CLI arguments.

Consider adding a brief comment explaining the purpose of the severity field and how it affects the scanning process.


Line range hint 1-464: Summary: Severity override foundation laid, implementation incomplete

The changes introduce a new SeverityArg struct and integrate it into the ScanArg struct, laying the groundwork for implementing severity overrides. However, the implementation is not yet complete as the new severity information is not being used in the scanning process.

Next steps:

  1. Update relevant functions (e.g., run_with_config, run_scan) to utilize the new severity information.
  2. Add tests to verify the behavior of severity overrides.
  3. Update documentation to explain how users can use the new severity override feature.

Consider creating a new function to handle the application of severity overrides to the rules. This function could be called from run_with_config or run_scan and would modify the rule severities based on the user-provided overrides.


Unused severity field in ScanArg

The SeverityArg is included in the ScanArg struct, but it's not utilized in the run_with_config or run_scan functions. Please ensure that the severity overrides are appropriately applied within these functions to leverage the new severity configurations.

🔗 Analysis chain

Line range hint 1-464: Verify usage of the new severity field

While the SeverityArg has been properly integrated into the ScanArg struct, it appears that the rest of the file doesn't yet make use of this new information. Consider updating relevant functions (e.g., run_with_config or run_scan) to utilize the severity overrides provided by the user.

To ensure the new severity field is properly utilized, you can run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of the severity field in relevant functions

# Test: Search for references to the severity field in key functions
rg -n 'fn (run_with_config|run_scan)' -A 20 -B 5 | rg 'severity'

# Test: Look for any new functions that might be handling the severity logic
rg -n 'fn.*severity'

Length of output: 147

crates/cli/src/utils/rule_overwrite.rs (5)

9-12: Consider making RuleOverwrite struct public

The RuleOverwrite struct is currently private. If you intend for it to be used outside of this module (e.g., in other parts of the crate or by other crates), consider adding the pub keyword to make it public.

Apply this diff to make the struct public:

-struct RuleOverwrite {
+pub struct RuleOverwrite {
   default_severity: Option<Severity>,
   by_rule_id: HashMap<String, Severity>,
 }

14-28: Add documentation comments to read_severity function

Adding documentation to the read_severity function will improve code readability and maintainability. It will help other developers understand the purpose and usage of this function.

Apply this diff to add documentation:

+/// Reads the severity and updates the severity mappings.
+///
+/// If `ids` is `None`, the function returns immediately.
+/// If `ids` is an empty vector, it sets the `default_severity`.
+/// Otherwise, it inserts each `id` with the given `severity` into `by_rule_id`.
 fn read_severity(
   severity: Severity,
   ids: &Option<Vec<String>>,
   by_rule_id: &mut HashMap<String, Severity>,
   default_severity: &mut Option<Severity>,
 ) {

46-54: Optimize severity retrieval in find method

In the find method, cloning occurs even when not necessary. Since Severity is typically a small enum, you can derive Copy for Severity to avoid cloning, making the code more efficient.

Apply this diff to derive Copy and adjust the method:

 // In ast_grep_config/src/lib.rs or wherever `Severity` is defined
 #[derive(Debug, Clone)]
+#[derive(Copy)]
 pub enum Severity {
   Error,
   Warning,
   Info,
 }

 // In the `find` method
 pub fn find(&self, id: &str) -> OverwriteResult {
   let severity = self
     .by_rule_id
     .get(id)
-    .cloned()
-    .or_else(|| self.default_severity.clone());
+    .copied()
+    .or(self.default_severity);
   OverwriteResult { severity }
 }

56-58: Evaluate the necessity of making OverwriteResult public

The OverwriteResult struct is declared as pub, and its field severity is also public. If OverwriteResult is only used within this module or crate, you may not need to make it public. Alternatively, consider providing accessor methods if external access is required while keeping fields encapsulated.

Apply this diff to adjust the visibility:

-pub struct OverwriteResult {
-  pub severity: Option<Severity>,
+struct OverwriteResult {
+  severity: Option<Severity>,
 }

If external access is needed, you can add a public method to retrieve the severity:

 impl OverwriteResult {
+  pub fn severity(&self) -> Option<Severity> {
+    self.severity
+  }

60-69: Remove unused generic parameter L in overwrite method

The generic parameter L in overwrite<L> is constrained by L: Language but is not used within the method body. This can be simplified by removing the generic parameter and using impl Language directly in the type.

Apply this diff to simplify the method signature:

 impl OverwriteResult {
-  pub fn overwrite<L>(&self, rule: &mut SerializableRuleConfig<L>)
-  where
-    L: Language,
+  pub fn overwrite(&self, rule: &mut SerializableRuleConfig<impl Language>)
   {
     if let Some(severity) = &self.severity {
       rule.severity = severity.clone();
     }
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f9ce3be and 079229e.

📒 Files selected for processing (4)
  • crates/cli/src/scan.rs (3 hunks)
  • crates/cli/src/utils/args.rs (2 hunks)
  • crates/cli/src/utils/mod.rs (1 hunks)
  • crates/cli/src/utils/rule_overwrite.rs (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
crates/cli/src/utils/mod.rs (1)

8-8: LGTM. Verify usage of SeverityArg in the codebase.

The public export of SeverityArg is consistent with the PR's objective of adding severity override functionality.

To ensure proper integration, let's verify the usage of SeverityArg in the codebase:

✅ Verification successful

MSRV Compatibility Confirmed: Rust version 1.67 supports let else syntax

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the project's minimum supported Rust version.

# Test: Check for `rust-version` field in Cargo.toml. Expect: Version 1.65 or newer.
rg '^rust-version\s*=\s*"(1\.[6-9][5-9]|[2-9]\.\d+)"' Cargo.toml || echo "MSRV is below 1.65. Consider updating or avoiding 'let else' syntax."

Length of output: 88

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