|
| 1 | +use crate::RuleCategory; |
| 2 | + |
| 3 | +use super::{plugins::LintPlugins, AllowWarnDeny}; |
| 4 | +use std::{borrow::Cow, fmt}; |
| 5 | + |
| 6 | +/// Enables, disables, and sets the severity of lint rules. |
| 7 | +/// |
| 8 | +/// Filters come in 3 forms: |
| 9 | +/// 1. Filter by rule name and/or plugin: `no-const-assign`, `eslint/no-const-assign` |
| 10 | +/// 2. Filter an entire category: `correctness` |
| 11 | +/// 3. Some unknow filter. This is a fallback used when parsing a filter string, |
| 12 | +/// and is interpreted uniquely by the linter. |
| 13 | +#[derive(Debug, Clone)] |
| 14 | +#[cfg_attr(test, derive(PartialEq))] |
| 15 | +pub struct LintFilter { |
| 16 | + severity: AllowWarnDeny, |
| 17 | + kind: LintFilterKind, |
| 18 | +} |
| 19 | + |
| 20 | +impl LintFilter { |
| 21 | + /// # Errors |
| 22 | + /// |
| 23 | + /// If `kind` is an empty string, or is a `<plugin>/<rule>` filter but is missing either the |
| 24 | + /// plugin or the rule. |
| 25 | + pub fn new<F: TryInto<LintFilterKind>>( |
| 26 | + severity: AllowWarnDeny, |
| 27 | + kind: F, |
| 28 | + ) -> Result<Self, <F as TryInto<LintFilterKind>>::Error> { |
| 29 | + Ok(Self { severity, kind: kind.try_into()? }) |
| 30 | + } |
| 31 | + |
| 32 | + #[must_use] |
| 33 | + pub fn allow<F: Into<LintFilterKind>>(kind: F) -> Self { |
| 34 | + Self { severity: AllowWarnDeny::Allow, kind: kind.into() } |
| 35 | + } |
| 36 | + |
| 37 | + #[must_use] |
| 38 | + pub fn warn<F: Into<LintFilterKind>>(kind: F) -> Self { |
| 39 | + Self { severity: AllowWarnDeny::Warn, kind: kind.into() } |
| 40 | + } |
| 41 | + |
| 42 | + #[must_use] |
| 43 | + pub fn deny<F: Into<LintFilterKind>>(kind: F) -> Self { |
| 44 | + Self { severity: AllowWarnDeny::Deny, kind: kind.into() } |
| 45 | + } |
| 46 | + |
| 47 | + #[inline] |
| 48 | + pub fn severity(&self) -> AllowWarnDeny { |
| 49 | + self.severity |
| 50 | + } |
| 51 | + |
| 52 | + #[inline] |
| 53 | + pub fn kind(&self) -> &LintFilterKind { |
| 54 | + &self.kind |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl Default for LintFilter { |
| 59 | + fn default() -> Self { |
| 60 | + Self { |
| 61 | + severity: AllowWarnDeny::Warn, |
| 62 | + kind: LintFilterKind::Category(RuleCategory::Correctness), |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl From<LintFilter> for (AllowWarnDeny, LintFilterKind) { |
| 68 | + fn from(val: LintFilter) -> Self { |
| 69 | + (val.severity, val.kind) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl<'a> From<&'a LintFilter> for (AllowWarnDeny, &'a LintFilterKind) { |
| 74 | + fn from(val: &'a LintFilter) -> Self { |
| 75 | + (val.severity, &val.kind) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +#[derive(Debug, Clone)] |
| 80 | +#[cfg_attr(test, derive(PartialEq))] |
| 81 | +pub enum LintFilterKind { |
| 82 | + Generic(Cow<'static, str>), |
| 83 | + /// e.g. `no-const-assign` or `eslint/no-const-assign` |
| 84 | + Rule(LintPlugins, Cow<'static, str>), |
| 85 | + /// e.g. `correctness` |
| 86 | + Category(RuleCategory), |
| 87 | + // TODO: plugin + category? e.g `-A react:correctness` |
| 88 | +} |
| 89 | + |
| 90 | +impl LintFilterKind { |
| 91 | + /// # Errors |
| 92 | + /// |
| 93 | + /// If `filter` is an empty string, or is a `<plugin>/<rule>` filter but is missing either the |
| 94 | + /// plugin or the rule. |
| 95 | + pub fn parse(filter: Cow<'static, str>) -> Result<Self, InvalidFilterKind> { |
| 96 | + if filter.is_empty() { |
| 97 | + return Err(InvalidFilterKind::Empty); |
| 98 | + } |
| 99 | + |
| 100 | + if filter.contains('/') { |
| 101 | + // this is an unfortunate amount of code duplication, but it needs to be done for |
| 102 | + // `filter` to live long enough to avoid a String allocation for &'static str |
| 103 | + let (plugin, rule) = match filter { |
| 104 | + Cow::Borrowed(filter) => { |
| 105 | + let mut parts = filter.splitn(2, '/'); |
| 106 | + |
| 107 | + let plugin = parts |
| 108 | + .next() |
| 109 | + .ok_or(InvalidFilterKind::PluginMissing(Cow::Borrowed(filter)))?; |
| 110 | + if plugin.is_empty() { |
| 111 | + return Err(InvalidFilterKind::PluginMissing(Cow::Borrowed(filter))); |
| 112 | + } |
| 113 | + |
| 114 | + let rule = parts |
| 115 | + .next() |
| 116 | + .ok_or(InvalidFilterKind::RuleMissing(Cow::Borrowed(filter)))?; |
| 117 | + if rule.is_empty() { |
| 118 | + return Err(InvalidFilterKind::RuleMissing(Cow::Borrowed(filter))); |
| 119 | + } |
| 120 | + |
| 121 | + (LintPlugins::from(plugin), Cow::Borrowed(rule)) |
| 122 | + } |
| 123 | + Cow::Owned(filter) => { |
| 124 | + let mut parts = filter.splitn(2, '/'); |
| 125 | + |
| 126 | + let plugin = parts |
| 127 | + .next() |
| 128 | + .ok_or_else(|| InvalidFilterKind::PluginMissing(filter.clone().into()))?; |
| 129 | + if plugin.is_empty() { |
| 130 | + return Err(InvalidFilterKind::PluginMissing(filter.into())); |
| 131 | + } |
| 132 | + |
| 133 | + let rule = parts |
| 134 | + .next() |
| 135 | + .ok_or_else(|| InvalidFilterKind::RuleMissing(filter.clone().into()))?; |
| 136 | + if rule.is_empty() { |
| 137 | + return Err(InvalidFilterKind::RuleMissing(filter.into())); |
| 138 | + } |
| 139 | + |
| 140 | + (LintPlugins::from(plugin), Cow::Owned(rule.to_string())) |
| 141 | + } |
| 142 | + }; |
| 143 | + Ok(LintFilterKind::Rule(plugin, rule)) |
| 144 | + } else { |
| 145 | + match RuleCategory::try_from(filter.as_ref()) { |
| 146 | + Ok(category) => Ok(LintFilterKind::Category(category)), |
| 147 | + Err(()) => Ok(LintFilterKind::Generic(filter)), |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +impl TryFrom<String> for LintFilterKind { |
| 154 | + type Error = InvalidFilterKind; |
| 155 | + |
| 156 | + #[inline] |
| 157 | + fn try_from(filter: String) -> Result<Self, Self::Error> { |
| 158 | + Self::parse(Cow::Owned(filter)) |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +impl TryFrom<&'static str> for LintFilterKind { |
| 163 | + type Error = InvalidFilterKind; |
| 164 | + |
| 165 | + #[inline] |
| 166 | + fn try_from(filter: &'static str) -> Result<Self, Self::Error> { |
| 167 | + Self::parse(Cow::Borrowed(filter)) |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +impl TryFrom<Cow<'static, str>> for LintFilterKind { |
| 172 | + type Error = InvalidFilterKind; |
| 173 | + |
| 174 | + #[inline] |
| 175 | + fn try_from(filter: Cow<'static, str>) -> Result<Self, Self::Error> { |
| 176 | + Self::parse(filter) |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +impl From<RuleCategory> for LintFilterKind { |
| 181 | + #[inline] |
| 182 | + fn from(category: RuleCategory) -> Self { |
| 183 | + LintFilterKind::Category(category) |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 188 | +pub enum InvalidFilterKind { |
| 189 | + Empty, |
| 190 | + PluginMissing(Cow<'static, str>), |
| 191 | + RuleMissing(Cow<'static, str>), |
| 192 | +} |
| 193 | + |
| 194 | +impl fmt::Display for InvalidFilterKind { |
| 195 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 196 | + match self { |
| 197 | + Self::Empty => "Filter cannot be empty.".fmt(f), |
| 198 | + Self::PluginMissing(filter) => { |
| 199 | + write!( |
| 200 | + f, |
| 201 | + "Filter '{filter}' must match <plugin>/<rule> but is missing a plugin name." |
| 202 | + ) |
| 203 | + } |
| 204 | + Self::RuleMissing(filter) => { |
| 205 | + write!( |
| 206 | + f, |
| 207 | + "Filter '{filter}' must match <plugin>/<rule> but is missing a rule name." |
| 208 | + ) |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +impl std::error::Error for InvalidFilterKind {} |
| 215 | + |
| 216 | +#[cfg(test)] |
| 217 | +mod test { |
| 218 | + use super::*; |
| 219 | + |
| 220 | + #[test] |
| 221 | + fn test_from_category() { |
| 222 | + let correctness: LintFilter = LintFilter::new(AllowWarnDeny::Warn, "correctness").unwrap(); |
| 223 | + assert_eq!(correctness.severity(), AllowWarnDeny::Warn); |
| 224 | + assert!( |
| 225 | + matches!(correctness.kind(), LintFilterKind::Category(RuleCategory::Correctness)), |
| 226 | + "{:?}", |
| 227 | + correctness.kind() |
| 228 | + ); |
| 229 | + } |
| 230 | + |
| 231 | + #[test] |
| 232 | + fn test_eslint_deny() { |
| 233 | + let filter = LintFilter::deny(LintFilterKind::try_from("no-const-assign").unwrap()); |
| 234 | + assert_eq!(filter.severity(), AllowWarnDeny::Deny); |
| 235 | + assert_eq!(filter.kind(), &LintFilterKind::Generic("no-const-assign".into())); |
| 236 | + |
| 237 | + let filter = LintFilter::deny(LintFilterKind::try_from("eslint/no-const-assign").unwrap()); |
| 238 | + assert_eq!(filter.severity(), AllowWarnDeny::Deny); |
| 239 | + assert_eq!( |
| 240 | + filter.kind(), |
| 241 | + &LintFilterKind::Rule(LintPlugins::from("eslint"), "no-const-assign".into()) |
| 242 | + ); |
| 243 | + assert!(matches!(filter.kind(), LintFilterKind::Rule(_, _))); |
| 244 | + } |
| 245 | + |
| 246 | + #[test] |
| 247 | + fn test_parse() { |
| 248 | + let test_cases: Vec<(&'static str, LintFilterKind)> = vec![ |
| 249 | + ("import/namespace", LintFilterKind::Rule(LintPlugins::IMPORT, "namespace".into())), |
| 250 | + ( |
| 251 | + "react-hooks/exhaustive-deps", |
| 252 | + LintFilterKind::Rule(LintPlugins::REACT, "exhaustive-deps".into()), |
| 253 | + ), |
| 254 | + // categories |
| 255 | + ("nursery", LintFilterKind::Category("nursery".try_into().unwrap())), |
| 256 | + ("perf", LintFilterKind::Category("perf".try_into().unwrap())), |
| 257 | + // misc |
| 258 | + ("not-a-valid-filter", LintFilterKind::Generic("not-a-valid-filter".into())), |
| 259 | + ]; |
| 260 | + |
| 261 | + for (input, expected) in test_cases { |
| 262 | + let actual = LintFilterKind::try_from(input).unwrap(); |
| 263 | + assert_eq!(actual, expected, "input: {input}"); |
| 264 | + } |
| 265 | + } |
| 266 | + |
| 267 | + #[test] |
| 268 | + fn test_parse_invalid() { |
| 269 | + let test_cases = vec!["/rules-of-hooks", "import/", "", "/", "//"]; |
| 270 | + |
| 271 | + for input in test_cases { |
| 272 | + let actual = LintFilterKind::parse(Cow::Borrowed(input)); |
| 273 | + assert!( |
| 274 | + actual.is_err(), |
| 275 | + "input '{input}' produced filter '{:?}' but it should have errored", |
| 276 | + actual.unwrap() |
| 277 | + ); |
| 278 | + } |
| 279 | + } |
| 280 | +} |
0 commit comments