diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/logical_lines/whitespace_before_comment.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/logical_lines/whitespace_before_comment.rs index 366fc675b2311..235c12f7b6c65 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/logical_lines/whitespace_before_comment.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/logical_lines/whitespace_before_comment.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::Violation; +use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_parser::TokenKind; use ruff_python_trivia::PythonWhitespace; @@ -30,11 +30,15 @@ use crate::rules::pycodestyle::rules::logical_lines::LogicalLine; #[violation] pub struct TooFewSpacesBeforeInlineComment; -impl Violation for TooFewSpacesBeforeInlineComment { +impl AlwaysFixableViolation for TooFewSpacesBeforeInlineComment { #[derive_message_formats] fn message(&self) -> String { format!("Insert at least two spaces before an inline comment") } + + fn fix_title(&self) -> String { + format!("Insert spaces") + } } /// ## What it does @@ -155,10 +159,15 @@ pub(crate) fn whitespace_before_comment( let is_inline_comment = !line_text.trim_whitespace().is_empty(); if is_inline_comment { if range.start() - prev_end < " ".text_len() { - context.push( + let mut diagnostic = Diagnostic::new( TooFewSpacesBeforeInlineComment, TextRange::new(prev_end, range.start()), ); + diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( + " ".to_string(), + TextRange::new(prev_end, range.start()), + ))); + context.push_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap index ab8a934e470cc..f9a8790387e0b 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap +++ b/crates/ruff_linter/src/rules/pycodestyle/snapshots/ruff_linter__rules__pycodestyle__tests__E261_E26.py.snap @@ -1,7 +1,7 @@ --- source: crates/ruff_linter/src/rules/pycodestyle/mod.rs --- -E26.py:2:5: E261 Insert at least two spaces before an inline comment +E26.py:2:5: E261 [*] Insert at least two spaces before an inline comment | 1 | #: E261:1:5 2 | pass # an inline comment @@ -9,5 +9,14 @@ E26.py:2:5: E261 Insert at least two spaces before an inline comment 3 | #: E262:1:12 4 | x = x + 1 #Increment x | + = help: Insert spaces + +ℹ Fix +1 1 | #: E261:1:5 +2 |-pass # an inline comment + 2 |+pass # an inline comment +3 3 | #: E262:1:12 +4 4 | x = x + 1 #Increment x +5 5 | #: E262:1:12