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 00000000000000..fbfb852bf4d3cd --- /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 89ef60d46ca784..e6ff0e751bd373 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 c03d7c9fc0673f..d90a842911099b 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,16 @@ pub(crate) fn unnecessary_coding_comment( continue; } + // Do not apply to lines with continuations e.g. as a fix will result in invalid syntax + // ``` + // 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 00000000000000..870ad3bf5d6254 --- /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 +--- +