Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions crates/ruff_linter/src/settings/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,11 @@ impl ExtensionMapping {
let ext = path.extension()?.to_str()?;
self.0.get(ext).copied()
}

/// Return the [`Language`] for a given file extension.
pub fn get_extension(&self, ext: &str) -> Option<Language> {
self.0.get(ext).copied()
}
}

impl From<FxHashMap<String, Language>> for ExtensionMapping {
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_markdown/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ authors = { workspace = true }
license = { workspace = true }

[dependencies]
ruff_linter = { workspace = true }
ruff_python_ast = { workspace = true }
ruff_python_formatter = { workspace = true }
ruff_python_trivia = { workspace = true }
Expand Down
172 changes: 170 additions & 2 deletions crates/ruff_markdown/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,70 @@ static MARKDOWN_CODE_BLOCK: LazyLock<Regex> = LazyLock::new(|| {
.unwrap()
});

static OFF_ON_DIRECTIVES: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?imx)
^
\s*<!--\s*(?:blacken-docs|ruff)\s*:\s*(?<action>off|on)\s*-->
",
)
.unwrap()
});

pub fn format_code_blocks(
source: &str,
path: Option<&Path>,
settings: &FormatterSettings,
) -> MarkdownResult {
let mut ignore_ranges = Vec::new();
let mut last_off: Option<usize> = None;

// Find ruff:off directives and generate ranges to ignore formatting
for capture in OFF_ON_DIRECTIVES.captures_iter(source) {
let Some(action) = capture.name("action") else {
continue;
};

match action.as_str() {
"off" => last_off = last_off.or_else(|| Some(action.start())),
"on" => {
last_off = match last_off {
Some(last_off) => {
ignore_ranges.push(last_off..action.end());
None
}
None => None,
};
}
_ => {}
}
}
// no matching ruff:on, ignore to end of file
if let Some(last_off) = last_off {
ignore_ranges.push(last_off..source.len());
}

let mut changed = false;
let mut formatted = String::with_capacity(source.len());
let mut last_match = 0;

for capture in MARKDOWN_CODE_BLOCK.captures_iter(source) {
let m = capture.get_match();
if ignore_ranges.iter().any(|ir| ir.contains(&m.start())) {
continue;
}

let (_, [before, code_indent, language, code, after]) = capture.extract();

let py_source_type = PySourceType::from_extension(language);
// map code block to source type, accounting for configured extension mappings
let py_source_type = match settings
.extension
.get_extension(&language.to_ascii_lowercase())
{
None => PySourceType::from_extension(language),
Some(language) => PySourceType::from(language),
};

let unformatted_code = dedent(code);
let options = settings.to_format_options(py_source_type, &unformatted_code, path);

Expand All @@ -57,7 +108,6 @@ pub fn format_code_blocks(
if let Ok(formatted_code) = formatted_code {
if formatted_code.len() != unformatted_code.len() || formatted_code != *unformatted_code
{
let m = capture.get_match();
formatted.push_str(&source[last_match..m.start()]);

let indented_code = indent(&formatted_code, code_indent);
Expand All @@ -82,6 +132,7 @@ pub fn format_code_blocks(
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
use ruff_linter::settings::types::{ExtensionMapping, ExtensionPair, Language};
use ruff_workspace::FormatterSettings;

use crate::{MarkdownResult, format_code_blocks};
Expand Down Expand Up @@ -187,4 +238,121 @@ fn (foo: &str) -> &str {
format_code_blocks(code, None, &FormatterSettings::default()),
@"Unchanged");
}

#[test]
fn format_code_blocks_extension_mapping() {
// format "py" mapped as "pyi" instead
let code = r#"
```py
def foo(): ...
def bar(): ...
```
"#;
let mapping = ExtensionMapping::from_iter([ExtensionPair {
extension: "py".to_string(),
language: Language::Pyi,
}]);
assert_snapshot!(format_code_blocks(
code,
None,
&FormatterSettings {
extension: mapping,
..Default::default()
}
), @"Unchanged");
}

#[test]
fn format_code_blocks_ignore_blackendocs_off() {
let code = r#"
```py
print( 'hello' )
```

<!-- blacken-docs:off -->
```py
print( 'hello' )
```
<!-- blacken-docs:on -->

```py
print( 'hello' )
```
"#;
assert_snapshot!(format_code_blocks(
code,
None,
&FormatterSettings::default()
), @r#"
```py
print("hello")
```

<!-- blacken-docs:off -->
```py
print( 'hello' )
```
<!-- blacken-docs:on -->

```py
print("hello")
```
"#);
}

#[test]
fn format_code_blocks_ignore_ruff_off() {
let code = r#"
```py
print( 'hello' )
```

<!-- ruff:off -->
```py
print( 'hello' )
```
<!-- ruff:on -->

```py
print( 'hello' )
```
"#;
assert_snapshot!(format_code_blocks(
code,
None,
&FormatterSettings::default()
), @r#"
```py
print("hello")
```

<!-- ruff:off -->
```py
print( 'hello' )
```
<!-- ruff:on -->

```py
print("hello")
```
"#);
}
#[test]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tiny nit:

Suggested change
#[test]
#[test]

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sigh, why doesn't rustfmt take care of that for me 😅

fn format_code_blocks_ignore_to_end() {
let code = r#"
<!-- ruff:off -->
```py
print( 'hello' )
```

```py
print( 'hello' )
```
"#;
assert_snapshot!(format_code_blocks(
code,
None,
&FormatterSettings::default()
), @"Unchanged");
}
}