Skip to content

Commit 5848906

Browse files
committed
fix pretty-printing of multi-line literal strings
this also improves performance and simplifies pretty-printing
1 parent 178a351 commit 5848906

File tree

2 files changed

+29
-30
lines changed

2 files changed

+29
-30
lines changed

src/display_utils.rs

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,10 @@ where
3131
T: Write,
3232
{
3333
fn write_str(&mut self, s: &str) -> fmt::Result {
34-
let mut first = true;
35-
for line in s.split('\n') {
36-
if !first {
37-
write!(self.0, "\n{INDENT}")?;
38-
}
39-
self.0.write_str(line)?;
40-
first = false;
34+
self.0.write_str(s)?;
35+
// Our NewLine and SpaceOrNewline utils always print individual newlines as a single-character string.
36+
if s == "\n" {
37+
self.0.write_str(INDENT)?;
4138
}
4239
Ok(())
4340
}
@@ -98,36 +95,24 @@ pub(crate) fn indented_list<T: fmt::Display>(f: &mut fmt::Formatter, slice: &[T]
9895
mod tests {
9996
use super::*;
10097

101-
struct DisplayCharByChar<T: Display>(T);
98+
#[test]
99+
fn test_indent() {
100+
struct TwoLines;
102101

103-
impl<T: Display> Display for DisplayCharByChar<T> {
104-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105-
for c in self.0.to_string().chars() {
106-
write!(f, "{}", c)?;
102+
impl Display for TwoLines {
103+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104+
f.write_str("line 1")?;
105+
SpaceOrNewline.fmt(f)?;
106+
f.write_str("line 2")
107107
}
108-
Ok(())
109108
}
110-
}
111109

112-
#[test]
113-
fn test_indent() {
114-
let original = "line 1\nline 2";
115-
let indent = Indent(original);
110+
let indent = Indent(TwoLines);
116111
assert_eq!(
117112
indent.to_string(),
118-
original,
113+
TwoLines.to_string(),
119114
"Only the alternate form should be indented"
120115
);
121-
let expected = " line 1\n line 2";
122-
assert_eq!(format!("{:#}", indent), expected);
123-
let display_char_by_char = DisplayCharByChar(original);
124-
assert_eq!(format!("{:#}", Indent(display_char_by_char)), expected);
125-
}
126-
127-
#[test]
128-
fn test_space_or_newline() {
129-
let space_or_newline = SpaceOrNewline;
130-
assert_eq!(format!("{}", space_or_newline), " ");
131-
assert_eq!(format!("{:#}", space_or_newline), "\n");
116+
assert_eq!(format!("{:#}", indent), " line 1\n line 2");
132117
}
133118
}

tests/pretty_print.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,17 @@ FROM
155155
"#.trim()
156156
);
157157
}
158+
159+
#[test]
160+
fn test_pretty_print_multiline_string() {
161+
assert_eq!(
162+
prettify("SELECT 'multiline\nstring' AS str"),
163+
r#"
164+
SELECT
165+
'multiline
166+
string' AS str
167+
"#
168+
.trim(),
169+
"A literal string with a newline should be kept as is. The contents of the string should not be indented."
170+
);
171+
}

0 commit comments

Comments
 (0)