[`ruff_linter`] - Use LibCST in `adjust_indentation` for mixed whitespace (#12740)

This commit is contained in:
Steve C 2024-08-08 04:49:58 -04:00 committed by GitHub
parent df7345e118
commit 6d9205e346
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 50 additions and 4 deletions

View File

@ -238,3 +238,9 @@ def indent(x, y, w, z):
# comment
c = 3
return z
def f():
if True:
return True
else:
return False

View File

@ -300,11 +300,25 @@ pub(crate) fn adjust_indentation(
indexer: &Indexer,
stylist: &Stylist,
) -> Result<String> {
let contents = locator.slice(range);
// If the range includes a multi-line string, use LibCST to ensure that we don't adjust the
// whitespace _within_ the string.
if indexer.multiline_ranges().intersects(range) || indexer.fstring_ranges().intersects(range) {
let contents = locator.slice(range);
let contains_multiline_string =
indexer.multiline_ranges().intersects(range) || indexer.fstring_ranges().intersects(range);
// If the range has mixed indentation, we will use LibCST as well.
let mixed_indentation = contents.universal_newlines().any(|line| {
let trimmed = line.trim_whitespace_start();
if trimmed.is_empty() {
return false;
}
let line_indentation: &str = &line[..line.len() - trimmed.len()];
line_indentation.contains('\t') && line_indentation.contains(' ')
});
if contains_multiline_string || mixed_indentation {
let module_text = format!("def f():{}{contents}", stylist.line_ending().as_str());
let mut tree = match_statement(&module_text)?;
@ -322,7 +336,6 @@ pub(crate) fn adjust_indentation(
Ok(module_text)
} else {
// Otherwise, we can do a simple adjustment ourselves.
let contents = locator.slice(range);
Ok(dedent_to(contents, indentation))
}
}

View File

@ -215,4 +215,12 @@ RET505.py:237:5: RET505 Unnecessary `else` after `return` statement
|
= help: Remove unnecessary `else`
RET505.py:245:2: RET505 Unnecessary `else` after `return` statement
|
243 | if True:
244 | return True
245 | else:
| ^^^^ RET505
246 | return False
|
= help: Remove unnecessary `else`

View File

@ -460,5 +460,24 @@ RET505.py:237:5: RET505 [*] Unnecessary `else` after `return` statement
240 |- return z
238 |+ c = 3
239 |+ return z
241 240 |
242 241 | def f():
243 242 | if True:
RET505.py:245:2: RET505 [*] Unnecessary `else` after `return` statement
|
243 | if True:
244 | return True
245 | else:
| ^^^^ RET505
246 | return False
|
= help: Remove unnecessary `else`
Safe fix
242 242 | def f():
243 243 | if True:
244 244 | return True
245 |- else:
246 |- return False
245 |+ return False