dprint_plugin_jsonc/
format_text.rs

1use dprint_core::formatting::{PrintOptions};
2use dprint_core::configuration::resolve_new_line_kind;
3use jsonc_parser::{parse_to_ast, ParseOptions};
4use super::configuration::Configuration;
5use super::parser::parse_items;
6
7pub fn format_text(text: &str, config: &Configuration) -> Result<String, String> {
8    let parse_result = parse_to_ast(text, &ParseOptions { comments: true, tokens: true });
9    let parse_result = match parse_result {
10        Ok(result) => result,
11        Err(err) => return Err(dprint_core::formatting::utils::string_utils::format_diagnostic(
12            Some((err.range.start, err.range.end)),
13            &err.message,
14            text
15        )),
16    };
17
18    Ok(dprint_core::formatting::format(|| parse_items(parse_result, text, config), PrintOptions {
19        indent_width: config.indent_width,
20        max_width: config.line_width,
21        use_tabs: config.use_tabs,
22        new_line_text: resolve_new_line_kind(text, config.new_line_kind),
23    }))
24}
25
26#[cfg(test)]
27mod tests {
28    use dprint_core::configuration::*;
29    use std::collections::HashMap;
30    use super::super::configuration::resolve_config;
31    use super::*;
32
33    #[test]
34    fn should_error_on_syntax_diagnostic() {
35        let global_config = resolve_global_config(HashMap::new()).config;
36        let config = resolve_config(HashMap::new(), &global_config).config;
37        let message = format_text("{ &*&* }", &config).err().unwrap();
38        assert_eq!(
39            message,
40            concat!(
41                "Line 1, column 3: Unexpected token\n",
42                "\n",
43                "  { &*&* }\n",
44                "    ~"
45            )
46        );
47    }
48}