Skip to content

Commit

Permalink
Tweak prefix match to use .all_rules() (#5512)
Browse files Browse the repository at this point in the history
## Summary

No behavior change, but I think this is a little cleaner.
  • Loading branch information
charliermarsh authored Jul 4, 2023
1 parent d7214e7 commit 485d997
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
12 changes: 12 additions & 0 deletions crates/ruff/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ use crate::rules;
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct NoqaCode(&'static str, &'static str);

impl NoqaCode {
/// Return the prefix for the [`NoqaCode`], e.g., `SIM` for `SIM101`.
pub fn prefix(&self) -> &str {
self.0
}

/// Return the suffix for the [`NoqaCode`], e.g., `101` for `SIM101`.
pub fn suffix(&self) -> &str {
self.1
}
}

impl std::fmt::Debug for NoqaCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
Expand Down
14 changes: 4 additions & 10 deletions crates/ruff/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,17 @@ pub trait AsRule {
impl Rule {
pub fn from_code(code: &str) -> Result<Self, FromCodeError> {
let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?;
let prefix: RuleCodePrefix = RuleCodePrefix::parse(&linter, code)?;
let rule = prefix.rules().next().unwrap();
// TODO(charlie): Add a method to return an individual code, rather than matching on the
// prefix.
if rule.noqa_code().to_string() != format!("{}{}", linter.common_prefix(), code) {
return Err(FromCodeError::Prefix);
}
Ok(rule)
linter
.all_rules()
.find(|rule| rule.noqa_code().suffix() == code)
.ok_or(FromCodeError::Unknown)
}
}

#[derive(thiserror::Error, Debug)]
pub enum FromCodeError {
#[error("unknown rule code")]
Unknown,
#[error("expected a rule code (like `SIM101`), not a prefix (like `SIM` or `SIM1`)")]
Prefix,
}

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

0 comments on commit 485d997

Please sign in to comment.