Skip to content

Commit 485d997

Browse files
Tweak prefix match to use .all_rules() (#5512)
## Summary No behavior change, but I think this is a little cleaner.
1 parent d7214e7 commit 485d997

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

crates/ruff/src/codes.rs

+12
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,18 @@ use crate::rules;
1414
#[derive(PartialEq, Eq, PartialOrd, Ord)]
1515
pub struct NoqaCode(&'static str, &'static str);
1616

17+
impl NoqaCode {
18+
/// Return the prefix for the [`NoqaCode`], e.g., `SIM` for `SIM101`.
19+
pub fn prefix(&self) -> &str {
20+
self.0
21+
}
22+
23+
/// Return the suffix for the [`NoqaCode`], e.g., `101` for `SIM101`.
24+
pub fn suffix(&self) -> &str {
25+
self.1
26+
}
27+
}
28+
1729
impl std::fmt::Debug for NoqaCode {
1830
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1931
std::fmt::Display::fmt(self, f)

crates/ruff/src/registry.rs

+4-10
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,17 @@ pub trait AsRule {
1818
impl Rule {
1919
pub fn from_code(code: &str) -> Result<Self, FromCodeError> {
2020
let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?;
21-
let prefix: RuleCodePrefix = RuleCodePrefix::parse(&linter, code)?;
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)
21+
linter
22+
.all_rules()
23+
.find(|rule| rule.noqa_code().suffix() == code)
24+
.ok_or(FromCodeError::Unknown)
2925
}
3026
}
3127

3228
#[derive(thiserror::Error, Debug)]
3329
pub enum FromCodeError {
3430
#[error("unknown rule code")]
3531
Unknown,
36-
#[error("expected a rule code (like `SIM101`), not a prefix (like `SIM` or `SIM1`)")]
37-
Prefix,
3832
}
3933

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

0 commit comments

Comments
 (0)