Skip to content

Commit

Permalink
Avoid D301 autofix for u prefixed strings (#8495)
Browse files Browse the repository at this point in the history
This PR avoids creating the fix for `D301` if the string is prefixed
with `u` i.e., it's a unicode string. The reason being that `u` and `r`
cannot be used together as it's a syntax error.

Refer:
#8402 (comment)
  • Loading branch information
dhruvmanila authored Nov 5, 2023
1 parent e57bccd commit b3c2935
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
4 changes: 4 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pydocstyle/D301.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,7 @@ def make_unique_pod_id(pod_id: str) -> str | None:
:param pod_id: requested pod name
:return: ``str`` valid Pod name of appropriate length
"""


def shouldnt_add_raw_here2():
u"Sum\\mary."
20 changes: 12 additions & 8 deletions crates/ruff_linter/src/rules/pydocstyle/rules/backslashes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use memchr::memchr_iter;

use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged;

Expand Down Expand Up @@ -46,14 +46,16 @@ use crate::docstrings::Docstring;
#[violation]
pub struct EscapeSequenceInDocstring;

impl AlwaysFixableViolation for EscapeSequenceInDocstring {
impl Violation for EscapeSequenceInDocstring {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;

#[derive_message_formats]
fn message(&self) -> String {
format!(r#"Use `r"""` if any backslashes in a docstring"#)
}

fn fix_title(&self) -> String {
format!(r#"Add `r` prefix"#)
fn fix_title(&self) -> Option<String> {
Some(format!(r#"Add `r` prefix"#))
}
}

Expand All @@ -74,10 +76,12 @@ pub(crate) fn backslashes(checker: &mut Checker, docstring: &Docstring) {
}) {
let mut diagnostic = Diagnostic::new(EscapeSequenceInDocstring, docstring.range());

diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
"r".to_owned() + docstring.contents,
docstring.range(),
)));
if !docstring.leading_quote().contains(['u', 'U']) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
"r".to_owned() + docstring.contents,
docstring.range(),
)));
}

checker.diagnostics.push(diagnostic);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,12 @@ D301.py:2:5: D301 [*] Use `r"""` if any backslashes in a docstring
4 4 |
5 5 | def double_quotes_backslash_raw():

D301.py:37:5: D301 Use `r"""` if any backslashes in a docstring
|
36 | def shouldnt_add_raw_here2():
37 | u"Sum\\mary."
| ^^^^^^^^^^^^^ D301
|
= help: Add `r` prefix


0 comments on commit b3c2935

Please sign in to comment.