aft_base/compress/
ruff.rs1use 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 RuffCompressor;
10
11impl Compressor for RuffCompressor {
12 fn matches(&self, command: &str) -> bool {
13 command_tokens(command).any(|token| token == "ruff")
14 }
15
16 fn compress_with_exit_code(
17 &self,
18 _command: &str,
19 output: &str,
20 exit_code: Option<i64>,
21 ) -> CompressionResult {
22 let compressed = compress_ruff(output);
23 if matches!(exit_code, Some(code) if code != 0) && compressed.text.trim() == "ruff: clean" {
24 GenericCompressor::compress_output(output).into()
25 } else {
26 compressed
27 }
28 }
29
30 fn matches_output(&self, output: &str) -> bool {
31 looks_like_ruff_clean_output(output)
32 || looks_like_ruff_text_output(output)
33 || looks_like_ruff_json_output(output)
34 }
35
36 fn matches_output_probe(&self, probe: &OutputProbe<'_>) -> bool {
37 looks_like_ruff_clean_output(probe.output())
38 || looks_like_ruff_text_output(probe.output())
39 || (probe.output().trim_start().starts_with('[')
40 && probe.json().is_some_and(is_ruff_json))
41 }
42
43 fn compress_with_output_probe(
44 &self,
45 _command: &str,
46 probe: &OutputProbe<'_>,
47 exit_code: Option<i64>,
48 ) -> CompressionResult {
49 let compressed = compress_ruff_probed(probe);
50 if matches!(exit_code, Some(code) if code != 0) && compressed.text.trim() == "ruff: clean" {
51 GenericCompressor::compress_output(probe.output()).into()
52 } else {
53 compressed
54 }
55 }
56
57 fn compress_output_probe_match(
58 &self,
59 probe: &OutputProbe<'_>,
60 exit_code: Option<i64>,
61 ) -> CompressionResult {
62 self.compress_with_output_probe("", probe, exit_code)
63 }
64}
65
66fn is_ruff_json(value: &Value) -> bool {
67 value.as_array().is_some_and(|diagnostics| {
68 !diagnostics.is_empty()
69 && diagnostics.iter().any(|diagnostic| {
70 diagnostic.get("code").is_some()
71 && diagnostic.get("filename").is_some()
72 && diagnostic.get("location").is_some()
73 })
74 })
75}
76
77fn looks_like_ruff_clean_output(output: &str) -> bool {
78 output
79 .lines()
80 .any(|line| line.trim() == "All checks passed!")
81}
82
83fn looks_like_ruff_text_output(output: &str) -> bool {
84 let mut has_violation = false;
85 let mut has_summary = false;
86 for line in output.lines() {
87 let trimmed = line.trim();
88 has_violation |= is_violation_line(trimmed);
89 has_summary |= is_ruff_error_summary_line(trimmed);
90 }
91 has_violation && has_summary
92}
93
94fn looks_like_ruff_json_output(output: &str) -> bool {
95 let trimmed = output.trim_start();
96 if !trimmed.starts_with('[') {
97 return false;
98 }
99
100 super::record_output_probe_json_parse();
101 serde_json::from_str::<Value>(trimmed)
102 .ok()
103 .is_some_and(|value| is_ruff_json(&value))
104}
105
106fn compress_ruff(output: &str) -> CompressionResult {
107 compress_ruff_probed(&OutputProbe::new(output))
108}
109
110fn compress_ruff_probed(probe: &OutputProbe<'_>) -> CompressionResult {
111 let output = probe.output();
112 let trimmed = output.trim();
113 if trimmed.is_empty() || trimmed == "All checks passed!" {
114 return CompressionResult::new("ruff: clean");
115 }
116
117 if trimmed.starts_with('[') && trimmed.ends_with(']') {
118 if let Some(compressed) = probe.json_trimmed().and_then(compress_json) {
119 return finish(compressed);
120 }
121 return GenericCompressor::compress_output(output).into();
122 }
123
124 let mut blocks = Vec::new();
125 for line in output.lines() {
126 let trimmed = line.trim();
127 if is_violation_line(trimmed) {
128 blocks.push(ClassifiedBlock::new(DropClass::Error, line.to_string()));
129 } else if is_summary_line(trimmed) || trimmed.starts_with("[*]") {
130 blocks.push(ClassifiedBlock::unclassified(line.to_string()));
131 }
132 }
133
134 if blocks.is_empty() {
135 return GenericCompressor::compress_output(output).into();
136 }
137
138 let capped = cap_classified_blocks(blocks);
139 finish(CompressionResult::with_class_drops(
140 capped.text,
141 capped.dropped_by_class,
142 ))
143}
144
145fn command_tokens(command: &str) -> impl Iterator<Item = String> + '_ {
146 command
147 .split_whitespace()
148 .map(|token| token.trim_matches(|ch| matches!(ch, '\'' | '"')))
149 .filter(|token| {
150 !matches!(
151 *token,
152 "npx" | "pnpm" | "yarn" | "bun" | "bunx" | "exec" | "-m"
153 )
154 })
155 .map(|token| {
156 token
157 .rsplit(['/', '\\'])
158 .next()
159 .unwrap_or(token)
160 .trim_end_matches(".cmd")
161 .to_string()
162 })
163}
164
165fn compress_json(input: &Value) -> Option<CompressionResult> {
166 let diagnostics = input.as_array()?;
167 if diagnostics.is_empty() {
168 return Some(CompressionResult::new("ruff: clean"));
169 }
170
171 let mut by_rule: BTreeMap<String, Vec<String>> = BTreeMap::new();
172 let mut blocks = Vec::new();
173 for diagnostic in diagnostics {
174 let code = string_field(&diagnostic, "code").unwrap_or("RUF");
175 let filename = string_field(&diagnostic, "filename").unwrap_or("<unknown>");
176 let row = diagnostic
177 .pointer("/location/row")
178 .and_then(Value::as_u64)
179 .unwrap_or(0);
180 let location = format!("{filename}:{row}");
181 by_rule
182 .entry(code.to_string())
183 .or_default()
184 .push(location.clone());
185 blocks.push(ClassifiedBlock::new(
186 DropClass::Error,
187 format!("{code}: {location}"),
188 ));
189 }
190
191 let total = by_rule.values().map(Vec::len).sum::<usize>();
192 blocks.push(ClassifiedBlock::unclassified(format!(
193 "ruff: {total} violations across {} rules",
194 by_rule.len()
195 )));
196 for (rule, locations) in by_rule {
197 blocks.push(ClassifiedBlock::unclassified(format!(
198 "{rule}: {}",
199 locations.len()
200 )));
201 }
202
203 let capped = cap_classified_blocks(blocks);
204 Some(CompressionResult::with_class_drops(
205 capped.text,
206 capped.dropped_by_class,
207 ))
208}
209
210fn is_violation_line(trimmed: &str) -> bool {
211 let parts: Vec<&str> = trimmed.splitn(4, ':').collect();
212 if parts.len() != 4 {
213 return false;
214 }
215 if parts[0].is_empty()
216 || parts[1].parse::<usize>().is_err()
217 || parts[2].parse::<usize>().is_err()
218 {
219 return false;
220 }
221 parts[3].split_whitespace().next().is_some_and(is_rule_code)
222}
223
224fn is_rule_code(token: &str) -> bool {
225 let mut chars = token.chars();
226 chars.next().is_some_and(|ch| ch.is_ascii_uppercase()) && chars.any(|ch| ch.is_ascii_digit())
227}
228
229fn is_ruff_error_summary_line(trimmed: &str) -> bool {
230 let Some(rest) = trimmed.strip_prefix("Found ") else {
231 return false;
232 };
233 let Some((count, rest)) = rest.split_once(' ') else {
234 return false;
235 };
236 !count.is_empty()
237 && count.chars().all(|ch| ch.is_ascii_digit())
238 && (rest.starts_with("error.") || rest.starts_with("errors."))
239}
240
241fn is_summary_line(trimmed: &str) -> bool {
242 is_ruff_error_summary_line(trimmed)
243}
244
245fn string_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
246 value.get(key).and_then(Value::as_str)
247}
248
249fn finish(input: CompressionResult) -> CompressionResult {
250 input.map_text(|text| {
251 let stripped = strip_ansi(text);
252 dedup_consecutive(&stripped).trim_end().to_string()
253 })
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn matches_ruff_invocations() {
262 let compressor = RuffCompressor;
263 assert!(compressor.matches("ruff check ."));
264 assert!(compressor.matches("python -m ruff format"));
265 assert!(compressor.matches("python3 -m ruff check"));
266 assert!(compressor.matches("pnpm exec ruff check"));
267 assert!(!compressor.matches("cargo build"));
268 assert!(!compressor.matches("ls"));
269 }
270
271 #[test]
272 fn compresses_real_clean_text_pass() {
273 let output = "All checks passed!\n";
274 let compressed = compress_ruff(output).text;
275 assert_eq!(compressed, "ruff: clean");
276 assert!(compressed.len() < output.len());
277 }
278
279 #[test]
280 fn preserves_text_errors_verbatim() {
281 let output = "src/a.py:10:5: E501 Line too long (88 > 79 characters)\nsrc/a.py:25:1: F401 `os` imported but unused\nsrc/b.py:3:8: E711 Comparison to None should be 'cond is None'\nFound 3 errors.\n[*] 1 fixable with the `--fix` option.\n";
282 let compressed = compress_ruff(output).text;
283 assert!(compressed.contains("src/a.py:10:5: E501 Line too long (88 > 79 characters)"));
284 assert!(compressed.contains("src/a.py:25:1: F401 `os` imported but unused"));
285 assert!(
286 compressed.contains("src/b.py:3:8: E711 Comparison to None should be 'cond is None'")
287 );
288 assert!(compressed.contains("Found 3 errors."));
289 }
290
291 #[test]
292 fn groups_json_output_by_rule() {
293 let output = r#"[{"code":"E501","filename":"src/a.py","location":{"row":10,"column":5},"message":"Line too long"},{"code":"E501","filename":"src/b.py","location":{"row":5,"column":1},"message":"Line too long"},{"code":"F401","filename":"src/c.py","location":{"row":1,"column":8},"message":"unused"}]"#;
294 let compressed = compress_ruff(output).text;
295 assert!(compressed.contains("E501: src/a.py:10"));
296 assert!(compressed.contains("E501: src/b.py:5"));
297 assert!(compressed.contains("F401: src/c.py:1"));
298 assert!(compressed.contains("ruff: 3 violations across 2 rules"));
299 assert!(compressed.contains("E501: 2"));
300 }
301
302 #[test]
303 fn compresses_large_json_input() {
304 let mut items = Vec::new();
305 for index in 0..500 {
306 items.push(format!(
307 r#"{{"code":"E501","filename":"src/file{index}.py","location":{{"row":{},"column":5}},"message":"Line too long"}}"#,
308 index + 1
309 ));
310 }
311 let output = format!("[{}]", items.join(","));
312 let result = compress_ruff(&output);
313 let compressed = result.text;
314 assert!(compressed.contains("ruff: 500 violations across 1 rules"));
315 assert!(compressed.contains("E501: 500"));
316 assert_eq!(result.dropped_by_class.get(&DropClass::Error), Some(&480));
317 assert!(compressed.len() < output.len() / 2);
318 }
319}