1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use super::configuration::Configuration;

use anyhow::Result;
use dprint_core::configuration::resolve_new_line_kind;
use parcel_css::stylesheet::{ParserOptions, PrinterOptions, StyleSheet};
use std::path::Path;

const PARSER_OPTS: ParserOptions = ParserOptions {
    nesting: true,
    css_modules: false,
    custom_media: false,
};
const PRINTER_OPTS: PrinterOptions = PrinterOptions {
    minify: false,
    source_map: false,
    analyze_dependencies: false,
    targets: None,
    pseudo_classes: None,
};

pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Result<String> {
    let filename = "".to_string();
    // TODO: get rid of unwrap
    let stylesheet = match StyleSheet::parse(filename, text, PARSER_OPTS) {
        Ok(v) => v,
        Err(_) => {
            eprintln!("Error parsing file");
            std::process::exit(1);
        }
    };
    let css = stylesheet.to_css(PRINTER_OPTS).unwrap();
    let text = css.code;

    // ensure ends with newline
    let text = if !text.ends_with('\n') {
        let mut text = text;
        text.push('\n');
        text
    } else {
        text
    };

    // newline
    Ok(
        if resolve_new_line_kind(&text, config.new_line_kind) == "\n" {
            text.replace("\r\n", "\n")
        } else {
            // lazy
            text.replace("\r\n", "\n").replace("\n", "\r\n")
        },
    )
}