forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruff_cmd.rs
More file actions
384 lines (332 loc) · 11.8 KB
/
ruff_cmd.rs
File metadata and controls
384 lines (332 loc) · 11.8 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
//! Filters Ruff linter and formatter output.
use crate::core::config;
use crate::core::runner;
use crate::core::utils::{resolved_command, truncate};
use anyhow::Result;
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
struct RuffLocation {
#[allow(dead_code)]
row: usize,
#[allow(dead_code)]
column: usize,
}
#[derive(Debug, Deserialize)]
struct RuffFix {
#[allow(dead_code)]
applicability: Option<String>,
}
#[derive(Debug, Deserialize)]
struct RuffDiagnostic {
code: String,
#[allow(dead_code)]
message: String,
#[allow(dead_code)]
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, 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');
result.push_str("═══════════════════════════════════════\n");
// Show top rules
let mut rule_counts: Vec<_> = by_rule.iter().collect();
rule_counts.sort_by(|a, b| b.1.cmp(a.1));
if !rule_counts.is_empty() {
result.push_str("Top rules:\n");
for (rule, count) in rule_counts.iter().take(10) {
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(10) {
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() > 10 {
result.push_str(&format!("\n... +{} more files\n", file_counts.len() - 10));
}
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()
));
result.push_str("═══════════════════════════════════════\n");
for (i, file) in files_to_format.iter().take(10).enumerate() {
result.push_str(&format!("{}. {}\n", i + 1, compact_path(file)));
}
if files_to_format.len() > 10 {
result.push_str(&format!(
"\n... +{} more files\n",
files_to_format.len() - 10
));
}
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"));
}
#[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_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");
}
}