Tweak prefix match to use .all_rules() (#5512)

## Summary

No behavior change, but I think this is a little cleaner.
This commit is contained in:
Charlie Marsh 2023-07-04 16:02:57 -04:00 committed by GitHub
parent d7214e77e6
commit 485d997d35
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 10 deletions

View file

@ -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)

View file

@ -18,14 +18,10 @@ 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)
}
}
@ -33,8 +29,6 @@ impl Rule {
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)]