diff --git a/crates/ruff/resources/test/fixtures/pyupgrade/UP009_9.py b/crates/ruff/resources/test/fixtures/pyupgrade/UP009_9.py new file mode 100644 index 0000000000000..fbfb852bf4d3c --- /dev/null +++ b/crates/ruff/resources/test/fixtures/pyupgrade/UP009_9.py @@ -0,0 +1,7 @@ +x = 1 \ + # coding=utf8 +x = 2 + +""" +Should not be modified due to continuation in preceding line +""" diff --git a/crates/ruff/src/rules/pyupgrade/mod.rs b/crates/ruff/src/rules/pyupgrade/mod.rs index 89ef60d46ca78..e6ff0e751bd37 100644 --- a/crates/ruff/src/rules/pyupgrade/mod.rs +++ b/crates/ruff/src/rules/pyupgrade/mod.rs @@ -70,6 +70,7 @@ mod tests { #[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_6.py"))] #[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_7.py"))] #[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_8.py"))] + #[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_9.py"))] #[test_case(Rule::UnicodeKindPrefix, Path::new("UP025.py"))] #[test_case(Rule::UnnecessaryBuiltinImport, Path::new("UP029.py"))] #[test_case(Rule::UnnecessaryClassParentheses, Path::new("UP039.py"))] diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs index c03d7c9fc0673..1d2b1d195ef0b 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs @@ -65,6 +65,17 @@ pub(crate) fn unnecessary_coding_comment( continue; } + // Do not apply to lines with continuations; a fix will result in invalid syntax + // Ex) + // ``` + // x = 1 \ + // # coding=utf8 + // x = 2 + // ``` + if let Some(_) = indexer.preceded_by_continuations(line_range.start(), locator) { + continue; + } + let mut diagnostic = Diagnostic::new(UTF8EncodingDeclaration, *comment_range); if settings.rules.should_fix(diagnostic.kind.rule()) { diagnostic.set_fix(Fix::automatic(Edit::deletion( diff --git a/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP009_9.py.snap b/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP009_9.py.snap new file mode 100644 index 0000000000000..870ad3bf5d625 --- /dev/null +++ b/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP009_9.py.snap @@ -0,0 +1,4 @@ +--- +source: crates/ruff/src/rules/pyupgrade/mod.rs +--- +