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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use crate::config::FmtConfig;
use crate::{expand_exe, expand_if_path, expand_path};
use anyhow::{anyhow, Result};
use console::style;
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
use log::debug;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, path::Path, path::PathBuf, process::Command};
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FormatterName(String);
impl Serialize for FormatterName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.0)
}
}
struct FormatterNameVisitor;
impl<'de> Visitor<'de> for FormatterNameVisitor {
type Value = FormatterName;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(FormatterName(value))
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(FormatterName(value.to_string()))
}
}
impl<'de> Deserialize<'de> for FormatterName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(FormatterNameVisitor)
}
}
impl fmt::Display for FormatterName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Debug, Clone)]
pub struct Formatter {
pub name: FormatterName,
pub command: PathBuf,
pub options: Vec<String>,
pub work_dir: PathBuf,
pub includes: GlobSet,
pub excludes: GlobSet,
}
impl Formatter {
pub fn fmt(&self, paths: &[PathBuf]) -> Result<()> {
let mut cmd_arg = Command::new(&self.command);
cmd_arg.current_dir(&self.work_dir);
cmd_arg.args(&self.options);
cmd_arg.args(paths);
match cmd_arg.output() {
Ok(out) => {
if !out.status.success() {
debug!(
"Error using formatter {}:\n{stdout}:\n{}\n{stderr}:\n{}",
self.name,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
stdout = style("• [STDOUT]").bold().dim(),
stderr = style("• [STDERR]").bold().dim(),
);
match out.status.code() {
Some(scode) => {
return Err(anyhow!(
"{}'s formatter failed: exit status {}",
&self,
scode
));
}
None => {
return Err(anyhow!(
"{}'s formatter failed: unknown formatter error",
&self
));
}
}
}
Ok(())
}
Err(err) => {
Err(anyhow!("{} failed: {}", &self, err))
}
}
}
pub fn is_match<T: AsRef<Path>>(&self, path: T) -> bool {
let path = path.as_ref();
assert!(path.is_absolute());
if !path.starts_with(&self.work_dir) {
return false;
}
if self.excludes.is_match(path) {
return false;
}
if !self.includes.is_match(path) {
return false;
}
true
}
pub fn from_config(tree_root: &Path, name: &str, cfg: &FmtConfig) -> Result<Self> {
let name = FormatterName(name.to_string());
let work_dir = expand_path(&cfg.work_dir, &tree_root);
let command = expand_exe(&cfg.command, &tree_root)?;
debug!("Found {} at {}", cfg.command, command.display());
assert!(command.is_absolute());
if cfg.includes.is_empty() {
return Err(anyhow!("{} doesn't have any includes", name));
}
let includes = patterns_to_glob_set(tree_root, &cfg.includes)?;
let excludes = patterns_to_glob_set(tree_root, &cfg.excludes)?;
Ok(Self {
name,
command,
options: cfg.options.clone(),
work_dir,
includes,
excludes,
})
}
}
impl fmt::Display for Formatter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.name.0)
}
}
fn patterns_to_glob_set(tree_root: &Path, patterns: &[String]) -> Result<GlobSet> {
let mut sum = GlobSetBuilder::new();
for pattern in patterns {
let pattern = expand_if_path(pattern.to_string(), &tree_root);
let glob = GlobBuilder::new(&pattern).build()?;
sum.add(glob);
}
Ok(sum.build()?)
}