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
53
54
55
56
57
58
59
60
61
62
63
64
use anyhow::{format_err, Result};
use full_moon::ast::owned::Owned;
use full_moon::visitors::VisitorMut;
use serde::Deserialize;
mod formatters;
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum IndentType {
Tabs,
Spaces,
}
impl Default for IndentType {
fn default() -> Self {
IndentType::Tabs
}
}
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum LineEndings {
Unix,
Windows,
}
impl Default for LineEndings {
fn default() -> Self {
LineEndings::Unix
}
}
#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(default)]
pub struct Config {
line_endings: LineEndings,
indent_type: IndentType,
indent_width: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
line_endings: LineEndings::Unix,
indent_type: IndentType::Tabs,
indent_width: 4,
}
}
}
pub fn format_code(code: &str, config: Config) -> Result<String> {
let mut ast = match full_moon::parse(&code) {
Ok(ast) => ast.owned(),
Err(error) => {
return Err(format_err!("error parsing: {}", error));
}
};
let mut code_formatter = formatters::CodeFormatter::new(config);
ast = code_formatter.visit_ast(ast);
Ok(full_moon::print(&ast))
}