cargo_e/
e_command_builder.rs

1use regex::Regex;
2use std::collections::{HashMap, HashSet};
3use std::env;
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::mpsc::{channel, Sender};
9use std::time::SystemTime;
10use which::which;
11
12use crate::e_cargocommand_ext::CargoProcessResult;
13use crate::e_cargocommand_ext::{CargoCommandExt, CargoDiagnostic, CargoProcessHandle};
14use crate::e_eventdispatcher::{
15    CallbackResponse, CallbackType, CargoDiagnosticLevel, EventDispatcher,
16};
17use crate::e_runner::GLOBAL_CHILDREN;
18use crate::e_target::{CargoTarget, TargetKind, TargetOrigin};
19use std::sync::{Arc, Mutex};
20
21#[derive(Debug, Clone, PartialEq, Copy)]
22pub enum TerminalError {
23    NotConnected,
24    NoTerminal,
25    NoError,
26}
27
28impl Default for TerminalError {
29    fn default() -> Self {
30        TerminalError::NoError
31    }
32}
33
34/// A builder that constructs a Cargo command for a given target.
35#[derive(Clone, Debug)]
36pub struct CargoCommandBuilder {
37    pub target_name: String,
38    pub manifest_path: PathBuf,
39    pub args: Vec<String>,
40    pub subcommand: String,
41    pub pid: Option<u32>,
42    pub alternate_cmd: Option<String>,
43    pub execution_dir: Option<PathBuf>,
44    pub suppressed_flags: HashSet<String>,
45    pub stdout_dispatcher: Option<Arc<EventDispatcher>>,
46    pub stderr_dispatcher: Option<Arc<EventDispatcher>>,
47    pub progress_dispatcher: Option<Arc<EventDispatcher>>,
48    pub stage_dispatcher: Option<Arc<EventDispatcher>>,
49    pub terminal_error_flag: Arc<Mutex<bool>>,
50    pub sender: Option<Arc<Mutex<Sender<TerminalError>>>>,
51    pub diagnostics: Arc<Mutex<Vec<CargoDiagnostic>>>,
52    pub is_filter: bool,
53}
54
55impl std::fmt::Display for CargoCommandBuilder {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(
58            f,
59            "CargoCommandBuilder {{\n  target_name: {:?},\n  manifest_path: {:?},\n  args: {:?},\n  subcommand: {:?},\n  pid: {:?},\n  alternate_cmd: {:?},\n  execution_dir: {:?},\n  suppressed_flags: {:?},\n  is_filter: {:?}\n}}",
60            self.target_name,
61            self.manifest_path,
62            self.args,
63            self.subcommand,
64            self.pid,
65            self.alternate_cmd,
66            self.execution_dir,
67            self.suppressed_flags,
68            self.is_filter
69        )
70    }
71}
72impl Default for CargoCommandBuilder {
73    fn default() -> Self {
74        Self::new(
75            &String::new(),
76            &PathBuf::from("Cargo.toml"),
77            "run".into(),
78            false,
79        )
80    }
81}
82impl CargoCommandBuilder {
83    /// Creates a new, empty builder.
84    pub fn new(target_name: &str, manifest: &PathBuf, subcommand: &str, is_filter: bool) -> Self {
85        let (sender, _receiver) = channel::<TerminalError>();
86        let sender = Arc::new(Mutex::new(sender));
87        let mut builder = CargoCommandBuilder {
88            target_name: target_name.to_owned(),
89            manifest_path: manifest.clone(),
90            args: Vec::new(),
91            subcommand: subcommand.to_string(),
92            pid: None,
93            alternate_cmd: None,
94            execution_dir: None,
95            suppressed_flags: HashSet::new(),
96            stdout_dispatcher: None,
97            stderr_dispatcher: None,
98            progress_dispatcher: None,
99            stage_dispatcher: None,
100            terminal_error_flag: Arc::new(Mutex::new(false)),
101            sender: Some(sender),
102            diagnostics: Arc::new(Mutex::new(Vec::<CargoDiagnostic>::new())),
103            is_filter,
104        };
105        builder.set_default_dispatchers();
106
107        builder
108    }
109
110    // Switch to passthrough mode when the terminal error is detected
111    fn switch_to_passthrough_mode<F>(self: Arc<Self>, on_spawn: F) -> anyhow::Result<u32>
112    where
113        F: FnOnce(u32, CargoProcessHandle),
114    {
115        let mut command = self.build_command();
116
117        // Now, spawn the cargo process in passthrough mode
118        let cargo_process_handle = command.spawn_cargo_passthrough(Arc::clone(&self));
119        let pid = cargo_process_handle.pid;
120        // Notify observer
121        on_spawn(pid, cargo_process_handle);
122
123        Ok(pid)
124    }
125
126    // Set up the default dispatchers, which includes error detection
127    fn set_default_dispatchers(&mut self) {
128        if !self.is_filter {
129            // If this is a filter, we don't need to set up dispatchers
130            return;
131        }
132        let sender = self.sender.clone().unwrap();
133
134        let mut stdout_dispatcher = EventDispatcher::new();
135        stdout_dispatcher.add_callback(
136            r"listening on",
137            Box::new(|line, _captures, _state, stats, _prior_response| {
138                println!("(STDOUT) Dispatcher caught: {}", line);
139                // Use a regex to capture a URL from the line.
140                if let Ok(url_regex) = Regex::new(r"(http://[^\s]+)") {
141                    if let Some(url_caps) = url_regex.captures(line) {
142                        if let Some(url_match) = url_caps.get(1) {
143                            let url = url_match.as_str();
144                            // Call open::that on the captured URL.
145                            if let Err(e) = open::that_detached(url) {
146                                eprintln!("Failed to open URL: {}. Error: {}", url, e);
147                            } else {
148                                println!("Opened URL: {}", url);
149                            }
150                        }
151                    }
152                } else {
153                    eprintln!("Failed to create URL regex");
154                }
155                let mut stats = stats.lock().unwrap();
156                if stats.build_finished_time.is_none() {
157                    let now = SystemTime::now();
158                    stats.build_finished_time = Some(now);
159                }
160                None
161            }),
162        );
163
164        stdout_dispatcher.add_callback(
165            r"BuildFinished",
166            Box::new(|line, _captures, _state, stats, _prior_response| {
167                println!("******* {}", line);
168                let mut stats = stats.lock().unwrap();
169                if stats.build_finished_time.is_none() {
170                    let now = SystemTime::now();
171                    stats.build_finished_time = Some(now);
172                }
173                None
174            }),
175        );
176        stdout_dispatcher.add_callback(
177            r"server listening at:",
178            Box::new(|line, _captures, state, stats, _prior_response| {
179                // If we're not already in multiline mode, this is the initial match.
180                if !state.load(Ordering::Relaxed) {
181                    println!("Matched 'server listening at:' in: {}", line);
182                    state.store(true, Ordering::Relaxed);
183                    Some(CallbackResponse {
184                        callback_type: CallbackType::Note, // Choose as appropriate
185                        message: Some(format!("Started multiline mode after: {}", line)),
186                        file: None,
187                        line: None,
188                        column: None,
189                        suggestion: None,
190                        terminal_status: None,
191                    })
192                } else {
193                    // We are in multiline mode; process subsequent lines.
194                    println!("Multiline callback received: {}", line);
195                    // Use a regex to capture a URL from the line.
196                    let url_regex = match Regex::new(r"(http://[^\s]+)") {
197                        Ok(regex) => regex,
198                        Err(e) => {
199                            eprintln!("Failed to create URL regex: {}", e);
200                            return None;
201                        }
202                    };
203                    if let Some(url_caps) = url_regex.captures(line) {
204                        let url = url_caps.get(1).unwrap().as_str();
205                        // Call open::that on the captured URL.
206                        match open::that_detached(url) {
207                            Ok(_) => println!("Opened URL: {}", url),
208                            Err(e) => eprintln!("Failed to open URL: {}. Error: {}", url, e),
209                        }
210                        let mut stats = stats.lock().unwrap();
211                        if stats.build_finished_time.is_none() {
212                            let now = SystemTime::now();
213                            stats.build_finished_time = Some(now);
214                        }
215                        // End multiline mode.
216                        state.store(false, Ordering::Relaxed);
217                        Some(CallbackResponse {
218                            callback_type: CallbackType::Note, // Choose as appropriate
219                            message: Some(format!("Captured and opened URL: {}", url)),
220                            file: None,
221                            line: None,
222                            column: None,
223                            suggestion: None,
224                            terminal_status: None,
225                        })
226                    } else {
227                        None
228                    }
229                }
230            }),
231        );
232
233        let mut stderr_dispatcher = EventDispatcher::new();
234
235        let suggestion_mode = Arc::new(AtomicBool::new(false));
236        let suggestion_regex = Regex::new(r"^\s*(\d+)\s*\|\s*(.*)$").unwrap();
237        let warning_location: Arc<Mutex<Option<CallbackResponse>>> = Arc::new(Mutex::new(None));
238        let pending_diag: Arc<Mutex<Option<CargoDiagnostic>>> = Arc::new(Mutex::new(None));
239        let diagnostic_counts: Arc<Mutex<HashMap<CargoDiagnosticLevel, usize>>> =
240            Arc::new(Mutex::new(HashMap::new()));
241
242        let pending_d = Arc::clone(&pending_diag);
243        let counts = Arc::clone(&diagnostic_counts);
244
245        let diagnostics_arc = Arc::clone(&self.diagnostics);
246        // Callback for Rust panic messages (e.g., "thread 'main' panicked at ...")
247        stderr_dispatcher.add_callback(
248            r"^thread '([^']+)' panicked at (.+):(\d+):(\d+):$",
249            Box::new(|line, captures, multiline_flag, stats, prior_response| {
250                multiline_flag.store(false, Ordering::Relaxed);
251
252                if let Some(caps) = captures {
253                    multiline_flag.store(true, Ordering::Relaxed); // the next line is the panic message
254                    let thread = caps.get(1).map(|m| m.as_str()).unwrap_or("unknown");
255                    let message = caps.get(2).map(|m| m.as_str()).unwrap_or("unknown panic");
256                    let file = caps.get(3).map(|m| m.as_str()).unwrap_or("unknown file");
257                    let line_num = caps
258                        .get(4)
259                        .map(|m| m.as_str())
260                        .unwrap_or("0")
261                        .parse()
262                        .unwrap_or(0);
263                    let col_num = caps
264                        .get(5)
265                        .map(|m| m.as_str())
266                        .unwrap_or("0")
267                        .parse()
268                        .unwrap_or(0);
269                    println!("\n\n\n");
270                    println!("{}", line);
271                    // Use a global TTS instance via OnceCell for program lifetime
272
273                    #[cfg(feature = "uses_tts")]
274                    {
275                        let tts_mutex = crate::GLOBAL_TTS.get_or_init(|| {
276                            std::sync::Mutex::new(tts::Tts::default().expect("TTS engine failure"))
277                        });
278                        let mut tts = tts_mutex.lock().expect("Failed to lock TTS mutex");
279                        // Extract the filename without extension
280                        let filename = Path::new(message)
281                            .file_stem()
282                            .and_then(|s| s.to_str())
283                            .unwrap_or("unknown file");
284                        let speech =
285                            format!("thread {} panic, {} line {}", thread, filename, line_num);
286                        println!("TTS: {}", speech);
287                        let _ = tts.speak(&speech, false);
288                    }
289
290                    println!(
291                        "Panic detected: thread='{}', message='{}', file='{}:{}:{}'",
292                        thread, message, file, line_num, col_num
293                    );
294                    println!("\n\n\n");
295                    Some(CallbackResponse {
296                        callback_type: CallbackType::Error,
297                        message: Some(format!(
298                            "thread '{}' panicked at {} ({}:{}:{})",
299                            thread, message, file, line_num, col_num
300                        )),
301                        file: Some(message.to_string()),
302                        line: Some(file.parse::<usize>().unwrap_or(0)),
303                        column: Some(line_num),
304                        suggestion: None,
305                        terminal_status: None,
306                    })
307                } else {
308                    #[cfg(feature = "uses_tts")]
309                    {
310                        let tts_mutex = crate::GLOBAL_TTS.get_or_init(|| {
311                            std::sync::Mutex::new(tts::Tts::default().expect("TTS engine failure"))
312                        });
313                        let mut tts = tts_mutex.lock().expect("Failed to lock TTS mutex");
314                        // Extract the filename without extension
315                        let filename = Path::new(line)
316                            .file_stem()
317                            .and_then(|s| s.to_str())
318                            .unwrap_or("unknown file");
319
320                        let speech = format!("panic says {}", line);
321                        println!("TTS: {}", speech);
322                        let _ = tts.speak(&speech, true);
323
324                        if let Ok(e_window_path) = which("e_window") {
325                            // Compose a nice message for e_window's stdin
326                            let stats = stats.lock().unwrap();
327                            // Compose a table with cargo-e and its version, plus panic info
328                            let cargo_e_version = env!("CARGO_PKG_VERSION");
329
330                            let anchor: String = {
331                                // Try to parse the line as "file:line:col"
332                                let mut parts = line.split(':');
333                                let file = parts.next().unwrap_or("");
334                                let line_num = parts.next().unwrap_or("");
335                                let col_num = parts.next().unwrap_or("");
336
337                                let full_path = std::fs::canonicalize(file).unwrap_or_else(|_| {
338                                    file.into()
339
340                                    //  let manifest_dir = self.manifest_path.parent().unwrap_or_else(|| {
341                                    //      eprintln!("Failed to determine parent directory for manifest: {:?}", self.manifest_path);
342                                    //      Path::new(".")
343                                    //  });
344                                    //     let fallback_path = manifest_dir.join(file);
345                                    //     std::fs::canonicalize(&fallback_path).unwrap_or_else(|_| {
346                                    //         let parent_fallback_path = manifest_dir.join("../").join(file);
347                                    //         std::fs::canonicalize(&parent_fallback_path).unwrap_or_else(|_| {
348                                    //             eprintln!("Failed to resolve full path for: {} using ../", file);
349                                    //             file.into()
350                                    //         })
351                                    //     })
352                                });
353                                let stripped_file =
354                                    full_path.to_string_lossy().replace("\\?\\", "");
355                                // Only add anchor if we have a line and column
356                                if !stripped_file.is_empty()
357                                    && !line_num.is_empty()
358                                    && !col_num.is_empty()
359                                {
360                                    format!(
361                                        "\nanchor:code {}|\"{}\" --goto \"{}:{}:{}\"\n",
362                                        line, stripped_file, stripped_file, line_num, col_num
363                                    )
364                                } else {
365                                    let code_path =
366                                        which("code").unwrap_or_else(|_| "code".to_string().into());
367                                    if let Some(ref prior) = prior_response {
368                                        String::from(format!(
369                                            "\nanchor: code {} {} {}|\"{}\" --goto \"{}:{}:{}\"\n",
370                                            prior.file.as_deref().unwrap_or(""),
371                                            prior.line.unwrap_or(0),
372                                            prior.column.unwrap_or(0),
373                                            code_path.display(),
374                                            prior.file.as_deref().unwrap_or(""),
375                                            prior.line.unwrap_or(0),
376                                            prior.column.unwrap_or(0)
377                                        ))
378                                    } else {
379                                        String::from(format!(
380                                            "\nanchor: code X{} {} {}|\n",
381                                            file, line_num, col_num
382                                        ))
383                                    }
384                                }
385                            };
386
387                            let mut card = format!(
388                                "--title \"panic: {target}\" --width 400 --height 300\n\
389                        target | {target} | string\n\
390                        cargo-e | {version} | string\n\
391                        \n\
392                        panic: {target}\n{line}",
393                                target = stats.target_name,
394                                version = cargo_e_version,
395                                line = line
396                            );
397                            if let Some(prior) = prior_response {
398                                if let Some(msg) = &prior.message {
399                                    card = format!("{}\n{}", card, msg);
400                                }
401                            }
402                            if !anchor.is_empty() {
403                                card = format!("{}{}", card, anchor);
404                            }
405                            let child = std::process::Command::new(e_window_path)
406                                .stdin(std::process::Stdio::piped())
407                                .spawn();
408                            if let Ok(mut child) = child {
409                                if let Some(stdin) = child.stdin.as_mut() {
410                                    use std::io::Write;
411                                    let _ = stdin.write_all(card.as_bytes());
412                                }
413                            }
414                        }
415                    }
416                    None
417                }
418            }),
419        );
420
421        // Add a callback to detect "could not compile" errors
422        stderr_dispatcher.add_callback(
423            r"error: could not compile `(?P<crate_name>.+)` \((?P<due_to>.+)\) due to (?P<error_count>\d+) previous errors; (?P<warning_count>\d+) warnings emitted",
424            Box::new(|line, captures, _state, stats, _prior_response| {
425                println!("{}", line);
426            if let Some(caps) = captures {
427                // Extract dynamic fields from the error message
428                let crate_name = caps.name("crate_name").map(|m| m.as_str()).unwrap_or("unknown");
429                let due_to = caps.name("due_to").map(|m| m.as_str()).unwrap_or("unknown");
430                let error_count: usize = caps
431                .name("error_count")
432                .map(|m| m.as_str().parse().unwrap_or(0))
433                .unwrap_or(0);
434                let warning_count: usize = caps
435                .name("warning_count")
436                .map(|m| m.as_str().parse().unwrap_or(0))
437                .unwrap_or(0);
438
439                // Log the captured information (optional)
440                println!(
441                "Detected compilation failure: crate=`{}`, due_to=`{}`, errors={}, warnings={}",
442                crate_name, due_to, error_count, warning_count
443                );
444
445                // Set `is_could_not_compile` to true in the stats
446                let mut stats = stats.lock().unwrap();
447                stats.is_could_not_compile = true;
448            }
449            None // No callback response needed
450            }),
451        );
452
453        // Clone diagnostics_arc for this closure to avoid move
454        let diagnostics_arc_for_diag = Arc::clone(&diagnostics_arc);
455        stderr_dispatcher.add_callback(
456            r"^(?P<level>\w+)(\[(?P<error_code>E\d+)\])?:\s+(?P<msg>.+)$", // Regex for diagnostic line
457            Box::new(
458                move |_line, caps, _multiline_flag, _stats, _prior_response| {
459                    if let Some(caps) = caps {
460                        let mut counts = counts.lock().unwrap();
461                        // Create a PendingDiag and save the message
462                        let mut pending_diag = pending_d.lock().unwrap();
463                        let mut last_lineref = String::new();
464                        if let Some(existing_diag) = pending_diag.take() {
465                            let mut diags = diagnostics_arc_for_diag.lock().unwrap();
466                            last_lineref = existing_diag.lineref.clone();
467                            diags.push(existing_diag.clone());
468                        }
469                        log::trace!("Diagnostic line: {}", _line);
470                        let level = caps["level"].to_string(); // e.g., "warning", "error"
471                        let message = caps["msg"].to_string();
472                        // If the message contains "generated" followed by one or more digits,
473                        // then ignore this diagnostic by returning None.
474                        let re_generated = regex::Regex::new(r"generated\s+\d+").unwrap();
475                        if re_generated.is_match(&message) {
476                            log::trace!("Skipping generated diagnostic: {}", _line);
477                            return None;
478                        }
479
480                        let error_code = caps.name("error_code").map(|m| m.as_str().to_string());
481                        let diag_level = match level.as_str() {
482                            "error" => CargoDiagnosticLevel::Error,
483                            "warning" => CargoDiagnosticLevel::Warning,
484                            "help" => CargoDiagnosticLevel::Help,
485                            "note" => CargoDiagnosticLevel::Note,
486                            _ => {
487                                println!("Unknown diagnostic level: {}", level);
488                                return None; // Ignore unknown levels
489                            }
490                        };
491                        // Increment the count for this level
492                        *counts.entry(diag_level).or_insert(0) += 1;
493
494                        let current_count = counts.get(&diag_level).unwrap_or(&0);
495                        let diag = CargoDiagnostic {
496                            error_code: error_code.clone(),
497                            lineref: last_lineref.clone(),
498                            level: level.clone(),
499                            message,
500                            suggestion: None,
501                            help: None,
502                            note: None,
503                            uses_color: true,
504                            diag_num_padding: Some(2),
505                            diag_number: Some(*current_count),
506                        };
507
508                        // Save the new diagnostic
509                        *pending_diag = Some(diag);
510
511                        // Track the count of diagnostics for each level
512                        return Some(CallbackResponse {
513                            callback_type: CallbackType::LevelMessage, // Treat subsequent lines as warnings
514                            message: None,
515                            file: None,
516                            line: None,
517                            column: None,
518                            suggestion: None, // This is the suggestion part
519                            terminal_status: None,
520                        });
521                    } else {
522                        println!("No captures found in line: {}", _line);
523                        None
524                    }
525                },
526            ),
527        );
528        // Look-behind buffer for last 6 lines before backtrace
529        let look_behind = Arc::new(Mutex::new(Vec::<String>::new()));
530        {
531            let look_behind = Arc::clone(&look_behind);
532            // This callback runs for every stderr line to update the look-behind buffer
533            stderr_dispatcher.add_callback(
534                r"^(?P<msg>.*)$",
535                Box::new(move |line, _captures, _state, _stats, _prior_response| {
536                    let mut buf = look_behind.lock().unwrap();
537                    if line.trim().is_empty() {
538                        return None;
539                    }
540                    buf.push(line.to_string());
541                    if buf.len() > 6 {
542                        buf.remove(0);
543                    }
544                    None
545                }),
546            );
547        }
548
549        // --- Patch: Use look_behind before backtrace_lines in the note ---
550        {
551            let pending_diag = Arc::clone(&pending_diag);
552            let diagnostics_arc = Arc::clone(&diagnostics_arc);
553            let backtrace_mode = Arc::new(AtomicBool::new(false));
554            let backtrace_lines = Arc::new(Mutex::new(Vec::<String>::new()));
555            let look_behind = Arc::clone(&look_behind);
556            let stored_lines_behind = Arc::new(Mutex::new(Vec::<String>::new()));
557
558            // Enable backtrace mode when we see "stack backtrace:"
559            {
560                let backtrace_mode = Arc::clone(&backtrace_mode);
561                let backtrace_lines = Arc::clone(&backtrace_lines);
562                let stored_lines_behind = Arc::clone(&stored_lines_behind);
563                let look_behind = Arc::clone(&look_behind);
564                stderr_dispatcher.add_callback(
565                    r"stack backtrace:",
566                    Box::new(move |_line, _captures, _state, _stats, _prior_response| {
567                        backtrace_mode.store(true, Ordering::Relaxed);
568                        backtrace_lines.lock().unwrap().clear();
569                        // Save the current look_behind buffer into a shared stored_lines_behind for later use
570                        {
571                            let look_behind_buf = look_behind.lock().unwrap();
572                            let mut stored = stored_lines_behind.lock().unwrap();
573                            *stored = look_behind_buf.clone();
574                        }
575                        None
576                    }),
577                );
578            }
579
580            // Process backtrace lines, filter and summarize
581            {
582                let backtrace_mode = Arc::clone(&backtrace_mode);
583                let backtrace_lines = Arc::clone(&backtrace_lines);
584                let pending_diag = Arc::clone(&pending_diag);
585                let diagnostics_arc = Arc::clone(&diagnostics_arc);
586                let look_behind = Arc::clone(&look_behind);
587
588                // Regex for numbered backtrace line: "  0: type::path"
589                let re_number_type = Regex::new(r"^\s*(\d+):\s+(.*)$").unwrap();
590                // Regex for "at path:line"
591                let re_at_path = Regex::new(r"^\s*at\s+([^\s:]+):(\d+)").unwrap();
592
593                stderr_dispatcher.add_callback(
594                    r"^(?P<msg>.*)$",
595                    Box::new(
596                        move |mut line, _captures, _state, _stats, _prior_response| {
597                            if backtrace_mode.load(Ordering::Relaxed) {
598                                line = line.trim();
599                                // End of backtrace if empty line or new diagnostic/note
600                                if line.trim().is_empty()
601                                    || line.starts_with("note:")
602                                    || line.starts_with("error:")
603                                {
604                                    let mut bt_lines = Vec::new();
605                                    let mut skip_next = false;
606                                    let mut last_number_type: Option<(String, String)> = None;
607                                    for l in backtrace_lines.lock().unwrap().iter() {
608                                        if let Some(caps) = re_number_type.captures(l) {
609                                            // Save the (number, type) line, but don't push yet
610                                            last_number_type =
611                                                Some((caps[1].to_string(), caps[2].to_string()));
612                                            skip_next = true;
613                                        } else if skip_next && re_at_path.is_match(l) {
614                                            let path_caps = re_at_path.captures(l).unwrap();
615                                            let path = path_caps.get(1).unwrap().as_str();
616                                            let line_num = path_caps.get(2).unwrap().as_str();
617                                            if path.starts_with("/rustc")
618                                                || path.contains(".cargo")
619                                                || path.contains(".rustup")
620                                            {
621                                                // Skip both the number: type and the at line
622                                                // (do not push either)
623                                            } else {
624                                                // Push both the number: type and the at line, on the same line
625                                                if let Some((num, typ)) = last_number_type.take() {
626                                                    // Canonicalize the path if possible for better readability
627                                                    let path = match std::fs::canonicalize(path) {
628                                                        Ok(canon) => canon.display().to_string(),
629                                                        Err(_) => path.to_string(),
630                                                    };
631
632                                                    bt_lines.push(format!(
633                                                        "{}: {} @ {}:{}",
634                                                        num, typ, path, line_num
635                                                    ));
636                                                }
637                                            }
638                                            skip_next = false;
639                                        } else if let Some((num, typ)) = last_number_type.take() {
640                                            // If the previous number: type was not followed by an at line, push it
641                                            bt_lines.push(format!("{}: {}", num, typ));
642                                            if !l.trim().is_empty() {
643                                                bt_lines.push(l.clone());
644                                            }
645                                            skip_next = false;
646                                        } else if !l.trim().is_empty() {
647                                            bt_lines.push(l.clone());
648                                            skip_next = false;
649                                        }
650                                    }
651                                    if !bt_lines.is_empty() {
652                                        let mut pending_diag = pending_diag.lock().unwrap();
653                                        if let Some(ref mut diag) = *pending_diag {
654                                            // --- Insert stored_lines_behind lines before backtrace_lines ---
655                                            let stored_lines = {
656                                                let buf = stored_lines_behind.lock().unwrap();
657                                                buf.clone()
658                                            };
659                                            let note = diag.note.get_or_insert_with(String::new);
660                                            if !stored_lines.is_empty() {
661                                                note.push_str(&stored_lines.join("\n"));
662                                                note.push('\n');
663                                            }
664                                            note.push_str(&bt_lines.join("\n"));
665                                            let mut diags = diagnostics_arc.lock().unwrap();
666                                            diags.push(diag.clone());
667                                        }
668                                    }
669                                    backtrace_mode.store(false, Ordering::Relaxed);
670                                    backtrace_lines.lock().unwrap().clear();
671                                    return None;
672                                }
673
674                                // Only keep lines that are part of the backtrace
675                                if re_number_type.is_match(line) || re_at_path.is_match(line) {
676                                    backtrace_lines.lock().unwrap().push(line.to_string());
677                                }
678                                // Ignore further lines
679                                return None;
680                            }
681                            None
682                        },
683                    ),
684                );
685            }
686        }
687
688        // suggestion callback
689        {
690            let location_lock_clone = Arc::clone(&warning_location);
691            let suggestion_m = Arc::clone(&suggestion_mode);
692
693            // Suggestion callback that adds subsequent lines as suggestions
694            stderr_dispatcher.add_callback(
695                r"^(?P<msg>.*)$", // Capture all lines following the location
696                Box::new(
697                    move |line, _captures, _multiline_flag, _stats, _prior_response| {
698                        if suggestion_m.load(Ordering::Relaxed) {
699                            // Only process lines that match the suggestion format
700                            if let Some(caps) = suggestion_regex.captures(line.trim()) {
701                                // Capture the line number and code from the suggestion line
702                                // let line_num = caps[1].parse::<usize>().unwrap_or(0);
703                                let code = caps[2].to_string();
704
705                                // Lock the pending_diag to add the suggestion
706                                if let Ok(mut lock) = location_lock_clone.lock() {
707                                    if let Some(mut loc) = lock.take() {
708                                        // let file = loc.file.clone().unwrap_or_default();
709                                        // let col = loc.column.unwrap_or(0);
710
711                                        // Concatenate the suggestion line to the message
712                                        let mut msg = loc.message.unwrap_or_default();
713                                        msg.push_str(&format!("\n{}", code));
714
715                                        // Print the concatenated suggestion for debugging
716                                        // println!("daveSuggestion for {}:{}:{} - {}", file, line_num, col, msg);
717
718                                        // Update the location with the new concatenated message
719                                        loc.message = Some(msg.clone());
720                                        // println!("Updating location lock with new suggestion: {}", msg);
721                                        // Save the updated location back to shared state
722                                        // if let Ok(mut lock) = location_lock_clone.lock() {
723                                        // println!("Updating location lock with new suggestion: {}", msg);
724                                        lock.replace(loc);
725                                        // } else {
726                                        //     eprintln!("Failed to acquire lock for location_lock_clone");
727                                        // }
728                                    }
729                                    // return Some(CallbackResponse {
730                                    //     callback_type: CallbackType::Warning, // Treat subsequent lines as warnings
731                                    //     message: Some(msg.clone()),
732                                    //     file: Some(file),
733                                    //     line: Some(line_num),
734                                    //     column: Some(col),
735                                    //     suggestion: Some(msg),  // This is the suggestion part
736                                    //     terminal_status: None,
737                                    // });
738                                }
739                            }
740                        } else {
741                            // println!("Suggestion mode is not active. Ignoring line: {}", line);
742                        }
743
744                        None
745                    },
746                ),
747            );
748        }
749        {
750            let suggestion_m = Arc::clone(&suggestion_mode);
751            let pending_diag_clone = Arc::clone(&pending_diag);
752            let diagnostics_arc = Arc::clone(&self.diagnostics);
753            // Callback for handling when an empty line or new diagnostic is received
754            stderr_dispatcher.add_callback(
755                r"^\s*$", // Regex to capture empty line
756                Box::new(
757                    move |_line, _captures, _multiline_flag, _stats, _prior_response| {
758                        // println!("Empty line detected: {}", line);
759                        suggestion_m.store(false, Ordering::Relaxed);
760                        // End of current diagnostic: take and process it.
761                        if let Some(pending_diag) = pending_diag_clone.lock().unwrap().take() {
762                            //println!("{:?}", pending_diag);
763                            // Use diagnostics_arc instead of self.diagnostices
764                            let mut diags = diagnostics_arc.lock().unwrap();
765                            diags.push(pending_diag.clone());
766                        } else {
767                            // println!("No pending diagnostic to process.");
768                        }
769                        // Handle empty line scenario to end the current diagnostic processing
770                        // if let Some(pending_diag) = pending_diag_clone.lock().unwrap().take() {
771                        //     println!("{:?}", pending_diag);
772                        //     let mut diags = self.diagnostics.lock().unwrap();
773                        //     diags.push(pending_diag.clone());
774                        //                             // let diag = crate::e_eventdispatcher::convert_message_to_diagnostic(msg, &msg_str);
775                        //                             // diags.push(diag.clone());
776                        //                             // if let Some(ref sd) = stage_disp_clone {
777                        //                             //     sd.dispatch(&format!("Stage: Diagnostic occurred at {:?}", now));
778                        //                             // }
779                        //     // Handle the saved PendingDiag and its CallbackResponse
780                        //     // if let Some(callback_response) = pending_diag.callback_response {
781                        //     //     println!("End of Diagnostic: {:?}", callback_response);
782                        //     // }
783                        // } else {
784                        //     println!("No pending diagnostic to process.");
785                        // }
786
787                        None
788                    },
789                ),
790            );
791        }
792
793        // {
794        //     let pending_diag = Arc::clone(&pending_diag);
795        //     let location_lock = Arc::clone(&warning_location);
796        //     let suggestion_m = Arc::clone(&suggestion_mode);
797
798        // let suggestion_regex = Regex::new(r"^\s*(\d+)\s*\|\s*(.*)$").unwrap();
799
800        //     stderr_dispatcher.add_callback(
801        //     r"^\s*(\d+)\s*\|\s*(.*)$",  // Match suggestion line format
802        //     Box::new(move |line, _captures, _multiline_flag| {
803        //         if suggestion_m.load(Ordering::Relaxed) {
804        //             // Only process lines that match the suggestion format
805        //             if let Some(caps) = suggestion_regex.captures(line.trim()) {
806        //                 // Capture the line number and code from the suggestion line
807        //                 let line_num = caps[1].parse::<usize>().unwrap_or(0);
808        //                 let code = caps[2].to_string();
809
810        //                 // Lock the pending_diag to add the suggestion
811        //                 if let Some(mut loc) = location_lock.lock().unwrap().take() {
812        //                     println!("Suggestion line: {}", line);
813        //                     let file = loc.file.clone().unwrap_or_default();
814        //                     let col = loc.column.unwrap_or(0);
815
816        //                     // Concatenate the suggestion line to the message
817        //                     let mut msg = loc.message.unwrap_or_default();
818        //                     msg.push_str(&format!("\n{} | {}", line_num, code));  // Append the suggestion properly
819
820        //                     // Print the concatenated suggestion for debugging
821        //                     println!("Suggestion for {}:{}:{} - {}", file, line_num, col, msg);
822
823        //                     // Update the location with the new concatenated message
824        //                     loc.message = Some(msg.clone());
825
826        //                     // Save the updated location back to shared state
827        //                     location_lock.lock().unwrap().replace(loc);
828
829        //                     // return Some(CallbackResponse {
830        //                     //     callback_type: CallbackType::Warning, // Treat subsequent lines as warnings
831        //                     //     message: Some(msg.clone()),
832        //                     //     file: Some(file),
833        //                     //     line: Some(line_num),
834        //                     //     column: Some(col),
835        //                     //     suggestion: Some(msg),  // This is the suggestion part
836        //                     //     terminal_status: None,
837        //                     // });
838        //                 } else {
839        //                     println!("No location information available for suggestion line: {}", line);
840        //                 }
841        //             } else {
842        //                 println!("Suggestion line does not match expected format: {}", line);
843        //             }
844        //         } else {
845        //             println!("Suggestion mode is not active. Ignoring line: {}", line);
846        //         }
847
848        //         None
849        //     }),
850        // );
851
852        // }
853
854        {
855            let location_lock = Arc::clone(&warning_location);
856            let pending_diag = Arc::clone(&pending_diag);
857            let suggestion_mode = Arc::clone(&suggestion_mode);
858            stderr_dispatcher.add_callback(
859                r"^(?P<msg>.*)$", // Capture all lines following the location
860                Box::new(
861                    move |line, _captures, _multiline_flag, _stats, _prior_response| {
862                        // Lock the location to fetch the original diagnostic info
863                        if let Ok(location_guard) = location_lock.lock() {
864                            if let Some(loc) = location_guard.as_ref() {
865                                let file = loc.file.clone().unwrap_or_default();
866                                let line_num = loc.line.unwrap_or(0);
867                                let col = loc.column.unwrap_or(0);
868                                // println!("SUGGESTION: Suggestion for {}:{}:{} {}", file, line_num, col, line);
869
870                                // Only treat lines starting with | or numbers as suggestion lines
871                                if line.trim().starts_with('|')
872                                    || line.trim().starts_with(char::is_numeric)
873                                {
874                                    // Get the existing suggestion and append the new line
875                                    let suggestion = line.trim();
876
877                                    // Print the suggestion for debugging
878                                    // println!("Suggestion for {}:{}:{} - {}", file, line_num, col, suggestion);
879
880                                    // Lock the pending_diag and update its callback_response field
881                                    let mut pending_diag = match pending_diag.lock() {
882                                        Ok(lock) => lock,
883                                        Err(e) => {
884                                            eprintln!("Failed to acquire lock: {}", e);
885                                            return None; // Handle the error appropriately
886                                        }
887                                    };
888                                    if let Some(diag) = pending_diag.take() {
889                                        // If a PendingDiag already exists, update the existing callback response with the new suggestion
890                                        let mut diag = diag;
891
892                                        // Append the new suggestion to the existing one
893                                        if let Some(ref mut existing) = diag.suggestion {
894                                            diag.suggestion =
895                                                Some(format!("{}\n{}", existing, suggestion));
896                                        } else {
897                                            diag.suggestion = Some(suggestion.to_string());
898                                        }
899
900                                        // Update the shared state with the new PendingDiag
901                                        *pending_diag = Some(diag.clone());
902                                        return Some(CallbackResponse {
903                                            callback_type: CallbackType::Suggestion, // Treat subsequent lines as warnings
904                                            message: Some(
905                                                diag.clone().suggestion.clone().unwrap().clone(),
906                                            ),
907                                            file: Some(file),
908                                            line: Some(line_num),
909                                            column: Some(col),
910                                            suggestion: diag.clone().suggestion.clone(), // This is the suggestion part
911                                            terminal_status: None,
912                                        });
913                                    } else {
914                                        // println!("No pending diagnostic to process for suggestion line: {}", line);
915                                    }
916                                } else {
917                                    // If the line doesn't match the suggestion format, just return it as is
918                                    if line.trim().is_empty() {
919                                        // Ignore empty lines
920                                        suggestion_mode.store(false, Ordering::Relaxed);
921                                        return None;
922                                    }
923                                }
924                            } else {
925                                // println!("No location information available for suggestion line: {}", line);
926                            }
927                        }
928                        None
929                    },
930                ),
931            );
932        }
933
934        // 2) Location callback stores its response into that shared state
935        {
936            let pending_diag = Arc::clone(&pending_diag);
937            let warning_location = Arc::clone(&warning_location);
938            let location_lock = Arc::clone(&warning_location);
939            let suggestion_mode = Arc::clone(&suggestion_mode);
940            let manifest_path = self.manifest_path.clone();
941            stderr_dispatcher.add_callback(
942                // r"^\s*-->\s+(?P<file>[^:]+):(?P<line>\d+):(?P<col>\d+)$",
943                r"^\s*-->\s+(?P<file>.+?)(?::(?P<line>\d+))?(?::(?P<col>\d+))?\s*$",
944                Box::new(
945                    move |_line, caps, _multiline_flag, _stats, _prior_response| {
946                        log::trace!("Location line: {}", _line);
947                        // if multiline_flag.load(Ordering::Relaxed) {
948                        if let Some(caps) = caps {
949                            let file = caps["file"].to_string();
950                            let resolved_path = resolve_file_path(&manifest_path, &file);
951                            let file = resolved_path.to_str().unwrap_or_default().to_string();
952                            let line = caps["line"].parse::<usize>().unwrap_or(0);
953                            let column = caps["col"].parse::<usize>().unwrap_or(0);
954                            let resp = CallbackResponse {
955                                callback_type: CallbackType::Location,
956                                message: format!("{}:{}:{}", file, line, column).into(),
957                                file: Some(file.clone()),
958                                line: Some(line),
959                                column: Some(column),
960                                suggestion: None,
961                                terminal_status: None,
962                            };
963                            // Lock the pending_diag and update its callback_response field
964                            let mut pending_diag = pending_diag.lock().unwrap();
965                            if let Some(diag) = pending_diag.take() {
966                                // If a PendingDiag already exists, save the new callback response in the existing PendingDiag
967                                let mut diag = diag;
968                                diag.lineref = format!("{}:{}:{}", file, line, column); // Update the lineref
969                                                                                        // diag.save_callback_response(resp.clone()); // Save the callback response
970                                                                                        // Update the shared state with the new PendingDiag
971                                *pending_diag = Some(diag);
972                            }
973                            // Save it for the generic callback to see
974                            *warning_location.lock().unwrap() = Some(resp.clone());
975                            *location_lock.lock().unwrap() = Some(resp.clone());
976                            // Set suggestion mode to true as we've encountered a location line
977                            suggestion_mode.store(true, Ordering::Relaxed);
978                            return Some(resp.clone());
979                        } else {
980                            println!("No captures found in line: {}", _line);
981                        }
982                        // }
983                        None
984                    },
985                ),
986            );
987        }
988
989        // // 3) Note callback — attach note to pending_diag
990        {
991            let pending_diag = Arc::clone(&pending_diag);
992            stderr_dispatcher.add_callback(
993                r"^\s*=\s*note:\s*(?P<msg>.+)$",
994                Box::new(move |_line, caps, _state, _stats, _prior_response| {
995                    if let Some(caps) = caps {
996                        let mut pending_diag = pending_diag.lock().unwrap();
997                        if let Some(ref mut resp) = *pending_diag {
998                            // Prepare the new note with the blue prefix
999                            let new_note = format!("note: {}", caps["msg"].to_string());
1000
1001                            // Append or set the note
1002                            if let Some(existing_note) = &resp.note {
1003                                // If there's already a note, append with newline and the new note
1004                                resp.note = Some(format!("{}\n{}", existing_note, new_note));
1005                            } else {
1006                                // If no existing note, just set the new note
1007                                resp.note = Some(new_note);
1008                            }
1009                        }
1010                    }
1011                    None
1012                }),
1013            );
1014        }
1015
1016        // 4) Help callback — attach help to pending_diag
1017        {
1018            let pending_diag = Arc::clone(&pending_diag);
1019            stderr_dispatcher.add_callback(
1020                r"^\s*(?:\=|\|)\s*help:\s*(?P<msg>.+)$", // Regex to match both '=' and '|' before help:
1021                Box::new(move |_line, caps, _state, _stats, _prior_response| {
1022                    if let Some(caps) = caps {
1023                        let mut pending_diag = pending_diag.lock().unwrap();
1024                        if let Some(ref mut resp) = *pending_diag {
1025                            // Create the new help message with the orange "h:" prefix
1026                            let new_help =
1027                                format!("\x1b[38;5;214mhelp: {}\x1b[0m", caps["msg"].to_string());
1028
1029                            // Append or set the help message
1030                            if let Some(existing_help) = &resp.help {
1031                                // If there's already a help message, append with newline
1032                                resp.help = Some(format!("{}\n{}", existing_help, new_help));
1033                            } else {
1034                                // If no existing help message, just set the new one
1035                                resp.help = Some(new_help);
1036                            }
1037                        }
1038                    }
1039                    None
1040                }),
1041            );
1042        }
1043
1044        stderr_dispatcher.add_callback(
1045    r"(?:\x1b\[[0-9;]*[A-Za-z])*\s*Serving(?:\x1b\[[0-9;]*[A-Za-z])*\s+at\s+(http://[^\s]+)",
1046    Box::new(|line, captures, _state, stats , _prior_response| {
1047        if let Some(caps) = captures {
1048            let url = caps.get(1).unwrap().as_str();
1049            let url = url.replace("0.0.0.0", "127.0.0.1");
1050            println!("(STDERR) Captured URL: {}", url);
1051            match open::that_detached(&url) {
1052                Ok(_) => println!("(STDERR) Opened URL: {}",&url),
1053                Err(e) => eprintln!("(STDERR) Failed to open URL: {}. Error: {:?}", url, e),
1054            }
1055             let mut stats = stats.lock().unwrap();
1056             if stats.build_finished_time.is_none() {
1057              let now = SystemTime::now();
1058             stats.build_finished_time = Some(now);
1059             }
1060            Some(CallbackResponse {
1061                callback_type: CallbackType::OpenedUrl, // Choose as appropriate
1062                message: Some(format!("Captured and opened URL: {}", url)),
1063                file: None,
1064                line: None,
1065                column: None,
1066                suggestion: None,
1067                terminal_status: None,
1068            })
1069        } else {
1070            println!("(STDERR) No URL captured in line: {}", line);
1071            None
1072        }
1073    }),
1074);
1075
1076        let finished_flag = Arc::new(AtomicBool::new(false));
1077
1078        // 0) Finished‐profile summary callback
1079        {
1080            let finished_flag = Arc::clone(&finished_flag);
1081            stderr_dispatcher.add_callback(
1082        r"^Finished\s+`(?P<profile>[^`]+)`\s+profile\s+\[(?P<opts>[^\]]+)\]\s+target\(s\)\s+in\s+(?P<dur>[0-9.]+s)$",
1083        Box::new(move |_line, caps, _multiline_flag, stats, _prior_response | {
1084            if let Some(caps) = caps {
1085                finished_flag.store(true, Ordering::Relaxed);
1086                let profile = &caps["profile"];
1087                let opts    = &caps["opts"];
1088                let dur     = &caps["dur"];
1089                             let mut stats = stats.lock().unwrap();
1090             if stats.build_finished_time.is_none() {
1091              let now = SystemTime::now();
1092             stats.build_finished_time = Some(now);
1093             }
1094                Some(CallbackResponse {
1095                    callback_type: CallbackType::Note,
1096                    message: Some(format!("Finished `{}` [{}] in {}", profile, opts, dur)),
1097                    file: None, line: None, column: None, suggestion: None, terminal_status: None,
1098                })
1099            } else {
1100                None
1101            }
1102        }),
1103    );
1104        }
1105
1106        let summary_flag = Arc::new(AtomicBool::new(false));
1107        {
1108            let summary_flag = Arc::clone(&summary_flag);
1109            stderr_dispatcher.add_callback(
1110    r"^(?P<level>warning|error):\s+`(?P<name>[^`]+)`\s+\((?P<otype>lib|bin)\)\s+generated\s+(?P<count>\d+)\s+(?P<kind>warnings|errors).*run\s+`(?P<cmd>[^`]+)`\s+to apply\s+(?P<fixes>\d+)\s+suggestions",
1111    Box::new(move |_line, caps, multiline_flag, _stats, _prior_response | {
1112        let summary_flag = Arc::clone(&summary_flag);
1113        if let Some(caps) = caps {
1114            summary_flag.store(true, Ordering::Relaxed);
1115            // Always start fresh
1116            multiline_flag.store(false, Ordering::Relaxed);
1117
1118            let level    = &caps["level"];
1119            let name     = &caps["name"];
1120            let otype    = &caps["otype"];
1121            let count: usize = caps["count"].parse().unwrap_or(0);
1122            let kind     = &caps["kind"];   // "warnings" or "errors"
1123            let cmd      = caps["cmd"].to_string();
1124            let fixes: usize = caps["fixes"].parse().unwrap_or(0);
1125
1126            println!("SUMMARIZATION CALLBACK {}",
1127                    &format!("{}: `{}` ({}) generated {} {}; run `{}` to apply {} fixes",
1128                    level, name, otype, count, kind, cmd, fixes));
1129            Some(CallbackResponse {
1130                callback_type: CallbackType::Note,  // treat as informational
1131                message: Some(format!(
1132                    "{}: `{}` ({}) generated {} {}; run `{}` to apply {} fixes",
1133                    level, name, otype, count, kind, cmd, fixes
1134                )),
1135                file: None,
1136                line: None,
1137                column: None,
1138                suggestion: Some(cmd),
1139                terminal_status: None,
1140            })
1141        } else {
1142            None
1143        }
1144    }),
1145    );
1146        }
1147
1148        // {
1149        //     let summary_flag = Arc::clone(&summary_flag);
1150        //     let finished_flag = Arc::clone(&finished_flag);
1151        //     let warning_location = Arc::clone(&warning_location);
1152        //     // Warning callback for stdout.
1153        //     stderr_dispatcher.add_callback(
1154        //         r"^warning:\s+(?P<msg>.+)$",
1155        //         Box::new(
1156        //             move |line: &str, captures: Option<regex::Captures>, multiline_flag: Arc<AtomicBool>| {
1157        //                             // If summary or finished just matched, skip
1158        //             if summary_flag.swap(false, Ordering::Relaxed)
1159        //                 || finished_flag.swap(false, Ordering::Relaxed)
1160        //             {
1161        //                 return None;
1162        //             }
1163
1164        //         // 2) If this line *matches* the warning regex, handle as a new warning
1165        //         if let Some(caps) = captures {
1166        //             let msg = caps.name("msg").unwrap().as_str().to_string();
1167        //                    // 1) If a location was saved, print file:line:col – msg
1168        //             // println!("*WARNING detected: {:?}", msg);
1169        //                 multiline_flag.store(true, Ordering::Relaxed);
1170        //         if let Some(loc) = warning_location.lock().unwrap().take() {
1171        //                 let file = loc.file.unwrap_or_default();
1172        //                 let line_num = loc.line.unwrap_or(0);
1173        //                 let col  = loc.column.unwrap_or(0);
1174        //                 println!("{}:{}:{} - {}", file, line_num, col, msg);
1175        //                 return Some(CallbackResponse {
1176        //                     callback_type: CallbackType::Warning,
1177        //                     message: Some(msg.to_string()),
1178        //                     file: None, line: None, column: None, suggestion: None, terminal_status: None,
1179        //                 });
1180        //         }
1181        //             return Some(CallbackResponse {
1182        //                 callback_type: CallbackType::Warning,
1183        //                 message: Some(msg),
1184        //                 file: None,
1185        //                 line: None,
1186        //                 column: None,
1187        //                 suggestion: None,
1188        //                 terminal_status: None,
1189        //             });
1190        //         }
1191
1192        //                 // 3) Otherwise, if we’re in multiline mode, treat as continuation
1193        //         if multiline_flag.load(Ordering::Relaxed) {
1194        //             let text = line.trim();
1195        //             if text.is_empty() {
1196        //                 multiline_flag.store(false, Ordering::Relaxed);
1197        //                 return None;
1198        //             }
1199        //             // println!("   - {:?}", text);
1200        //             return Some(CallbackResponse {
1201        //                 callback_type: CallbackType::Warning,
1202        //                 message: Some(text.to_string()),
1203        //                 file: None,
1204        //                 line: None,
1205        //                 column: None,
1206        //                 suggestion: None,
1207        //                 terminal_status: None,
1208        //             });
1209        //         }
1210        //                     None
1211        //             },
1212        //         ),
1213        //     );
1214        // }
1215
1216        stderr_dispatcher.add_callback(
1217            r"IO\(Custom \{ kind: NotConnected",
1218            Box::new(move |line, _captures, _state, _stats, _prior_response| {
1219                println!("(STDERR) Terminal error detected: {:?}", &line);
1220                let result = if line.contains("NotConnected") {
1221                    TerminalError::NoTerminal
1222                } else {
1223                    TerminalError::NoError
1224                };
1225                let sender = sender.lock().unwrap();
1226                sender.send(result).ok();
1227                Some(CallbackResponse {
1228                    callback_type: CallbackType::Warning, // Choose as appropriate
1229                    message: Some(format!("Terminal Error: {}", line)),
1230                    file: None,
1231                    line: None,
1232                    column: None,
1233                    suggestion: None,
1234                    terminal_status: None,
1235                })
1236            }),
1237        );
1238        stderr_dispatcher.add_callback(
1239            r".*",
1240            Box::new(|line, _captures, _state, _stats, _prior_response| {
1241                log::trace!("stdraw[{:?}]", line);
1242                None // We're just printing, so no callback response is needed.
1243            }),
1244        );
1245        // need to implement autosense/filtering for tool installers; TBD
1246        // stderr_dispatcher.add_callback(
1247        //     r"Command 'perl' not found\. Is perl installed\?",
1248        //     Box::new(|line, _captures, _state, stats| {
1249        //     println!("cargo e sees a perl issue; maybe a prompt in the future or auto-resolution.");
1250        //     crate::e_autosense::auto_sense_perl();
1251        //     None
1252        //     }),
1253        // );
1254        // need to implement autosense/filtering for tool installers; TBD
1255        // stderr_dispatcher.add_callback(
1256        //     r"Error configuring OpenSSL build:\s+Command 'perl' not found\. Is perl installed\?",
1257        //     Box::new(|line, _captures, _state, stats| {
1258        //     println!("Detected OpenSSL build error due to missing 'perl'. Attempting auto-resolution.");
1259        //     crate::e_autosense::auto_sense_perl();
1260        //     None
1261        //     }),
1262        // );
1263        self.stderr_dispatcher = Some(Arc::new(stderr_dispatcher));
1264
1265        // let mut progress_dispatcher = EventDispatcher::new();
1266        // progress_dispatcher.add_callback(r"Progress", Box::new(|line, _captures,_state| {
1267        //     println!("(Progress) {}", line);
1268        //     None
1269        // }));
1270        // self.progress_dispatcher = Some(Arc::new(progress_dispatcher));
1271
1272        // let mut stage_dispatcher = EventDispatcher::new();
1273        // stage_dispatcher.add_callback(r"Stage:", Box::new(|line, _captures, _state| {
1274        //     println!("(Stage) {}", line);
1275        //     None
1276        // }));
1277        // self.stage_dispatcher = Some(Arc::new(stage_dispatcher));
1278    }
1279
1280    pub fn run<F>(self: Arc<Self>, on_spawn: F) -> anyhow::Result<u32>
1281    where
1282        F: FnOnce(u32, CargoProcessHandle),
1283    {
1284        if !self.is_filter {
1285            return self.switch_to_passthrough_mode(on_spawn);
1286        }
1287        let mut command = self.build_command();
1288
1289        let mut cargo_process_handle = command.spawn_cargo_capture(
1290            self.clone(),
1291            self.stdout_dispatcher.clone(),
1292            self.stderr_dispatcher.clone(),
1293            self.progress_dispatcher.clone(),
1294            self.stage_dispatcher.clone(),
1295            None,
1296        );
1297        cargo_process_handle.diagnostics = Arc::clone(&self.diagnostics);
1298        let pid = cargo_process_handle.pid;
1299
1300        // Notify observer
1301        on_spawn(pid, cargo_process_handle);
1302
1303        Ok(pid)
1304    }
1305
1306    // pub fn run(self: Arc<Self>) -> anyhow::Result<u32> {
1307    //     // Build the command using the builder's configuration
1308    //     let mut command = self.build_command();
1309
1310    //     // Spawn the cargo process handle
1311    //     let cargo_process_handle = command.spawn_cargo_capture(
1312    //         self.stdout_dispatcher.clone(),
1313    //         self.stderr_dispatcher.clone(),
1314    //         self.progress_dispatcher.clone(),
1315    //         self.stage_dispatcher.clone(),
1316    //         None,
1317    //     );
1318    // let pid = cargo_process_handle.pid;
1319    // let mut global = GLOBAL_CHILDREN.lock().unwrap();
1320    // global.insert(pid, Arc::new(Mutex::new(cargo_process_handle)));
1321    //     Ok(pid)
1322    // }
1323
1324    pub fn wait(self: Arc<Self>, pid: Option<u32>) -> anyhow::Result<CargoProcessResult> {
1325        let mut global = GLOBAL_CHILDREN.lock().unwrap();
1326        if let Some(pid) = pid {
1327            // Lock the global list of processes and attempt to find the cargo process handle directly by pid
1328            if let Some(cargo_process_handle) = global.get_mut(&pid) {
1329                let mut cargo_process_handle = cargo_process_handle.lock().unwrap();
1330
1331                // Wait for the process to finish and retrieve the result
1332                // println!("Waiting for process with PID: {}", pid);
1333                // let result = cargo_process_handle.wait();
1334                // println!("Process with PID {} finished", pid);
1335                loop {
1336                    println!("Waiting for process with PID: {}", pid);
1337
1338                    // Attempt to wait for the process, but don't block indefinitely
1339                    let status = cargo_process_handle.child.try_wait()?;
1340
1341                    // If the status is `Some(status)`, the process has finished
1342                    if let Some(status) = status {
1343                        if status.code() == Some(101) {
1344                            println!("Process with PID {} finished with cargo error", pid);
1345                        }
1346
1347                        // Check the terminal error flag and update the result if there is an error
1348                        if *cargo_process_handle.terminal_error_flag.lock().unwrap()
1349                            != TerminalError::NoError
1350                        {
1351                            let terminal_error =
1352                                *cargo_process_handle.terminal_error_flag.lock().unwrap();
1353                            cargo_process_handle.result.terminal_error = Some(terminal_error);
1354                        }
1355
1356                        let final_diagnostics = {
1357                            let diag_lock = self.diagnostics.lock().unwrap();
1358                            diag_lock.clone()
1359                        };
1360                        cargo_process_handle.result.diagnostics = final_diagnostics.clone();
1361                        cargo_process_handle.result.exit_status = Some(status);
1362                        cargo_process_handle.result.end_time = Some(SystemTime::now());
1363                        cargo_process_handle.result.elapsed_time = Some(
1364                            cargo_process_handle
1365                                .result
1366                                .end_time
1367                                .unwrap()
1368                                .duration_since(cargo_process_handle.result.start_time.unwrap())
1369                                .unwrap(),
1370                        );
1371                        println!(
1372                            "Process with PID {} finished {:?} {}",
1373                            pid,
1374                            status,
1375                            final_diagnostics.len()
1376                        );
1377                        return Ok(cargo_process_handle.result.clone());
1378                        // return Ok(CargoProcessResult { exit_status: status, ..Default::default() });
1379                    }
1380
1381                    // Sleep briefly to yield control back to the system and avoid blocking
1382                    std::thread::sleep(std::time::Duration::from_secs(1));
1383                }
1384
1385                // Return the result
1386                // match result {
1387                //     Ok(res) => Ok(res),
1388                //     Err(e) => Err(anyhow::anyhow!("Failed to wait for cargo process: {}", e).into()),
1389                // }
1390            } else {
1391                Err(anyhow::anyhow!(
1392                    "Process handle with PID {} not found in GLOBAL_CHILDREN",
1393                    pid
1394                )
1395                .into())
1396            }
1397        } else {
1398            Err(anyhow::anyhow!("No PID provided for waiting on cargo process").into())
1399        }
1400    }
1401
1402    // pub fn run_wait(self: Arc<Self>) -> anyhow::Result<CargoProcessResult> {
1403    //     // Run the cargo command and get the process handle (non-blocking)
1404    //     let pid = self.clone().run()?; // adds to global list of processes
1405    //     let result = self.wait(Some(pid)); // Wait for the process to finish
1406    //     // Remove the completed process from GLOBAL_CHILDREN
1407    //     let mut global = GLOBAL_CHILDREN.lock().unwrap();
1408    //     global.remove(&pid);
1409
1410    //     result
1411    // }
1412
1413    // Runs the cargo command using the builder's configuration.
1414    // pub fn run(&self) -> anyhow::Result<CargoProcessResult> {
1415    //     // Build the command using the builder's configuration
1416    //     let mut command = self.build_command();
1417
1418    //     // Now use the `spawn_cargo_capture` extension to run the command
1419    //     let mut cargo_process_handle = command.spawn_cargo_capture(
1420    //         self.stdout_dispatcher.clone(),
1421    //         self.stderr_dispatcher.clone(),
1422    //         self.progress_dispatcher.clone(),
1423    //         self.stage_dispatcher.clone(),
1424    //         None,
1425    //     );
1426
1427    //     // Wait for the process to finish and retrieve the results
1428    //     cargo_process_handle.wait().context("Failed to execute cargo process")
1429    // }
1430
1431    /// Configure the command based on the target kind.
1432    pub fn with_target(mut self, target: &CargoTarget) -> Self {
1433        if let Some(origin) = target.origin.clone() {
1434            println!("Target origin: {:?}", origin);
1435        } else {
1436            println!("Target origin is not set");
1437        }
1438        match target.kind {
1439            TargetKind::Unknown | TargetKind::Plugin => {
1440                return self;
1441            }
1442            TargetKind::Bench => {
1443                // // To run benchmarks, use the "bench" command.
1444                //  let exe_path = match which("bench") {
1445                //     Ok(path) => path,
1446                //     Err(err) => {
1447                //         eprintln!("Error: 'trunk' not found in PATH: {}", err);
1448                //         return self;
1449                //     }
1450                // };
1451                // self.alternate_cmd = Some("bench".to_string())
1452                self.args.push("bench".into());
1453                self.args.push(target.name.clone());
1454            }
1455            TargetKind::Test => {
1456                self.args.push("test".into());
1457                // Pass the target's name as a filter to run specific tests.
1458                self.args.push(target.name.clone());
1459            }
1460            TargetKind::UnknownExample
1461            | TargetKind::UnknownExtendedExample
1462            | TargetKind::Example
1463            | TargetKind::ExtendedExample => {
1464                self.args.push(self.subcommand.clone());
1465                //self.args.push("--message-format=json".into());
1466                self.args.push("--example".into());
1467                self.args.push(target.name.clone());
1468                self.args.push("--manifest-path".into());
1469                self.args.push(
1470                    target
1471                        .manifest_path
1472                        .clone()
1473                        .to_str()
1474                        .unwrap_or_default()
1475                        .to_owned(),
1476                );
1477                self = self.with_required_features(&target.manifest_path, target);
1478            }
1479            TargetKind::UnknownBinary
1480            | TargetKind::UnknownExtendedBinary
1481            | TargetKind::Binary
1482            | TargetKind::ExtendedBinary => {
1483                self.args.push(self.subcommand.clone());
1484                self.args.push("--bin".into());
1485                self.args.push(target.name.clone());
1486                self.args.push("--manifest-path".into());
1487                self.args.push(
1488                    target
1489                        .manifest_path
1490                        .clone()
1491                        .to_str()
1492                        .unwrap_or_default()
1493                        .to_owned(),
1494                );
1495                self = self.with_required_features(&target.manifest_path, target);
1496            }
1497            TargetKind::Manifest => {
1498                self.suppressed_flags.insert("quiet".to_string());
1499                self.args.push(self.subcommand.clone());
1500                self.args.push("--manifest-path".into());
1501                self.args.push(
1502                    target
1503                        .manifest_path
1504                        .clone()
1505                        .to_str()
1506                        .unwrap_or_default()
1507                        .to_owned(),
1508                );
1509            }
1510            TargetKind::ManifestTauriExample => {
1511                self.suppressed_flags.insert("quiet".to_string());
1512                self.args.push(self.subcommand.clone());
1513                self.args.push("--example".into());
1514                self.args.push(target.name.clone());
1515                self.args.push("--manifest-path".into());
1516                self.args.push(
1517                    target
1518                        .manifest_path
1519                        .clone()
1520                        .to_str()
1521                        .unwrap_or_default()
1522                        .to_owned(),
1523                );
1524                self = self.with_required_features(&target.manifest_path, target);
1525            }
1526            TargetKind::ScriptScriptisto => {
1527                let exe_path = match which("scriptisto") {
1528                    Ok(path) => path,
1529                    Err(err) => {
1530                        eprintln!("Error: 'scriptisto' not found in PATH: {}", err);
1531                        return self;
1532                    }
1533                };
1534                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1535                let candidate_opt = match &target.origin {
1536                    Some(TargetOrigin::SingleFile(path))
1537                    | Some(TargetOrigin::DefaultBinary(path)) => Some(path),
1538                    _ => None,
1539                };
1540                if let Some(candidate) = candidate_opt {
1541                    self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1542                    self.args.push(candidate.to_string_lossy().to_string());
1543                } else {
1544                    println!("No scriptisto origin found for: {:?}", target);
1545                }
1546            }
1547            TargetKind::ScriptRustScript => {
1548                let exe_path = match crate::e_installer::ensure_rust_script() {
1549                    Ok(p) => p,
1550                    Err(e) => {
1551                        eprintln!("{}", e);
1552                        return self;
1553                    }
1554                };
1555                let candidate_opt = match &target.origin {
1556                    Some(TargetOrigin::SingleFile(path))
1557                    | Some(TargetOrigin::DefaultBinary(path)) => Some(path),
1558                    _ => None,
1559                };
1560                if let Some(candidate) = candidate_opt {
1561                    self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1562                    if self.is_filter {
1563                        self.args.push("-c".into()); // ask for cargo output
1564                    }
1565                    self.args.push(candidate.to_string_lossy().to_string());
1566                } else {
1567                    println!("No rust-script origin found for: {:?}", target);
1568                }
1569            }
1570            TargetKind::ManifestTauri => {
1571                // First, locate the Cargo.toml using the existing function
1572                let manifest_path = crate::locate_manifest(true).unwrap_or_else(|_| {
1573                    eprintln!("Error: Unable to locate Cargo.toml file.");
1574                    std::process::exit(1);
1575                });
1576
1577                // Now, get the workspace parent from the manifest directory
1578                let manifest_dir = Path::new(&manifest_path)
1579                    .parent()
1580                    .unwrap_or(Path::new(".."));
1581
1582                // Ensure npm dependencies are handled at the workspace parent level
1583                let pnpm =
1584                    crate::e_installer::check_pnpm_and_install(manifest_dir).unwrap_or_else(|_| {
1585                        eprintln!("Error: Unable to check pnpm dependencies.");
1586                        PathBuf::new()
1587                    });
1588                if pnpm == PathBuf::new() {
1589                    crate::e_installer::check_npm_and_install(manifest_dir).unwrap_or_else(|_| {
1590                        eprintln!("Error: Unable to check npm dependencies.");
1591                    });
1592                }
1593
1594                self.suppressed_flags.insert("quiet".to_string());
1595                // Helper closure to check for tauri.conf.json in a directory.
1596                let has_tauri_conf = |dir: &Path| -> bool { dir.join("tauri.conf.json").exists() };
1597
1598                // Helper closure to check for tauri.conf.json and package.json in a directory.
1599                let has_file = |dir: &Path, filename: &str| -> bool { dir.join(filename).exists() };
1600                // Try candidate's parent (if origin is SingleFile or DefaultBinary).
1601                let candidate_dir_opt = match &target.origin {
1602                    Some(TargetOrigin::SingleFile(path))
1603                    | Some(TargetOrigin::DefaultBinary(path)) => path.parent(),
1604                    _ => None,
1605                };
1606
1607                if let Some(candidate_dir) = candidate_dir_opt {
1608                    if has_tauri_conf(candidate_dir) {
1609                        println!("Using candidate directory: {}", candidate_dir.display());
1610                        self.execution_dir = Some(candidate_dir.to_path_buf());
1611                    } else if let Some(manifest_parent) = target.manifest_path.parent() {
1612                        if has_tauri_conf(manifest_parent) {
1613                            println!("Using manifest parent: {}", manifest_parent.display());
1614                            self.execution_dir = Some(manifest_parent.to_path_buf());
1615                        } else if let Some(grandparent) = manifest_parent.parent() {
1616                            if has_tauri_conf(grandparent) {
1617                                println!("Using manifest grandparent: {}", grandparent.display());
1618                                self.execution_dir = Some(grandparent.to_path_buf());
1619                            } else {
1620                                println!("No tauri.conf.json found in candidate, manifest parent, or grandparent; defaulting to manifest parent: {}", manifest_parent.display());
1621                                self.execution_dir = Some(manifest_parent.to_path_buf());
1622                            }
1623                        } else {
1624                            println!("No grandparent for manifest; defaulting to candidate directory: {}", candidate_dir.display());
1625                            self.execution_dir = Some(candidate_dir.to_path_buf());
1626                        }
1627                    } else {
1628                        println!(
1629                            "No manifest parent found for: {}",
1630                            target.manifest_path.display()
1631                        );
1632                    }
1633                    // Check for package.json and run npm ls if found.
1634                    println!("Checking for package.json in: {}", candidate_dir.display());
1635                    if has_file(candidate_dir, "package.json") {
1636                        crate::e_installer::check_npm_and_install(candidate_dir).ok();
1637                    }
1638                } else if let Some(manifest_parent) = target.manifest_path.parent() {
1639                    if has_tauri_conf(manifest_parent) {
1640                        println!("Using manifest parent: {}", manifest_parent.display());
1641                        self.execution_dir = Some(manifest_parent.to_path_buf());
1642                    } else if let Some(grandparent) = manifest_parent.parent() {
1643                        if has_tauri_conf(grandparent) {
1644                            println!("Using manifest grandparent: {}", grandparent.display());
1645                            self.execution_dir = Some(grandparent.to_path_buf());
1646                        } else {
1647                            println!(
1648                                "No tauri.conf.json found; defaulting to manifest parent: {}",
1649                                manifest_parent.display()
1650                            );
1651                            self.execution_dir = Some(manifest_parent.to_path_buf());
1652                        }
1653                    }
1654                    // Check for package.json and run npm ls if found.
1655                    println!(
1656                        "Checking for package.json in: {}",
1657                        manifest_parent.display()
1658                    );
1659                    if has_file(manifest_parent, "package.json") {
1660                        crate::e_installer::check_npm_and_install(manifest_parent).ok();
1661                    }
1662                    if has_file(Path::new("."), "package.json") {
1663                        crate::e_installer::check_npm_and_install(manifest_parent).ok();
1664                    }
1665                } else {
1666                    println!(
1667                        "No manifest parent found for: {}",
1668                        target.manifest_path.display()
1669                    );
1670                }
1671                self.args.push("tauri".into());
1672                self.args.push("dev".into());
1673            }
1674            TargetKind::ManifestLeptos => {
1675                let readme_path = target
1676                    .manifest_path
1677                    .parent()
1678                    .map(|p| p.join("README.md"))
1679                    .filter(|p| p.exists())
1680                    .or_else(|| {
1681                        target
1682                            .manifest_path
1683                            .parent()
1684                            .map(|p| p.join("readme.md"))
1685                            .filter(|p| p.exists())
1686                    });
1687
1688                if let Some(readme) = readme_path {
1689                    if let Ok(mut file) = std::fs::File::open(&readme) {
1690                        let mut contents = String::new();
1691                        if file.read_to_string(&mut contents).is_ok()
1692                            && contents.contains("cargo leptos watch")
1693                        {
1694                            // Use cargo leptos watch
1695                            println!("Detected 'cargo leptos watch' in {}", readme.display());
1696                            crate::e_installer::ensure_leptos().unwrap_or_else(|_| {
1697                                eprintln!("Error: Unable to ensure leptos installation.");
1698                                PathBuf::new() // Return an empty PathBuf as a fallback
1699                            });
1700                            self.execution_dir =
1701                                target.manifest_path.parent().map(|p| p.to_path_buf());
1702
1703                            self.alternate_cmd = Some("cargo".to_string());
1704                            self.args.push("leptos".into());
1705                            self.args.push("watch".into());
1706                            self = self.with_required_features(&target.manifest_path, target);
1707                            if let Some(exec_dir) = &self.execution_dir {
1708                                if exec_dir.join("package.json").exists() {
1709                                    println!(
1710                                        "Found package.json in execution directory: {}",
1711                                        exec_dir.display()
1712                                    );
1713                                    crate::e_installer::check_npm_and_install(exec_dir).ok();
1714                                }
1715                            }
1716                            return self;
1717                        }
1718                    }
1719                }
1720
1721                // fallback to trunk
1722                let exe_path = match crate::e_installer::ensure_trunk() {
1723                    Ok(p) => p,
1724                    Err(e) => {
1725                        eprintln!("{}", e);
1726                        return self;
1727                    }
1728                };
1729
1730                if let Some(manifest_parent) = target.manifest_path.parent() {
1731                    println!("Manifest path: {}", target.manifest_path.display());
1732                    println!(
1733                        "Execution directory (same as manifest folder): {}",
1734                        manifest_parent.display()
1735                    );
1736                    self.execution_dir = Some(manifest_parent.to_path_buf());
1737                } else {
1738                    println!(
1739                        "No manifest parent found for: {}",
1740                        target.manifest_path.display()
1741                    );
1742                }
1743                if let Some(exec_dir) = &self.execution_dir {
1744                    if exec_dir.join("package.json").exists() {
1745                        println!(
1746                            "Found package.json in execution directory: {}",
1747                            exec_dir.display()
1748                        );
1749                        crate::e_installer::check_npm_and_install(exec_dir).ok();
1750                    }
1751                }
1752                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1753                self.args.push("serve".into());
1754                self.args.push("--open".into());
1755                self.args.push("--color".into());
1756                self.args.push("always".into());
1757                self = self.with_required_features(&target.manifest_path, target);
1758            }
1759            TargetKind::ManifestDioxus => {
1760                // For Dioxus targets, print the manifest path and set the execution directory
1761                let exe_path = match crate::e_installer::ensure_dx() {
1762                    Ok(path) => path,
1763                    Err(e) => {
1764                        eprintln!("Error locating `dx`: {}", e);
1765                        return self;
1766                    }
1767                };
1768                // to be the same directory as the manifest.
1769                if let Some(manifest_parent) = target.manifest_path.parent() {
1770                    println!("Manifest path: {}", target.manifest_path.display());
1771                    println!(
1772                        "Execution directory (same as manifest folder): {}",
1773                        manifest_parent.display()
1774                    );
1775                    self.execution_dir = Some(manifest_parent.to_path_buf());
1776                } else {
1777                    println!(
1778                        "No manifest parent found for: {}",
1779                        target.manifest_path.display()
1780                    );
1781                }
1782                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1783                self.args.push("serve".into());
1784                self = self.with_required_features(&target.manifest_path, target);
1785            }
1786            TargetKind::ManifestDioxusExample => {
1787                let exe_path = match crate::e_installer::ensure_dx() {
1788                    Ok(path) => path,
1789                    Err(e) => {
1790                        eprintln!("Error locating `dx`: {}", e);
1791                        return self;
1792                    }
1793                };
1794                // For Dioxus targets, print the manifest path and set the execution directory
1795                // to be the same directory as the manifest.
1796                if let Some(manifest_parent) = target.manifest_path.parent() {
1797                    println!("Manifest path: {}", target.manifest_path.display());
1798                    println!(
1799                        "Execution directory (same as manifest folder): {}",
1800                        manifest_parent.display()
1801                    );
1802                    self.execution_dir = Some(manifest_parent.to_path_buf());
1803                } else {
1804                    println!(
1805                        "No manifest parent found for: {}",
1806                        target.manifest_path.display()
1807                    );
1808                }
1809                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
1810                self.args.push("serve".into());
1811                self.args.push("--example".into());
1812                self.args.push(target.name.clone());
1813                self = self.with_required_features(&target.manifest_path, target);
1814            }
1815        }
1816        self
1817    }
1818
1819    /// Configure the command using CLI options.
1820    pub fn with_cli(mut self, cli: &crate::Cli) -> Self {
1821        if cli.quiet && !self.suppressed_flags.contains("quiet") {
1822            // Insert --quiet right after "run" if present.
1823            if let Some(pos) = self.args.iter().position(|arg| arg == &self.subcommand) {
1824                self.args.insert(pos + 1, "--quiet".into());
1825            } else {
1826                self.args.push("--quiet".into());
1827            }
1828        }
1829        if cli.release {
1830            // Insert --release right after the initial "run" command if applicable.
1831            // For example, if the command already contains "run", insert "--release" after it.
1832            if let Some(pos) = self.args.iter().position(|arg| arg == &self.subcommand) {
1833                self.args.insert(pos + 1, "--release".into());
1834            } else {
1835                // If not running a "run" command (like in the Tauri case), simply push it.
1836                self.args.push("--release".into());
1837            }
1838        }
1839        // Append extra arguments (if any) after a "--" separator.
1840        if !cli.extra.is_empty() {
1841            self.args.push("--".into());
1842            self.args.extend(cli.extra.iter().cloned());
1843        }
1844        self
1845    }
1846    /// Append required features based on the manifest, target kind, and name.
1847    /// This method queries your manifest helper function and, if features are found,
1848    /// appends "--features" and the feature list.
1849    pub fn with_required_features(mut self, manifest: &PathBuf, target: &CargoTarget) -> Self {
1850        if !self.args.contains(&"--features".to_string()) {
1851            if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
1852                manifest,
1853                &target.kind,
1854                &target.name,
1855            ) {
1856                self.args.push("--features".to_string());
1857                self.args.push(features);
1858            }
1859        }
1860        self
1861    }
1862
1863    /// Appends extra arguments to the command.
1864    pub fn with_extra_args(mut self, extra: &[String]) -> Self {
1865        if !extra.is_empty() {
1866            // Use "--" to separate Cargo arguments from target-specific arguments.
1867            self.args.push("--".into());
1868            self.args.extend(extra.iter().cloned());
1869        }
1870        self
1871    }
1872
1873    /// Builds the final vector of command-line arguments.
1874    pub fn build(self) -> Vec<String> {
1875        self.args
1876    }
1877
1878    pub fn is_compiler_target(&self) -> bool {
1879        let supported_subcommands = ["run", "build", "check", "leptos", "tauri"];
1880        if let Some(alternate) = &self.alternate_cmd {
1881            if alternate == "trunk" {
1882                return true;
1883            }
1884            if alternate != "cargo" {
1885                return false;
1886            }
1887        }
1888        if let Some(_) = self
1889            .args
1890            .iter()
1891            .position(|arg| supported_subcommands.contains(&arg.as_str()))
1892        {
1893            return true;
1894        }
1895        false
1896    }
1897
1898    pub fn injected_args(&self) -> (String, Vec<String>) {
1899        let mut new_args = self.args.clone();
1900        let supported_subcommands = [
1901            "run", "build", "test", "bench", "clean", "doc", "publish", "update",
1902        ];
1903
1904        if self.is_filter {
1905            if let Some(pos) = new_args
1906                .iter()
1907                .position(|arg| supported_subcommands.contains(&arg.as_str()))
1908            {
1909                // If the command is a supported subcommand like "cargo run", insert the JSON output format and color options.
1910                new_args.insert(pos + 1, "--message-format=json".into());
1911                new_args.insert(pos + 2, "--color".into());
1912                new_args.insert(pos + 3, "always".into());
1913            }
1914        }
1915
1916        let program = self.alternate_cmd.as_deref().unwrap_or("cargo").to_string();
1917        (program, new_args)
1918    }
1919
1920    pub fn print_command(&self) {
1921        let (program, new_args) = self.injected_args();
1922        println!("{} {}", program, new_args.join(" "));
1923    }
1924
1925    /// builds a std::process::Command.
1926    pub fn build_command(&self) -> Command {
1927        let (program, new_args) = self.injected_args();
1928
1929        let mut cmd = Command::new(program);
1930        cmd.args(new_args);
1931
1932        if let Some(dir) = &self.execution_dir {
1933            cmd.current_dir(dir);
1934        }
1935
1936        cmd
1937    }
1938    /// Runs the command and returns everything it printed (stdout + stderr),
1939    /// regardless of exit status.
1940    pub fn capture_output(&self) -> anyhow::Result<String> {
1941        // Build and run
1942        let mut cmd = self.build_command();
1943        let output = cmd
1944            .output()
1945            .map_err(|e| anyhow::anyhow!("Failed to spawn cargo process: {}", e))?;
1946
1947        // Decode both stdout and stderr lossily
1948        let mut all = String::new();
1949        all.push_str(&String::from_utf8_lossy(&output.stdout));
1950        all.push_str(&String::from_utf8_lossy(&output.stderr));
1951
1952        // Return the combined string, even if exit was !success
1953        Ok(all)
1954    }
1955}
1956/// Resolves a file path by:
1957///   1. If the path is relative, try to resolve it relative to the current working directory.
1958///   2. If that file does not exist, try to resolve it relative to the parent directory of the manifest path.
1959///   3. Otherwise, return the original relative path.
1960pub(crate) fn resolve_file_path(manifest_path: &PathBuf, file_str: &str) -> PathBuf {
1961    let file_path = Path::new(file_str);
1962    if file_path.is_relative() {
1963        // 1. Try resolving relative to the current working directory.
1964        if let Ok(cwd) = env::current_dir() {
1965            let cwd_path = cwd.join(file_path);
1966            if cwd_path.exists() {
1967                return cwd_path;
1968            }
1969        }
1970        // 2. Try resolving relative to the parent of the manifest path.
1971        if let Some(manifest_parent) = manifest_path.parent() {
1972            let parent_path = manifest_parent.join(file_path);
1973            if parent_path.exists() {
1974                return parent_path;
1975            }
1976        }
1977        // 3. Neither existed; return the relative path as-is.
1978        return file_path.to_path_buf();
1979    }
1980    file_path.to_path_buf()
1981}
1982
1983// --- Example usage ---
1984#[cfg(test)]
1985mod tests {
1986    use crate::e_target::TargetOrigin;
1987
1988    use super::*;
1989
1990    #[test]
1991    fn test_command_builder_example() {
1992        let target_name = "my_example".to_string();
1993        let target = CargoTarget {
1994            name: "my_example".to_string(),
1995            display_name: "My Example".to_string(),
1996            manifest_path: "Cargo.toml".into(),
1997            kind: TargetKind::Example,
1998            extended: true,
1999            toml_specified: false,
2000            origin: Some(TargetOrigin::SingleFile(PathBuf::from(
2001                "examples/my_example.rs",
2002            ))),
2003        };
2004
2005        let extra_args = vec!["--flag".to_string(), "value".to_string()];
2006
2007        let manifest_path = PathBuf::from("Cargo.toml");
2008        let args = CargoCommandBuilder::new(&target_name, &manifest_path, "run", false)
2009            .with_target(&target)
2010            .with_extra_args(&extra_args)
2011            .build();
2012
2013        // For an example target, we expect something like:
2014        // cargo run --example my_example --manifest-path Cargo.toml -- --flag value
2015        assert!(args.contains(&"--example".to_string()));
2016        assert!(args.contains(&"my_example".to_string()));
2017        assert!(args.contains(&"--manifest-path".to_string()));
2018        assert!(args.contains(&"Cargo.toml".to_string()));
2019        assert!(args.contains(&"--".to_string()));
2020        assert!(args.contains(&"--flag".to_string()));
2021        assert!(args.contains(&"value".to_string()));
2022    }
2023}