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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use anyhow::{format_err, Result};
use serde::Deserialize;
#[macro_use]
mod context;
mod formatters;
mod shape;
#[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(Debug, Copy, Clone, Deserialize)]
pub enum QuoteStyle {
AutoPreferDouble,
AutoPreferSingle,
ForceDouble,
ForceSingle,
}
impl Default for QuoteStyle {
fn default() -> Self {
QuoteStyle::AutoPreferDouble
}
}
#[derive(Debug, Copy, Clone, Deserialize)]
pub struct Range {
start: Option<usize>,
end: Option<usize>,
}
impl Range {
pub fn from_values(start: Option<usize>, end: Option<usize>) -> Self {
Self { start, end }
}
}
#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
column_width: usize,
line_endings: LineEndings,
indent_type: IndentType,
indent_width: usize,
quote_style: QuoteStyle,
no_call_parentheses: bool,
}
impl Config {
pub fn new() -> Self {
Config::default()
}
pub fn with_column_width(self, column_width: usize) -> Self {
Self {
column_width,
..self
}
}
pub fn with_line_endings(self, line_endings: LineEndings) -> Self {
Self {
line_endings,
..self
}
}
pub fn with_indent_type(self, indent_type: IndentType) -> Self {
Self {
indent_type,
..self
}
}
pub fn with_indent_width(self, indent_width: usize) -> Self {
Self {
indent_width,
..self
}
}
pub fn with_quote_style(self, quote_style: QuoteStyle) -> Self {
Self {
quote_style,
..self
}
}
pub fn with_no_call_parentheses(self, no_call_parentheses: bool) -> Self {
Self {
no_call_parentheses,
..self
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
column_width: 120,
line_endings: LineEndings::Unix,
indent_type: IndentType::Tabs,
indent_width: 4,
quote_style: QuoteStyle::default(),
no_call_parentheses: false,
}
}
}
pub fn format_code(code: &str, config: Config, range: Option<Range>) -> Result<String> {
let ast = match full_moon::parse(&code) {
Ok(ast) => ast,
Err(error) => {
return Err(format_err!("error parsing: {}", error));
}
};
let code_formatter = formatters::CodeFormatter::new(config, range);
let ast = code_formatter.format(ast);
Ok(full_moon::print(&ast))
}