cargo_e/e_cargocommand_ext.rs
1use crate::e_command_builder::{CargoCommandBuilder, TerminalError};
2use crate::e_eventdispatcher::{EventDispatcher, ThreadLocalContext};
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 let builder_for_result = builder.clone();
806 let builder_for_closure = builder.clone();
807 let builder_stdout = builder.clone();
808 let builder_stderr = builder.clone();
809 // println!("Spawning cargo process with capture {:?}",self);
810 let mut child = self.spawn().expect("Failed to spawn cargo process");
811 let pid = child.id();
812 let start_time = SystemTime::now();
813 let diagnostics = Arc::new(Mutex::new(Vec::<CargoDiagnostic>::new()));
814 let s = CargoStats {
815 target_name: builder.target_name.clone(),
816 is_comiler_target: builder.is_compiler_target(),
817 is_could_not_compile: false,
818 start_time: Some(start_time),
819 ..Default::default()
820 };
821 let stats = Arc::new(Mutex::new(s));
822
823 // Two separate counters: one for build output and one for runtime output.
824 let stderr_compiler_msg = Arc::new(Mutex::new(VecDeque::<String>::new()));
825 let build_progress_counter = Arc::new(AtomicUsize::new(0));
826 let runtime_progress_counter = Arc::new(AtomicUsize::new(0));
827
828 // Clone dispatchers and counters for use in threads.
829 let _stdout_disp_clone = stdout_dispatcher.clone();
830 let progress_disp_clone_stdout = progress_dispatcher.clone();
831 let stage_disp_clone = stage_dispatcher.clone();
832
833 let stats_stdout_clone = Arc::clone(&stats);
834 let stats_stderr_clone = Arc::clone(&stats);
835 let _build_counter_stdout = Arc::clone(&build_progress_counter);
836 let _runtime_counter_stdout = Arc::clone(&runtime_progress_counter);
837
838 // Spawn a thread to process stdout.
839 let _stderr_compiler_msg_clone = Arc::clone(&stderr_compiler_msg);
840 let stdout = child.stdout.take().expect("Failed to capture stdout");
841 // println!("{}: Capturing stdout", pid);
842 let stdout_handle = thread::spawn(move || {
843 ThreadLocalContext::set_context(
844 &builder_stdout.target_name.clone(),
845 builder_stdout.manifest_path.to_str().unwrap_or_default(),
846 );
847
848 let stdout_reader = BufReader::new(stdout);
849 // This flag marks whether we are still in the build phase.
850 #[allow(unused_mut)]
851 let mut _in_build_phase = true;
852 let stdout_buffer = Arc::new(Mutex::new(Vec::<String>::new()));
853 let buf = Arc::clone(&stdout_buffer);
854 {
855 for line in stdout_reader.lines().map(|line| line) {
856 if let Ok(line) = line {
857 // println!("{}: {}", pid, line);
858 // Try to parse the line as a JSON cargo message.
859
860 #[cfg(not(feature = "uses_serde"))]
861 println!("{}", line);
862 #[cfg(feature = "uses_serde")]
863 match serde_json::from_str::<Message>(&line) {
864 Ok(msg) => {
865 // let msg_str = format!("{:?}", msg);
866 // if let Some(ref disp) = stdout_disp_clone {
867 // disp.dispatch(&msg_str);
868 // }
869 // Add message length to the appropriate counter.
870 // if in_build_phase {
871 // build_counter_stdout.fetch_add(msg_str.len(), Ordering::Relaxed);
872 // } else {
873 // runtime_counter_stdout.fetch_add(msg_str.len(), Ordering::Relaxed);
874 // }
875 if let Some(total) = estimate_bytes {
876 let current = if _in_build_phase {
877 _build_counter_stdout.load(Ordering::Relaxed)
878 } else {
879 _runtime_counter_stdout.load(Ordering::Relaxed)
880 };
881 let progress = (current as f64 / total as f64) * 100.0;
882 if let Some(ref pd) = progress_disp_clone_stdout {
883 pd.dispatch(
884 &format!("Progress: {:.2}%", progress),
885 stats_stdout_clone.clone(),
886 );
887 }
888 }
889
890 let now = SystemTime::now();
891 // Process known cargo message variants.
892 match msg {
893 Message::BuildFinished(_) => {
894 // Mark the end of the build phase.
895 if _in_build_phase {
896 _in_build_phase = false;
897 let mut s = stats_stdout_clone.lock().unwrap();
898 s.build_finished_count += 1;
899 s.build_finished_time.get_or_insert(now);
900 drop(s);
901 // self.result.build_finished_time = Some(now);
902 if let Some(ref sd) = stage_disp_clone {
903 sd.dispatch(
904 &format!(
905 "Stage: BuildFinished occurred at {:?}",
906 now
907 ),
908 stats_stdout_clone.clone(),
909 );
910 }
911 if let Some(ref sd) = stage_disp_clone {
912 sd.dispatch(
913 "Stage: Switching to runtime passthrough",
914 stats_stdout_clone.clone(),
915 );
916 }
917 }
918 }
919 Message::CompilerMessage(msg) => {
920 // println!("parsed{}: {:?}", pid, msg);
921 let mut s = stats_stdout_clone.lock().unwrap();
922 s.compiler_message_count += 1;
923 if s.compiler_message_time.is_none() {
924 s.compiler_message_time = Some(now);
925 drop(s);
926 if let Some(ref sd) = stage_disp_clone {
927 sd.dispatch(
928 &format!(
929 "Stage: CompilerMessage occurred at {:?}",
930 now
931 ),
932 stats_stdout_clone.clone(),
933 );
934 }
935 }
936 let mut msg_vec =
937 _stderr_compiler_msg_clone.lock().unwrap();
938 msg_vec.push_back(format!(
939 "{}\n\n",
940 msg.message.rendered.unwrap_or_default()
941 ));
942 // let mut diags = diagnostics.lock().unwrap();
943 // let diag = crate::e_eventdispatcher::convert_message_to_diagnostic(msg, &msg_str);
944 // diags.push(diag.clone());
945 // if let Some(ref sd) = stage_disp_clone {
946 // sd.dispatch(&format!("Stage: Diagnostic occurred at {:?}", now));
947 // }
948 }
949 Message::CompilerArtifact(a) => {
950 let mut s = stats_stdout_clone.lock().unwrap();
951 // if let Some(exe) = a.executable.as_deref() {
952 // if !exe.as_str().is_empty() {
953 // let m = crate::GLOBAL_MANAGER.get();
954 // if let Some(ref m) = m {
955 // // println!(
956 // // "Persisting executable for target {}: {}",
957 // // builder.target_name, exe
958 // // );
959 // // if let Err(e) = m.persist_executable_for_target(
960 // // &builder.target_name,
961 // // exe.as_str()
962 // // ) {
963 // // eprintln!(
964 // // "Error persisting executable for target {}: {}",
965 // // builder.target_name, e
966 // // );
967 // // }
968
969 // }
970 // }
971 // }
972 s.compiler_artifact_count += 1;
973 if s.compiler_artifact_time.is_none() {
974 s.compiler_artifact_time = Some(now);
975 drop(s);
976 if let Some(ref sd) = stage_disp_clone {
977 sd.dispatch(
978 &format!(
979 "Stage: CompilerArtifact occurred at {:?}",
980 now
981 ),
982 stats_stdout_clone.clone(),
983 );
984 }
985 }
986 }
987 Message::BuildScriptExecuted(_) => {
988 let mut s = stats_stdout_clone.lock().unwrap();
989 s.build_script_executed_count += 1;
990 if s.build_script_executed_time.is_none() {
991 s.build_script_executed_time = Some(now);
992 drop(s);
993 if let Some(ref sd) = stage_disp_clone {
994 sd.dispatch(
995 &format!(
996 "Stage: BuildScriptExecuted occurred at {:?}",
997 now
998 ),
999 stats_stdout_clone.clone(),
1000 );
1001 }
1002 }
1003 }
1004 _ => {}
1005 }
1006 }
1007 Err(_err) => {
1008 // println!("ERROR {} {}: {}",_err, pid, line);
1009 // If JSON parsing fails, assume this is plain runtime output.
1010 // If still in build phase, we assume the build phase has ended.
1011 if _in_build_phase {
1012 _in_build_phase = false;
1013 let now = SystemTime::now();
1014 let mut s = stats_stdout_clone.lock().unwrap();
1015 s.build_finished_count += 1;
1016 s.build_finished_time.get_or_insert(now);
1017 drop(s);
1018 if let Some(ref sd) = stage_disp_clone {
1019 sd.dispatch(
1020 &format!(
1021 "Stage: BuildFinished (assumed) occurred at {:?}",
1022 now
1023 ),
1024 stats_stdout_clone.clone(),
1025 );
1026 }
1027 buf.lock().unwrap().push(line.to_string());
1028 } else {
1029 // build is done: first flush anything we buffered
1030 let mut b = buf.lock().unwrap();
1031 for l in b.drain(..) {
1032 println!("{}", l);
1033 }
1034 // then print live
1035 println!("{}", line);
1036 }
1037 if let Some(ref disp) = _stdout_disp_clone {
1038 disp.dispatch(&line, stats_stdout_clone.clone());
1039 }
1040 // Print the runtime output.
1041 // println!("{}: {}", pid, line);
1042 if line.contains("not a terminal") {
1043 println!(
1044 "{}NOT A TERMINAL - MARK AND RUN AGAIN: {}",
1045 pid, line
1046 );
1047 }
1048 _runtime_counter_stdout.fetch_add(line.len(), Ordering::Relaxed);
1049 if let Some(total) = estimate_bytes {
1050 let current = _runtime_counter_stdout.load(Ordering::Relaxed);
1051 let progress = (current as f64 / total as f64) * 100.0;
1052 if let Some(ref pd) = progress_disp_clone_stdout {
1053 pd.dispatch(
1054 &format!("Progress: {:.2}%", progress),
1055 stats_stdout_clone.clone(),
1056 );
1057 }
1058 }
1059 }
1060 }
1061 }
1062 }
1063 }
1064 }); // End of stdout thread
1065 let tflag = TerminalError::NoError;
1066 // Create a flag to indicate if the process is a terminal process.
1067 let terminal_flag = Arc::new(Mutex::new(TerminalError::NoError));
1068 // Spawn a thread to capture stderr.
1069 let stderr = child.stderr.take().expect("Failed to capture stderr");
1070 let stderr_disp_clone = stderr_dispatcher.clone();
1071 // let terminal_flag_clone = Arc::clone(&terminal_flag);
1072 // let build_counter_stderr = Arc::clone(&build_progress_counter);
1073 // let runtime_counter_stderr = Arc::clone(&runtime_progress_counter);
1074 // let progress_disp_clone_stderr = progress_dispatcher.clone();
1075 let escape_sequence = "\u{1b}[1m\u{1b}[32m";
1076 // let diagnostics_clone = Arc::clone(&diagnostics);
1077 let stderr_compiler_msg_clone = Arc::clone(&stderr_compiler_msg);
1078 let mut stderr_reader = BufReader::new(stderr);
1079 let stderr_handle = thread::spawn(move || {
1080 ThreadLocalContext::set_context(
1081 &builder_stderr.target_name.clone(),
1082 builder_stderr.manifest_path.to_str().unwrap_or_default(),
1083 );
1084 // let mut msg_vec = stderr_compiler_msg_clone.lock().unwrap();
1085 loop {
1086 // println!("looping stderr thread {}", pid);
1087 // Lock the deque and pop all messages available in a while loop
1088 while let Some(message) = {
1089 let mut guard = match stderr_compiler_msg_clone.lock() {
1090 Ok(guard) => guard,
1091 Err(err) => {
1092 eprintln!("Failed to lock stderr_compiler_msg_clone: {}", err);
1093 return; // Exit the function or loop in case of an error
1094 }
1095 };
1096 guard.pop_front()
1097 } {
1098 for line in message.lines().map(|line| line) {
1099 if let Some(ref disp) = stderr_disp_clone {
1100 // Dispatch the line and receive the Vec<Option<CallbackResponse>>.
1101 let responses = disp.dispatch(line, stats_stderr_clone.clone());
1102
1103 // Iterate over the responses.
1104 for ret in responses {
1105 if let Some(response) = ret {
1106 if response.terminal_status == Some(TerminalError::NoTerminal) {
1107 // If the response indicates a terminal error, set the flag.
1108 println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1109 } else if response.terminal_status
1110 == Some(TerminalError::NoError)
1111 {
1112 // If the response indicates no terminal error, set the flag to NoError.
1113 } else if response.terminal_status
1114 == Some(TerminalError::NoTerminal)
1115 {
1116 // If the response indicates not a terminal, set the flag to NoTerminal.
1117 println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1118 }
1119 // if let Some(ref msg) = response.message {
1120 // println!("DISPATCH RESULT {} {}", pid, msg);
1121 // // }
1122 // let diag = crate::e_eventdispatcher::convert_response_to_diagnostic(response, &line);
1123 // // let mut diags = diagnostics_clone.lock().unwrap();
1124
1125 // let in_multiline = disp.callbacks
1126 // .lock().unwrap()
1127 // .iter()
1128 // .any(|cb| cb.is_reading_multiline.load(Ordering::Relaxed));
1129
1130 // if !in_multiline {
1131 // // start of a new diagnostic
1132 // diags.push(diag);
1133 // } else {
1134 // // continuation → child of the last diagnostic
1135 // if let Some(parent) = diags.last_mut() {
1136 // parent.children.push(diag);
1137 // } else {
1138 // // no parent yet (unlikely), just push
1139 // diags.push(diag);
1140 // }
1141 // }
1142 }
1143 }
1144 }
1145 }
1146 }
1147 // Sleep briefly if no messages are available to avoid busy waiting
1148 thread::sleep(Duration::from_millis(100));
1149 // If still in build phase, add to the build counter.
1150 // break;
1151
1152 // println!("{}: dave stderr", pid);
1153 // let mut flag = terminal_flag_clone.lock().unwrap();
1154 for line in stderr_reader.by_ref().lines() {
1155 // println!("SPAWN{}: {:?}", pid, line);
1156 if let Ok(line) = line {
1157 // if line.contains("IO(Custom { kind: NotConnected") {
1158 // println!("{} IS A TERMINAL PROCESS - {}", pid,line);
1159 // continue;
1160 // }
1161 let line = if line.starts_with(escape_sequence) {
1162 // If the line starts with the escape sequence, preserve it and remove leading spaces
1163 let rest_of_line = &line[escape_sequence.len()..]; // Get the part of the line after the escape sequence
1164 format!("{}{}", escape_sequence, rest_of_line.trim_start())
1165 // Reassemble the escape sequence and the trimmed text
1166 } else {
1167 line // If it doesn't start with the escape sequence, leave it unchanged
1168 };
1169 if let Some(ref disp) = stderr_disp_clone {
1170 // Dispatch the line and receive the Vec<Option<CallbackResponse>>.
1171 let responses = disp.dispatch(&line, stats_stderr_clone.clone());
1172 let mut has_match = false;
1173 // Iterate over the responses.
1174 for ret in responses {
1175 if let Some(_response) = ret {
1176 has_match = true;
1177 // if response.terminal_status == Some(TerminalError::NoTerminal) {
1178 // // If the response indicates a terminal error, set the flag.
1179 // *flag = TerminalError::NoTerminal;
1180 // println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1181 // } else if response.terminal_status == Some(TerminalError::NoError) {
1182 // // If the response indicates no terminal error, set the flag to NoError.
1183 // *flag = TerminalError::NoError;
1184 // } else if response.terminal_status == Some(TerminalError::NoTerminal) {
1185 // // If the response indicates not a terminal, set the flag to NoTerminal.
1186 // *flag = TerminalError::NoTerminal;
1187 // println!("{} IS A TERMINAL PROCESS - {}", pid, line);
1188 // }
1189 // if let Some(ref msg) = response.message {
1190 // println!("DISPATCH RESULT {} {}", pid, msg);
1191 // }
1192 // let diag = crate::e_eventdispatcher::convert_response_to_diagnostic(response, &line);
1193 // // let mut diags = diagnostics_clone.lock().unwrap();
1194
1195 // let in_multiline = disp.callbacks
1196 // .lock().unwrap()
1197 // .iter()
1198 // .any(|cb| cb.is_reading_multiline.load(Ordering::Relaxed));
1199
1200 // if !in_multiline {
1201 // // start of a new diagnostic
1202 // diags.push(diag);
1203 // } else {
1204 // // continuation → child of the last diagnostic
1205 // if let Some(parent) = diags.last_mut() {
1206 // parent.children.push(diag);
1207 // } else {
1208 // // no parent yet (unlikely), just push
1209 // diags.push(diag);
1210 // }
1211 // }
1212 }
1213 }
1214 if !has_match && !line.trim().is_empty() && !line.eq("...") {
1215 // If the line doesn't match any pattern, print it as is.
1216 println!("{}", line);
1217 }
1218 } else {
1219 println!("ALLLINES {}", line.trim()); //all lines
1220 }
1221 // if let Some(ref disp) = stderr_disp_clone {
1222 // if let Some(ret) = disp.dispatch(&line) {
1223 // if let Some(ref msg) = ret.message {
1224 // println!("DISPATCH RESULT {} {}", pid, msg);
1225 // }
1226 // }
1227 // }
1228 // // Here, we assume stderr is less structured. We add its length to runtime counter.
1229 // runtime_counter_stderr.fetch_add(line.len(), Ordering::Relaxed);
1230 // if let Some(total) = estimate_bytes {
1231 // let current = runtime_counter_stderr.load(Ordering::Relaxed);
1232 // let progress = (current as f64 / total as f64) * 100.0;
1233 // if let Some(ref pd) = progress_disp_clone_stderr {
1234 // pd.dispatch(&format!("Progress: {:.2}%", progress));
1235 // }
1236 // }
1237 }
1238 }
1239 // println!("{}: dave stderr end", pid);
1240 } //loop
1241 }); // End of stderr thread
1242
1243 let final_diagnostics = {
1244 let diag_lock = diagnostics.lock().unwrap();
1245 diag_lock.clone()
1246 };
1247 let pid = child.id();
1248 let (cmd, args) = builder_for_result.injected_args();
1249 let stats_snapshot = stats.lock().unwrap().clone();
1250 let result = CargoProcessResult {
1251 target_name: builder_for_closure.target_name.clone(),
1252 cmd: cmd,
1253 args: args,
1254 pid,
1255 exit_status: None,
1256 start_time: Some(start_time),
1257 build_finished_time: None,
1258 end_time: None,
1259 elapsed_time: None,
1260 build_elapsed: None,
1261 runtime_elapsed: None,
1262 stats: stats_snapshot.clone(),
1263 build_output_size: 0,
1264 runtime_output_size: 0,
1265 terminal_error: Some(tflag),
1266 diagnostics: final_diagnostics,
1267 is_filter: builder_for_closure.is_filter,
1268 is_could_not_compile: stats_snapshot.is_could_not_compile,
1269 };
1270 CargoProcessHandle {
1271 child,
1272 result,
1273 pid,
1274 stdout_handle,
1275 stderr_handle,
1276 start_time,
1277 stats,
1278 stdout_dispatcher,
1279 stderr_dispatcher,
1280 progress_dispatcher,
1281 stage_dispatcher,
1282 estimate_bytes,
1283 build_progress_counter,
1284 runtime_progress_counter,
1285 requested_exit: false,
1286 terminal_error_flag: terminal_flag,
1287 diagnostics,
1288 is_filter: builder_for_result.is_filter,
1289 }
1290 }
1291}