cargo_e/
e_runner.rs

1use crate::e_processmanager::ProcessManager;
2use crate::{e_target::TargetOrigin, prelude::*};
3// #[cfg(not(feature = "equivalent"))]
4// use ctrlc;
5use crate::e_cargocommand_ext::CargoProcessHandle;
6use crate::e_target::CargoTarget;
7#[cfg(feature = "uses_plugins")]
8use crate::plugins::plugin_api::Target as PluginTarget;
9use anyhow::Result;
10use once_cell::sync::Lazy;
11use regex::Regex;
12use std::collections::HashMap;
13use std::fs::File;
14use std::io::{self, BufRead};
15use std::path::Path;
16use std::process::Command;
17use std::sync::atomic::{AtomicUsize, Ordering};
18use std::thread;
19use which::which; // Adjust the import based on your project structure
20
21// lazy_static! {
22//     pub static ref GLOBAL_CHILDREN: Arc<Mutex<Vec<Arc<CargoProcessHandle>>>> = Arc::new(Mutex::new(Vec::new()));
23//     static CTRL_C_COUNT: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0));
24// }
25
26// pub static GLOBAL_CHILDREN:     Lazy<Arc<Mutex<Vec<Arc<Mutex<CargoProcessHandle>>>>>> = Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
27pub static GLOBAL_CHILDREN: Lazy<Arc<Mutex<HashMap<u32, Arc<Mutex<CargoProcessHandle>>>>>> =
28    Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
29
30static CTRL_C_COUNT: AtomicUsize = AtomicUsize::new(0);
31
32// Global shared container for the currently running child process.
33// pub static GLOBAL_CHILD: Lazy<Arc<Mutex<Option<Child>>>> = Lazy::new(|| Arc::new(Mutex::new(None)));
34// static CTRL_C_COUNT: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0));
35
36// pub static GLOBAL_CHILDREN: Lazy<Arc<Mutex<VecDeque<CargoProcessHandle>>>> = Lazy::new(|| Arc::new(Mutex::new(VecDeque::new())));
37/// Resets the Ctrl+C counter.
38/// This can be called to reset the count when starting a new program or at any other point.
39pub fn reset_ctrl_c_count() {
40    CTRL_C_COUNT.store(0, std::sync::atomic::Ordering::SeqCst);
41}
42
43// pub fn kill_last_process() -> Result<()> {
44//     let mut global = GLOBAL_CHILDREN.lock().unwrap();
45
46//     if let Some(mut child_handle) = global.pop_back() {
47//         // Kill the most recent process
48//         eprintln!("Killing the most recent child process...");
49//         let _ = child_handle.kill();
50//         Ok(())
51//     } else {
52//         eprintln!("No child processes to kill.");
53//         Err(anyhow::anyhow!("No child processes to kill").into())
54//     }
55// }
56
57pub fn take_process_results(pid: u32) -> Option<CargoProcessHandle> {
58    let mut global = GLOBAL_CHILDREN.lock().ok()?;
59    // Take ownership
60    // let handle = global.remove(&pid)?;
61    // let mut handle = handle.lock().ok()?;
62    let handle = global.remove(&pid)?;
63    // global.remove(&pid)
64    // This will succeed only if no other Arc exists
65    Arc::try_unwrap(handle)
66        .ok()? // fails if other Arc exists
67        .into_inner()
68        .ok() // fails if poisoned
69}
70
71pub fn get_process_results_in_place(
72    pid: u32,
73) -> Option<crate::e_cargocommand_ext::CargoProcessResult> {
74    let global = GLOBAL_CHILDREN.lock().ok()?; // MutexGuard<HashMap>
75    let handle = global.get(&pid)?.clone(); // Arc<Mutex<CargoProcessHandle>>
76    let handle = handle.lock().ok()?; // MutexGuard<CargoProcessHandle>
77    Some(handle.result.clone()) // ✅ return the result field
78}
79
80// /// Registers a global Ctrl+C handler that interacts with the `GLOBAL_CHILDREN` process container.
81// pub fn register_ctrlc_handler() -> Result<(), Box<dyn Error>> {
82//     println!("Registering Ctrl+C handler...");
83//     ctrlc::set_handler(move || {
84//          let count = CTRL_C_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
85//         {
86//             eprintln!("Ctrl+C pressed");
87
88//     // lock only ONE mutex safely
89//     if let Ok(mut global) = GLOBAL_CHILDREN.try_lock() {
90//             // let mut global = GLOBAL_CHILDREN.lock().unwrap();
91//             eprintln!("Ctrl+C got lock on global container");
92
93//             // If there are processes in the global container, terminate the most recent one
94//             if let Some((pid, child_handle)) = global.iter_mut().next() {
95//                 eprintln!("Ctrl+C pressed, terminating the child process with PID: {}", pid);
96
97//                 // Lock the child process and kill it
98//                 let mut child_handle = child_handle.lock().unwrap();
99//                 if child_handle.requested_exit {
100//                     eprintln!("Child process is already requested kill...");
101//                 } else {
102//                     eprintln!("Child process is not running, no need to kill.");
103//                     child_handle.requested_exit=true;
104//                     println!("Killing child process with PID: {}", pid);
105//                     let _ = child_handle.kill();  // Attempt to kill the process
106//                     println!("Killed child process with PID: {}", pid);
107
108//                     reset_ctrl_c_count();
109//                     return;  // Exit after successfully terminating the process
110//                 }
111
112//                 // Now remove the process from the global container
113//                 // let pid_to_remove = *pid;
114
115//                 // // Reacquire the lock after killing and remove the process from global
116//                 // drop(global);  // Drop the first borrow
117
118//                 // // Re-lock global and safely remove the entry using the pid
119//                 // let mut global = GLOBAL_CHILDREN.lock().unwrap();
120//                 // global.remove(&pid_to_remove); // Remove the process entry by PID
121//                 // println!("Removed process with PID: {}", pid_to_remove);
122//             }
123
124//     } else {
125//         eprintln!("Couldn't acquire GLOBAL_CHILDREN lock safely");
126//     }
127
128/// Registers a global Ctrl+C handler that uses the process manager.
129pub fn register_ctrlc_handler(process_manager: Arc<ProcessManager>) -> Result<(), Box<dyn Error>> {
130    println!("Registering Ctrl+C handler...");
131    ctrlc::set_handler(move || {
132        let count = CTRL_C_COUNT.fetch_add(1, Ordering::SeqCst) + 1;
133        eprintln!("Ctrl+C pressed");
134
135        // Use the process manager's API to handle killing
136        match process_manager.kill_one() {
137            Ok(true) => {
138                eprintln!("Process was successfully terminated.");
139                reset_ctrl_c_count();
140                return; // Exit handler early after a successful kill.
141            }
142            Ok(false) => {
143                eprintln!("No process was killed this time.");
144            }
145            Err(e) => {
146                eprintln!("Error killing process: {:?}", e);
147            }
148        }
149
150        // Handle Ctrl+C count logic for exiting the program.
151        if count == 3 {
152            eprintln!("Ctrl+C pressed 3 times with no child process running. Exiting.");
153            std::process::exit(0);
154        } else if count == 2 {
155            eprintln!("Ctrl+C pressed 2 times, press one more to exit.");
156        } else {
157            eprintln!("Ctrl+C pressed {} times, no child process running.", count);
158        }
159    })?;
160    Ok(())
161}
162
163//         }
164
165//         // Now handle the Ctrl+C count and display messages
166//         // If Ctrl+C is pressed 3 times without any child process, exit the program.
167//         if count == 3 {
168//             eprintln!("Ctrl+C pressed 3 times with no child process running. Exiting.");
169//             std::process::exit(0);
170//         } else if count == 2 {
171//             // Notify that one more Ctrl+C will exit the program.
172//             eprintln!("Ctrl+C pressed 2 times, press one more to exit.");
173//         } else {
174//             eprintln!("Ctrl+C pressed {} times, no child process running.", count);
175//         }
176//     })?;
177//     Ok(())
178// }
179
180// /// Registers a global Ctrl+C handler once.
181// /// The handler checks GLOBAL_CHILD and kills the child process if present.
182// pub fn register_ctrlc_handler() -> Result<(), Box<dyn Error>> {
183//     ctrlc::set_handler(move || {
184//         let mut count_lock = CTRL_C_COUNT.lock().unwrap();
185//         *count_lock += 1;
186
187//         let count = *count_lock;
188
189//         // If there is no child process and Ctrl+C is pressed 3 times, exit the program
190//         if count == 3 {
191//             eprintln!("Ctrl+C pressed 3 times with no child process running. Exiting.");
192//             exit(0);
193//         } else {
194//             let mut child_lock = GLOBAL_CHILD.lock().unwrap();
195//             if let Some(child) = child_lock.as_mut() {
196//                 eprintln!(
197//                     "Ctrl+C pressed {} times, terminating running child process...",
198//                     count
199//                 );
200//                 let _ = child.kill();
201//             } else {
202//                 eprintln!("Ctrl+C pressed {} times, no child process running.", count);
203//             }
204//         }
205//     })?;
206//     Ok(())
207// }
208
209/// Asynchronously launches the GenAI summarization example for the given target.
210/// It builds the command using the target's manifest path as the "origin" argument.
211pub async fn open_ai_summarize_for_target(target: &CargoTarget) {
212    // Extract the origin path from the target (e.g. the manifest path).
213    let origin_path = match &target.origin {
214        Some(TargetOrigin::SingleFile(path)) | Some(TargetOrigin::DefaultBinary(path)) => path,
215        _ => return,
216    };
217
218    let exe_path = match which("cargoe_ai_summarize") {
219        Ok(path) => path,
220        Err(err) => {
221            eprintln!("Error: 'cargoe_ai_summarize' not found in PATH: {}", err);
222            return;
223        }
224    };
225    // Build the command based on the platform.
226    // let mut cmd = if cfg!(target_os = "windows") {
227    //     let command_str = format!(
228    //         "e_ai_summarize --streaming --stdin {}",
229    //         origin_path.as_os_str().to_string_lossy()
230    //     );
231    //     println!("Running command: {}", command_str);
232    //     let mut command = Command::new("cmd");
233    //     command.args(["/C", &command_str]);
234    //     command
235    // } else {
236    let mut cmd = Command::new(exe_path);
237    cmd.arg("--streaming");
238    cmd.arg("--stdin");
239    // cmd.arg(".");
240    cmd.arg(origin_path);
241    // command
242    // };
243
244    cmd.stdin(Stdio::inherit())
245        .stdout(Stdio::inherit())
246        .stderr(Stdio::inherit());
247
248    // Spawn the command and wait for it to finish.
249    let child = cmd.spawn();
250    let status = child
251        .expect("Failed to spawn command")
252        .wait()
253        .expect("Failed to wait for command");
254
255    if !status.success() {
256        eprintln!("Command exited with status: {}", status);
257    }
258
259    // // Build the command to run the example.
260    // let output = if cfg!(target_os = "windows") {
261    //     let command_str = format!("e_ai_summarize --stdin {}", origin_path.as_os_str().to_string_lossy());
262    //     println!("Running command: {}", command_str);
263    //     Command::new("cmd")
264    //         .args([
265    //             "/C",
266    //             command_str.as_str(),
267    //         ])
268    //         .output()
269    // } else {
270    //     Command::new("e_ai_summarize")
271    //         .args([origin_path])
272    //         .output()
273    // };
274
275    // // Handle the output from the command.
276    // match output {
277    //     Ok(output) if output.status.success() => {
278    //         // The summarization example ran successfully.
279    //         println!("----
280    //         {}", String::from_utf8_lossy(&output.stdout));
281    //     }
282    //     Ok(output) => {
283    //         let msg = format!(
284    //             "Error running summarization example:\nstdout: {}\nstderr: {}",
285    //             String::from_utf8_lossy(&output.stdout),
286    //             String::from_utf8_lossy(&output.stderr)
287    //         );
288    //         error!("{}", msg);
289    //     }
290    //     Err(e) => {
291    //         let msg = format!("Failed to execute summarization command: {}", e);
292    //         error!("{}", msg);
293    //     }
294    // }
295}
296
297fn library_hint(lib: &str) -> &str {
298    match lib {
299        "javascriptcoregtk-4.1" => "libjavascriptcoregtk-4.1-dev",
300        "libsoup-3.0" => "libsoup-3.0-dev",
301        "webkit2gtk-4.1" => "libwebkit2gtk-4.1-dev",
302        "openssl" => "libssl-dev",
303        _ => lib, // Fallback, assume same name
304    }
305}
306
307/// In "equivalent" mode, behave exactly like "cargo run --example <name>"
308#[cfg(feature = "equivalent")]
309pub fn run_equivalent_example(
310    cli: &crate::Cli,
311) -> Result<std::process::ExitStatus, Box<dyn Error>> {
312    // In "equivalent" mode, behave exactly like "cargo run --example <name>"
313    let mut cmd = Command::new("cargo");
314    cmd.args([
315        "run",
316        "--example",
317        cli.explicit_example.as_deref().unwrap_or(""),
318    ]);
319    if !cli.extra.is_empty() {
320        cmd.arg("--").args(cli.extra.clone());
321    }
322    // Inherit the standard input (as well as stdout/stderr) so that input is passed through.
323    use std::process::Stdio;
324    cmd.stdin(Stdio::inherit())
325        .stdout(Stdio::inherit())
326        .stderr(Stdio::inherit());
327
328    let status = cmd.status()?;
329    std::process::exit(status.code().unwrap_or(1));
330}
331
332/// Runs the given example (or binary) target.
333pub fn run_example(
334    manager: Arc<ProcessManager>,
335    cli: &crate::Cli,
336    target: &crate::e_target::CargoTarget,
337) -> anyhow::Result<Option<std::process::ExitStatus>> {
338    crate::e_runall::set_rustflags_if_quiet(cli.quiet);
339    // Retrieve the current package name at compile time.
340    let current_bin = env!("CARGO_PKG_NAME");
341
342    // Avoid running our own binary.
343    if target.kind == crate::e_target::TargetKind::Binary && target.name == current_bin {
344        println!(
345            "Skipping automatic run: {} is the same as the running binary",
346            target.name
347        );
348        return Ok(None);
349    }
350
351    // If this is a plugin-provided target, execute it via the plugin's in-process run
352    #[cfg(feature = "uses_plugins")]
353    if target.kind == crate::e_target::TargetKind::Plugin {
354        if let Some(crate::e_target::TargetOrigin::Plugin { plugin_path, .. }) = &target.origin {
355            // Current working directory
356            let cwd = std::env::current_dir()?;
357            // Load the plugin directly based on its file extension
358            let ext = plugin_path
359                .extension()
360                .and_then(|s| s.to_str())
361                .unwrap_or("");
362            let plugin: Box<dyn crate::plugins::plugin_api::Plugin> = match ext {
363                "lua" => {
364                    #[cfg(feature = "uses_lua")]
365                    {
366                        Box::new(crate::plugins::lua_plugin::LuaPlugin::load(
367                            plugin_path,
368                            cli,
369                            manager.clone(),
370                        )?)
371                    }
372                    #[cfg(not(feature = "uses_lua"))]
373                    {
374                        return Err(anyhow::anyhow!("Lua plugin support is not enabled"));
375                    }
376                }
377                "rhai" => {
378                    #[cfg(feature = "uses_rhai")]
379                    {
380                        Box::new(crate::plugins::rhai_plugin::RhaiPlugin::load(
381                            plugin_path,
382                            cli,
383                            manager.clone(),
384                        )?)
385                    }
386                    #[cfg(not(feature = "uses_rhai"))]
387                    {
388                        return Err(anyhow::anyhow!("Rhai plugin support is not enabled"));
389                    }
390                }
391                "wasm" => {
392                    #[cfg(feature = "uses_wasm")]
393                    {
394                        if let Some(wp) =
395                            crate::plugins::wasm_plugin::WasmPlugin::load(plugin_path)?
396                        {
397                            Box::new(wp)
398                        } else {
399                            // Fallback to generic export plugin
400                            Box::new(
401                                crate::plugins::wasm_export_plugin::WasmExportPlugin::load(
402                                    plugin_path,
403                                )?
404                                .expect("Failed to load export plugin"),
405                            )
406                        }
407                    }
408                    #[cfg(not(feature = "uses_wasm"))]
409                    {
410                        return Err(anyhow::anyhow!("WASM plugin support is not enabled"));
411                    }
412                }
413                "dll" => {
414                    #[cfg(feature = "uses_wasm")]
415                    {
416                        Box::new(
417                            crate::plugins::wasm_export_plugin::WasmExportPlugin::load(
418                                plugin_path,
419                            )?
420                            .expect("Failed to load export plugin"),
421                        )
422                    }
423                    #[cfg(not(feature = "uses_wasm"))]
424                    {
425                        return Err(anyhow::anyhow!("WASM export plugin support is not enabled"));
426                    }
427                }
428                other => {
429                    return Err(anyhow::anyhow!("Unknown plugin extension: {}", other));
430                }
431            };
432            // Run the plugin and capture output
433            let plugin_target = PluginTarget::from(target.clone());
434            let output = plugin.run(&cwd, &plugin_target)?;
435            // Print exit code and subsequent output lines
436            if !output.is_empty() {
437                if let Ok(code) = output[0].parse::<i32>() {
438                    eprintln!("Plugin exited with code: {}", code);
439                }
440                for line in &output[1..] {
441                    println!("{}", line);
442                }
443            }
444            return Ok(None);
445        }
446    }
447    // Not a plugin, continue with standard cargo invocation
448    let manifest_path = PathBuf::from(target.manifest_path.clone());
449    // Build the command using the CargoCommandBuilder.
450    let mut builder = crate::e_command_builder::CargoCommandBuilder::new(
451        &target.name,
452        &manifest_path,
453        &cli.subcommand,
454        cli.filter,
455        cli.cached,
456    )
457    .with_target(target)
458    .with_required_features(&target.manifest_path, target)
459    .with_cli(cli);
460
461    // Build the command.
462    let mut cmd = builder.clone().build_command();
463
464    // Before spawning, determine the directory to run from.
465    // If a custom execution directory was set (e.g. for Tauri targets), that is used.
466    // Otherwise, if the target is extended, run from its parent directory.
467    if let Some(ref exec_dir) = builder.execution_dir {
468        cmd.current_dir(exec_dir);
469    } else if target.extended {
470        if let Some(dir) = target.manifest_path.parent() {
471            cmd.current_dir(dir);
472        }
473    }
474
475    // Print the full command for debugging.
476    let full_command = format!(
477        "{} {}",
478        cmd.get_program().to_string_lossy(),
479        cmd.get_args()
480            .map(|arg| arg.to_string_lossy())
481            .collect::<Vec<_>>()
482            .join(" ")
483    );
484    println!("Running: {}", full_command);
485
486    // Check if the manifest triggers the workspace error.
487    let maybe_backup = crate::e_manifest::maybe_patch_manifest_for_run(&target.manifest_path)?;
488    let a_blder = Arc::new(builder.clone());
489    let pid = a_blder.run(|_pid, handle| {
490        manager.register(handle);
491    })?;
492    let result = manager.wait(pid, None)?;
493    // println!("HERE IS THE RESULT!{} {:?}",pid,manager.get(pid));
494    // println!("\n\nHERE IS THE RESULT!{} {:?}",pid,result);
495    if result
496        .exit_status
497        .map_or(false, |status| status.code() == Some(101))
498    {
499        println!(
500            "ProcessManager senses pid {} cargo error, running again to capture and analyze",
501            pid
502        );
503        match builder.clone().capture_output() {
504            Ok(output) => {
505                let system_lib_regex = Regex::new(
506                    r"\s*The system library `([^`]+)` required by crate `([^`]+)` was not found\.",
507                )
508                .unwrap();
509
510                if let Some(captures) = system_lib_regex.captures(&output) {
511                    let library = &captures[1];
512                    let crate_name = &captures[2];
513                    println!(
514                        "cargo-e detected missing system library '{}' required by crate '{}'.",
515                        library, crate_name
516                    );
517
518                    // Suggest installation based on common package managers
519                    println!(
520                        "You might need to install '{}' via your system package manager.",
521                        library
522                    );
523                    println!("For example:");
524
525                    println!(
526                        "  • Debian/Ubuntu: sudo apt install {}",
527                        library_hint(library)
528                    );
529                    println!("  • Fedora: sudo dnf install {}", library_hint(library));
530                    println!("  • Arch: sudo pacman -S {}", library_hint(library));
531                    println!(
532                        "  • macOS (Homebrew): brew install {}",
533                        library_hint(library)
534                    );
535                    std::process::exit(0);
536                } else if output.contains("error: failed to load manifest for workspace member") {
537                    println!("cargo-e error: failed to load manifest for workspace member, please check your workspace configuration.");
538                    println!("cargo-e autorecovery: removing manfifest path from argument and changing to parent of Cargo.toml.");
539                    let cwd = target
540                        .manifest_path
541                        .parent()
542                        .unwrap_or_else(|| Path::new("."));
543                    // Rebuild the command with the new cwd
544                    builder.execution_dir = Some(cwd.to_path_buf());
545                    // Remove --manifest-path and its associated value from the args array
546                    if let Some(pos) = builder.args.iter().position(|arg| arg == "--manifest-path")
547                    {
548                        // Remove --manifest-path and the next argument (the manifest path value)
549                        builder.args.remove(pos); // Remove --manifest-path
550                        if pos < builder.args.len() {
551                            builder.args.remove(pos); // Remove the manifest path value
552                        }
553                    }
554                    let mut cmd = builder.clone().build_command();
555                    cmd.current_dir(cwd);
556
557                    // Retry the command execution
558                    let mut child = cmd.spawn()?;
559                    let status = child.wait()?;
560                    return Ok(Some(status)); // Return the exit status after retrying
561                                             // return run_example(manager, cli, target);  // Recursively call run_example
562                }
563                if output.contains("no such command: `tauri`") {
564                    println!("cargo tauri is not installed, please install it with cargo install tauri-cli");
565                    // Use the yesno function to prompt the user
566                    match crate::e_prompts::yesno(
567                        "Do you want to install tauri-cli?",
568                        Some(true), // Default to yes
569                    ) {
570                        Ok(Some(true)) => {
571                            println!("Installing tauri-cli...");
572                            match spawn_cargo_process(&["install", "tauri-cli"]) {
573                                Ok(mut child) => {
574                                    child.wait().ok(); // Wait for the installation to finish
575                                } // Installation successful
576                                Err(e) => {
577                                    eprintln!("Error installing tauri-cli: {}", e);
578                                }
579                            }
580                        }
581                        Ok(Some(false)) => {}
582                        Ok(None) => {
583                            println!("Installation cancelled (timeout or invalid input).");
584                        }
585                        Err(e) => {
586                            eprintln!("Error during prompt: {}", e);
587                        }
588                    }
589                } else if output.contains("error: no such command: `leptos`") {
590                    println!("cargo-leptos is not installed, please install it with cargo install cargo-leptos");
591                    // Use the yesno function to prompt the user
592                    match crate::e_prompts::yesno(
593                        "Do you want to install cargo-leptos?",
594                        Some(true), // Default to yes
595                    ) {
596                        Ok(Some(true)) => {
597                            println!("Installing cargo-leptos...");
598                            match spawn_cargo_process(&["install", "cargo-leptos"]) {
599                                Ok(mut child) => {
600                                    child.wait().ok(); // Wait for the installation to finish
601                                } // Installation successful
602                                Err(e) => {
603                                    eprintln!("Error installing cargo-leptos: {}", e);
604                                }
605                            }
606                        }
607                        Ok(Some(false)) => {}
608                        Ok(None) => {
609                            println!("Installation cancelled (timeout or invalid input).");
610                        }
611                        Err(e) => {
612                            eprintln!("Error during prompt: {}", e);
613                        }
614                    }
615                    // needed for cargo-leptos but as part of tool installer
616                    //   } else if output.contains("Command 'perl' not found. Is perl installed?") {
617                    //     println!("cargo e sees a perl issue; maybe a prompt in the future or auto-resolution.");
618                    //     crate::e_autosense::auto_sense_perl();
619                  }  else if output.contains("Unable to find libclang")
620      || output.contains("couldn't find any valid shared libraries matching: ['clang.dll', 'libclang.dll']") 
621{
622    crate::e_autosense::auto_sense_llvm();
623
624                } else if output.contains("no such command: `dx`") {
625                    println!("cargo dx is not installed, please install it with cargo install dioxus-cli");
626                } else if output.contains("no such command: `scriptisto`") {
627                    println!("cargo scriptisto is not installed, please install it with cargo install scriptisto");
628                } else if output.contains("no such command: `rust-script`") {
629                    println!("cargo rust-script is not installed, please install it with cargo install rust-script");
630                } else if output.contains(
631                    "No platform feature enabled. Please enable one of the following features:",
632                ) {
633                    println!("cargo e sees a dioxus issue; maybe a prompt in the future or auto-resolution.");
634                } else {
635                    //println!("cargo error: {}", output);
636                }
637            }
638            Err(e) => {
639                eprintln!("Error running cargo: {}", e);
640            }
641        }
642    }
643    // let is_run_command = matches!(cli.subcommand.as_str(), "run" | "r");
644    // if !is_run_command && result.is_filter || ( result.is_filter && !result.is_could_not_compile ) {
645    result.print_exact();
646    result.print_compact();
647    result.print_short();
648    manager.print_prefixed_summary();
649    let errors: Vec<_> = result
650        .diagnostics
651        .iter()
652        .filter(|d| d.level.eq("error"))
653        .collect();
654    let error_width = errors.len().to_string().len().max(1);
655    let line: Vec<String> = errors
656        .iter()
657        .enumerate()
658        .map(|(i, diag)| {
659            let index = format!("{:0width$}", i + 1, width = error_width);
660            let lineref = if diag.lineref.is_empty() {
661                ""
662            } else {
663                &diag.lineref
664            };
665            // Resolve filename to full path
666            let (filename, goto) = if let Some((file, line, col)) = diag
667                .lineref
668                .split_once(':')
669                .and_then(|(f, rest)| rest.split_once(':').and_then(|(l, c)| Some((f, l, c))))
670            {
671                let full_path = std::fs::canonicalize(file).unwrap_or_else(|_| {
672                    let manifest_dir = std::path::Path::new(&manifest_path)
673                        .parent()
674                        .unwrap_or_else(|| {
675                            eprintln!(
676                                "Failed to determine parent directory for manifest: {:?}",
677                                manifest_path
678                            );
679                            std::path::Path::new(".")
680                        });
681                    let fallback_path = manifest_dir.join(file);
682                    std::fs::canonicalize(&fallback_path).unwrap_or_else(|_| {
683                        let parent_fallback_path = manifest_dir.join("../").join(file);
684                        std::fs::canonicalize(&parent_fallback_path).unwrap_or_else(|_| {
685                            eprintln!("Failed to resolve full path for: {} using ../", file);
686                            file.into()
687                        })
688                    })
689                });
690                let stripped_file = full_path.to_string_lossy().replace("\\\\?\\", "");
691
692                (stripped_file.to_string(), format!("{}:{}", line, col))
693            } else {
694                ("".to_string(), "".to_string())
695            };
696            let code_path = which("code").unwrap_or_else(|_| "code".to_string().into());
697            format!(
698                "{}: {}\nanchor:{}: {}\\n {}|\"{}\" --goto \"{}:{}\"\n",
699                index,
700                diag.message.trim(),
701                index,
702                diag.message.trim(),
703                lineref,
704                code_path.display(),
705                filename,
706                goto,
707            )
708        })
709        .collect();
710    if !errors.is_empty() {
711        if let Ok(e_window_path) = which("e_window") {
712            // Compose a nice message for e_window's stdin
713            let stats = result.stats;
714            // Compose a table with cargo-e and its version, plus panic info
715            let cargo_e_version = env!("CARGO_PKG_VERSION");
716            let card = format!(
717                "--title \"failed build: {target}\" --width 400 --height 300 --decode-debug\n\
718                target | {target} | string\n\
719                cargo-e | {version} | string\n\
720                \n\
721                failed build: {target}\n{errors} errors.\n\n{additional_errors}",
722                target = stats.target_name,
723                version = cargo_e_version,
724                errors = errors.len(),
725                additional_errors = line
726                    .iter()
727                    .map(|l| l.as_str())
728                    .collect::<Vec<_>>()
729                    .join("\n"),
730            );
731            // Set the working directory to the manifest's parent directory
732            let manifest_dir = std::path::Path::new(&manifest_path)
733                .parent()
734                .unwrap_or_else(|| {
735                    eprintln!(
736                        "Failed to determine parent directory for manifest: {:?}",
737                        target.manifest_path
738                    );
739                    std::path::Path::new(".")
740                });
741
742            let child = std::process::Command::new(e_window_path)
743                .current_dir(manifest_dir) // Set working directory
744                .stdin(std::process::Stdio::piped())
745                .spawn();
746            if let Ok(mut child) = child {
747                if let Some(stdin) = child.stdin.as_mut() {
748                    use std::io::Write;
749                    let _ = stdin.write_all(card.as_bytes());
750                }
751            }
752        }
753    }
754
755    // }
756
757    // let handle=    Arc::new(builder).run_wait()?;
758    // Spawn the process.
759    // let child = cmd.spawn()?;
760    // {
761    //     let mut global = GLOBAL_CHILD.lock().unwrap();
762    //     *global = Some(child);
763    // }
764    // let status = {
765    //     let mut global = GLOBAL_CHILD.lock().unwrap();
766    //     if let Some(mut child) = global.take() {
767    //         child.wait()?
768    //     } else {
769    //         return Err(anyhow::anyhow!("Child process missing"));
770    //     }
771    // };
772
773    // Restore the manifest if we patched it.
774    if let Some(original) = maybe_backup {
775        fs::write(&target.manifest_path, original)?;
776    }
777    wait_for_tts_to_finish(15000);
778
779    Ok(result.exit_status)
780}
781
782#[cfg(feature = "uses_tts")]
783pub fn wait_for_tts_to_finish(max_wait_ms: u64) {
784    let tts_mutex = crate::GLOBAL_TTS.get();
785    if tts_mutex.is_none() {
786        eprintln!("TTS is not initialized, skipping wait.");
787        return;
788    }
789    let start = std::time::Instant::now();
790    let mut tts_guard = None;
791    for _ in 0..3 {
792        if let Ok(guard) = tts_mutex.unwrap().lock() {
793            tts_guard = Some(guard);
794            break;
795        } else {
796            std::thread::sleep(std::time::Duration::from_millis(100));
797        }
798        if start.elapsed().as_millis() as u64 >= max_wait_ms {
799            eprintln!("Timeout while trying to lock TTS mutex.");
800            return;
801        }
802    }
803    if let Some(tts) = tts_guard {
804        while tts.is_speaking().unwrap_or(false) {
805            if start.elapsed().as_millis() as u64 >= max_wait_ms {
806                eprintln!("Timeout while waiting for TTS to finish speaking.");
807                break;
808            }
809            std::thread::sleep(std::time::Duration::from_millis(100));
810        }
811    } else {
812        eprintln!("Failed to lock TTS mutex after 3 attempts, skipping wait.");
813    }
814}
815
816// /// Runs an example or binary target, applying a temporary manifest patch if a workspace error is detected.
817// /// This function uses the same idea as in the collection helpers: if the workspace error is found,
818// /// we patch the manifest, run the command, and then restore the manifest.
819// pub fn run_example(
820//     target: &crate::e_target::CargoTarget,
821//     extra_args: &[String],
822// ) -> Result<std::process::ExitStatus, Box<dyn Error>> {
823//     // Retrieve the current package name (or binary name) at compile time.
824
825//     use crate::e_target::TargetKind;
826
827//     let current_bin = env!("CARGO_PKG_NAME");
828
829//     // Avoid running our own binary if the target's name is the same.
830//     if target.kind == TargetKind::Binary && target.name == current_bin {
831//         return Err(format!(
832//             "Skipping automatic run: {} is the same as the running binary",
833//             target.name
834//         )
835//         .into());
836//     }
837
838//     let mut cmd = Command::new("cargo");
839//     // Determine which manifest file is used.
840//     let manifest_path: PathBuf;
841
842//     match target.kind {
843//         TargetKind::Bench => {
844//             manifest_path = PathBuf::from(target.manifest_path.clone());
845//             cmd.args([
846//                 "bench",
847//                 "--bench",
848//                 &target.name,
849//                 "--manifest-path",
850//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
851//             ]);
852//         }
853//         TargetKind::Test => {
854//             manifest_path = PathBuf::from(target.manifest_path.clone());
855//             cmd.args([
856//                 "test",
857//                 "--test",
858//                 &target.name,
859//                 "--manifest-path",
860//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
861//             ]);
862//         }
863//         TargetKind::Manifest => {
864//             manifest_path = PathBuf::from(target.manifest_path.clone());
865//             cmd.args([
866//                 "run",
867//                 "--release",
868//                 "--manifest-path",
869//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
870//                 "-p",
871//                 &target.name,
872//             ]);
873//         }
874//         TargetKind::Example => {
875//             if target.extended {
876//                 println!(
877//                     "Running extended example in folder: examples/{}",
878//                     target.name
879//                 );
880//                 // For extended examples, assume the manifest is inside the example folder.
881//                 manifest_path = PathBuf::from(format!("examples/{}/Cargo.toml", target.name));
882//                 cmd.arg("run")
883//                     .current_dir(format!("examples/{}", target.name));
884//             } else {
885//                 manifest_path = PathBuf::from(crate::locate_manifest(false)?);
886//                 cmd.args([
887//                     "run",
888//                     "--release",
889//                     "--example",
890//                     &target.name,
891//                     "--manifest-path",
892//                     &target.manifest_path.to_str().unwrap_or_default().to_owned(),
893//                 ]);
894//             }
895//         }
896//         TargetKind::Binary => {
897//             println!("Running binary: {}", target.name);
898//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
899//             cmd.args([
900//                 "run",
901//                 "--release",
902//                 "--bin",
903//                 &target.name,
904//                 "--manifest-path",
905//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
906//             ]);
907//         }
908//         TargetKind::ExtendedBinary => {
909//             println!("Running extended binary: {}", target.name);
910//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
911//             cmd.args([
912//                 "run",
913//                 "--release",
914//                 "--manifest-path",
915//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
916//                 "--bin",
917//                 &target.name,
918//             ]);
919//         }
920//         TargetKind::ExtendedExample => {
921//             println!("Running extended example: {}", target.name);
922//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
923//             cmd.args([
924//                 "run",
925//                 "--release",
926//                 "--manifest-path",
927//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
928//                 "--example",
929//                 &target.name,
930//             ]);
931//         }
932//         TargetKind::ManifestTauri => {
933//             println!("Running tauri: {}", target.name);
934//             // For a Tauri example, run `cargo tauri dev`
935//             manifest_path = PathBuf::from(target.manifest_path.clone());
936//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
937//             // Start a new command for tauri dev
938//             cmd.arg("tauri").arg("dev").current_dir(manifest_dir); // run from the folder where Cargo.toml is located
939//         }
940//         TargetKind::ManifestDioxus => {
941//             println!("Running dioxus: {}", target.name);
942//             cmd = Command::new("dx");
943//             // For a Tauri example, run `cargo tauri dev`
944//             manifest_path = PathBuf::from(target.manifest_path.clone());
945//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
946//             // Start a new command for tauri dev
947//             cmd.arg("serve").current_dir(manifest_dir); // run from the folder where Cargo.toml is located
948//         }
949//         TargetKind::ManifestDioxusExample => {
950//             println!("Running dioxus: {}", target.name);
951//             cmd = Command::new("dx");
952//             // For a Tauri example, run `cargo tauri dev`
953//             manifest_path = PathBuf::from(target.manifest_path.clone());
954//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
955//             // Start a new command for tauri dev
956//             cmd.arg("serve")
957//                 .arg("--example")
958//                 .arg(&target.name)
959//                 .current_dir(manifest_dir); // run from the folder where Cargo.toml is located
960//         }
961//     }
962
963//     // --- Add required-features support ---
964//     // This call will search the provided manifest, and if it's a workspace,
965//     // it will search workspace members for the target.
966//     if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
967//         manifest_path.as_path(),
968//         &target.kind,
969//         &target.name,
970//     ) {
971//         cmd.args(&["--features", &features]);
972//     }
973//     // --- End required-features support ---
974
975//     if !extra_args.is_empty() {
976//         cmd.arg("--").args(extra_args);
977//     }
978
979//     let full_command = format!(
980//         "{} {}",
981//         cmd.get_program().to_string_lossy(),
982//         cmd.get_args()
983//             .map(|arg| arg.to_string_lossy())
984//             .collect::<Vec<_>>()
985//             .join(" ")
986//     );
987//     println!("Running: {}", full_command);
988
989//     // Before spawning, check if the manifest triggers the workspace error.
990//     // If so, patch it temporarily.
991//     let maybe_backup = crate::e_manifest::maybe_patch_manifest_for_run(&manifest_path)?;
992
993//     // Spawn the process.
994//     let child = cmd.spawn()?;
995//     {
996//         let mut global = GLOBAL_CHILD.lock().unwrap();
997//         *global = Some(child);
998//     }
999//     let status = {
1000//         let mut global = GLOBAL_CHILD.lock().unwrap();
1001//         if let Some(mut child) = global.take() {
1002//             child.wait()?
1003//         } else {
1004//             return Err("Child process missing".into());
1005//         }
1006//     };
1007
1008//     // Restore the manifest if we patched it.
1009//     if let Some(original) = maybe_backup {
1010//         fs::write(&manifest_path, original)?;
1011//     }
1012
1013//     //    println!("Process exited with status: {:?}", status.code());
1014//     Ok(status)
1015// }
1016/// Helper function to spawn a cargo process.
1017/// On Windows, this sets the CREATE_NEW_PROCESS_GROUP flag.
1018pub fn spawn_cargo_process(args: &[&str]) -> Result<Child, Box<dyn Error>> {
1019    // #[cfg(windows)]
1020    // {
1021    //     use std::os::windows::process::CommandExt;
1022    //     const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
1023    //     let child = Command::new("cargo")
1024    //         .args(args)
1025    //         .creation_flags(CREATE_NEW_PROCESS_GROUP)
1026    //         .spawn()?;
1027    //     Ok(child)
1028    // }
1029    // #[cfg(not(windows))]
1030    // {
1031    let child = Command::new("cargo").args(args).spawn()?;
1032    Ok(child)
1033    // }
1034}
1035
1036/// Returns true if the file's a "scriptisto"
1037pub fn is_active_scriptisto<P: AsRef<Path>>(path: P) -> io::Result<bool> {
1038    let file = File::open(path)?;
1039    let mut reader = std::io::BufReader::new(file);
1040    let mut first_line = String::new();
1041    reader.read_line(&mut first_line)?;
1042    if !first_line.contains("scriptisto") || !first_line.starts_with("#") {
1043        return Ok(false);
1044    }
1045    Ok(true)
1046}
1047
1048/// Returns true if the file's a "rust-script"
1049pub fn is_active_rust_script<P: AsRef<Path>>(path: P) -> io::Result<bool> {
1050    let file = File::open(path)?;
1051    let mut reader = std::io::BufReader::new(file);
1052    let mut first_line = String::new();
1053    reader.read_line(&mut first_line)?;
1054    if !first_line.contains("rust-script") || !first_line.starts_with("#") {
1055        return Ok(false);
1056    }
1057    Ok(true)
1058}
1059
1060/// Checks if `scriptisto` is installed and suggests installation if it's not.
1061pub fn check_scriptisto_installed() -> Result<std::path::PathBuf, Box<dyn Error>> {
1062    let r = which("scriptisto");
1063    match r {
1064        Ok(_) => {
1065            // installed
1066        }
1067        Err(e) => {
1068            // scriptisto is not found in the PATH
1069            eprintln!("scriptisto is not installed.");
1070            println!("Suggestion: To install scriptisto, run the following command:");
1071            println!("cargo install scriptisto");
1072            return Err(e.into());
1073        }
1074    }
1075    Ok(r?)
1076}
1077
1078pub fn run_scriptisto<P: AsRef<Path>>(script_path: P, args: &[&str]) -> Option<Child> {
1079    let scriptisto = check_scriptisto_installed().ok()?;
1080
1081    let script: &std::path::Path = script_path.as_ref();
1082    let child = Command::new(scriptisto)
1083        .arg(script)
1084        .args(args)
1085        .spawn()
1086        .ok()?;
1087    Some(child)
1088}
1089
1090/// Checks if `rust-script` is installed and suggests installation if it's not.
1091pub fn check_rust_script_installed() -> Result<std::path::PathBuf, Box<dyn Error>> {
1092    let r = which("rust-script");
1093    match r {
1094        Ok(_) => {
1095            // rust-script is installed
1096        }
1097        Err(e) => {
1098            // rust-script is not found in the PATH
1099            eprintln!("rust-script is not installed.");
1100            println!("Suggestion: To install rust-script, run the following command:");
1101            println!("cargo install rust-script");
1102            return Err(e.into());
1103        }
1104    }
1105    Ok(r?)
1106}
1107
1108pub fn run_rust_script<P: AsRef<Path>>(script_path: P, args: &[&str]) -> Option<Child> {
1109    let rust_script = check_rust_script_installed();
1110    if rust_script.is_err() {
1111        return None;
1112    }
1113    let rust_script = rust_script.unwrap();
1114    let script: &std::path::Path = script_path.as_ref();
1115    let child = Command::new(rust_script)
1116        .arg(script)
1117        .args(args)
1118        .spawn()
1119        .ok()?;
1120    Some(child)
1121}
1122
1123pub fn run_rust_script_with_ctrlc_handling(explicit: String, extra_args: Vec<String>) {
1124    let explicit_path = Path::new(&explicit); // Construct Path outside the lock
1125
1126    if explicit_path.exists() {
1127        let extra_str_slice: Vec<String> = extra_args.iter().cloned().collect();
1128        if let Ok(true) = is_active_rust_script(explicit_path) {
1129            // Run the child process in a separate thread to allow Ctrl+C handling
1130            let handle = thread::spawn(move || {
1131                let extra_str_slice_cloned = extra_str_slice.clone();
1132                let mut child = run_rust_script(
1133                    &explicit,
1134                    &extra_str_slice_cloned
1135                        .iter()
1136                        .map(String::as_str)
1137                        .collect::<Vec<_>>(),
1138                )
1139                .unwrap_or_else(|| {
1140                    eprintln!("Failed to run rust-script: {:?}", &explicit);
1141                    std::process::exit(1); // Exit with an error code
1142                });
1143
1144                child.wait()
1145            });
1146
1147            match handle.join() {
1148                Ok(_) => {
1149                    println!("Child process finished successfully.");
1150                }
1151                Err(_) => {
1152                    eprintln!("Child process took too long to finish. Exiting...");
1153                    std::process::exit(1); // Exit if the process takes too long
1154                }
1155            }
1156        }
1157    }
1158}
1159
1160pub fn run_scriptisto_with_ctrlc_handling(explicit: String, extra_args: Vec<String>) {
1161    let relative: String = make_relative(Path::new(&explicit)).unwrap_or_else(|e| {
1162        eprintln!("Error computing relative path: {}", e);
1163        std::process::exit(1);
1164    });
1165
1166    let explicit_path = Path::new(&relative);
1167    if explicit_path.exists() {
1168        // let extra_args = EXTRA_ARGS.lock().unwrap(); // Locking the Mutex to access the data
1169        let extra_str_slice: Vec<String> = extra_args.to_vec();
1170
1171        if let Ok(true) = is_active_scriptisto(explicit_path) {
1172            // Run the child process in a separate thread to allow Ctrl+C handling
1173            let handle = thread::spawn(move || {
1174                let extra_str_slice_cloned: Vec<String> = extra_str_slice.clone();
1175                let child = run_scriptisto(
1176                    &relative,
1177                    &extra_str_slice_cloned
1178                        .iter()
1179                        .map(String::as_str)
1180                        .collect::<Vec<_>>(),
1181                )
1182                .unwrap_or_else(|| {
1183                    eprintln!("Failed to run rust-script: {:?}", &explicit);
1184                    std::process::exit(1); // Exit with an error code
1185                });
1186
1187                // // Lock global to store the child process
1188                // {
1189                //     let mut global = GLOBAL_CHILD.lock().unwrap();
1190                //     *global = Some(child);
1191                // }
1192
1193                // // Wait for the child process to complete
1194                // let status = {
1195                //     let mut global = GLOBAL_CHILD.lock().unwrap();
1196                //     if let Some(mut child) = global.take() {
1197                //         child.wait()
1198                //     } else {
1199                //         // Handle missing child process
1200                //         eprintln!("Child process missing");
1201                //         std::process::exit(1); // Exit with an error code
1202                //     }
1203                // };
1204
1205                // // Handle the child process exit status
1206                // match status {
1207                //     Ok(status) => {
1208                //         eprintln!("Child process exited with status code: {:?}", status.code());
1209                //         std::process::exit(status.code().unwrap_or(1)); // Exit with the child's status code
1210                //     }
1211                //     Err(err) => {
1212                //         eprintln!("Error waiting for child process: {}", err);
1213                //         std::process::exit(1); // Exit with an error code
1214                //     }
1215                // }
1216            });
1217
1218            // Wait for the thread to complete, but with a timeout
1219            // let timeout = Duration::from_secs(10);
1220            match handle.join() {
1221                Ok(_) => {
1222                    println!("Child process finished successfully.");
1223                }
1224                Err(_) => {
1225                    eprintln!("Child process took too long to finish. Exiting...");
1226                    std::process::exit(1); // Exit if the process takes too long
1227                }
1228            }
1229        }
1230    }
1231}
1232/// Given any path, produce a relative path string starting with `./` (or `.\` on Windows).
1233fn make_relative(path: &Path) -> std::io::Result<String> {
1234    let cwd = env::current_dir()?;
1235    // Try to strip the cwd prefix; if it isn’t under cwd, just use the original path.
1236    let rel: PathBuf = match path.strip_prefix(&cwd) {
1237        Ok(stripped) => stripped.to_path_buf(),
1238        Err(_) => path.to_path_buf(),
1239    };
1240
1241    let mut rel = if rel.components().count() == 0 {
1242        // special case: the same directory
1243        PathBuf::from(".")
1244    } else {
1245        rel
1246    };
1247
1248    // Prepend "./" (or ".\") if it doesn’t already start with "." or ".."
1249    let first = rel.components().next().unwrap();
1250    match first {
1251        std::path::Component::CurDir | std::path::Component::ParentDir => {}
1252        _ => {
1253            rel = PathBuf::from(".").join(rel);
1254        }
1255    }
1256
1257    // Convert back to a string with the correct separator
1258    let s = rel
1259        .to_str()
1260        .expect("Relative path should be valid UTF-8")
1261        .to_string();
1262
1263    Ok(s)
1264}
1265
1266// trait JoinTimeout {
1267//     fn join_timeout(self, timeout: Duration) -> Result<(), ()>;
1268// }
1269
1270// impl<T> JoinTimeout for thread::JoinHandle<T> {
1271//     fn join_timeout(self, timeout: Duration) -> Result<(), ()> {
1272//         println!("Waiting for thread to finish...{}", timeout.as_secs());
1273//         let _ = thread::sleep(timeout);
1274//         match self.join() {
1275//             Ok(_) => Ok(()),
1276//             Err(_) => Err(()),
1277//         }
1278//     }
1279// }