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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use anyhow::{bail, Context, Result};
use console::{style, Term};
use indicatif::{MultiProgress, ProgressBar};
use linter::Linter;
use log::debug;
use path::AbsPath;
use regex::Regex;
use render::{render_lint_messages, render_lint_messages_json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use std::{collections::HashSet, process::Command};
pub mod lint_config;
pub mod lint_message;
pub mod linter;
pub mod path;
pub mod render;
use lint_message::LintMessage;
use render::PrintedLintErrors;
pub fn get_paths_cmd_files(paths_cmd: String) -> Result<Vec<AbsPath>> {
debug!("Running paths_cmd: {}", paths_cmd);
let output = Command::new("sh")
.arg("-c")
.arg(paths_cmd)
.output()
.context("failed to run provided paths_cmd")?;
let files = std::str::from_utf8(&output.stdout).context("failed to parse paths_cmd output")?;
let files = files
.lines()
.map(|s| s.to_string())
.collect::<HashSet<String>>();
let mut files = files.into_iter().collect::<Vec<String>>();
files.sort();
files
.into_iter()
.map(|f| AbsPath::new(PathBuf::from(f)))
.collect::<Result<_>>()
}
fn is_head_public() -> Result<bool> {
let output = Command::new("git")
.arg("rev-parse")
.arg("--abbrev-ref")
.arg("origin/HEAD")
.output()?;
if !output.status.success() {
bail!("Failed to determine whether commit was public; git rev-parse failed");
}
let default_branch = std::str::from_utf8(&output.stdout)?.trim();
let status = Command::new("git")
.arg("merge-base")
.arg("--is-ancestor")
.arg("HEAD")
.arg(default_branch)
.status()?;
match status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
_ => bail!("Failed to determine whether commit was public; git merge-base failed"),
}
}
fn get_changed_files() -> Result<Vec<AbsPath>> {
let mut commit_files: Option<HashSet<String>> = None;
if !is_head_public()? {
let output = Command::new("git")
.arg("diff-tree")
.arg("--no-commit-id")
.arg("--name-status")
.arg("-r")
.arg("HEAD")
.output()?;
if !output.status.success() {
bail!("Failed to determine files to lint; git diff-tree failed");
}
let commit_files_str = std::str::from_utf8(&output.stdout)?;
let re = Regex::new(r"^[A-Z]\s+")?;
commit_files = Some(
commit_files_str
.split("\n")
.map(|x| x.to_string())
.filter(|line| !line.starts_with("D"))
.map(|line| {
re.replace(&line, "").to_string()
})
.filter(|line| !line.is_empty())
.collect(),
);
debug!(
"HEAD commit is not public, linting commit diff files: {:?}",
commit_files
);
}
let output = Command::new("git")
.arg("diff-index")
.arg("--no-commit-id")
.arg("--name-only")
.arg("-r")
.arg("HEAD")
.output()?;
if !output.status.success() {
bail!("Failed to determine files to lint; git diff-index failed");
}
let working_tree_files_str = std::str::from_utf8(&output.stdout)?;
let working_tree_files: HashSet<String> = working_tree_files_str
.lines()
.filter(|line| !line.is_empty())
.map(|x| x.to_string())
.collect();
debug!("Linting working tree diff files: {:?}", working_tree_files);
let mut all_changed_files = working_tree_files;
if let Some(commit_files) = commit_files {
for file in commit_files {
all_changed_files.insert(file);
}
}
let mut all_changed_files: Vec<String> = all_changed_files.into_iter().collect();
all_changed_files.sort();
all_changed_files
.into_iter()
.map(|f| {
AbsPath::new(PathBuf::from(&f)).with_context(|| {
format!("Failed to find file while gathering files to lint: {}", f)
})
})
.collect::<Result<_>>()
}
fn group_lints_by_file(
all_lints: &mut HashMap<Option<String>, Vec<LintMessage>>,
lints: Vec<LintMessage>,
) {
lints.into_iter().fold(all_lints, |acc, lint| {
acc.entry(lint.path.clone())
.or_insert_with(Vec::new)
.push(lint);
acc
});
}
fn apply_patches(lint_messages: &Vec<LintMessage>) -> Result<()> {
let mut patched_paths = HashSet::new();
for lint_message in lint_messages {
if let (Some(replacement), Some(path)) = (&lint_message.replacement, &lint_message.path) {
let path = AbsPath::new(PathBuf::from(path))?;
if patched_paths.contains(&path) {
bail!(
"Two different linters proposed changes for the same file:
{}.\n This is not yet supported, file an issue if you want it.",
path.as_pathbuf().display()
);
}
patched_paths.insert(path.clone());
std::fs::write(path.as_pathbuf(), replacement).context(format!(
"Failed to write apply patch to file: '{}'",
path.as_pathbuf().display()
))?;
}
}
Ok(())
}
pub fn do_init(linters: Vec<Linter>, dry_run: bool) -> Result<i32> {
debug!(
"Initializing linters: {:?}",
linters.iter().map(|l| &l.code).collect::<Vec<_>>()
);
for linter in linters {
linter.init(dry_run)?;
}
Ok(0)
}
fn remove_patchable_lints(lints: Vec<LintMessage>) -> Vec<LintMessage> {
lints
.into_iter()
.filter(|lint| lint.replacement.is_none())
.collect()
}
fn get_paths_from_input(paths: Vec<String>) -> Result<Vec<AbsPath>> {
let mut ret = Vec::new();
for path in &paths {
let path = AbsPath::new(PathBuf::from(path))
.with_context(|| format!("Failed to lint provided file: '{}'", path))?;
ret.push(path);
}
Ok(ret)
}
pub enum PathsToLint {
Auto,
PathsCmd(String),
Paths(Vec<String>),
}
pub fn do_lint(
linters: Vec<Linter>,
paths_to_lint: PathsToLint,
should_apply_patches: bool,
render_as_json: bool,
enable_spinners: bool,
) -> Result<i32> {
debug!(
"Running linters: {:?}",
linters.iter().map(|l| &l.code).collect::<Vec<_>>()
);
let all_lints = Arc::new(Mutex::new(HashMap::new()));
let files = match paths_to_lint {
PathsToLint::Auto => get_changed_files()?,
PathsToLint::PathsCmd(paths_cmd) => get_paths_cmd_files(paths_cmd)?,
PathsToLint::Paths(paths) => get_paths_from_input(paths)?,
};
let files = Arc::new(files);
debug!("Linting files: {:#?}", files);
let mut thread_handles = Vec::new();
let spinners = Arc::new(MultiProgress::new());
for linter in linters {
let all_lints = Arc::clone(&all_lints);
let files = Arc::clone(&files);
let spinners = Arc::clone(&spinners);
let handle = thread::spawn(move || -> Result<()> {
let mut spinner = None;
if enable_spinners {
let _spinner = spinners.add(ProgressBar::new_spinner());
_spinner.set_message(format!("{} running...", linter.code));
_spinner.enable_steady_tick(100);
spinner = Some(_spinner);
}
let lints = linter.run(&files);
let lints = if should_apply_patches {
apply_patches(&lints)?;
remove_patchable_lints(lints)
} else {
lints
};
let mut all_lints = all_lints.lock().unwrap();
let is_success = lints.is_empty();
group_lints_by_file(&mut all_lints, lints);
let spinner_message = if is_success {
format!("{} {}", linter.code, style("success!").green())
} else {
format!("{} {}", linter.code, style("failure").red())
};
if enable_spinners {
spinner.unwrap().finish_with_message(spinner_message);
}
Ok(())
});
thread_handles.push(handle);
}
spinners.join()?;
for handle in thread_handles {
handle.join().unwrap()?;
}
let all_lints = all_lints.lock().unwrap();
let mut stdout = Term::stdout();
let did_print = if render_as_json {
render_lint_messages_json(&mut stdout, &all_lints)?
} else {
render_lint_messages(&mut stdout, &all_lints)?
};
if should_apply_patches {
stdout.write_line("Successfully applied all patches.")?;
}
match did_print {
PrintedLintErrors::No => Ok(0),
PrintedLintErrors::Yes => Ok(1),
}
}