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
use crate::error::Error;
use crate::linter::{Lint, Linter, Location};
use crate::utils::get_absolute_file_path;
use serde::Deserialize;
use serde_json;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct RustFmt {}
impl Linter for RustFmt {
fn lints(&self, working_dir: PathBuf) -> Result<Vec<Lint>, Error> {
println!(
"[RustFmt] - checking format for directory {}",
&working_dir.to_str().unwrap_or("<no directory>")
);
let rustfmt_output = Self::fmt(working_dir)?;
lints(&rustfmt_output)
}
}
impl RustFmt {
fn command_parameters() -> Vec<&'static str> {
vec!["+nightly", "fmt", "--", "--emit", "json"]
}
#[cfg_attr(tarpaulin, skip)]
fn fmt(path: impl AsRef<Path>) -> Result<String, Error> {
let fmt_output = Command::new("cargo")
.current_dir(path)
.args(Self::command_parameters())
.output()
.expect("failed to run cargo fmt");
if fmt_output.status.success() {
Ok(String::from_utf8(fmt_output.stdout)?)
} else {
Err(Error::Command(String::from_utf8(fmt_output.stderr)?))
}
}
}
#[derive(Deserialize, Debug)]
struct FmtLint {
name: String,
mismatches: Vec<FmtMismatch>,
}
#[derive(Deserialize, Debug)]
struct FmtMismatch {
original_begin_line: u32,
original_end_line: u32,
original: String,
expected: String,
}
fn lints(fmt_output: &str) -> Result<Vec<Lint>, Error> {
let mut lints = Vec::new();
let fmt_lints: Vec<FmtLint> = serde_json::from_str(fmt_output)?;
for fmt_lint in fmt_lints {
lints.append(
&mut fmt_lint
.mismatches
.iter()
.filter_map(|mismatch| {
if let Ok(path) = get_absolute_file_path(fmt_lint.name.clone()) {
Some(Lint {
message: display_mismatch(mismatch, &path),
location: Location {
path,
lines: [mismatch.original_begin_line, mismatch.original_end_line],
},
})
} else {
None
}
})
.collect::<Vec<Lint>>(),
);
}
Ok(lints)
}
fn display_mismatch(mismatch: &FmtMismatch, path: &str) -> String {
if mismatch.original_begin_line == mismatch.original_end_line {
format!(
"Diff in {} at line {}:\n-{}\n+{}\n",
path, mismatch.original_begin_line, mismatch.original, mismatch.expected
)
} else {
format!(
"Diff in {} between lines {} and {}:\n{}\n{}\n",
path,
mismatch.original_begin_line,
mismatch.original_end_line,
mismatch
.original
.lines()
.map(|line| format!("-{}", line))
.collect::<Vec<String>>()
.join("\n"),
mismatch
.expected
.lines()
.map(|line| format!("+{}", line))
.collect::<Vec<String>>()
.join("\n")
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_command_parameters() {
assert_eq!(
vec!["+nightly", "fmt", "--", "--emit", "json"],
RustFmt::command_parameters()
);
}
#[test]
fn test_display_mismatch_one_line() -> Result<(), Error> {
let mismatch = FmtMismatch {
original_begin_line: 1,
original_end_line: 1,
original: " this is a test mismatch".to_string(),
expected: "this is a test mismatch".to_string(),
};
let path = get_absolute_file_path("src/foo/bar.txt")?;
let expected_display = format!(
"Diff in {} at line 1:\n- this is a test mismatch\n+this is a test mismatch\n",
path
);
let actual_display = display_mismatch(&mismatch, &path);
assert_eq!(expected_display, actual_display);
Ok(())
}
#[test]
fn test_display_mismatch_several_lines() -> Result<(), Error> {
let mismatch = FmtMismatch {
original_begin_line: 1,
original_end_line: 2,
original: " this is a test mismatch\n the indent is wrong".to_string(),
expected: "this is a test mismatch\nthe indent is wrong".to_string(),
};
let path = get_absolute_file_path("src/foo/bar.txt")?;
let expected_display = format!("Diff in {} between lines 1 and 2:\n- this is a test mismatch\n- the indent is wrong\n+this is a test mismatch\n+the indent is wrong\n", path);
let actual_display = display_mismatch(&mismatch, &path);
assert_eq!(expected_display, actual_display);
Ok(())
}
#[test]
fn test_lints() -> Result<(), crate::error::Error> {
let fmt_output = r#"[{"name":"cargo-scout/cargo-scout-lib/src/lib.rs","mismatches":[{"original_begin_line":1,"original_end_line":1,"expected_begin_line":1,"expected_end_line":1,"original":" pub mod config;","expected":"pub mod config;"}]}]"#;
let path = get_absolute_file_path("cargo-scout/cargo-scout-lib/src/lib.rs")?;
let expected_lints = vec![Lint {
location: Location {
lines: [1, 1],
path: path.clone(),
},
message: format!(
"Diff in {} at line 1:\n- pub mod config;\n+pub mod config;\n",
path
),
}];
let actual_lints = lints(fmt_output).unwrap();
assert_eq!(expected_lints, actual_lints);
Ok(())
}
}