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        &manifest_path,
452        &cli.subcommand,
453        cli.filter,
454    )
455    .with_target(target)
456    .with_required_features(&target.manifest_path, target)
457    .with_cli(cli);
458
459    if !cli.extra.is_empty() {
460        builder = builder.with_extra_args(&cli.extra);
461    }
462
463    // Build the command.
464    let mut cmd = builder.clone().build_command();
465
466    // Before spawning, determine the directory to run from.
467    // If a custom execution directory was set (e.g. for Tauri targets), that is used.
468    // Otherwise, if the target is extended, run from its parent directory.
469    if let Some(ref exec_dir) = builder.execution_dir {
470        cmd.current_dir(exec_dir);
471    } else if target.extended {
472        if let Some(dir) = target.manifest_path.parent() {
473            cmd.current_dir(dir);
474        }
475    }
476
477    // Print the full command for debugging.
478    let full_command = format!(
479        "{} {}",
480        cmd.get_program().to_string_lossy(),
481        cmd.get_args()
482            .map(|arg| arg.to_string_lossy())
483            .collect::<Vec<_>>()
484            .join(" ")
485    );
486    println!("Running: {}", full_command);
487
488    // Check if the manifest triggers the workspace error.
489    let maybe_backup = crate::e_manifest::maybe_patch_manifest_for_run(&target.manifest_path)?;
490    let a_blder = Arc::new(builder.clone());
491    let pid = a_blder.run(|_pid, handle| {
492        manager.register(handle);
493    })?;
494    let result = manager.wait(pid, None)?;
495    // println!("HERE IS THE RESULT!{} {:?}",pid,manager.get(pid));
496    // println!("\n\nHERE IS THE RESULT!{} {:?}",pid,result);
497    if result
498        .exit_status
499        .map_or(false, |status| status.code() == Some(101))
500    {
501        println!(
502            "ProcessManager senses pid {} cargo error, running again to capture and analyze",
503            pid
504        );
505        match builder.clone().capture_output() {
506            Ok(output) => {
507                let system_lib_regex = Regex::new(
508                    r"\s*The system library `([^`]+)` required by crate `([^`]+)` was not found\.",
509                )
510                .unwrap();
511
512                if let Some(captures) = system_lib_regex.captures(&output) {
513                    let library = &captures[1];
514                    let crate_name = &captures[2];
515                    println!(
516                        "cargo-e detected missing system library '{}' required by crate '{}'.",
517                        library, crate_name
518                    );
519
520                    // Suggest installation based on common package managers
521                    println!(
522                        "You might need to install '{}' via your system package manager.",
523                        library
524                    );
525                    println!("For example:");
526
527                    println!(
528                        "  • Debian/Ubuntu: sudo apt install {}",
529                        library_hint(library)
530                    );
531                    println!("  • Fedora: sudo dnf install {}", library_hint(library));
532                    println!("  • Arch: sudo pacman -S {}", library_hint(library));
533                    println!(
534                        "  • macOS (Homebrew): brew install {}",
535                        library_hint(library)
536                    );
537                    std::process::exit(0);
538                } else if output.contains("error: failed to load manifest for workspace member") {
539                    println!("cargo-e error: failed to load manifest for workspace member, please check your workspace configuration.");
540                    println!("cargo-e autorecovery: removing manfifest path from argument and changing to parent of Cargo.toml.");
541                    let cwd = target
542                        .manifest_path
543                        .parent()
544                        .unwrap_or_else(|| Path::new("."));
545                    // Rebuild the command with the new cwd
546                    builder.execution_dir = Some(cwd.to_path_buf());
547                    // Remove --manifest-path and its associated value from the args array
548                    if let Some(pos) = builder.args.iter().position(|arg| arg == "--manifest-path")
549                    {
550                        // Remove --manifest-path and the next argument (the manifest path value)
551                        builder.args.remove(pos); // Remove --manifest-path
552                        if pos < builder.args.len() {
553                            builder.args.remove(pos); // Remove the manifest path value
554                        }
555                    }
556                    let mut cmd = builder.clone().build_command();
557                    cmd.current_dir(cwd);
558
559                    // Retry the command execution
560                    let mut child = cmd.spawn()?;
561                    let status = child.wait()?;
562                    return Ok(Some(status)); // Return the exit status after retrying
563                                             // return run_example(manager, cli, target);  // Recursively call run_example
564                }
565                if output.contains("no such command: `tauri`") {
566                    println!("cargo tauri is not installed, please install it with cargo install tauri-cli");
567                    // Use the yesno function to prompt the user
568                    match crate::e_prompts::yesno(
569                        "Do you want to install tauri-cli?",
570                        Some(true), // Default to yes
571                    ) {
572                        Ok(Some(true)) => {
573                            println!("Installing tauri-cli...");
574                            match spawn_cargo_process(&["install", "tauri-cli"]) {
575                                Ok(mut child) => {
576                                    child.wait().ok(); // Wait for the installation to finish
577                                } // Installation successful
578                                Err(e) => {
579                                    eprintln!("Error installing tauri-cli: {}", e);
580                                }
581                            }
582                        }
583                        Ok(Some(false)) => {}
584                        Ok(None) => {
585                            println!("Installation cancelled (timeout or invalid input).");
586                        }
587                        Err(e) => {
588                            eprintln!("Error during prompt: {}", e);
589                        }
590                    }
591                } else if output.contains("error: no such command: `leptos`") {
592                    println!("cargo-leptos is not installed, please install it with cargo install cargo-leptos");
593                    // Use the yesno function to prompt the user
594                    match crate::e_prompts::yesno(
595                        "Do you want to install cargo-leptos?",
596                        Some(true), // Default to yes
597                    ) {
598                        Ok(Some(true)) => {
599                            println!("Installing cargo-leptos...");
600                            match spawn_cargo_process(&["install", "cargo-leptos"]) {
601                                Ok(mut child) => {
602                                    child.wait().ok(); // Wait for the installation to finish
603                                } // Installation successful
604                                Err(e) => {
605                                    eprintln!("Error installing cargo-leptos: {}", e);
606                                }
607                            }
608                        }
609                        Ok(Some(false)) => {}
610                        Ok(None) => {
611                            println!("Installation cancelled (timeout or invalid input).");
612                        }
613                        Err(e) => {
614                            eprintln!("Error during prompt: {}", e);
615                        }
616                    }
617                  }  else if output.contains("Unable to find libclang")
618      || output.contains("couldn't find any valid shared libraries matching: ['clang.dll', 'libclang.dll']") 
619{
620    crate::e_autosense::auto_sense_llvm();
621
622                } else if output.contains("no such command: `dx`") {
623                    println!("cargo dx is not installed, please install it with cargo install dioxus-cli");
624                } else if output.contains("no such command: `scriptisto`") {
625                    println!("cargo scriptisto is not installed, please install it with cargo install scriptisto");
626                } else if output.contains("no such command: `rust-script`") {
627                    println!("cargo rust-script is not installed, please install it with cargo install rust-script");
628                } else if output.contains(
629                    "No platform feature enabled. Please enable one of the following features:",
630                ) {
631                    println!("cargo e sees a dioxus issue; maybe a prompt in the future or auto-resolution.");
632                } else {
633                    println!("cargo error: {}", output);
634                }
635            }
636            Err(e) => {
637                eprintln!("Error running cargo: {}", e);
638            }
639        }
640    }
641    if result.is_filter {
642        result.print_exact();
643        result.print_short();
644        result.print_compact();
645
646        // manager.print_shortened_output();
647        manager.print_prefixed_summary();
648        // manager.print_compact();
649    }
650
651    // let handle=    Arc::new(builder).run_wait()?;
652    // Spawn the process.
653    // let child = cmd.spawn()?;
654    // {
655    //     let mut global = GLOBAL_CHILD.lock().unwrap();
656    //     *global = Some(child);
657    // }
658    // let status = {
659    //     let mut global = GLOBAL_CHILD.lock().unwrap();
660    //     if let Some(mut child) = global.take() {
661    //         child.wait()?
662    //     } else {
663    //         return Err(anyhow::anyhow!("Child process missing"));
664    //     }
665    // };
666
667    // Restore the manifest if we patched it.
668    if let Some(original) = maybe_backup {
669        fs::write(&target.manifest_path, original)?;
670    }
671
672    Ok(result.exit_status)
673}
674// /// Runs an example or binary target, applying a temporary manifest patch if a workspace error is detected.
675// /// This function uses the same idea as in the collection helpers: if the workspace error is found,
676// /// we patch the manifest, run the command, and then restore the manifest.
677// pub fn run_example(
678//     target: &crate::e_target::CargoTarget,
679//     extra_args: &[String],
680// ) -> Result<std::process::ExitStatus, Box<dyn Error>> {
681//     // Retrieve the current package name (or binary name) at compile time.
682
683//     use crate::e_target::TargetKind;
684
685//     let current_bin = env!("CARGO_PKG_NAME");
686
687//     // Avoid running our own binary if the target's name is the same.
688//     if target.kind == TargetKind::Binary && target.name == current_bin {
689//         return Err(format!(
690//             "Skipping automatic run: {} is the same as the running binary",
691//             target.name
692//         )
693//         .into());
694//     }
695
696//     let mut cmd = Command::new("cargo");
697//     // Determine which manifest file is used.
698//     let manifest_path: PathBuf;
699
700//     match target.kind {
701//         TargetKind::Bench => {
702//             manifest_path = PathBuf::from(target.manifest_path.clone());
703//             cmd.args([
704//                 "bench",
705//                 "--bench",
706//                 &target.name,
707//                 "--manifest-path",
708//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
709//             ]);
710//         }
711//         TargetKind::Test => {
712//             manifest_path = PathBuf::from(target.manifest_path.clone());
713//             cmd.args([
714//                 "test",
715//                 "--test",
716//                 &target.name,
717//                 "--manifest-path",
718//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
719//             ]);
720//         }
721//         TargetKind::Manifest => {
722//             manifest_path = PathBuf::from(target.manifest_path.clone());
723//             cmd.args([
724//                 "run",
725//                 "--release",
726//                 "--manifest-path",
727//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
728//                 "-p",
729//                 &target.name,
730//             ]);
731//         }
732//         TargetKind::Example => {
733//             if target.extended {
734//                 println!(
735//                     "Running extended example in folder: examples/{}",
736//                     target.name
737//                 );
738//                 // For extended examples, assume the manifest is inside the example folder.
739//                 manifest_path = PathBuf::from(format!("examples/{}/Cargo.toml", target.name));
740//                 cmd.arg("run")
741//                     .current_dir(format!("examples/{}", target.name));
742//             } else {
743//                 manifest_path = PathBuf::from(crate::locate_manifest(false)?);
744//                 cmd.args([
745//                     "run",
746//                     "--release",
747//                     "--example",
748//                     &target.name,
749//                     "--manifest-path",
750//                     &target.manifest_path.to_str().unwrap_or_default().to_owned(),
751//                 ]);
752//             }
753//         }
754//         TargetKind::Binary => {
755//             println!("Running binary: {}", target.name);
756//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
757//             cmd.args([
758//                 "run",
759//                 "--release",
760//                 "--bin",
761//                 &target.name,
762//                 "--manifest-path",
763//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
764//             ]);
765//         }
766//         TargetKind::ExtendedBinary => {
767//             println!("Running extended binary: {}", target.name);
768//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
769//             cmd.args([
770//                 "run",
771//                 "--release",
772//                 "--manifest-path",
773//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
774//                 "--bin",
775//                 &target.name,
776//             ]);
777//         }
778//         TargetKind::ExtendedExample => {
779//             println!("Running extended example: {}", target.name);
780//             manifest_path = PathBuf::from(crate::locate_manifest(false)?);
781//             cmd.args([
782//                 "run",
783//                 "--release",
784//                 "--manifest-path",
785//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
786//                 "--example",
787//                 &target.name,
788//             ]);
789//         }
790//         TargetKind::ManifestTauri => {
791//             println!("Running tauri: {}", target.name);
792//             // For a Tauri example, run `cargo tauri dev`
793//             manifest_path = PathBuf::from(target.manifest_path.clone());
794//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
795//             // Start a new command for tauri dev
796//             cmd.arg("tauri").arg("dev").current_dir(manifest_dir); // run from the folder where Cargo.toml is located
797//         }
798//         TargetKind::ManifestDioxus => {
799//             println!("Running dioxus: {}", target.name);
800//             cmd = Command::new("dx");
801//             // For a Tauri example, run `cargo tauri dev`
802//             manifest_path = PathBuf::from(target.manifest_path.clone());
803//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
804//             // Start a new command for tauri dev
805//             cmd.arg("serve").current_dir(manifest_dir); // run from the folder where Cargo.toml is located
806//         }
807//         TargetKind::ManifestDioxusExample => {
808//             println!("Running dioxus: {}", target.name);
809//             cmd = Command::new("dx");
810//             // For a Tauri example, run `cargo tauri dev`
811//             manifest_path = PathBuf::from(target.manifest_path.clone());
812//             let manifest_dir = PathBuf::from(manifest_path.parent().expect("expected a parent"));
813//             // Start a new command for tauri dev
814//             cmd.arg("serve")
815//                 .arg("--example")
816//                 .arg(&target.name)
817//                 .current_dir(manifest_dir); // run from the folder where Cargo.toml is located
818//         }
819//     }
820
821//     // --- Add required-features support ---
822//     // This call will search the provided manifest, and if it's a workspace,
823//     // it will search workspace members for the target.
824//     if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
825//         manifest_path.as_path(),
826//         &target.kind,
827//         &target.name,
828//     ) {
829//         cmd.args(&["--features", &features]);
830//     }
831//     // --- End required-features support ---
832
833//     if !extra_args.is_empty() {
834//         cmd.arg("--").args(extra_args);
835//     }
836
837//     let full_command = format!(
838//         "{} {}",
839//         cmd.get_program().to_string_lossy(),
840//         cmd.get_args()
841//             .map(|arg| arg.to_string_lossy())
842//             .collect::<Vec<_>>()
843//             .join(" ")
844//     );
845//     println!("Running: {}", full_command);
846
847//     // Before spawning, check if the manifest triggers the workspace error.
848//     // If so, patch it temporarily.
849//     let maybe_backup = crate::e_manifest::maybe_patch_manifest_for_run(&manifest_path)?;
850
851//     // Spawn the process.
852//     let child = cmd.spawn()?;
853//     {
854//         let mut global = GLOBAL_CHILD.lock().unwrap();
855//         *global = Some(child);
856//     }
857//     let status = {
858//         let mut global = GLOBAL_CHILD.lock().unwrap();
859//         if let Some(mut child) = global.take() {
860//             child.wait()?
861//         } else {
862//             return Err("Child process missing".into());
863//         }
864//     };
865
866//     // Restore the manifest if we patched it.
867//     if let Some(original) = maybe_backup {
868//         fs::write(&manifest_path, original)?;
869//     }
870
871//     //    println!("Process exited with status: {:?}", status.code());
872//     Ok(status)
873// }
874/// Helper function to spawn a cargo process.
875/// On Windows, this sets the CREATE_NEW_PROCESS_GROUP flag.
876pub fn spawn_cargo_process(args: &[&str]) -> Result<Child, Box<dyn Error>> {
877    // #[cfg(windows)]
878    // {
879    //     use std::os::windows::process::CommandExt;
880    //     const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
881    //     let child = Command::new("cargo")
882    //         .args(args)
883    //         .creation_flags(CREATE_NEW_PROCESS_GROUP)
884    //         .spawn()?;
885    //     Ok(child)
886    // }
887    // #[cfg(not(windows))]
888    // {
889    let child = Command::new("cargo").args(args).spawn()?;
890    Ok(child)
891    // }
892}
893
894/// Returns true if the file's a "scriptisto"
895pub fn is_active_scriptisto<P: AsRef<Path>>(path: P) -> io::Result<bool> {
896    let file = File::open(path)?;
897    let mut reader = std::io::BufReader::new(file);
898    let mut first_line = String::new();
899    reader.read_line(&mut first_line)?;
900    if !first_line.contains("scriptisto") || !first_line.starts_with("#") {
901        return Ok(false);
902    }
903    Ok(true)
904}
905
906/// Returns true if the file's a "rust-script"
907pub fn is_active_rust_script<P: AsRef<Path>>(path: P) -> io::Result<bool> {
908    let file = File::open(path)?;
909    let mut reader = std::io::BufReader::new(file);
910    let mut first_line = String::new();
911    reader.read_line(&mut first_line)?;
912    if !first_line.contains("rust-script") || !first_line.starts_with("#") {
913        return Ok(false);
914    }
915    Ok(true)
916}
917
918/// Checks if `scriptisto` is installed and suggests installation if it's not.
919pub fn check_scriptisto_installed() -> Result<std::path::PathBuf, Box<dyn Error>> {
920    let r = which("scriptisto");
921    match r {
922        Ok(_) => {
923            // installed
924        }
925        Err(e) => {
926            // scriptisto is not found in the PATH
927            eprintln!("scriptisto is not installed.");
928            println!("Suggestion: To install scriptisto, run the following command:");
929            println!("cargo install scriptisto");
930            return Err(e.into());
931        }
932    }
933    Ok(r?)
934}
935
936pub fn run_scriptisto<P: AsRef<Path>>(script_path: P, args: &[&str]) -> Option<Child> {
937    let scriptisto = check_scriptisto_installed().ok()?;
938
939    let script: &std::path::Path = script_path.as_ref();
940    let child = Command::new(scriptisto)
941        .arg(script)
942        .args(args)
943        .spawn()
944        .ok()?;
945    Some(child)
946}
947
948/// Checks if `rust-script` is installed and suggests installation if it's not.
949pub fn check_rust_script_installed() -> Result<std::path::PathBuf, Box<dyn Error>> {
950    let r = which("rust-script");
951    match r {
952        Ok(_) => {
953            // rust-script is installed
954        }
955        Err(e) => {
956            // rust-script is not found in the PATH
957            eprintln!("rust-script is not installed.");
958            println!("Suggestion: To install rust-script, run the following command:");
959            println!("cargo install rust-script");
960            return Err(e.into());
961        }
962    }
963    Ok(r?)
964}
965
966pub fn run_rust_script<P: AsRef<Path>>(script_path: P, args: &[&str]) -> Option<Child> {
967    let rust_script = check_rust_script_installed();
968    if rust_script.is_err() {
969        return None;
970    }
971    let rust_script = rust_script.unwrap();
972    let script: &std::path::Path = script_path.as_ref();
973    let child = Command::new(rust_script)
974        .arg(script)
975        .args(args)
976        .spawn()
977        .ok()?;
978    Some(child)
979}
980
981pub fn run_rust_script_with_ctrlc_handling(explicit: String, extra_args: Vec<String>) {
982    let explicit_path = Path::new(&explicit); // Construct Path outside the lock
983
984    if explicit_path.exists() {
985        let extra_str_slice: Vec<String> = extra_args.iter().cloned().collect();
986        if let Ok(true) = is_active_rust_script(explicit_path) {
987            // Run the child process in a separate thread to allow Ctrl+C handling
988            let handle = thread::spawn(move || {
989                let extra_str_slice_cloned = extra_str_slice.clone();
990                let mut child = run_rust_script(
991                    &explicit,
992                    &extra_str_slice_cloned
993                        .iter()
994                        .map(String::as_str)
995                        .collect::<Vec<_>>(),
996                )
997                .unwrap_or_else(|| {
998                    eprintln!("Failed to run rust-script: {:?}", &explicit);
999                    std::process::exit(1); // Exit with an error code
1000                });
1001
1002                child.wait()
1003            });
1004
1005            match handle.join() {
1006                Ok(_) => {
1007                    println!("Child process finished successfully.");
1008                }
1009                Err(_) => {
1010                    eprintln!("Child process took too long to finish. Exiting...");
1011                    std::process::exit(1); // Exit if the process takes too long
1012                }
1013            }
1014        }
1015    }
1016}
1017
1018pub fn run_scriptisto_with_ctrlc_handling(explicit: String, extra_args: Vec<String>) {
1019    let relative: String = make_relative(Path::new(&explicit)).unwrap_or_else(|e| {
1020        eprintln!("Error computing relative path: {}", e);
1021        std::process::exit(1);
1022    });
1023
1024    let explicit_path = Path::new(&relative);
1025    if explicit_path.exists() {
1026        // let extra_args = EXTRA_ARGS.lock().unwrap(); // Locking the Mutex to access the data
1027        let extra_str_slice: Vec<String> = extra_args.to_vec();
1028
1029        if let Ok(true) = is_active_scriptisto(explicit_path) {
1030            // Run the child process in a separate thread to allow Ctrl+C handling
1031            let handle = thread::spawn(move || {
1032                let extra_str_slice_cloned: Vec<String> = extra_str_slice.clone();
1033                let mut child = run_scriptisto(
1034                    &relative,
1035                    &extra_str_slice_cloned
1036                        .iter()
1037                        .map(String::as_str)
1038                        .collect::<Vec<_>>(),
1039                )
1040                .unwrap_or_else(|| {
1041                    eprintln!("Failed to run rust-script: {:?}", &explicit);
1042                    std::process::exit(1); // Exit with an error code
1043                });
1044
1045                // // Lock global to store the child process
1046                // {
1047                //     let mut global = GLOBAL_CHILD.lock().unwrap();
1048                //     *global = Some(child);
1049                // }
1050
1051                // // Wait for the child process to complete
1052                // let status = {
1053                //     let mut global = GLOBAL_CHILD.lock().unwrap();
1054                //     if let Some(mut child) = global.take() {
1055                child.wait()
1056                //     } else {
1057                //         // Handle missing child process
1058                //         eprintln!("Child process missing");
1059                //         std::process::exit(1); // Exit with an error code
1060                //     }
1061                // };
1062
1063                // // Handle the child process exit status
1064                // match status {
1065                //     Ok(status) => {
1066                //         eprintln!("Child process exited with status code: {:?}", status.code());
1067                //         std::process::exit(status.code().unwrap_or(1)); // Exit with the child's status code
1068                //     }
1069                //     Err(err) => {
1070                //         eprintln!("Error waiting for child process: {}", err);
1071                //         std::process::exit(1); // Exit with an error code
1072                //     }
1073                // }
1074            });
1075
1076            // Wait for the thread to complete, but with a timeout
1077            // let timeout = Duration::from_secs(10);
1078            match handle.join() {
1079                Ok(_) => {
1080                    println!("Child process finished successfully.");
1081                }
1082                Err(_) => {
1083                    eprintln!("Child process took too long to finish. Exiting...");
1084                    std::process::exit(1); // Exit if the process takes too long
1085                }
1086            }
1087        }
1088    }
1089}
1090/// Given any path, produce a relative path string starting with `./` (or `.\` on Windows).
1091fn make_relative(path: &Path) -> std::io::Result<String> {
1092    let cwd = env::current_dir()?;
1093    // Try to strip the cwd prefix; if it isn’t under cwd, just use the original path.
1094    let rel: PathBuf = match path.strip_prefix(&cwd) {
1095        Ok(stripped) => stripped.to_path_buf(),
1096        Err(_) => path.to_path_buf(),
1097    };
1098
1099    let mut rel = if rel.components().count() == 0 {
1100        // special case: the same directory
1101        PathBuf::from(".")
1102    } else {
1103        rel
1104    };
1105
1106    // Prepend "./" (or ".\") if it doesn’t already start with "." or ".."
1107    let first = rel.components().next().unwrap();
1108    match first {
1109        std::path::Component::CurDir | std::path::Component::ParentDir => {}
1110        _ => {
1111            rel = PathBuf::from(".").join(rel);
1112        }
1113    }
1114
1115    // Convert back to a string with the correct separator
1116    let s = rel
1117        .to_str()
1118        .expect("Relative path should be valid UTF-8")
1119        .to_string();
1120
1121    Ok(s)
1122}
1123
1124// trait JoinTimeout {
1125//     fn join_timeout(self, timeout: Duration) -> Result<(), ()>;
1126// }
1127
1128// impl<T> JoinTimeout for thread::JoinHandle<T> {
1129//     fn join_timeout(self, timeout: Duration) -> Result<(), ()> {
1130//         println!("Waiting for thread to finish...{}", timeout.as_secs());
1131//         let _ = thread::sleep(timeout);
1132//         match self.join() {
1133//             Ok(_) => Ok(()),
1134//             Err(_) => Err(()),
1135//         }
1136//     }
1137// }