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
use once_cell::sync::OnceCell;
use std::io::Write;
use std::process::{Command, Stdio};
pub static CLANG_FORMAT_STYLE: OnceCell<ClangFormatStyle> = OnceCell::new();
#[derive(Debug, PartialEq)]
pub enum ClangFormatStyle {
Chromium,
Default,
File,
Google,
Llvm,
Mozilla,
WebKit,
}
impl ClangFormatStyle {
fn as_str(&self) -> &'static str {
match self {
Self::Chromium => "Chromium",
Self::Default => "{}",
Self::File => "file",
Self::Google => "Google",
Self::Llvm => "LLVM",
Self::Mozilla => "Mozilla",
Self::WebKit => "WebKit",
}
}
}
#[derive(Debug)]
pub enum ClangFormatError {
SpawnFailure,
StdInFailure,
StdInWriteFailure,
Utf8FormatError,
WaitFailure,
}
fn clang_format_with_style(
input: &str,
style: &ClangFormatStyle,
) -> Result<String, ClangFormatError> {
if let Ok(mut child) = Command::new("clang-format")
.arg(format!("--style={}", style.as_str()))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
{
if let Some(mut stdin) = child.stdin.take() {
if write!(stdin, "{}", input).is_err() {
return Err(ClangFormatError::StdInWriteFailure);
}
} else {
return Err(ClangFormatError::StdInFailure);
}
if let Ok(output) = child.wait_with_output() {
if let Ok(stdout) = String::from_utf8(output.stdout) {
Ok(stdout)
} else {
Err(ClangFormatError::Utf8FormatError)
}
} else {
Err(ClangFormatError::WaitFailure)
}
} else {
Err(ClangFormatError::SpawnFailure)
}
}
pub fn clang_format(input: &str) -> Result<String, ClangFormatError> {
let style = CLANG_FORMAT_STYLE.get_or_init(|| ClangFormatStyle::Default);
clang_format_with_style(input, style)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_default() {
let input = r#"
struct Test {
};
"#;
let output = clang_format_with_style(input, &ClangFormatStyle::Default);
assert!(output.is_ok());
assert_eq!(output.unwrap(), "\nstruct Test {};\n");
}
#[test]
fn format_mozilla() {
let input = r#"
struct Test {
};
"#;
let output = clang_format_with_style(input, &ClangFormatStyle::Mozilla);
assert!(output.is_ok());
assert_eq!(output.unwrap(), "\nstruct Test\n{};\n");
}
}