Skip to content

Commit

Permalink
Prototype Black's string joining/splitting (#4449)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser authored May 16, 2023
1 parent e5101e8 commit ddf7de7
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 1 deletion.
75 changes: 74 additions & 1 deletion crates/ruff_python_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ mod tests {
use std::path::Path;

use anyhow::Result;
use similar::TextDiff;
use insta::assert_snapshot;

use ruff_testing_macros::fixture;
use ruff_text_size::TextSize;
use similar::TextDiff;

use crate::fmt;

Expand Down Expand Up @@ -176,6 +178,77 @@ mod tests {
);
}

#[test]
fn string_processing() {
use ruff_formatter::prelude::*;
use ruff_formatter::{format, format_args, write};

struct FormatString<'a>(&'a str);

impl Format<SimpleFormatContext> for FormatString<'_> {
fn fmt(
&self,
f: &mut ruff_formatter::formatter::Formatter<SimpleFormatContext>,
) -> FormatResult<()> {
let format_str = format_with(|f| {
write!(f, [text("\"")])?;

let mut words = self.0.split_whitespace().peekable();
let mut fill = f.fill();

let separator = format_with(|f| {
group(&format_args![
if_group_breaks(&text("\"")),
soft_line_break_or_space(),
if_group_breaks(&text("\" "))
])
.fmt(f)
});

while let Some(word) = words.next() {
let is_last = words.peek().is_none();
let format_word = format_with(|f| {
write!(f, [dynamic_text(word, TextSize::default())])?;

if is_last {
write!(f, [text("\"")])?;
}

Ok(())
});

fill.entry(&separator, &format_word);
}

fill.finish()
});

write!(
f,
[group(&format_args![
if_group_breaks(&text("(")),
soft_block_indent(&format_str),
if_group_breaks(&text(")"))
])]
)
}
}

// 77 after g group (leading quote)
let fits =
r#"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg h"#;
let breaks =
r#"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg hh"#;

let output = format!(
SimpleFormatContext::default(),
[FormatString(fits), hard_line_break(), FormatString(breaks)]
)
.expect("Formatting to succeed");

assert_snapshot!(output.print().expect("Printing to succeed").as_code());
}

struct Header<'a> {
title: &'a str,
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: "output.print().expect(\"Printing to succeed\").as_code()"
---
"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg h"
(
"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg"
" hh"
)

0 comments on commit ddf7de7

Please sign in to comment.