dprint_plugin_css/
format_text.rs1use anyhow::{anyhow, Result};
2use dprint_core::configuration::resolve_new_line_kind;
3use dprint_core::formatting::PrintOptions;
4use raffia::ast::Stylesheet;
5use raffia::token::Comment;
6use raffia::ParserBuilder;
7use std::path::Path;
8
9use crate::configuration::Configuration;
10use crate::generation::generate;
11
12pub struct Ast<'a> {
13 pub stylesheet: Stylesheet<'a>,
14 pub comments: Vec<Comment<'a>>,
15}
16
17pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Result<String> {
18 let ast = parse_ast(text)?;
19
20 Ok(dprint_core::formatting::format(
21 || generate(ast, text, config),
22 config_to_print_options(text, config),
23 ))
24}
25
26fn parse_ast(text: &str) -> Result<Ast> {
27 let mut comments = vec![];
28 let mut parser = ParserBuilder::new(text).comments(&mut comments).build();
29 let stylesheet = parser
30 .parse::<Stylesheet>()
31 .map_err(|err| anyhow!("parser error {:#?}", err))?;
32 Ok(Ast {
33 stylesheet,
34 comments,
35 })
36}
37
38fn config_to_print_options(text: &str, config: &Configuration) -> PrintOptions {
39 PrintOptions {
40 indent_width: config.indent_width,
41 max_width: config.line_width,
42 use_tabs: config.use_tabs,
43 new_line_text: resolve_new_line_kind(text, config.new_line_kind),
44 }
45}