Skip to content

Commit 952c623

Browse files
Avoid returning first-match for rule prefixes (#5511)
Closes #5495, but there's a TODO here to improve this further. The current `from_code` implementation feels really indirect.
1 parent 0a26201 commit 952c623

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

crates/ruff/src/registry.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,22 @@ impl Rule {
1919
pub fn from_code(code: &str) -> Result<Self, FromCodeError> {
2020
let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?;
2121
let prefix: RuleCodePrefix = RuleCodePrefix::parse(&linter, code)?;
22-
Ok(prefix.rules().next().unwrap())
22+
let rule = prefix.rules().next().unwrap();
23+
// TODO(charlie): Add a method to return an individual code, rather than matching on the
24+
// prefix.
25+
if rule.noqa_code().to_string() != format!("{}{}", linter.common_prefix(), code) {
26+
return Err(FromCodeError::Prefix);
27+
}
28+
Ok(rule)
2329
}
2430
}
2531

2632
#[derive(thiserror::Error, Debug)]
2733
pub enum FromCodeError {
2834
#[error("unknown rule code")]
2935
Unknown,
36+
#[error("expected a rule code (like `SIM101`), not a prefix (like `SIM` or `SIM1`)")]
37+
Prefix,
3038
}
3139

3240
#[derive(EnumIter, Debug, PartialEq, Eq, Clone, Hash, RuleNamespace)]

crates/ruff_cli/src/commands/rule.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ pub(crate) fn rule(rule: Rule, format: HelpFormat) -> Result<()> {
3131
output.push('\n');
3232
output.push('\n');
3333

34-
let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap();
3534
output.push_str(&format!("Derived from the **{}** linter.", linter.name()));
3635
output.push('\n');
3736
output.push('\n');

0 commit comments

Comments
 (0)