forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoutput_summary.rs
More file actions
321 lines (283 loc) · 10 KB
/
Copy pathoutput_summary.rs
File metadata and controls
321 lines (283 loc) · 10 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
//! Library API for command-output summarization.
//!
//! The CLI `summary` command and downstream embedders share this module so the
//! heuristic stays consistent instead of forking one copy per integration.
use crate::core::utils::truncate;
use regex::Regex;
/// Options describing the command output being summarized.
#[derive(Debug, Clone, Copy)]
pub struct CommandOutputSummaryOptions<'a> {
/// Human-readable command or tool label used only for summary context.
pub command: &'a str,
/// Whether the command completed successfully.
pub success: bool,
}
impl<'a> CommandOutputSummaryOptions<'a> {
pub fn new(command: &'a str, success: bool) -> Self {
Self { command, success }
}
}
/// Produce a compact, heuristic summary of command output.
///
/// This is intentionally deterministic and local: embedders can use it in hot
/// tool-preview paths without spawning `contextcrawler` or calling a model.
pub fn summarize_command_output(
output: &str,
options: CommandOutputSummaryOptions<'_>,
) -> String {
let lines: Vec<&str> = output.lines().collect();
let mut result = Vec::new();
let status_icon = if options.success { "[ok]" } else { "[FAIL]" };
result.push(format!(
"{} Command: {}",
status_icon,
truncate(options.command, 60)
));
result.push(format!(" {} lines of output", lines.len()));
result.push(String::new());
match detect_output_type(output, options.command) {
OutputType::TestResults => summarize_tests(output, &mut result),
OutputType::BuildOutput => summarize_build(output, &mut result),
OutputType::LogOutput => summarize_logs_quick(output, &mut result),
OutputType::ListOutput => summarize_list(output, &mut result),
OutputType::JsonOutput => summarize_json(output, &mut result),
OutputType::Generic => summarize_generic(output, &mut result),
}
result.join("\n")
}
#[derive(Debug)]
enum OutputType {
TestResults,
BuildOutput,
LogOutput,
ListOutput,
JsonOutput,
Generic,
}
fn detect_output_type(output: &str, command: &str) -> OutputType {
let cmd_lower = command.to_lowercase();
let out_lower = output.to_lowercase();
if cmd_lower.contains("test") || out_lower.contains("passed") && out_lower.contains("failed") {
OutputType::TestResults
} else if cmd_lower.contains("build")
|| cmd_lower.contains("compile")
|| out_lower.contains("compiling")
{
OutputType::BuildOutput
} else if out_lower.contains("error:")
|| out_lower.contains("warn:")
|| out_lower.contains("[info]")
{
OutputType::LogOutput
} else if output.trim_start().starts_with('{') || output.trim_start().starts_with('[') {
OutputType::JsonOutput
} else if output.lines().all(|l| {
l.len() < 200
&& if l.contains('\t') {
false
} else {
l.split_whitespace().count() < 10
}
}) {
OutputType::ListOutput
} else {
OutputType::Generic
}
}
fn summarize_tests(output: &str, result: &mut Vec<String>) {
result.push("Test Results:".to_string());
let mut passed = 0;
let mut failed = 0;
let mut skipped = 0;
let mut failures = Vec::new();
for line in output.lines() {
let lower = line.to_lowercase();
if lower.contains("passed") || lower.contains("✓") || lower.contains("ok") {
if let Some(n) = extract_number(&lower, "passed") {
passed = n;
} else {
passed += 1;
}
}
if lower.contains("failed") || lower.contains("[x]") || lower.contains("fail") {
if let Some(n) = extract_number(&lower, "failed") {
failed = n;
}
if !line.contains("0 failed") {
failures.push(line.to_string());
}
}
if lower.contains("skipped") || lower.contains("ignored") {
if let Some(n) = extract_number(&lower, "skipped").or(extract_number(&lower, "ignored"))
{
skipped = n;
}
}
}
result.push(format!(" [ok] {} passed", passed));
if failed > 0 {
result.push(format!(" [FAIL] {} failed", failed));
}
if skipped > 0 {
result.push(format!(" skip {} skipped", skipped));
}
if !failures.is_empty() {
result.push(String::new());
result.push(" Failures:".to_string());
for f in failures.iter().take(5) {
result.push(format!(" • {}", truncate(f, 70)));
}
}
}
fn summarize_build(output: &str, result: &mut Vec<String>) {
result.push("Build Summary:".to_string());
let mut errors = 0;
let mut warnings = 0;
let mut compiled = 0;
let mut error_msgs = Vec::new();
for line in output.lines() {
let lower = line.to_lowercase();
if lower.contains("error") && !lower.contains("0 error") {
errors += 1;
if error_msgs.len() < 5 {
error_msgs.push(line.to_string());
}
}
if lower.contains("warning") && !lower.contains("0 warning") {
warnings += 1;
}
if lower.contains("compiling") || lower.contains("compiled") {
compiled += 1;
}
}
if compiled > 0 {
result.push(format!(" {} crates/files compiled", compiled));
}
if errors > 0 {
result.push(format!(" [error] {} errors", errors));
}
if warnings > 0 {
result.push(format!(" [warn] {} warnings", warnings));
}
if errors == 0 && warnings == 0 {
result.push(" [ok] Build successful".to_string());
}
if !error_msgs.is_empty() {
result.push(String::new());
result.push(" Errors:".to_string());
for e in &error_msgs {
result.push(format!(" • {}", truncate(e, 70)));
}
}
}
fn summarize_logs_quick(output: &str, result: &mut Vec<String>) {
result.push("Log Summary:".to_string());
let mut errors = 0;
let mut warnings = 0;
let mut info = 0;
for line in output.lines() {
let lower = line.to_lowercase();
if lower.contains("error") || lower.contains("fatal") {
errors += 1;
} else if lower.contains("warn") {
warnings += 1;
} else if lower.contains("info") {
info += 1;
}
}
result.push(format!(" [error] {} errors", errors));
result.push(format!(" [warn] {} warnings", warnings));
result.push(format!(" [info] {} info", info));
}
fn summarize_list(output: &str, result: &mut Vec<String>) {
let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
result.push(format!("List ({} items):", lines.len()));
for line in lines.iter().take(10) {
result.push(format!(" • {}", truncate(line, 70)));
}
if lines.len() > 10 {
result.push(format!(" ... +{} more", lines.len() - 10));
}
}
fn summarize_json(output: &str, result: &mut Vec<String>) {
result.push("JSON Output:".to_string());
if let Ok(value) = serde_json::from_str::<serde_json::Value>(output) {
match &value {
serde_json::Value::Array(arr) => {
result.push(format!(" Array with {} items", arr.len()));
}
serde_json::Value::Object(obj) => {
result.push(format!(" Object with {} keys:", obj.len()));
for key in obj.keys().take(10) {
result.push(format!(" • {}", key));
}
if obj.len() > 10 {
result.push(format!(" ... +{} more keys", obj.len() - 10));
}
}
_ => {
result.push(format!(" {}", truncate(&value.to_string(), 100)));
}
}
} else {
result.push(" (Invalid JSON)".to_string());
}
}
fn summarize_generic(output: &str, result: &mut Vec<String>) {
let lines: Vec<&str> = output.lines().collect();
result.push("Output:".to_string());
for line in lines.iter().take(5) {
if !line.trim().is_empty() {
result.push(format!(" {}", truncate(line, 75)));
}
}
if lines.len() > 10 {
result.push(" ...".to_string());
for line in lines.iter().skip(lines.len() - 3) {
if !line.trim().is_empty() {
result.push(format!(" {}", truncate(line, 75)));
}
}
}
}
fn extract_number(text: &str, after: &str) -> Option<usize> {
let re = Regex::new(&format!(r"(\d+)\s*{}", after)).ok()?;
re.captures(text)
.and_then(|c| c.get(1))
.and_then(|m| m.as_str().parse().ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn summarize_command_output_classifies_build_errors() {
let output = "Compiling demo\nerror: expected expression\nwarning: unused variable";
let summary = summarize_command_output(
output,
CommandOutputSummaryOptions::new("cargo build", false),
);
assert!(summary.contains("[FAIL] Command: cargo build"), "{summary}");
assert!(summary.contains("Build Summary:"), "{summary}");
assert!(summary.contains("[error] 1 errors"), "{summary}");
assert!(summary.contains("[warn] 1 warnings"), "{summary}");
}
#[test]
fn summarize_command_output_compacts_long_generic_output() {
let output = (0..30)
.map(|i| {
format!(
"generic output line {i} with enough words to avoid list classification"
)
})
.collect::<Vec<_>>()
.join("\n");
let summary = summarize_command_output(
&output,
CommandOutputSummaryOptions::new("tool output", true),
);
assert!(summary.contains("[ok] Command: tool output"), "{summary}");
assert!(summary.contains("line 0"), "{summary}");
assert!(summary.contains("line 29"), "{summary}");
assert!(!summary.contains("line 10"), "{summary}");
}
}