Skip to main content

aft_base/compress/
eslint.rs

1use std::collections::BTreeMap;
2
3use serde_json::Value;
4
5use crate::compress::caps::{cap_classified_blocks, ClassifiedBlock, DropClass};
6use crate::compress::generic::{dedup_consecutive, strip_ansi, GenericCompressor};
7use crate::compress::{CompressionResult, Compressor, OutputProbe};
8
9pub struct EslintCompressor;
10
11#[derive(Clone, Debug)]
12struct Issue {
13    line: usize,
14    column: usize,
15    severity: String,
16    message: String,
17    rule: Option<String>,
18}
19
20impl Compressor for EslintCompressor {
21    fn matches(&self, command: &str) -> bool {
22        command_tokens(command).any(|token| token == "eslint")
23    }
24
25    fn compress_with_exit_code(
26        &self,
27        _command: &str,
28        output: &str,
29        _exit_code: Option<i64>,
30    ) -> CompressionResult {
31        compress_eslint(output)
32    }
33
34    fn matches_output(&self, output: &str) -> bool {
35        output
36            .lines()
37            .any(|line| is_summary_line(line.trim_start()))
38            || looks_like_eslint_json_output(output)
39    }
40
41    fn matches_output_probe(&self, probe: &OutputProbe<'_>) -> bool {
42        probe
43            .output()
44            .lines()
45            .any(|line| is_summary_line(line.trim_start()))
46            || (probe.output().trim_start().starts_with('[')
47                && probe.json().is_some_and(is_eslint_json))
48    }
49
50    fn compress_with_output_probe(
51        &self,
52        _command: &str,
53        probe: &OutputProbe<'_>,
54        _exit_code: Option<i64>,
55    ) -> CompressionResult {
56        compress_eslint_probed(probe)
57    }
58
59    fn compress_output_probe_match(
60        &self,
61        probe: &OutputProbe<'_>,
62        exit_code: Option<i64>,
63    ) -> CompressionResult {
64        self.compress_with_output_probe("", probe, exit_code)
65    }
66}
67
68fn is_eslint_json(value: &Value) -> bool {
69    value.as_array().is_some_and(|files| {
70        !files.is_empty()
71            && files
72                .iter()
73                .any(|file| file.get("filePath").is_some() && file.get("messages").is_some())
74    })
75}
76
77fn looks_like_eslint_json_output(output: &str) -> bool {
78    let trimmed = output.trim_start();
79    if !trimmed.starts_with('[') {
80        return false;
81    }
82
83    super::record_output_probe_json_parse();
84    serde_json::from_str::<Value>(trimmed)
85        .ok()
86        .is_some_and(|value| is_eslint_json(&value))
87}
88
89fn compress_eslint(output: &str) -> CompressionResult {
90    compress_eslint_probed(&OutputProbe::new(output))
91}
92
93fn compress_eslint_probed(probe: &OutputProbe<'_>) -> CompressionResult {
94    let output = probe.output();
95    let trimmed = output.trim_start();
96    if trimmed.starts_with("[{") {
97        if let Some(compressed) = probe.json().and_then(compress_json) {
98            return finish(compressed);
99        }
100        return GenericCompressor::compress_output(output).into();
101    }
102
103    if let Some(compressed) = compress_text(output) {
104        return finish(compressed);
105    }
106
107    GenericCompressor::compress_output(output).into()
108}
109
110fn command_tokens(command: &str) -> impl Iterator<Item = String> + '_ {
111    command
112        .split_whitespace()
113        .map(|token| token.trim_matches(|ch| matches!(ch, '\'' | '"')))
114        .filter(|token| !matches!(*token, "npx" | "pnpm" | "yarn" | "bun" | "bunx"))
115        .map(|token| {
116            token
117                .rsplit(['/', '\\'])
118                .next()
119                .unwrap_or(token)
120                .trim_end_matches(".cmd")
121                .to_string()
122        })
123}
124
125fn compress_json(results: &Value) -> Option<CompressionResult> {
126    let files = results.as_array()?;
127    let mut grouped = BTreeMap::new();
128    let mut errors = 0usize;
129    let mut warnings = 0usize;
130
131    for file in files {
132        let path = string_field(file, "filePath").unwrap_or("<unknown>");
133        let mut issues = Vec::new();
134        for message in file
135            .get("messages")
136            .and_then(Value::as_array)
137            .into_iter()
138            .flatten()
139        {
140            let severity = severity_name(message.get("severity"));
141            if severity == "error" {
142                errors += 1;
143            } else if severity == "warning" {
144                warnings += 1;
145            }
146            issues.push(Issue {
147                line: number_field(message, "line").unwrap_or(0),
148                column: number_field(message, "column").unwrap_or(0),
149                severity: severity.to_string(),
150                message: string_field(message, "message").unwrap_or("").to_string(),
151                rule: string_field(message, "ruleId").map(ToString::to_string),
152            });
153        }
154        if !issues.is_empty() {
155            grouped.insert(path.to_string(), issues);
156        }
157    }
158
159    let total = errors + warnings;
160    if total == 0 {
161        return Some(CompressionResult::new("eslint: no issues"));
162    }
163
164    let mut blocks = vec![ClassifiedBlock::unclassified(format!(
165        "eslint: {total} issues ({errors} errors, {warnings} warnings)"
166    ))];
167    append_grouped_issues(&mut blocks, &grouped);
168    let capped = cap_classified_blocks(blocks);
169    Some(CompressionResult::with_class_drops(
170        capped.text,
171        capped.dropped_by_class,
172    ))
173}
174
175fn compress_text(output: &str) -> Option<CompressionResult> {
176    let mut grouped: BTreeMap<String, Vec<Issue>> = BTreeMap::new();
177    let mut current_file: Option<String> = None;
178    let mut summary = None;
179    let mut parsed_issues = 0usize;
180
181    for line in output.lines() {
182        let trimmed = line.trim();
183        if trimmed.is_empty() {
184            continue;
185        }
186        if is_summary_line(trimmed) {
187            summary = Some(trimmed.to_string());
188            continue;
189        }
190        if let Some((file, issue)) = parse_colon_issue(trimmed) {
191            grouped.entry(file).or_default().push(issue);
192            parsed_issues += 1;
193            continue;
194        }
195        if let Some(file) = current_file.as_deref() {
196            if let Some(issue) = parse_stylish_issue(trimmed) {
197                grouped.entry(file.to_string()).or_default().push(issue);
198                parsed_issues += 1;
199                continue;
200            }
201        }
202        if is_file_header(line) {
203            current_file = Some(trimmed.to_string());
204        }
205    }
206
207    if parsed_issues == 0 {
208        return summary.map(CompressionResult::new);
209    }
210
211    let mut blocks = Vec::new();
212    append_grouped_issues(&mut blocks, &grouped);
213    if let Some(summary) = summary {
214        blocks.push(ClassifiedBlock::unclassified(summary));
215    }
216    let capped = cap_classified_blocks(blocks);
217    Some(CompressionResult::with_class_drops(
218        capped.text,
219        capped.dropped_by_class,
220    ))
221}
222
223fn parse_colon_issue(line: &str) -> Option<(String, Issue)> {
224    let parts: Vec<&str> = line.splitn(4, ':').collect();
225    if parts.len() != 4 {
226        return None;
227    }
228    let line_number = parts.get(1)?.trim().parse().ok()?;
229    let column = parts.get(2)?.trim().parse().ok()?;
230    let (severity, message, rule) = parse_severity_message(parts.get(3)?.trim())?;
231    Some((
232        parts.first()?.trim().to_string(),
233        Issue {
234            line: line_number,
235            column,
236            severity,
237            message,
238            rule,
239        },
240    ))
241}
242
243fn parse_stylish_issue(line: &str) -> Option<Issue> {
244    let mut parts = line.split_whitespace();
245    let location = parts.next()?;
246    let (line_text, column_text) = location.split_once(':')?;
247    let line_number = line_text.parse().ok()?;
248    let column = column_text.parse().ok()?;
249    let severity = parts.next()?;
250    if !matches!(severity, "error" | "warning") {
251        return None;
252    }
253    let rest = parts.collect::<Vec<_>>().join(" ");
254    let (message, rule) = split_message_rule(&rest);
255    Some(Issue {
256        line: line_number,
257        column,
258        severity: severity.to_string(),
259        message,
260        rule,
261    })
262}
263
264fn parse_severity_message(rest: &str) -> Option<(String, String, Option<String>)> {
265    let mut parts = rest.split_whitespace();
266    let severity = parts.next()?;
267    if !matches!(severity, "error" | "warning") {
268        return None;
269    }
270    let rest = parts.collect::<Vec<_>>().join(" ");
271    let (message, rule) = split_message_rule(&rest);
272    Some((severity.to_string(), message, rule))
273}
274
275fn split_message_rule(rest: &str) -> (String, Option<String>) {
276    let Some((message, rule)) = rest.rsplit_once(' ') else {
277        return (rest.to_string(), None);
278    };
279    if looks_like_rule(rule) {
280        (message.trim_end().to_string(), Some(rule.to_string()))
281    } else {
282        (rest.to_string(), None)
283    }
284}
285
286fn looks_like_rule(token: &str) -> bool {
287    token.contains('/') || token.contains('-') || token.starts_with('@')
288}
289
290fn append_grouped_issues(
291    blocks: &mut Vec<ClassifiedBlock>,
292    grouped: &BTreeMap<String, Vec<Issue>>,
293) {
294    for (file, issues) in grouped {
295        for issue in issues {
296            let rule = issue.rule.as_deref().unwrap_or("unknown");
297            let text = format!(
298                "{file}\n  {}:{} {} {} {}",
299                issue.line, issue.column, issue.severity, rule, issue.message
300            );
301            blocks.push(ClassifiedBlock::new(issue_class(issue), text));
302        }
303    }
304}
305
306fn issue_class(issue: &Issue) -> DropClass {
307    match issue.severity.as_str() {
308        "error" => DropClass::Error,
309        "warning" => DropClass::Warning,
310        _ => DropClass::Issue,
311    }
312}
313
314fn severity_name(value: Option<&Value>) -> &'static str {
315    match value.and_then(Value::as_u64) {
316        Some(2) => "error",
317        Some(1) => "warning",
318        _ => "info",
319    }
320}
321
322fn string_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
323    value.get(key).and_then(Value::as_str)
324}
325
326fn number_field(value: &Value, key: &str) -> Option<usize> {
327    value
328        .get(key)
329        .and_then(Value::as_u64)
330        .and_then(|number| usize::try_from(number).ok())
331}
332
333fn is_summary_line(trimmed: &str) -> bool {
334    (trimmed.starts_with('✖') || trimmed.starts_with('✔'))
335        && (trimmed.contains(" problem") || trimmed.contains(" problems"))
336}
337
338fn is_file_header(line: &str) -> bool {
339    !line.starts_with(char::is_whitespace)
340        && !line.trim().contains(": ")
341        && (line.contains('/') || line.contains('\\') || line.contains('.'))
342}
343
344fn finish(input: CompressionResult) -> CompressionResult {
345    input.map_text(|text| {
346        let stripped = strip_ansi(text);
347        dedup_consecutive(&stripped).trim_end().to_string()
348    })
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn matches_eslint_tokens_without_matching_npm_run_lint() {
357        let compressor = EslintCompressor;
358        assert!(compressor.matches("npx eslint src"));
359        assert!(compressor.matches("./node_modules/.bin/eslint src"));
360        assert!(!compressor.matches("npm run lint"));
361    }
362
363    #[test]
364    fn compresses_stylish_text_grouped_by_file() {
365        let output = r#"/repo/src/foo.js
366  1:10  error    'foo' is defined but never used  no-unused-vars
367  2:3   warning  Unexpected console statement      no-console
368
369/repo/src/bar.js
370  5:1  error  Missing semicolon  semi
371
372✖ 3 problems (2 errors, 1 warning)
373"#;
374
375        let compressed = compress_eslint(output).text;
376
377        assert!(compressed.contains("/repo/src/foo.js"));
378        assert!(compressed.contains("1:10 error no-unused-vars 'foo' is defined but never used"));
379        assert!(compressed.contains("✖ 3 problems (2 errors, 1 warning)"));
380    }
381
382    #[test]
383    fn compresses_colon_text_shape() {
384        let output = "src/foo.ts:4:12: error Unexpected any @typescript-eslint/no-explicit-any\n✖ 1 problem (1 error, 0 warnings)\n";
385
386        let compressed = compress_eslint(output).text;
387
388        assert!(compressed.contains("src/foo.ts"));
389        assert!(compressed.contains("4:12 error @typescript-eslint/no-explicit-any Unexpected any"));
390    }
391
392    #[test]
393    fn compresses_json_formatter_output() {
394        let output = r#"[{"filePath":"/repo/fullOfProblems.js","messages":[{"ruleId":"no-unused-vars","severity":2,"message":"'addOne' is defined but never used.","line":1,"column":10},{"ruleId":"semi","severity":1,"message":"Missing semicolon.","line":3,"column":20}],"errorCount":1,"warningCount":1}]"#;
395
396        let compressed = compress_eslint(output).text;
397
398        assert!(compressed.starts_with("eslint: 2 issues (1 errors, 1 warnings)"));
399        assert!(
400            compressed.contains("1:10 error no-unused-vars 'addOne' is defined but never used.")
401        );
402        assert!(compressed.contains("3:20 warning semi Missing semicolon."));
403    }
404
405    #[test]
406    fn malformed_json_falls_back_safely() {
407        let output = "[{not-json";
408
409        let compressed = compress_eslint(output).text;
410
411        assert_eq!(compressed, output);
412    }
413
414    #[test]
415    fn caps_large_text_output_per_file() {
416        let mut output = String::from("src/foo.js\n");
417        for index in 1..=25 {
418            output.push_str(&format!(
419                "  {index}:1  error  Problem number {index}  no-alert\n"
420            ));
421        }
422        output.push_str("✖ 25 problems (25 errors, 0 warnings)\n");
423
424        let result = compress_eslint(&output);
425        let compressed = result.text;
426
427        assert_eq!(result.dropped_by_class.get(&DropClass::Error), Some(&5));
428        assert!(!compressed.contains("Problem number 25  no-alert"));
429    }
430}