Skip to content

Commit 30ee447

Browse files
authored
Fix I002 import insertion after docstring with multiple string statements (#19222)
1 parent fd69533 commit 30ee447

File tree

4 files changed

+27
-10
lines changed

4 files changed

+27
-10
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""This is a docstring."""
2+
"This is not a docstring."
3+
"This is also not a docstring."
4+
5+
x = 1

crates/ruff_linter/src/importer/insertion.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -275,19 +275,12 @@ impl<'a> Insertion<'a> {
275275
}
276276
}
277277

278-
/// Find the end of the last docstring.
278+
/// Find the end of the docstring (first string statement).
279279
fn match_docstring_end(body: &[Stmt]) -> Option<TextSize> {
280-
let mut iter = body.iter();
281-
let mut stmt = iter.next()?;
280+
let stmt = body.first()?;
282281
if !is_docstring_stmt(stmt) {
283282
return None;
284283
}
285-
for next in iter {
286-
if !is_docstring_stmt(next) {
287-
break;
288-
}
289-
stmt = next;
290-
}
291284
Some(stmt.end())
292285
}
293286

@@ -367,7 +360,7 @@ mod tests {
367360
.trim_start();
368361
assert_eq!(
369362
insert(contents)?,
370-
Insertion::own_line("", TextSize::from(40), "\n")
363+
Insertion::own_line("", TextSize::from(20), "\n")
371364
);
372365

373366
let contents = r"

crates/ruff_linter/src/rules/isort/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,7 @@ mod tests {
912912
#[test_case(Path::new("docstring.pyi"))]
913913
#[test_case(Path::new("docstring_only.py"))]
914914
#[test_case(Path::new("empty.py"))]
915+
#[test_case(Path::new("multiple_strings.py"))]
915916
fn required_imports(path: &Path) -> Result<()> {
916917
let snapshot = format!("required_imports_{}", path.to_string_lossy());
917918
let diagnostics = test_path(
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
source: crates/ruff_linter/src/rules/isort/mod.rs
3+
---
4+
multiple_strings.py:1:1: I002 [*] Missing required import: `from __future__ import annotations`
5+
Safe fix
6+
1 1 | """This is a docstring."""
7+
2 |+from __future__ import annotations
8+
2 3 | "This is not a docstring."
9+
3 4 | "This is also not a docstring."
10+
4 5 |
11+
12+
multiple_strings.py:1:1: I002 [*] Missing required import: `from __future__ import generator_stop`
13+
Safe fix
14+
1 1 | """This is a docstring."""
15+
2 |+from __future__ import generator_stop
16+
2 3 | "This is not a docstring."
17+
3 4 | "This is also not a docstring."
18+
4 5 |

0 commit comments

Comments
 (0)