Skip to content

Commit

Permalink
feat: Add an option to inline over the top level tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
lu-zero committed Jan 15, 2025
1 parent 77b7b30 commit 3239e35
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,16 @@ impl<'a> Formatter<'a> {
self.add_new_line(query);
self.indentation.increase_top_level();
query.push_str(&self.equalize_whitespace(&self.format_reserved_word(token.value)));
self.add_new_line(query);
let len = self.top_level_tokens_span();
if self
.options
.max_inline_top_level
.map_or(true, |limit| limit < len)
{
self.add_new_line(query);
} else {
query.push(' ');
}
}

fn format_top_level_reserved_word_no_indent(&mut self, token: &Token<'_>, query: &mut String) {
Expand Down Expand Up @@ -485,6 +494,16 @@ impl<'a> Formatter<'a> {
query.len() - self.line_start + self.next_token(1).map_or(0, |t| t.value.len())
}

fn top_level_tokens_span(&self) -> usize {
assert_eq!(self.tokens[self.index].kind, TokenKind::ReservedTopLevel);

self.tokens[self.index..]
.iter()
.skip(1)
.map(|token| token.value.len())
.sum()
}

fn format_no_change(&self, token: &Token<'_>, query: &mut String) {
query.push_str(token.value);
}
Expand Down
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ pub struct FormatOptions<'a> {
///
/// Default: None
pub max_inline_arguments: Option<usize>,
/// Inline the argument at the top level if they would fit a line
///
/// Default: None
pub max_inline_top_level: Option<usize>,
}

impl<'a> Default for FormatOptions<'a> {
Expand All @@ -69,6 +73,7 @@ impl<'a> Default for FormatOptions<'a> {
inline: false,
max_inline_block: 50,
max_inline_arguments: None,
max_inline_top_level: None,
}
}
}
Expand Down Expand Up @@ -221,6 +226,35 @@ mod tests {
assert_eq!(format(input, &QueryParams::None, &options), expected);
}

#[test]
fn inline_arguments_when_possible() {
let input = indoc! {
"
SELECT
a,
b,
c,
d,
e,
f,
g,
h
FROM foo;"
};
let options = FormatOptions {
max_inline_arguments: Some(50),
max_inline_top_level: Some(20),
..Default::default()
};
let expected = indoc! {
"
SELECT
a, b, c, d, e, f, g, h
FROM foo;"
};
assert_eq!(format(input, &QueryParams::None, &options), expected);
}

#[test]
fn it_formats_select_with_complex_where() {
let input = indoc!(
Expand Down

0 comments on commit 3239e35

Please sign in to comment.