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