dprint_plugin_sql/
format_text.rs

1use super::configuration::Configuration;
2
3use anyhow::Result;
4use dprint_core::configuration::resolve_new_line_kind;
5use sqlformat::FormatOptions;
6use sqlformat::Indent;
7use sqlformat::QueryParams;
8use std::path::Path;
9
10pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Result<Option<String>> {
11  let input_text = text;
12  let text = sqlformat::format(
13    text,
14    &QueryParams::None,
15    FormatOptions {
16      indent: if config.use_tabs {
17        Indent::Tabs
18      } else {
19        Indent::Spaces(config.indent_width)
20      },
21      uppercase: config.uppercase,
22      lines_between_queries: config.lines_between_queries,
23    },
24  );
25
26  // ensure ends with newline
27  let text = if !text.ends_with('\n') {
28    let mut text = text;
29    text.push('\n');
30    text
31  } else {
32    text
33  };
34
35  // newline
36  let text = if resolve_new_line_kind(&text, config.new_line_kind) == "\n" {
37    text.replace("\r\n", "\n")
38  } else {
39    // lazy
40    text.replace("\r\n", "\n").replace("\n", "\r\n")
41  };
42
43  if text == input_text {
44    Ok(None)
45  } else {
46    Ok(Some(text))
47  }
48}