-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathruff_cmd.rs
More file actions
469 lines (410 loc) · 14.9 KB
/
ruff_cmd.rs
File metadata and controls
469 lines (410 loc) · 14.9 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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Filters Ruff linter and formatter output.
use crate::core::config;
use crate::core::runner;
use crate::core::truncate::CAP_WARNINGS;
use crate::core::utils::{resolved_command, truncate};
use crate::parser::truncate_output;
use anyhow::Result;
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
struct RuffLocation {
row: usize,
column: usize,
}
#[derive(Debug, Deserialize)]
struct RuffFix {
#[allow(dead_code)]
applicability: Option<String>,
}
#[derive(Debug, Deserialize)]
struct RuffDiagnostic {
code: String,
message: String,
location: RuffLocation,
#[allow(dead_code)]
end_location: Option<RuffLocation>,
filename: String,
fix: Option<RuffFix>,
}
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let is_check = args.is_empty()
|| args[0] == "check"
|| (!args[0].starts_with('-') && args[0] != "format" && args[0] != "version");
let is_format = args.iter().any(|a| a == "format");
let mut cmd = resolved_command("ruff");
if is_check {
if !args.contains(&"--output-format".to_string()) {
cmd.arg("check").arg("--output-format=json");
} else {
cmd.arg("check");
}
let start_idx = if !args.is_empty() && args[0] == "check" {
1
} else {
0
};
for arg in &args[start_idx..] {
cmd.arg(arg);
}
if args
.iter()
.skip(start_idx)
.all(|a| a.starts_with('-') || a.contains('='))
{
cmd.arg(".");
}
} else {
for arg in args {
cmd.arg(arg);
}
}
if verbose > 0 {
eprintln!("Running: ruff {}", args.join(" "));
}
runner::run_filtered(
cmd,
"ruff",
&args.join(" "),
move |stdout| {
if is_check && !stdout.trim().is_empty() {
filter_ruff_check_json(stdout)
} else if is_format {
filter_ruff_format(stdout)
} else {
stdout.trim().to_string()
}
},
runner::RunOptions::stdout_only(),
)
}
/// Filter ruff check JSON output - group by rule and file
pub fn filter_ruff_check_json(output: &str) -> String {
let diagnostics: Result<Vec<RuffDiagnostic>, _> = serde_json::from_str(output);
let diagnostics = match diagnostics {
Ok(d) => d,
Err(e) => {
// Fallback if JSON parsing fails
return format!(
"Ruff check (JSON parse failed: {})\n{}",
e,
truncate_output(output, config::limits().passthrough_max_chars)
);
}
};
if diagnostics.is_empty() {
return "Ruff: No issues found".to_string();
}
let total_issues = diagnostics.len();
let fixable_count = diagnostics.iter().filter(|d| d.fix.is_some()).count();
// Count unique files
let unique_files: std::collections::HashSet<_> =
diagnostics.iter().map(|d| &d.filename).collect();
let total_files = unique_files.len();
// Group by rule code
let mut by_rule: HashMap<String, usize> = HashMap::new();
for diag in &diagnostics {
*by_rule.entry(diag.code.clone()).or_insert(0) += 1;
}
// Group by file
let mut by_file: HashMap<&str, usize> = HashMap::new();
for diag in &diagnostics {
*by_file.entry(&diag.filename).or_insert(0) += 1;
}
let mut file_counts: Vec<_> = by_file.iter().collect();
file_counts.sort_by(|a, b| b.1.cmp(a.1));
// Build output
let mut result = String::new();
result.push_str(&format!(
"Ruff: {} issues in {} files",
total_issues, total_files
));
if fixable_count > 0 {
result.push_str(&format!(" ({} fixable)", fixable_count));
}
result.push('\n');
// Show top rules
let mut rule_counts: Vec<_> = by_rule.iter().collect();
rule_counts.sort_by(|a, b| b.1.cmp(a.1));
const MAX_RUFF_RULES: usize = CAP_WARNINGS;
const MAX_RUFF_FILES: usize = CAP_WARNINGS;
if !rule_counts.is_empty() {
result.push_str("Top rules:\n");
for (rule, count) in rule_counts.iter().take(MAX_RUFF_RULES) {
result.push_str(&format!(" {} ({}x)\n", rule, count));
}
result.push('\n');
}
// Show top files
result.push_str("Top files:\n");
for (file, count) in file_counts.iter().take(MAX_RUFF_FILES) {
let short_path = compact_path(file);
result.push_str(&format!(" {} ({} issues)\n", short_path, count));
// Show top 3 rules in this file
let mut file_rules: HashMap<String, usize> = HashMap::new();
for diag in diagnostics.iter().filter(|d| &d.filename == *file) {
*file_rules.entry(diag.code.clone()).or_insert(0) += 1;
}
let mut file_rule_counts: Vec<_> = file_rules.iter().collect();
file_rule_counts.sort_by(|a, b| b.1.cmp(a.1));
for (rule, count) in file_rule_counts.iter().take(3) {
result.push_str(&format!(" {} ({})\n", rule, count));
}
}
if file_counts.len() > MAX_RUFF_FILES {
result.push_str(&format!(
"\n... +{} more files\n",
file_counts.len() - MAX_RUFF_FILES
));
}
const MAX_VIOLATIONS: usize = 50;
let violation_lines: Vec<String> = diagnostics
.iter()
.map(|diag| {
format!(
" {}:{}:{} {} {}\n",
compact_path(&diag.filename),
diag.location.row,
diag.location.column,
diag.code,
truncate(diag.message.trim(), 100),
)
})
.collect();
result.push_str("\nViolations:\n");
for line in violation_lines.iter().take(MAX_VIOLATIONS) {
result.push_str(line);
}
if violation_lines.len() > MAX_VIOLATIONS {
result.push_str(&format!(
" … +{} more\n",
violation_lines.len() - MAX_VIOLATIONS
));
let full: String = violation_lines.concat();
if let Some(hint) =
crate::core::tee::force_tee_tail_hint(&full, "ruff-check", MAX_VIOLATIONS + 1)
{
result.push_str(&format!(" {}\n", hint));
}
}
if fixable_count > 0 {
result.push_str(&format!(
"\n[hint] Run `ruff check --fix` to auto-fix {} issues\n",
fixable_count
));
}
result.trim().to_string()
}
/// Filter ruff format output - show files that need formatting
pub fn filter_ruff_format(output: &str) -> String {
let mut files_to_format: Vec<String> = Vec::new();
let mut files_checked = 0;
for line in output.lines() {
let trimmed = line.trim();
let lower = trimmed.to_lowercase();
// Count "would reformat" lines (check mode) - case insensitive
if lower.contains("would reformat:") {
// Extract filename from "Would reformat: path/to/file.py"
if let Some(filename) = trimmed.split(':').nth(1) {
files_to_format.push(filename.trim().to_string());
}
}
// Count total checked files - look for patterns like "3 files left unchanged"
if lower.contains("left unchanged") {
// Find "X file(s) left unchanged" pattern specifically
// Split by comma to handle "2 files would be reformatted, 3 files left unchanged"
let parts: Vec<&str> = trimmed.split(',').collect();
for part in parts {
let part_lower = part.to_lowercase();
if part_lower.contains("left unchanged") {
let words: Vec<&str> = part.split_whitespace().collect();
// Look for number before "file" or "files"
for (i, word) in words.iter().enumerate() {
if (word == &"file" || word == &"files") && i > 0 {
if let Ok(count) = words[i - 1].parse::<usize>() {
files_checked = count;
break;
}
}
}
break;
}
}
}
}
let output_lower = output.to_lowercase();
// Check if all files are formatted
if files_to_format.is_empty() && output_lower.contains("left unchanged") {
return "Ruff format: All files formatted correctly".to_string();
}
let mut result = String::new();
if output_lower.contains("would reformat") {
// Check mode: show files that need formatting
if files_to_format.is_empty() {
result.push_str("Ruff format: All files formatted correctly\n");
} else {
result.push_str(&format!(
"Ruff format: {} files need formatting\n",
files_to_format.len()
));
const MAX_RUFF_FORMAT_FILES: usize = CAP_WARNINGS;
for (i, file) in files_to_format
.iter()
.take(MAX_RUFF_FORMAT_FILES)
.enumerate()
{
result.push_str(&format!("{}. {}\n", i + 1, compact_path(file)));
}
if files_to_format.len() > MAX_RUFF_FORMAT_FILES {
result.push_str(&format!(
"\n... +{} more files\n",
files_to_format.len() - MAX_RUFF_FORMAT_FILES
));
}
if files_checked > 0 {
result.push_str(&format!("\n{} files already formatted\n", files_checked));
}
result.push_str("\n[hint] Run `ruff format` to format these files\n");
}
} else {
// Write mode or other output - show summary
result.push_str(output.trim());
}
result.trim().to_string()
}
/// Compact file path (remove common prefixes)
fn compact_path(path: &str) -> String {
let path = path.replace('\\', "/");
if let Some(pos) = path.rfind("/src/") {
format!("src/{}", &path[pos + 5..])
} else if let Some(pos) = path.rfind("/lib/") {
format!("lib/{}", &path[pos + 5..])
} else if let Some(pos) = path.rfind("/tests/") {
format!("tests/{}", &path[pos + 7..])
} else if let Some(pos) = path.rfind('/') {
path[pos + 1..].to_string()
} else {
path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_ruff_check_no_issues() {
let output = "[]";
let result = filter_ruff_check_json(output);
assert!(result.contains("Ruff"));
assert!(result.contains("No issues found"));
}
#[test]
fn test_filter_ruff_check_with_issues() {
let output = r#"[
{
"code": "F401",
"message": "`os` imported but unused",
"location": {"row": 1, "column": 8},
"end_location": {"row": 1, "column": 10},
"filename": "src/main.py",
"fix": {"applicability": "safe"}
},
{
"code": "F401",
"message": "`sys` imported but unused",
"location": {"row": 2, "column": 8},
"end_location": {"row": 2, "column": 11},
"filename": "src/main.py",
"fix": null
},
{
"code": "E501",
"message": "Line too long (100 > 88 characters)",
"location": {"row": 10, "column": 89},
"end_location": {"row": 10, "column": 100},
"filename": "src/utils.py",
"fix": null
}
]"#;
let result = filter_ruff_check_json(output);
assert!(result.contains("3 issues"));
assert!(result.contains("2 files"));
assert!(result.contains("1 fixable"));
assert!(result.contains("F401"));
assert!(result.contains("E501"));
assert!(result.contains("main.py"));
assert!(result.contains("utils.py"));
assert!(result.contains("Violations:"), "Violations section missing");
assert!(result.contains("1:8"), "line:col location missing");
}
#[test]
fn test_filter_ruff_check_parse_failure_marks_truncated_passthrough() {
let long_invalid_json = "{".repeat(crate::core::config::limits().passthrough_max_chars + 20);
let result = filter_ruff_check_json(&long_invalid_json);
assert!(result.contains("Ruff check (JSON parse failed:"));
assert!(
result.contains("[RTK:PASSTHROUGH] Output truncated"),
"parse fallback should make truncation visible, got:\n{result}"
);
}
#[test]
fn test_filter_ruff_format_all_formatted() {
let output = "5 files left unchanged";
let result = filter_ruff_format(output);
assert!(result.contains("Ruff format"));
assert!(result.contains("All files formatted correctly"));
}
#[test]
fn test_filter_ruff_format_needs_formatting() {
let output = r#"Would reformat: src/main.py
Would reformat: tests/test_utils.py
2 files would be reformatted, 3 files left unchanged"#;
let result = filter_ruff_format(output);
assert!(result.contains("2 files need formatting"));
assert!(result.contains("main.py"));
assert!(result.contains("test_utils.py"));
assert!(result.contains("3 files already formatted"));
}
#[test]
fn test_filter_ruff_check_caps_violations_and_emits_hint() {
// Mirror ruff's pretty-printed JSON shape so the input-vs-output
// comparison reflects what a real `ruff check --output-format=json` emits.
let mut diags = Vec::new();
for i in 0..200 {
diags.push(format!(
" {{\n \"code\": \"F401\",\n \"message\": \"`module_{i}` imported but unused\",\n \"location\": {{\"row\": {i}, \"column\": 4}},\n \"end_location\": {{\"row\": {i}, \"column\": 20}},\n \"filename\": \"/Users/dev/project/src/feature_{i}.py\",\n \"fix\": null\n }}"
));
}
let json = format!("[\n{}\n]", diags.join(",\n"));
let result = filter_ruff_check_json(&json);
let in_section = result.split("Violations:").nth(1).unwrap_or("");
let listed = in_section
.lines()
.filter(|l| l.trim().starts_with("src/"))
.count();
assert!(listed <= 50, "violations cap not enforced: got {listed}");
assert!(
result.contains("… +150 more"),
"missing '+N more' indicator"
);
let raw_tokens = json.split_whitespace().count();
let out_tokens = result.split_whitespace().count();
let savings = 100.0 - (out_tokens as f64 / raw_tokens as f64) * 100.0;
assert!(
savings >= 60.0,
"token savings dropped below 60%: {savings:.1}%"
);
}
#[test]
fn test_compact_path() {
assert_eq!(
compact_path("/Users/foo/project/src/main.py"),
"src/main.py"
);
assert_eq!(compact_path("/home/user/app/lib/utils.py"), "lib/utils.py");
assert_eq!(
compact_path("C:\\Users\\foo\\project\\tests\\test.py"),
"tests/test.py"
);
assert_eq!(compact_path("relative/file.py"), "file.py");
}
}