feat: add severity override#1537
Conversation
WalkthroughThe pull request introduces a new struct, Changes
Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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"tovalue_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_argsandrequire_equalsattributes to use the same quotation style asvalue_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
SeverityArgstruct is well-implemented and follows good practices for defining command-line arguments usingclap. 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
SeverityArgintoScanArgis 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
rustdocto include this information in generated documentation.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 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 newseverityfield.The initialization of the
severityfield in thedefault_scan_argfunction is correct and consistent with theSeverityArgstruct definition. Setting all fields toNoneis 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
SeverityArgstruct and its integration into theScanArgstruct are well-implemented. The changes follow existing code patterns and make good use of theclapderive macros for defining command-line arguments.Key points:
- The new
SeverityArgstruct provides a flexible way to specify rule severities.- The integration into
ScanArgusing#[clap(flatten)]is appropriate.- The default initialization in
default_scan_argis correct.Minor suggestions for improvement:
- Add documentation comments to the
SeverityArgstruct and its fields.- Use doc comments (
///) instead of regular comments for consistency.These changes enhance the CLI's functionality while maintaining code quality and consistency.
Codecov ReportAttention: Patch coverage is
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. |
There was a problem hiding this comment.
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_overwritemodule 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-structuredSeverityArgfor fine-grained severity control.The new
SeverityArgstruct provides a clear and flexible way to override rule severities:
- Each severity level (error, warning, info, hint, off) can accept multiple rule IDs.
- The use of
Option<Vec<String>>allows for easy handling of cases where no rules are specified for a level.- The
require_equals = trueattribute enforces clear syntax for specifying values.Consider adding a brief doc comment to the
SeverityArgstruct 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 goodThe addition of the
severityfield of typeSeverityArgto theScanArgstruct 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
severityfield and how it affects the scanning process.
Line range hint
1-464: Summary: Severity override foundation laid, implementation incompleteThe changes introduce a new
SeverityArgstruct and integrate it into theScanArgstruct, 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:
- Update relevant functions (e.g.,
run_with_config,run_scan) to utilize the new severity information.- Add tests to verify the behavior of severity overrides.
- 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_configorrun_scanand would modify the rule severities based on the user-provided overrides.
Unused
severityfield inScanArgThe
SeverityArgis included in theScanArgstruct, but it's not utilized in therun_with_configorrun_scanfunctions. Please ensure that the severity overrides are appropriately applied within these functions to leverage the newseverityconfigurations.🔗 Analysis chain
Line range hint
1-464: Verify usage of the new severity fieldWhile the
SeverityArghas been properly integrated into theScanArgstruct, 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_configorrun_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 makingRuleOverwritestruct publicThe
RuleOverwritestruct 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 thepubkeyword 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 toread_severityfunctionAdding documentation to the
read_severityfunction 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 infindmethodIn the
findmethod, cloning occurs even when not necessary. SinceSeverityis typically a small enum, you can deriveCopyforSeverityto avoid cloning, making the code more efficient.Apply this diff to derive
Copyand 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 makingOverwriteResultpublicThe
OverwriteResultstruct is declared aspub, and its fieldseverityis also public. IfOverwriteResultis 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 parameterLinoverwritemethodThe generic parameter
Linoverwrite<L>is constrained byL: Languagebut is not used within the method body. This can be simplified by removing the generic parameter and usingimpl Languagedirectly 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
📒 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 ofSeverityArgin the codebase.The public export of
SeverityArgis consistent with the PR's objective of adding severity override functionality.To ensure proper integration, let's verify the usage of
SeverityArgin the codebase:✅ Verification successful
MSRV Compatibility Confirmed: Rust version 1.67 supports
let elsesyntax🏁 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
Summary by CodeRabbit
New Features
Documentation