cargo_e/e_cargocommand_ext.rs
1use crate::e_command_builder::{CargoCommandBuilder, TerminalError};
2use crate::e_eventdispatcher::EventDispatcher;
3#[allow(unused_imports)]
4use cargo_metadata::Message;
5use nu_ansi_term::{Color, Style};
6#[cfg(feature = "uses_serde")]
7use serde_json;
8use std::collections::VecDeque;
9use std::io::{BufRead, BufReader, Read};
10use std::process::ExitStatus;
11use std::process::{Child, Command, Stdio};
12#[allow(unused_imports)]
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, SystemTime};
16use std::{fmt, thread};
17// enum CaptureMode {
18// Filtering(DispatcherSet),
19// Passthrough { stdout: std::io::Stdout, stderr: std::io::Stderr },
20// }
21// struct DispatcherSet {
22// stdout: Option<Arc<EventDispatcher>>,
23// stderr: Option<Arc<EventDispatcher>>,
24// progress: Option<Arc<EventDispatcher>>,
25// stage: Option<Arc<EventDispatcher>>,
26// }
27
28/// CargoStats tracks counts for different cargo events and also stores the first occurrence times.
29#[derive(Debug, Default, Clone)]
30pub struct CargoStats {
31 pub target_name: String,
32 pub is_comiler_target: bool,
33 pub is_could_not_compile: bool,
34 pub start_time: Option<SystemTime>,
35 pub compiler_message_count: usize,
36 pub compiler_artifact_count: usize,
37 pub build_script_executed_count: usize,
38 pub build_finished_count: usize,
39 // Record the first occurrence of each stage.
40 pub compiler_message_time: Option<SystemTime>,
41 pub compiler_artifact_time: Option<SystemTime>,
42 pub build_script_executed_time: Option<SystemTime>,
43 pub build_finished_time: Option<SystemTime>,
44}
45
46#[derive(Clone)]
47pub struct CargoDiagnostic {
48 pub lineref: String,
49 pub level: String,
50 pub message: String,
51 pub error_code: Option<String>,
52 pub suggestion: Option<String>,
53 pub note: Option<String>,
54 pub help: Option<String>,
55 pub uses_color: bool,
56 pub diag_number: Option<usize>,
57 pub diag_num_padding: Option<usize>,
58}
59
60impl CargoDiagnostic {
61 pub fn print_short(&self) {
62 // Render the full Debug output
63 let full = format!("{:?}", self);
64 // Grab only the first line (or an empty string if somehow there isn't one)
65 let first = full.lines().next().unwrap_or("");
66 println!("{}", first);
67 }
68}
69impl CargoDiagnostic {
70 #[allow(clippy::too_many_arguments)]
71 pub fn new(
72 lineref: String,
73 level: String,
74 message: String,
75 error_code: Option<String>,
76 suggestion: Option<String>,
77 note: Option<String>,
78 help: Option<String>,
79 uses_color: bool,
80 diag_number: Option<usize>,
81 diag_num_padding: Option<usize>,
82 ) -> Self {
83 CargoDiagnostic {
84 lineref,
85 level,
86 message,
87 error_code,
88 suggestion,
89 note,
90 help,
91 uses_color,
92 diag_number,
93 diag_num_padding,
94 }
95 }
96
97 fn update_suggestion_with_lineno(
98 &self,
99 suggestion: &str,
100 file: String,
101 line_number: usize,
102 ) -> String {
103 // Regex to match line number in the suggestion (e.g., "79 | fn clean<S: AsRef<str>>(s: S) -> String {")
104 let suggestion_regex = regex::Regex::new(r"(?P<line>\d+)\s*\|\s*(.*)").unwrap();
105
106 // Iterate through suggestion lines and check line numbers
107 suggestion
108 .lines()
109 .filter_map(|line| {
110 let binding = line.replace(['|', '^', '-', '_'], "");
111 let cleaned_line = binding.trim();
112
113 // If the line becomes empty after removing | and ^, skip it
114 if cleaned_line.is_empty() {
115 return None; // Skip empty lines
116 }
117
118 if let Some(caps) = suggestion_regex.captures(line.trim()) {
119 let suggestion_line: usize = caps["line"].parse().unwrap_or(line_number); // If parsing fails, use the default line number
120 // Replace the line number if it doesn't match the diagnostic's line number
121 if suggestion_line != line_number {
122 return Some(format!(
123 "{}:{} | {}",
124 file,
125 suggestion_line, // Replace with the actual diagnostic line number
126 caps.get(2).map_or("", |m| m.as_str())
127 ));
128 } else {
129 // If the line number matches, return the original suggestion line without line number
130 return Some(
131 caps.get(2)
132 .map_or("".to_owned(), |m| m.as_str().to_string()),
133 );
134 }
135 }
136 Some(line.to_string())
137 })
138 .collect::<Vec<String>>()
139 .join("\n")
140 }
141}
142
143impl fmt::Debug for CargoDiagnostic {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 // Capitalize the first letter of the level
146 let level_cap = self
147 .level
148 .chars()
149 .next()
150 .unwrap_or(' ')
151 .to_uppercase()
152 .to_string();
153
154 // Extract the file and line number from lineref (e.g., "cargo-e\src\e_command_builder.rs:79:8")
155 let lineref_regex = regex::Regex::new(r"(?P<file>.*):(?P<line>\d+):(?P<col>\d+)").unwrap();
156 let lineref_caps = lineref_regex.captures(&self.lineref);
157
158 let file = lineref_caps
159 .as_ref()
160 .and_then(|caps| caps.name("file").map(|m| m.as_str().to_string()))
161 .unwrap_or_else(|| "unknown file".to_string());
162 let line_number: usize = lineref_caps
163 .as_ref()
164 .and_then(|caps| caps.name("line").map(|m| m.as_str().parse().unwrap_or(0)))
165 .unwrap_or(0);
166
167 // Format the diagnostic number with padding
168 let padded_diag_number = if let Some(dn) = &self.diag_number {
169 format!("{:0width$}", dn, width = self.diag_num_padding.unwrap_or(0))
170 } else {
171 String::new()
172 };
173
174 // Combine the level and diagnostic number
175 let diag_number = format!("{}{}:", level_cap, padded_diag_number);
176
177 // Color the diagnostic number if color is enabled
178 let diag_number_colored = if self.uses_color {
179 match self.level.as_str() {
180 "warning" => Color::Yellow.paint(&diag_number).to_string(),
181 "error" => Color::Red.paint(&diag_number).to_string(),
182 "help" => Color::Purple.paint(&diag_number).to_string(),
183 _ => Color::Green.paint(&diag_number).to_string(),
184 }
185 } else {
186 diag_number.clone()
187 };
188
189 // Print the diagnostic number and lineref
190 if self.uses_color {
191 write!(f, "{} ", diag_number_colored)?;
192 let underlined_text = Style::new().underline().paint(&self.lineref).to_string();
193 write!(f, "\x1b[4m{}\x1b[0m ", underlined_text)?; // Apply underline using ANSI codes
194 } else {
195 write!(f, "{} ", diag_number)?;
196 write!(f, "{} ", self.lineref)?; // Plain lineref without color
197 }
198
199 // Print the message
200 write!(f, "{}: ", self.message)?;
201
202 // Print the suggestion if present
203 if let Some(suggestion) = &self.suggestion {
204 let suggestion = self.update_suggestion_with_lineno(suggestion, file, line_number);
205 let suggestion = suggestion.replace(
206 "help: if this is intentional, prefix it with an underscore: ",
207 "",
208 );
209 let suggestion = regex::Regex::new(r"\^{3,}")
210 .map(|re| re.replace_all(&suggestion, "^^").to_string())
211 .unwrap_or_else(|_| suggestion.clone());
212
213 let suggestion = regex::Regex::new(r"-{3,}")
214 .map(|re| re.replace_all(&suggestion, "^-").to_string())
215 .unwrap_or_else(|_| suggestion.clone());
216
217 let suggestion_text = if self.uses_color {
218 Color::Green.paint(suggestion.clone()).to_string()
219 } else {
220 suggestion.clone()
221 };
222
223 let mut lines = suggestion.lines();
224 if let Some(first_line) = lines.next() {
225 let mut formatted_suggestion = first_line.to_string();
226 for line in lines {
227 if line.trim_start().starts_with(['|', '^', '-', '_']) {
228 let cleaned_line = line
229 .trim_start_matches(|c| c == '|' || c == '^' || c == '-' || c == '_')
230 .trim_start();
231
232 let cleaned_line = if self.uses_color {
233 Color::Blue
234 .paint(&format!(" // {}", cleaned_line))
235 .to_string()
236 } else {
237 format!(" // {}", cleaned_line)
238 };
239
240 formatted_suggestion.push_str(&cleaned_line);
241 } else {
242 formatted_suggestion.push('\n');
243 formatted_suggestion.push_str(line);
244 }
245 }
246
247 let formatted_suggestion = formatted_suggestion
248 .lines()
249 .map(|line| format!(" {}", line))
250 .collect::<Vec<String>>()
251 .join("\n");
252 write!(f, "{} ", formatted_suggestion)?;
253 } else {
254 let suggestion_text = suggestion_text
255 .lines()
256 .map(|line| format!(" {}", line))
257 .collect::<Vec<String>>()
258 .join("\n");
259 write!(f, "{} ", suggestion_text)?;
260 }
261 }
262
263 // Print the note if present
264 if let Some(note) = &self.note {
265 let note = regex::Regex::new(r"for more information, see <(https?://[^>]+)>")
266 .map(|re| re.replace_all(¬e, "$1").to_string())
267 .unwrap_or_else(|_| note.clone());
268
269 let note = regex::Regex::new(r"`#\[warn\((.*?)\)\]` on by default")
270 .map(|re| re.replace_all(¬e, "#[allow($1)]").to_string())
271 .unwrap_or_else(|_| note.clone());
272 let note = if self.uses_color {
273 Color::Blue.paint(¬e).to_string()
274 } else {
275 note.clone()
276 };
277 let formatted_note = note
278 .lines()
279 .map(|line| format!(" {}", line))
280 .collect::<Vec<String>>()
281 .join("\n");
282 write!(f, "\n{}", formatted_note)?;
283 }
284
285 // Print the help if present
286 if let Some(help) = &self.help {
287 let help_text = if self.uses_color {
288 Color::LightYellow.paint(help).to_string()
289 } else {
290 help.clone()
291 };
292 write!(f, "\n {} ", help_text)?;
293 }
294
295 // Finish the debug formatting
296 write!(f, "") // No further fields are needed
297 }
298}
299
300/// CargoProcessResult is returned when the cargo process completes.
301#[derive(Debug, Default, Clone)]
302pub struct CargoProcessResult {
303 pub target_name: String,
304 pub cmd: String,
305 pub args: Vec<String>,
306 pub pid: u32,
307 pub terminal_error: Option<TerminalError>,
308 pub exit_status: Option<ExitStatus>,
309 pub start_time: Option<SystemTime>,
310 pub build_finished_time: Option<SystemTime>,
311 pub end_time: Option<SystemTime>,
312 pub build_elapsed: Option<Duration>,
313 pub runtime_elapsed: Option<Duration>,
314 pub elapsed_time: Option<Duration>,
315 pub stats: CargoStats,
316 pub build_output_size: usize,
317 pub runtime_output_size: usize,
318 pub diagnostics: Vec<CargoDiagnostic>,
319 pub is_filter: bool,
320 pub is_could_not_compile: bool,
321}
322
323impl CargoProcessResult {
324 /// Print every diagnostic in full detail.
325 pub fn print_exact(&self) {
326 if self.diagnostics.is_empty() {
327 return;
328 }
329 println!(
330 "--- Full Diagnostics for PID {} --- {}",
331 self.pid,
332 self.diagnostics.len()
333 );
334 for diag in &self.diagnostics {
335 println!("{:?}", diag);
336 }
337 }
338
339 /// Print warnings first, then errors, one‐line summary.
340 pub fn print_short(&self) {
341 if self.diagnostics.is_empty() {
342 return;
343 }
344 // let warnings: Vec<_> = self.diagnostics.iter()
345 // .filter(|d| d.level.eq("warning"))
346 // .collect();
347 let errors: Vec<_> = self
348 .diagnostics
349 .iter()
350 .filter(|d| d.level.eq("error"))
351 .collect();
352
353 // println!("--- Warnings ({} total) ---", warnings.len());
354 // for d in warnings {
355 // d.print_short();
356 // }
357
358 println!("--- Errors ({} total) ---", errors.len());
359 for d in errors {
360 d.print_short();
361 }
362 }
363
364 /// Print a compact, zero‑padded, numbered list of *all* diagnostics.
365 pub fn print_compact(&self) {
366 if self.diagnostics.is_empty() {
367 return;
368 }
369 let total = self.diagnostics.len();
370 let pid = self.pid; // Assuming `pid` is accessible in this context
371 println!("--- All Diagnostics for PID {} ({} total) ---", pid, total);
372
373 for diag in self.diagnostics.iter() {
374 let max_lineref_len = self
375 .diagnostics
376 .iter()
377 .map(|d| d.lineref.len())
378 .max()
379 .unwrap_or(0);
380
381 let padded_diag_number = if let Some(dn) = &diag.diag_number {
382 format!("{:0width$}", dn, width = diag.diag_num_padding.unwrap_or(0))
383 } else {
384 String::new()
385 };
386
387 if diag.level != "help" && diag.level != "note" {
388 println!(
389 "{}{}: {:<width$} {}",
390 diag.level,
391 padded_diag_number,
392 diag.lineref,
393 diag.message.lines().next().unwrap_or("").trim(),
394 width = max_lineref_len
395 );
396 }
397 }
398 }
399}
400
401/// CargoProcessHandle holds the cargo process and related state.
402#[derive(Debug)]
403pub struct CargoProcessHandle {
404 pub child: Child,
405 pub result: CargoProcessResult,
406 pub pid: u32,
407 pub requested_exit: bool,
408 pub stdout_handle: thread::JoinHandle<()>,
409 pub stderr_handle: thread::JoinHandle<()>,
410 pub start_time: SystemTime,
411 pub stats: Arc<Mutex<CargoStats>>,
412 pub stdout_dispatcher: Option<Arc<EventDispatcher>>,
413 pub stderr_dispatcher: Option<Arc<EventDispatcher>>,
414 pub progress_dispatcher: Option<Arc<EventDispatcher>>,
415 pub stage_dispatcher: Option<Arc<EventDispatcher>>,
416 pub estimate_bytes: Option<usize>,
417 // Separate progress counters for build and runtime output.
418 pub build_progress_counter: Arc<AtomicUsize>,
419 pub runtime_progress_counter: Arc<AtomicUsize>,
420 pub terminal_error_flag: Arc<Mutex<TerminalError>>,
421 pub diagnostics: Arc<Mutex<Vec<CargoDiagnostic>>>,
422 pub is_filter: bool,
423}
424
425impl CargoProcessHandle {
426 pub fn print_results(result: &CargoProcessResult) {
427 let start_time = result.start_time.unwrap_or(SystemTime::now());
428 println!("-------------------------------------------------");
429 println!("Process started at: {:?}", result.start_time);
430 if let Some(build_time) = result.build_finished_time {
431 println!("Build phase ended at: {:?}", build_time);
432 println!(
433 "Build phase elapsed: {}",
434 crate::e_fmt::format_duration(
435 build_time
436 .duration_since(start_time)
437 .unwrap_or_else(|_| Duration::new(0, 0))
438 )
439 );
440 } else {
441 println!("No BuildFinished timestamp recorded.");
442 }
443 println!("Process ended at: {:?}", result.end_time);
444 if let Some(runtime_dur) = result.runtime_elapsed {
445 println!(
446 "Runtime phase elapsed: {}",
447 crate::e_fmt::format_duration(runtime_dur)
448 );
449 }
450 if let Some(build_dur) = result.build_elapsed {
451 println!(
452 "Build phase elapsed: {}",
453 crate::e_fmt::format_duration(build_dur)
454 );
455 }
456 if let Some(total_elapsed) = result
457 .end_time
458 .and_then(|end| end.duration_since(start_time).ok())
459 {
460 println!(
461 "Total elapsed time: {}",
462 crate::e_fmt::format_duration(total_elapsed)
463 );
464 } else {
465 println!("No total elapsed time available.");
466 }
467 println!(
468 "Build output size: {} ({} bytes)",
469 crate::e_fmt::format_bytes(result.build_output_size),
470 result.build_output_size
471 );
472 println!(
473 "Runtime output size: {} ({} bytes)",
474 crate::e_fmt::format_bytes(result.runtime_output_size),
475 result.runtime_output_size
476 );
477 println!("-------------------------------------------------");
478 }
479
480 /// Kill the cargo process if needed.
481 pub fn kill(&mut self) -> std::io::Result<()> {
482 self.child.kill()
483 }
484 pub fn pid(&self) -> u32 {
485 self.pid
486 }
487
488 // pub fn wait(&mut self) -> std::io::Result<CargoProcessResult> {
489 // // Lock the instance since `self` is an `Arc`
490 // // let mut cargo_process_handle = self.lock().unwrap(); // `lock()` returns a mutable reference
491
492 // // Call wait on the child process
493 // let status = self.child.wait()?; // Call wait on the child process
494
495 // println!("Cargo process finished with status: {:?}", status);
496
497 // let end_time = SystemTime::now();
498
499 // // Retrieve the statistics from the process handle
500 // let stats = Arc::try_unwrap(self.stats.clone())
501 // .map(|mutex| mutex.into_inner().unwrap())
502 // .unwrap_or_else(|arc| (*arc.lock().unwrap()).clone());
503
504 // let build_out = self.build_progress_counter.load(Ordering::Relaxed);
505 // let runtime_out = self.runtime_progress_counter.load(Ordering::Relaxed);
506
507 // // Calculate phase durations if build_finished_time is recorded
508 // let (build_elapsed, runtime_elapsed) = if let Some(build_finished) = stats.build_finished_time {
509 // let build_dur = build_finished.duration_since(self.start_time)
510 // .unwrap_or_else(|_| Duration::new(0, 0));
511 // let runtime_dur = end_time.duration_since(build_finished)
512 // .unwrap_or_else(|_| Duration::new(0, 0));
513 // (Some(build_dur), Some(runtime_dur))
514 // } else {
515 // (None, None)
516 // };
517
518 // self.result.exit_status = Some(status);
519 // self.result.end_time = Some(end_time);
520 // self.result.build_output_size = self.build_progress_counter.load(Ordering::Relaxed);
521 // self.result.runtime_output_size = self.runtime_progress_counter.load(Ordering::Relaxed);
522
523 // Ok(self.result.clone())
524 // // Return the final process result
525 // // Ok(CargoProcessResult {
526 // // pid: self.pid,
527 // // exit_status: Some(status),
528 // // start_time: Some(self.start_time),
529 // // build_finished_time: stats.build_finished_time,
530 // // end_time: Some(end_time),
531 // // build_elapsed,
532 // // runtime_elapsed,
533 // // stats,
534 // // build_output_size: build_out,
535 // // runtime_output_size: runtime_out,
536 // // })
537 // }
538
539 // pub fn wait(self: Arc<Self>) -> std::io::Result<CargoProcessResult> {
540 // let mut global = GLOBAL_CHILDREN.lock().unwrap();
541
542 // // Lock and access the CargoProcessHandle inside the Mutex
543 // if let Some(cargo_process_handle) = global.iter_mut().find(|handle| {
544 // handle.lock().unwrap().pid == self.pid // Compare the pid to find the correct handle
545 // }) {
546 // let mut cargo_process_handle = cargo_process_handle.lock().unwrap(); // Mutably borrow the process handle
547
548 // let status = cargo_process_handle.child.wait()?; // Call wait on the child process
549
550 // println!("Cargo process finished with status: {:?}", status);
551
552 // let end_time = SystemTime::now();
553
554 // // Retrieve the statistics from the process handle
555 // let stats = Arc::try_unwrap(cargo_process_handle.stats.clone())
556 // .map(|mutex| mutex.into_inner().unwrap())
557 // .unwrap_or_else(|arc| (*arc.lock().unwrap()).clone());
558
559 // let build_out = cargo_process_handle.build_progress_counter.load(Ordering::Relaxed);
560 // let runtime_out = cargo_process_handle.runtime_progress_counter.load(Ordering::Relaxed);
561
562 // // Calculate phase durations if build_finished_time is recorded
563 // let (build_elapsed, runtime_elapsed) = if let Some(build_finished) = stats.build_finished_time {
564 // let build_dur = build_finished.duration_since(cargo_process_handle.start_time)
565 // .unwrap_or_else(|_| Duration::new(0, 0));
566 // let runtime_dur = end_time.duration_since(build_finished)
567 // .unwrap_or_else(|_| Duration::new(0, 0));
568 // (Some(build_dur), Some(runtime_dur))
569 // } else {
570 // (None, None)
571 // };
572
573 // // Return the final process result
574 // Ok(CargoProcessResult {
575 // exit_status: status,
576 // start_time: cargo_process_handle.start_time,
577 // build_finished_time: stats.build_finished_time,
578 // end_time,
579 // build_elapsed,
580 // runtime_elapsed,
581 // stats,
582 // build_output_size: build_out,
583 // runtime_output_size: runtime_out,
584 // })
585 // } else {
586 // Err(std::io::Error::new(std::io::ErrorKind::NotFound, "Process handle not found").into())
587 // }
588 // }
589
590 // Wait for the process and output threads to finish.
591 // Computes elapsed times for the build phase and runtime phase, and returns a CargoProcessResult.
592 // pub fn wait(mut self) -> std::io::Result<CargoProcessResult> {
593 // let status = self.child.wait()?;
594 // println!("Cargo process finished with status: {:?}", status);
595
596 // self.stdout_handle.join().expect("stdout thread panicked");
597 // self.stderr_handle.join().expect("stderr thread panicked");
598
599 // let end_time = SystemTime::now();
600
601 // // Retrieve the statistics.
602 // let stats = Arc::try_unwrap(self.stats)
603 // .map(|mutex| mutex.into_inner().unwrap())
604 // .unwrap_or_else(|arc| (*arc.lock().unwrap()).clone());
605
606 // let build_out = self.build_progress_counter.load(Ordering::Relaxed);
607 // let runtime_out = self.runtime_progress_counter.load(Ordering::Relaxed);
608
609 // // Calculate phase durations if build_finished_time is recorded.
610 // let (build_elapsed, runtime_elapsed) = if let Some(build_finished) = stats.build_finished_time {
611 // let build_dur = build_finished.duration_since(self.start_time).unwrap_or_else(|_| Duration::new(0, 0));
612 // let runtime_dur = end_time.duration_since(build_finished).unwrap_or_else(|_| Duration::new(0, 0));
613 // (Some(build_dur), Some(runtime_dur))
614 // } else {
615 // (None, None)
616 // };
617
618 // Ok(CargoProcessResult {
619 // exit_status: status,
620 // start_time: self.start_time,
621 // build_finished_time: stats.build_finished_time,
622 // end_time,
623 // build_elapsed,
624 // runtime_elapsed,
625 // stats,
626 // build_output_size: build_out,
627 // runtime_output_size: runtime_out,
628 // })
629 // }
630
631 /// Returns a formatted status string.
632 /// If `system` is provided, CPU/memory and runtime info is displayed on the right.
633 /// Otherwise, only the start time is shown.
634 pub fn format_status(&self, process: Option<&sysinfo::Process>) -> String {
635 // Ensure the start time is available.
636 let start_time = self
637 .result
638 .start_time
639 .expect("start_time should be initialized");
640 let start_dt: chrono::DateTime<chrono::Local> = start_time.into();
641 let start_str = start_dt.format("%H:%M:%S").to_string();
642 // Use ANSI coloring for the left display.
643 let colored_start = nu_ansi_term::Color::Green.paint(&start_str).to_string();
644
645 if let Some(process) = process {
646 // if let Some(process) = system.process((self.pid as usize).into()) {
647 let cpu_usage = process.cpu_usage();
648 let mem_kb = process.memory();
649 let mem_human = if mem_kb >= 1024 {
650 format!("{:.2} MB", mem_kb as f64 / 1024.0)
651 } else {
652 format!("{} KB", mem_kb)
653 };
654
655 let now = SystemTime::now();
656 let runtime_duration = now.duration_since(start_time).unwrap();
657 let runtime_str = crate::e_fmt::format_duration(runtime_duration);
658
659 let left_display = format!(
660 "{} | CPU: {:.2}% | Mem: {}",
661 colored_start, cpu_usage, mem_human
662 );
663 // Use plain text for length calculations.
664 let left_plain = format!(
665 "{} | CPU: {:.2}% | Mem: {}",
666 start_str, cpu_usage, mem_human
667 );
668
669 // Get terminal width.
670 #[cfg(feature = "tui")]
671 let (cols, _) = crossterm::terminal::size().unwrap_or((80, 20));
672 #[cfg(not(feature = "tui"))]
673 let (cols, _) = (80, 20);
674 let total_width = cols as usize;
675
676 // Format the runtime info with underlining.
677 let right_display = nu_ansi_term::Style::new()
678 .reset_before_style()
679 .underline()
680 .paint(&runtime_str)
681 .to_string();
682 let left_len = left_plain.len();
683 let right_len = runtime_str.len();
684 let padding = if total_width > left_len + right_len {
685 total_width - left_len - right_len
686 } else {
687 1
688 };
689
690 let ret = format!("{}{}{}", left_display, " ".repeat(padding), right_display);
691 if ret.trim().is_empty() {
692 String::from("No output available")
693 } else {
694 ret
695 }
696 } else {
697 // return format!("Process {} not found",(self.pid as usize));
698 String::new()
699 }
700 // } else {
701 // // If system monitoring is disabled, just return the start time.
702 // colored_start
703 // }
704 }
705}
706
707/// Extension trait to add cargo-specific capture capabilities to Command.
708pub trait CargoCommandExt {
709 fn spawn_cargo_capture(
710 &mut self,
711 builder: Arc<CargoCommandBuilder>,
712 stdout_dispatcher: Option<Arc<EventDispatcher>>,
713 stderr_dispatcher: Option<Arc<EventDispatcher>>,
714 progress_dispatcher: Option<Arc<EventDispatcher>>,
715 stage_dispatcher: Option<Arc<EventDispatcher>>,
716 estimate_bytes: Option<usize>,
717 ) -> CargoProcessHandle;
718 fn spawn_cargo_passthrough(&mut self, builder: Arc<CargoCommandBuilder>) -> CargoProcessHandle;
719}
720
721impl CargoCommandExt for Command {
722 fn spawn_cargo_passthrough(&mut self, builder: Arc<CargoCommandBuilder>) -> CargoProcessHandle {
723 // Spawn the child process without redirecting stdout and stderr
724 let child = self.spawn().unwrap_or_else(|_| {
725 panic!(
726 "Failed to spawn cargo process {:?} {:?}",
727 &builder.alternate_cmd, builder.args
728 )
729 });
730
731 let pid = child.id();
732 let start_time = SystemTime::now();
733 let diagnostics = Arc::clone(&builder.diagnostics);
734 let s = CargoStats {
735 is_comiler_target: builder.is_compiler_target(), // Ensure this field is now valid
736 start_time: Some(start_time),
737 build_finished_time: Some(start_time),
738 target_name: builder.target_name.clone(),
739 ..Default::default()
740 };
741 let stats = Arc::new(Mutex::new(s.clone()));
742 // Try to take ownership of the Vec<CargoDiagnostic> out of the Arc.
743
744 let (cmd, args) = builder.injected_args();
745 // Create the CargoProcessHandle
746 let result = CargoProcessResult {
747 target_name: builder.target_name.clone(),
748 cmd: cmd,
749 args: args,
750 pid,
751 terminal_error: None,
752 exit_status: None,
753 start_time: Some(start_time),
754 build_finished_time: None,
755 end_time: None,
756 elapsed_time: None,
757 build_elapsed: None,
758 runtime_elapsed: None,
759 stats: s, // CargoStats::default(),
760 build_output_size: 0,
761 runtime_output_size: 0,
762 diagnostics: Vec::new(),
763 is_filter: builder.is_filter,
764 is_could_not_compile: false,
765 };
766
767 // Return the CargoProcessHandle that owns the child process
768 CargoProcessHandle {
769 child, // The child process is now owned by the handle
770 result, // The result contains information about the process
771 pid, // The PID of the process
772 stdout_handle: thread::spawn(move || {
773 // This thread is now unnecessary if we are not capturing anything
774 // We can leave it empty or remove it altogether
775 }),
776 stderr_handle: thread::spawn(move || {
777 // This thread is also unnecessary if we are not capturing anything
778 }),
779 start_time,
780 stats,
781 stdout_dispatcher: None, // No dispatcher is needed
782 stderr_dispatcher: None, // No dispatcher is needed
783 progress_dispatcher: None, // No dispatcher is needed
784 stage_dispatcher: None, // No dispatcher is needed
785 estimate_bytes: None,
786 build_progress_counter: Arc::new(AtomicUsize::new(0)),
787 runtime_progress_counter: Arc::new(AtomicUsize::new(0)),
788 requested_exit: false,
789 terminal_error_flag: Arc::new(Mutex::new(TerminalError::NoError)),
790 diagnostics,
791 is_filter: builder.is_filter,
792 }
793 }
794
795 fn spawn_cargo_capture(
796 &mut self,
797 builder: Arc<CargoCommandBuilder>,
798 stdout_dispatcher: Option<Arc<EventDispatcher>>,
799 stderr_dispatcher: Option<Arc<EventDispatcher>>,
800 progress_dispatcher: Option<Arc<EventDispatcher>>,
801 stage_dispatcher: Option<Arc<EventDispatcher>>,
802 estimate_bytes: Option<usize>,
803 ) -> CargoProcessHandle {
804 self.stdout(Stdio::piped()).stderr(Stdio::piped());
805 // println!("Spawning cargo process with capture {:?}",self);
806 let mut child = self.spawn().expect("Failed to spawn cargo process");
807 let pid = child.id();
808 let start_time = SystemTime::now();
809 let diagnostics = Arc::new(Mutex::new(Vec::<CargoDiagnostic>::new()));
810 let s = CargoStats {
811 target_name: builder.target_name.clone(),
812 is_comiler_target: builder.is_compiler_target(),
813 is_could_not_compile: false,
814 start_time: Some(start_time),
815 ..Default::default()
816 };
817 let stats = Arc::new(Mutex::new(s));
818
819 // Two separate counters: one for build output and one for runtime output.
820 let stderr_compiler_msg = Arc::new(Mutex::new(VecDeque::<String>::new()));
821 let build_progress_counter = Arc::new(AtomicUsize::new(0));
822 let runtime_progress_counter = Arc::new(AtomicUsize::new(0));
823
824 // Clone dispatchers and counters for use in threads.
825 let _stdout_disp_clone = stdout_dispatcher.clone();
826 let progress_disp_clone_stdout = progress_dispatcher.clone();
827 let stage_disp_clone = stage_dispatcher.clone();
828
829 let stats_stdout_clone = Arc::clone(&stats);
830 let stats_stderr_clone = Arc::clone(&stats);
831 let _build_counter_stdout = Arc::clone(&build_progress_counter);
832 let _runtime_counter_stdout = Arc::clone(&runtime_progress_counter);
833
834 // Spawn a thread to process stdout.
835 let _stderr_compiler_msg_clone = Arc::clone(&stderr_compiler_msg);
836 let stdout = child.stdout.take().expect("Failed to capture stdout");
837 // println!("{}: Capturing stdout", pid);
838 let stdout_handle = thread::spawn(move || {
839 let stdout_reader = BufReader::new(stdout);
840 // This flag marks whether we are still in the build phase.
841 #[allow(unused_mut)]
842 let mut _in_build_phase = true;
843 let stdout_buffer = Arc::new(Mutex::new(Vec::<String>::new()));
844 let buf = Arc::clone(&stdout_buffer);
845 {
846 for line in stdout_reader.lines().map(|line| line) {
847 if let Ok(line) = line {
848 // println!("{}: {}", pid, line);
849 // Try to parse the line as a JSON cargo message.
850
851 #[cfg(not(feature = "uses_serde"))]
852 println!("{}", line);
853 #[cfg(feature = "uses_serde")]
854 match serde_json::from_str::<Message>(&line) {
855 Ok(msg) => {
856 // let msg_str = format!("{:?}", msg);
857 // if let Some(ref disp) = stdout_disp_clone {
858 // disp.dispatch(&msg_str);
859 // }
860 // Add message length to the appropriate counter.
861 // if in_build_phase {
862 // build_counter_stdout.fetch_add(msg_str.len(), Ordering::Relaxed);
863 // } else {
864 // runtime_counter_stdout.fetch_add(msg_str.len(), Ordering::Relaxed);
865 // }
866 if let Some(total) = estimate_bytes {
867 let current = if _in_build_phase {
868 _build_counter_stdout.load(Ordering::Relaxed)
869 } else {
870 _runtime_counter_stdout.load(Ordering::Relaxed)
871 };
872 let progress = (current as f64 / total as f64) * 100.0;
873 if let Some(ref pd) = progress_disp_clone_stdout {
874 pd.dispatch(
875 &format!("Progress: {:.2}%", progress),
876 stats_stdout_clone.clone(),
877 );
878 }
879 }
880
881 let now = SystemTime::now();
882 // Process known cargo message variants.
883 match msg {
884 Message::BuildFinished(_) => {
885 // Mark the end of the build phase.
886 if _in_build_phase {
887 _in_build_phase = false;
888 let mut s = stats_stdout_clone.lock().unwrap();
889 s.build_finished_count += 1;
890 s.build_finished_time.get_or_insert(now);
891 drop(s);
892 // self.result.build_finished_time = Some(now);
893 if let Some(ref sd) = stage_disp_clone {
894 sd.dispatch(
895 &format!(
896 "Stage: BuildFinished occurred at {:?}",
897 now
898 ),
899 stats_stdout_clone.clone(),
900 );
901 }
902 if let Some(ref sd) = stage_disp_clone {
903 sd.dispatch(
904 "Stage: Switching to runtime passthrough",
905 stats_stdout_clone.clone(),
906 );
907 }
908 }
909 }
910 Message::CompilerMessage(msg) => {
911 // println!("parsed{}: {:?}", pid, msg);
912 let mut s = stats_stdout_clone.lock().unwrap();
913 s.compiler_message_count += 1;
914 if s.compiler_message_time.is_none() {
915 s.compiler_message_time = Some(now);
916 drop(s);
917 if let Some(ref sd) = stage_disp_clone {
918 sd.dispatch(
919 &format!(
920 "Stage: CompilerMessage occurred at {:?}",
921 now
922 ),
923 stats_stdout_clone.clone(),
924 );
925 }
926 }
927 let mut msg_vec =
928 _stderr_compiler_msg_clone.lock().unwrap();
929 msg_vec.push_back(format!(
930 "{}\n\n",
931 msg.message.rendered.unwrap_or_default()
932 ));
933 // let mut diags = diagnostics.lock().unwrap();
934 // let diag = crate::e_eventdispatcher::convert_message_to_diagnostic(msg, &msg_str);
935 // diags.push(diag.clone());
936 // if let Some(ref sd) = stage_disp_clone {
937 // sd.dispatch(&format!("Stage: Diagnostic occurred at {:?}", now));
938 // }
939 }
940 Message::CompilerArtifact(_) => {
941 let mut s = stats_stdout_clone.lock().unwrap();
942 s.compiler_artifact_count += 1;
943 if s.compiler_artifact_time.is_none() {
944 s.compiler_artifact_time = Some(now);
945 drop(s);
946 if let Some(ref sd) = stage_disp_clone {
947 sd.dispatch(
948 &format!(
949 "Stage: CompilerArtifact occurred at {:?}",
950 now
951 ),
952 stats_stdout_clone.clone(),
953 );
954 }
955 }
956 }
957 Message::BuildScriptExecuted(_) => {
958 let mut s = stats_stdout_clone.lock().unwrap();
959 s.build_script_executed_count += 1;
960 if s.build_script_executed_time.is_none() {
961 s.build_script_executed_time = Some(now);
962 drop(s);
963 if let Some(ref sd) = stage_disp_clone {
964 sd.dispatch(
965 &format!(
966 "Stage: BuildScriptExecuted occurred at {:?}",
967 now
968 ),
969 stats_stdout_clone.clone(),
970 );
971 }
972 }
973 }
974 _ => {}
975 }
976 }
977 Err(_err) => {
978 // println!("ERROR {} {}: {}",_err, pid, line);
979 // If JSON parsing fails, assume this is plain runtime output.
980 // If still in build phase, we assume the build phase has ended.
981 if _in_build_phase {
982 _in_build_phase = false;
983 let now = SystemTime::now();
984 let mut s = stats_stdout_clone.lock().unwrap();
985 s.build_finished_count += 1;
986 s.build_finished_time.get_or_insert(now);
987 drop(s);
988 if let Some(ref sd) = stage_disp_clone {
989 sd.dispatch(
990 &format!(
991 "Stage: BuildFinished (assumed) occurred at {:?}",
992 now
993 ),
994 stats_stdout_clone.clone(),
995 );
996 }
997 buf.lock().unwrap().push(line.to_string());
998 } else {
999 // build is done: first flush anything we buffered
1000 let mut b = buf.lock().unwrap();
1001 for l in b.drain(..) {
1002 println!("{}", l);
1003 }
1004 // then print live
1005 println!("{}", line);
1006 }
1007 if let Some(ref disp) = _stdout_disp_clone {
1008 disp.dispatch(&line, stats_stdout_clone.clone());
1009 }
1010 // Print the runtime output.
1011 // println!("{}: {}", pid, line);
1012 if line.contains("not a terminal") {
1013 println!(
1014 "{}NOT A TERMINAL - MARK AND RUN AGAIN: {}",
1015 pid, line
1016 );
1017 }
1018 _runtime_counter_stdout.fetch_add(line.len(), Ordering::Relaxed);
1019 if let Some(total) = estimate_bytes {
1020 let current = _runtime_counter_stdout.load(Ordering::Relaxed);
1021 let progress = (current as f64 / total as f64) * 100.0;
1022 if let Some(ref pd) = progress_disp_clone_stdout {
1023 pd.dispatch(
1024 &format!("Progress: {:.2}%", progress),
1025 stats_stdout_clone.clone(),
1026 );
1027 }
1028 }
1029 }
1030 }
1031 }
1032 }
1033 }
1034 }); // End of stdout thread
1035
1036 let tflag = TerminalError::NoError;
1037 // Create a flag to indicate if the process is a terminal process.
1038 let terminal_flag = Arc::new(Mutex::new(TerminalError::NoError));
1039 // Spawn a thread to capture stderr.
1040 let stderr = child.stderr.take().expect("Failed to capture stderr");
1041 let stderr_disp_clone = stderr_dispatcher.clone();
1042 // let terminal_flag_clone = Arc::clone(&terminal_flag);
1043 // let build_counter_stderr = Arc::clone(&build_progress_counter);
1044 // let runtime_counter_stderr = Arc::clone(&runtime_progress_counter);
1045 // let progress_disp_clone_stderr = progress_dispatcher.clone();
1046 let escape_sequence = "\u{1b}[1m\u{1b}[32m";
1047 // let diagnostics_clone = Arc::clone(&diagnostics);
1048 let stderr_compiler_msg_clone = Arc::clone(&stderr_compiler_msg);
1049 // println!("{}: Capturing stderr", pid);
1050 let mut stderr_reader = BufReader::new(stderr);
1051 let stderr_handle = thread::spawn(move || {
1052 // let mut msg_vec = stderr_compiler_msg_clone.lock().unwrap();
1053 loop {
1054 // println!("looping stderr thread {}", pid);
1055 // Lock the deque and pop all messages available in a while loop
1056 while let Some(message) = {
1057 let mut guard = match stderr_compiler_msg_clone.lock() {
1058 Ok(guard) => guard,
1059 Err(err) => {
1060 eprintln!("Failed to lock stderr_compiler_msg_clone: {}", err);
1061 return; // Exit the function or loop in case of an error
1062 }
1063 };
1064 guard.pop_front()
1065 } {
1066 for line in message.lines().map(|line| line) {
1067 if let Some(ref disp) = stderr_disp_clone {
1068 // Dispatch the line and receive the Vec<Option<CallbackResponse>>.
1069 let responses = disp.dispatch(line, stats_stderr_clone.clone());
1070
1071 // Iterate over the responses.
1072 for ret in responses {
1073 if let Some(response) = ret {
1074 if response.terminal_status == Some(TerminalError::NoTerminal) {
1075 // If the response indicates a terminal error, set the flag.
1076 println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1077 } else if response.terminal_status
1078 == Some(TerminalError::NoError)
1079 {
1080 // If the response indicates no terminal error, set the flag to NoError.
1081 } else if response.terminal_status
1082 == Some(TerminalError::NoTerminal)
1083 {
1084 // If the response indicates not a terminal, set the flag to NoTerminal.
1085 println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1086 }
1087 // if let Some(ref msg) = response.message {
1088 // println!("DISPATCH RESULT {} {}", pid, msg);
1089 // // }
1090 // let diag = crate::e_eventdispatcher::convert_response_to_diagnostic(response, &line);
1091 // // let mut diags = diagnostics_clone.lock().unwrap();
1092
1093 // let in_multiline = disp.callbacks
1094 // .lock().unwrap()
1095 // .iter()
1096 // .any(|cb| cb.is_reading_multiline.load(Ordering::Relaxed));
1097
1098 // if !in_multiline {
1099 // // start of a new diagnostic
1100 // diags.push(diag);
1101 // } else {
1102 // // continuation → child of the last diagnostic
1103 // if let Some(parent) = diags.last_mut() {
1104 // parent.children.push(diag);
1105 // } else {
1106 // // no parent yet (unlikely), just push
1107 // diags.push(diag);
1108 // }
1109 // }
1110 }
1111 }
1112 }
1113 }
1114 }
1115 // Sleep briefly if no messages are available to avoid busy waiting
1116 thread::sleep(Duration::from_millis(100));
1117 // If still in build phase, add to the build counter.
1118 // break;
1119
1120 // println!("{}: dave stderr", pid);
1121 // let mut flag = terminal_flag_clone.lock().unwrap();
1122 for line in stderr_reader.by_ref().lines() {
1123 // println!("SPAWN{}: {:?}", pid, line);
1124 if let Ok(line) = line {
1125 // if line.contains("IO(Custom { kind: NotConnected") {
1126 // println!("{} IS A TERMINAL PROCESS - {}", pid,line);
1127 // continue;
1128 // }
1129 let line = if line.starts_with(escape_sequence) {
1130 // If the line starts with the escape sequence, preserve it and remove leading spaces
1131 let rest_of_line = &line[escape_sequence.len()..]; // Get the part of the line after the escape sequence
1132 format!("{}{}", escape_sequence, rest_of_line.trim_start())
1133 // Reassemble the escape sequence and the trimmed text
1134 } else {
1135 line // If it doesn't start with the escape sequence, leave it unchanged
1136 };
1137 if let Some(ref disp) = stderr_disp_clone {
1138 // Dispatch the line and receive the Vec<Option<CallbackResponse>>.
1139 let responses = disp.dispatch(&line, stats_stderr_clone.clone());
1140 let mut has_match = false;
1141 // Iterate over the responses.
1142 for ret in responses {
1143 if let Some(_response) = ret {
1144 has_match = true;
1145 // if response.terminal_status == Some(TerminalError::NoTerminal) {
1146 // // If the response indicates a terminal error, set the flag.
1147 // *flag = TerminalError::NoTerminal;
1148 // println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1149 // } else if response.terminal_status == Some(TerminalError::NoError) {
1150 // // If the response indicates no terminal error, set the flag to NoError.
1151 // *flag = TerminalError::NoError;
1152 // } else if response.terminal_status == Some(TerminalError::NoTerminal) {
1153 // // If the response indicates not a terminal, set the flag to NoTerminal.
1154 // *flag = TerminalError::NoTerminal;
1155 // println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1156 // }
1157 // if let Some(ref msg) = response.message {
1158 // println!("DISPATCH RESULT {} {}", pid, msg);
1159 // }
1160 // let diag = crate::e_eventdispatcher::convert_response_to_diagnostic(response, &line);
1161 // // let mut diags = diagnostics_clone.lock().unwrap();
1162
1163 // let in_multiline = disp.callbacks
1164 // .lock().unwrap()
1165 // .iter()
1166 // .any(|cb| cb.is_reading_multiline.load(Ordering::Relaxed));
1167
1168 // if !in_multiline {
1169 // // start of a new diagnostic
1170 // diags.push(diag);
1171 // } else {
1172 // // continuation → child of the last diagnostic
1173 // if let Some(parent) = diags.last_mut() {
1174 // parent.children.push(diag);
1175 // } else {
1176 // // no parent yet (unlikely), just push
1177 // diags.push(diag);
1178 // }
1179 // }
1180 }
1181 }
1182 if !has_match && !line.trim().is_empty() && !line.eq("...") {
1183 // If the line doesn't match any pattern, print it as is.
1184 println!("{}", line);
1185 }
1186 } else {
1187 println!("ALLLINES {}", line.trim()); //all lines
1188 }
1189 // if let Some(ref disp) = stderr_disp_clone {
1190 // if let Some(ret) = disp.dispatch(&line) {
1191 // if let Some(ref msg) = ret.message {
1192 // println!("DISPATCH RESULT {} {}", pid, msg);
1193 // }
1194 // }
1195 // }
1196 // // Here, we assume stderr is less structured. We add its length to runtime counter.
1197 // runtime_counter_stderr.fetch_add(line.len(), Ordering::Relaxed);
1198 // if let Some(total) = estimate_bytes {
1199 // let current = runtime_counter_stderr.load(Ordering::Relaxed);
1200 // let progress = (current as f64 / total as f64) * 100.0;
1201 // if let Some(ref pd) = progress_disp_clone_stderr {
1202 // pd.dispatch(&format!("Progress: {:.2}%", progress));
1203 // }
1204 // }
1205 }
1206 }
1207 // println!("{}: dave stderr end", pid);
1208 } //loop
1209 }); // End of stderr thread
1210
1211 let final_diagnostics = {
1212 let diag_lock = diagnostics.lock().unwrap();
1213 diag_lock.clone()
1214 };
1215 let pid = child.id();
1216 let (cmd, args) = builder.injected_args();
1217 let stats_snapshot = stats.lock().unwrap().clone();
1218 let result = CargoProcessResult {
1219 target_name: builder.target_name.clone(),
1220 cmd: cmd,
1221 args: args,
1222 pid,
1223 exit_status: None,
1224 start_time: Some(start_time),
1225 build_finished_time: None,
1226 end_time: None,
1227 elapsed_time: None,
1228 build_elapsed: None,
1229 runtime_elapsed: None,
1230 stats: stats_snapshot.clone(),
1231 build_output_size: 0,
1232 runtime_output_size: 0,
1233 terminal_error: Some(tflag),
1234 diagnostics: final_diagnostics,
1235 is_filter: builder.is_filter,
1236 is_could_not_compile: stats_snapshot.is_could_not_compile,
1237 };
1238 CargoProcessHandle {
1239 child,
1240 result,
1241 pid,
1242 stdout_handle,
1243 stderr_handle,
1244 start_time,
1245 stats,
1246 stdout_dispatcher,
1247 stderr_dispatcher,
1248 progress_dispatcher,
1249 stage_dispatcher,
1250 estimate_bytes,
1251 build_progress_counter,
1252 runtime_progress_counter,
1253 requested_exit: false,
1254 terminal_error_flag: terminal_flag,
1255 diagnostics,
1256 is_filter: builder.is_filter,
1257 }
1258 }
1259}