Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion crates/ruff_python_importer/src/insertion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,24 @@ impl<'a> Insertion<'a> {
contents.bom_start_offset()
};

// Skip over commented lines, with whitespace separation.
// Skip over commented lines, with whitespace separation. Track blank
// lines after comments so we can preserve them between comments and
// the first statement.
let mut seen_comment = false;
for line in
UniversalNewlineIterator::with_offset(&contents[location.to_usize()..], location)
{
let trimmed_line = line.trim_whitespace_start();
if trimmed_line.is_empty() {
if seen_comment {
location = line.full_end();
}
continue;
}

if trimmed_line.starts_with('#') {
location = line.full_end();
seen_comment = true;
} else {
break;
}
Expand Down Expand Up @@ -525,6 +533,35 @@ x = 1
Insertion::inline(" ", TextSize::from(20), ";")
);

// Script metadata comments followed by a blank line and imports.
// The blank line between the comments and the import should be preserved.
let contents = r"
# /// script
# dependencies = ['anyio']
# ///

import datetime as dt
"
.trim_start();
assert_eq!(
insert(contents)?,
Insertion::own_line("", TextSize::from(47), "\n")
);

// Comments without a blank line before imports should insert right
// after the comments (no blank line to preserve).
let contents = r"
# /// script
# dependencies = ['anyio']
# ///
import datetime as dt
"
.trim_start();
assert_eq!(
insert(contents)?,
Insertion::own_line("", TextSize::from(46), "\n")
);

Ok(())
}

Expand Down
Loading