|
| 1 | +use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; |
| 2 | +use ruff_macros::{derive_message_formats, violation}; |
| 3 | +use ruff_python_ast::Decorator; |
| 4 | +use ruff_python_trivia::is_python_whitespace; |
| 5 | +use ruff_text_size::{Ranged, TextRange, TextSize}; |
| 6 | + |
| 7 | +use crate::checkers::ast::Checker; |
| 8 | + |
| 9 | +/// ## What it does |
| 10 | +/// Checks for trailing whitespace after a decorator's opening `@`. |
| 11 | +/// |
| 12 | +/// ## Why is this bad? |
| 13 | +/// Including whitespace after the `@` symbol is not compliant with |
| 14 | +/// [PEP 8]. |
| 15 | +/// |
| 16 | +/// ## Example |
| 17 | +/// |
| 18 | +/// ```python |
| 19 | +/// @ decorator |
| 20 | +/// def func(): |
| 21 | +/// pass |
| 22 | +/// ``` |
| 23 | +/// |
| 24 | +/// Use instead: |
| 25 | +/// ```python |
| 26 | +/// @decorator |
| 27 | +/// def func(): |
| 28 | +/// pass |
| 29 | +/// ``` |
| 30 | +/// |
| 31 | +/// [PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length |
| 32 | +
|
| 33 | +#[violation] |
| 34 | +pub struct WhitespaceAfterDecorator; |
| 35 | + |
| 36 | +impl AlwaysFixableViolation for WhitespaceAfterDecorator { |
| 37 | + #[derive_message_formats] |
| 38 | + fn message(&self) -> String { |
| 39 | + format!("Whitespace after decorator") |
| 40 | + } |
| 41 | + |
| 42 | + fn fix_title(&self) -> String { |
| 43 | + "Remove whitespace".to_string() |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/// E204 |
| 48 | +pub(crate) fn whitespace_after_decorator(checker: &mut Checker, decorator_list: &[Decorator]) { |
| 49 | + for decorator in decorator_list { |
| 50 | + let decorator_text = checker.locator().slice(decorator); |
| 51 | + |
| 52 | + // Determine whether the `@` is followed by whitespace. |
| 53 | + if let Some(trailing) = decorator_text.strip_prefix('@') { |
| 54 | + // Collect the whitespace characters after the `@`. |
| 55 | + if trailing.chars().next().is_some_and(is_python_whitespace) { |
| 56 | + let end = trailing |
| 57 | + .chars() |
| 58 | + .position(|c| !(is_python_whitespace(c) || matches!(c, '\n' | '\r' | '\\'))) |
| 59 | + .unwrap_or(trailing.len()); |
| 60 | + |
| 61 | + let start = decorator.start() + TextSize::from(1); |
| 62 | + let end = start + TextSize::try_from(end).unwrap(); |
| 63 | + let range = TextRange::new(start, end); |
| 64 | + |
| 65 | + let mut diagnostic = Diagnostic::new(WhitespaceAfterDecorator, range); |
| 66 | + diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(range))); |
| 67 | + checker.diagnostics.push(diagnostic); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments