Add fix for E261 (#8114)

Closes https://github.com/astral-sh/ruff/issues/8068.
This commit is contained in:
Charlie Marsh 2023-10-21 20:41:05 -04:00 committed by GitHub
parent 7586091437
commit 8472a7e50f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 4 deletions

View file

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

View file

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