-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathanalysis.rs
More file actions
242 lines (208 loc) · 7.59 KB
/
analysis.rs
File metadata and controls
242 lines (208 loc) · 7.59 KB
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
use std::io::IsTerminal;
use owo_colors::OwoColorize;
use vite_shared::output;
#[derive(Debug, Clone)]
pub(super) struct CheckSummary {
pub duration: String,
pub files: usize,
pub threads: usize,
}
#[derive(Debug)]
pub(super) struct FmtSuccess {
pub summary: CheckSummary,
}
#[derive(Debug)]
pub(super) struct FmtFailure {
pub summary: CheckSummary,
pub issue_files: Vec<String>,
pub issue_count: usize,
}
#[derive(Debug)]
pub(super) struct LintSuccess {
pub summary: CheckSummary,
}
#[derive(Debug)]
pub(super) struct LintFailure {
pub summary: CheckSummary,
pub warnings: usize,
pub errors: usize,
pub diagnostics: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum LintMessageKind {
LintOnly,
LintAndTypeCheck,
// Used when lint rules are skipped but type-check still runs.
TypeCheckOnly,
}
impl LintMessageKind {
// Selects a variant from the `(lint, type-check)` enabled tuple callers have
// already resolved, avoiding a second config lookup inside the helper.
pub(super) fn from_flags(lint_enabled: bool, type_check_enabled: bool) -> Self {
match (lint_enabled, type_check_enabled) {
(true, true) => Self::LintAndTypeCheck,
(true, false) => Self::LintOnly,
(false, true) => Self::TypeCheckOnly,
(false, false) => {
unreachable!(
"from_flags called with (false, false) — caller must ensure lint or type-check runs before selecting a message kind"
)
}
}
}
pub(super) fn success_label(self) -> &'static str {
match self {
Self::LintOnly => "Found no warnings or lint errors",
Self::LintAndTypeCheck => "Found no warnings, lint errors, or type errors",
Self::TypeCheckOnly => "Found no type errors",
}
}
pub(super) fn warning_heading(self) -> &'static str {
match self {
Self::LintOnly => "Lint warnings found",
Self::LintAndTypeCheck => "Lint or type warnings found",
Self::TypeCheckOnly => "Type warnings found",
}
}
pub(super) fn issue_heading(self) -> &'static str {
match self {
Self::LintOnly => "Lint issues found",
Self::LintAndTypeCheck => "Lint or type issues found",
Self::TypeCheckOnly => "Type errors found",
}
}
}
pub(super) fn lint_config_type_check_enabled(lint_config: Option<&serde_json::Value>) -> bool {
lint_config
.and_then(|config| config.get("options"))
.and_then(|options| options.get("typeCheck"))
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
}
fn parse_check_summary(line: &str) -> Option<CheckSummary> {
let rest = line.strip_prefix("Finished in ")?;
let (duration, rest) = rest.split_once(" on ")?;
let files = rest.split_once(" file")?.0.parse().ok()?;
let (_, threads_part) = rest.rsplit_once(" using ")?;
let threads = threads_part.split_once(" thread")?.0.parse().ok()?;
Some(CheckSummary { duration: duration.to_string(), files, threads })
}
fn parse_issue_count(line: &str, prefix: &str) -> Option<usize> {
let rest = line.strip_prefix(prefix)?;
rest.split_once(" file")?.0.parse().ok()
}
fn parse_warning_error_counts(line: &str) -> Option<(usize, usize)> {
let rest = line.strip_prefix("Found ")?;
let (warnings, rest) = rest.split_once(" warning")?;
let (_, rest) = rest.split_once(" and ")?;
let errors = rest.split_once(" error")?.0;
Some((warnings.parse().ok()?, errors.parse().ok()?))
}
pub(super) fn format_elapsed(elapsed: std::time::Duration) -> String {
if elapsed.as_millis() < 1000 {
format!("{}ms", elapsed.as_millis())
} else {
format!("{:.1}s", elapsed.as_secs_f64())
}
}
pub(super) fn format_count(count: usize, singular: &str, plural: &str) -> String {
if count == 1 { format!("1 {singular}") } else { format!("{count} {plural}") }
}
pub(super) fn print_stdout_block(block: &str) {
let trimmed = block.trim_matches('\n');
if trimmed.is_empty() {
return;
}
use std::io::Write;
let mut stdout = std::io::stdout().lock();
let _ = stdout.write_all(trimmed.as_bytes());
let _ = stdout.write_all(b"\n");
}
pub(super) fn print_summary_line(message: &str) {
output::raw("");
if std::io::stdout().is_terminal() && message.contains('`') {
let mut formatted = String::with_capacity(message.len());
let mut segments = message.split('`');
if let Some(first) = segments.next() {
formatted.push_str(first);
}
let mut is_accent = true;
for segment in segments {
if is_accent {
formatted.push_str(&format!("{}", format!("`{segment}`").bright_blue()));
} else {
formatted.push_str(segment);
}
is_accent = !is_accent;
}
output::raw(&formatted);
} else {
output::raw(message);
}
}
pub(super) fn print_error_block(error_msg: &str, combined_output: &str, summary_msg: &str) {
output::error(error_msg);
if !combined_output.trim().is_empty() {
print_stdout_block(combined_output);
}
print_summary_line(summary_msg);
}
pub(super) fn print_pass_line(message: &str, detail: Option<&str>) {
if let Some(detail) = detail {
output::raw(&format!("{} {message} {}", "pass:".bright_blue().bold(), detail.dimmed()));
} else {
output::pass(message);
}
}
pub(super) fn analyze_fmt_check_output(output: &str) -> Option<Result<FmtSuccess, FmtFailure>> {
let trimmed = output.trim();
if trimmed.is_empty() {
return None;
}
let lines: Vec<&str> = trimmed.lines().collect();
let finish_line = lines.iter().rev().find(|line| line.starts_with("Finished in "))?;
let summary = parse_check_summary(finish_line)?;
if lines.iter().any(|line| *line == "All matched files use the correct format.") {
return Some(Ok(FmtSuccess { summary }));
}
let issue_line = lines.iter().find(|line| line.starts_with("Format issues found in above "))?;
let issue_count = parse_issue_count(issue_line, "Format issues found in above ")?;
let mut issue_files = Vec::new();
let mut collecting = false;
for line in lines {
if line == "Checking formatting..." {
collecting = true;
continue;
}
if !collecting {
continue;
}
if line.is_empty() {
continue;
}
if line.starts_with("Format issues found in above ") || line.starts_with("Finished in ") {
break;
}
issue_files.push(line.to_string());
}
Some(Err(FmtFailure { summary, issue_files, issue_count }))
}
pub(super) fn analyze_lint_output(output: &str) -> Option<Result<LintSuccess, LintFailure>> {
let trimmed = output.trim();
if trimmed.is_empty() {
return None;
}
let lines: Vec<&str> = trimmed.lines().collect();
let counts_idx = lines.iter().position(|line| {
line.starts_with("Found ") && line.contains(" warning") && line.contains(" error")
})?;
let finish_line =
lines.iter().skip(counts_idx + 1).find(|line| line.starts_with("Finished in "))?;
let summary = parse_check_summary(finish_line)?;
let (warnings, errors) = parse_warning_error_counts(lines[counts_idx])?;
let diagnostics = lines[..counts_idx].join("\n").trim_matches('\n').to_string();
if warnings == 0 && errors == 0 {
return Some(Ok(LintSuccess { summary }));
}
Some(Err(LintFailure { summary, warnings, errors, diagnostics }))
}