cargo_e/
e_runall.rs

1use crate::e_cli::RunAll;
2use crate::e_command_builder::CargoCommandBuilder;
3use crate::e_processmanager::ProcessManager;
4use crate::e_target::{CargoTarget, TargetKind};
5use anyhow::{Context, Result};
6use std::path::PathBuf;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::Arc;
9use std::time::Duration;
10use std::time::Instant;
11
12#[cfg(unix)]
13use nix::sys::signal::{kill, Signal};
14#[cfg(unix)]
15use nix::unistd::Pid;
16
17// #[cfg(target_os = "windows")]
18// use std::os::windows::process::CommandExt;
19
20// #[cfg(target_os = "windows")]
21// const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
22
23// #[cfg(target_os = "windows")]
24// fn send_ctrl_c(child: &mut Child) -> Result<()> {
25//     println!("Sending CTRL-C to child process...");
26//     use windows::Win32::System::Console::{GenerateConsoleCtrlEvent, CTRL_C_EVENT};
27
28//     // Send CTRL+C to the child process group.
29//     // The child must have been spawned with CREATE_NEW_PROCESS_GROUP.
30//     let result = unsafe { GenerateConsoleCtrlEvent(CTRL_C_EVENT, child.id()) };
31//     if result.is_err() {
32//         return Err(anyhow::anyhow!("Failed to send CTRL_C_EVENT on Windows"));
33//     }
34
35//     // Allow some time for the child to handle the signal gracefully.
36//     std::thread::sleep(std::time::Duration::from_millis(1000));
37
38//     Ok(())
39// }
40
41#[cfg(not(target_os = "windows"))]
42pub fn send_ctrl_c(child: &mut std::process::Child) -> Result<()> {
43    // On Unix, send SIGINT to the child.
44    kill(Pid::from_raw(child.id() as i32), Signal::SIGINT).context("Failed to send SIGINT")?;
45    // Wait briefly to allow graceful shutdown.
46    std::thread::sleep(Duration::from_millis(2000));
47    Ok(())
48}
49
50/// Runs all filtered targets with prebuild, child process management, and timeout‐based termination.
51///
52/// If the CLI flag `pre_build` is enabled, this function first prebuilds all targets by invoking
53/// `cargo build` with the appropriate flags (using `--example` or `--bin` and, for extended targets,
54/// the `--manifest-path` flag). Then it spawns a child process for each target using `cargo run`,
55/// waits for the duration specified by `cli.wait`, kills the child process, and then checks its output.
56///
57/// # Parameters
58///
59/// - `cli`: A reference to the CLI configuration (containing flags like `pre_build`, `wait`, and extra arguments).
60/// - `filtered_targets`: A slice of `Example` instances representing the targets to run.
61///
62/// # Errors
63///
64/// Returns an error if the prebuild step fails or if any child process fails to spawn or complete.
65pub fn run_all_examples(
66    manager: Arc<ProcessManager>,
67    cli: &crate::Cli,
68    filtered_targets: &[CargoTarget],
69) -> Result<bool> {
70    // Adjust RUSTFLAGS if --quiet was provided.
71    set_rustflags_if_quiet(cli.quiet);
72
73    // Prebuild targets if requested.
74    if cli.pre_build {
75        crate::e_prebuild::prebuild_examples(filtered_targets)
76            .context("Prebuild of targets failed")?;
77    }
78
79    let mut targets = filtered_targets.to_vec();
80    targets.sort_by(|a, b| a.display_name.cmp(&b.display_name));
81
82    let user_requested_quit = Arc::new(AtomicBool::new(false));
83
84    let chunk_size = cli.run_at_a_time;
85    let mut idx = 0;
86    while idx < targets.len() {
87        let chunk = &targets[idx..std::cmp::min(idx + chunk_size, targets.len())];
88        let mut handles = vec![];
89
90        for (chunk_idx, target) in chunk.iter().enumerate() {
91            let manager = Arc::clone(&manager);
92            let cli = cli.clone();
93            let target = target.clone();
94            let targets_len = targets.len();
95            let idx = idx + chunk_idx;
96            let user_requested_quit_thread = Arc::clone(&user_requested_quit);
97
98            // Spawn a thread for each target in the chunk
99            let handle = std::thread::spawn(move || {
100                // --- Begin: original per-target logic ---
101                let current_bin = env!("CARGO_PKG_NAME");
102                // Skip running our own binary.
103                if target.kind == TargetKind::Binary && target.name == current_bin {
104                    return Ok(()) as Result<()>;
105                }
106
107                let manifest_path = PathBuf::from(target.manifest_path.clone());
108                let builder = CargoCommandBuilder::new(
109                    &target.name,
110                    &manifest_path,
111                    &cli.subcommand,
112                    cli.filter,
113                    cli.cached,
114                    cli.default_binary_is_runner,
115                    cli.quiet || cli.json_all_targets,
116                    cli.detached,
117                )
118                .with_target(&target)
119                .with_cli(&cli)
120                .with_extra_args(&cli.extra);
121
122                builder.print_command();
123
124                let maybe_backup =
125                    crate::e_manifest::maybe_patch_manifest_for_run(&target.manifest_path)
126                        .context("Failed to patch manifest for run")?;
127
128                // let system = Arc::new(Mutex::new(System::new_all()));
129                // std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
130                // let mut system_guard = system.lock().unwrap();
131                // system_guard.refresh_processes_specifics(
132                //     ProcessesToUpdate::All,
133                //     true,
134                //     ProcessRefreshKind::nothing().with_cpu(),
135                // );
136                // drop(system_guard);
137
138                let start = Arc::new(std::sync::Mutex::new(None));
139                let start_for_callback = Arc::clone(&start);
140                let pid = Arc::new(builder).run({
141                    let manager_ref = Arc::clone(&manager);
142                    let t = target.clone();
143                    let len = targets_len;
144                    let start = Arc::clone(&start_for_callback);
145                    // let system_clone = system.clone();
146                    move |pid, handle| {
147                        let stats = {
148                            let handle_guard = handle.lock().unwrap();
149                            let stats = handle_guard.stats.lock().unwrap().clone();
150                            stats
151                        };
152                        let runtime_start = if stats.is_comiler_target {
153                            stats.build_finished_time
154                        } else {
155                            stats.start_time
156                        };
157                        let mut start_guard = start.lock().unwrap();
158                        if start_guard.is_none() {
159                            *start_guard = Some(Instant::now());
160                        }
161                        if !cli.no_status_lines {
162                            let status_display = ProcessManager::format_process_status(
163                                pid,
164                                runtime_start,
165                                &t,
166                                (idx + 1, len),
167                            );
168                            ProcessManager::update_status_line(&status_display, true).ok();
169                        }
170                        manager_ref.register(pid, handle);
171                    }
172                })?;
173
174                let timeout = match cli.run_all {
175                    RunAll::Timeout(secs) => Duration::from_secs(secs),
176                    RunAll::Forever => Duration::from_secs(u64::MAX),
177                    RunAll::NotSpecified => Duration::from_secs(cli.wait),
178                };
179
180                // Use an Arc<Mutex<Option<Instant>>> so it can be set in the run callback and accessed in the main loop.
181                let start_for_callback = Arc::clone(&start);
182                // let target_name_for_timeout = target.name.clone();
183                // let timeout_thread = std::thread::spawn({
184                //     let manager = Arc::clone(&manager);
185                //     let pid = pid.clone();
186                //     move || {
187                //         // Wait until `start` is Some, i.e., the process has started running
188                //         while start.is_none() {
189                //             println!(
190                //                 "Waiting for process {} to start before applying timeout...",
191                //                 pid
192                //             );
193                //             std::thread::sleep(Duration::from_millis(50));
194                //         }
195                //         let start_time = start.expect("start should have been set");
196                //         while start_time.elapsed() < timeout {
197                //             std::thread::sleep(Duration::from_millis(500));
198                //             if manager.try_wait(pid).is_ok() {
199                //                 return; // Process finished naturally
200                //             }
201                //             println!(
202                //                 "Process {} is still running, waiting for timeout...",
203                //                 pid
204                //             );
205                //         }
206                //         // Timeout reached, kill the process
207                //         println!(
208                //             "\nTimeout reached for target {}. Killing child process {}.",
209                //             target_name_for_timeout, pid
210                //         );
211                //         manager.kill_by_pid(pid).ok();
212                //         manager.remove(pid);
213                //     }
214                // });
215
216                // Main thread continues to monitor the process
217                loop {
218                    if manager.is_alive(pid) {
219                        std::thread::sleep(Duration::from_millis(500));
220                        match manager.try_wait(pid) {
221                            Ok(Some(status)) => {
222                                println!("Process {} finished naturally. {:?}", pid, status);
223                                let hold = cli.detached_hold.unwrap_or(0);
224                                if cli.detached_hold.is_some() && hold > 0 {
225                                    println!("holding for the duration (detached_hold enabled). Sleeping for {} seconds...", hold);
226                                    std::thread::sleep(std::time::Duration::from_secs(hold as u64));
227                                }
228                                // manager.e_window_kill(pid);
229                                // manager.remove(pid);
230                                break;
231                            }
232                            _ => {
233                                // Process is still running.
234                                // We can check for timeout here as well.
235                                if let Ok(start_guard) = start_for_callback.lock() {
236                                    if let Some(start_time) = *start_guard {
237                                        if start_time.elapsed() >= timeout {
238                                            println!(
239                                            "\nTimeout reached for target {}. Killing child process {}.",
240                                            target.name,pid);
241                                            let hold = cli.detached_hold.unwrap_or(0);
242                                            if cli.detached_hold.is_some() && hold > 0 {
243                                                println!("holding for the duration (detached_hold enabled). Sleeping for {} seconds...", hold);
244                                                std::thread::sleep(std::time::Duration::from_secs(hold as u64));
245                                            }
246                                            manager.kill_by_pid(pid).ok();
247                                            // manager.remove(pid);
248                                            // user_requested_kill_thread.store(true, Ordering::SeqCst);
249                                            // pids_to_kill_thread.lock().push(pid);
250                                            break;
251                                        }
252                                    }
253                                }
254                                std::thread::sleep(Duration::from_millis(100));
255                            }
256                        }
257                        if manager.has_signalled() > 0 {
258                            println!("Detected Ctrl+C. {}", manager.has_signalled());
259                            manager.remove(pid); // Clean up the process handle
260
261                            if manager.has_signalled() > 1 {
262                                if let Some(dur) = manager.time_between_signals() {
263                                    if dur < Duration::from_millis(350) {
264                                        println!("User requested quit two times quickly (<350ms).");
265                                        user_requested_quit_thread.store(true, Ordering::SeqCst);
266                                        break;
267                                    }
268                                }
269                            }
270                            println!("Dectected Ctrl+C, coninuing to next target.");
271                            manager.reset_signalled();
272                            break;
273                        }
274
275                        // let (_stats, runtime_start, end_time, status_display) = {
276                        //     let (stats, runtime_start, end_time) =
277                        //         if let Some(process_handle) = manager.get(pid) {
278                        //             if let Ok(handle) = process_handle.lock() {
279                        //                 let stats =
280                        //                     handle.stats.lock().map(|s| s.clone()).unwrap_or_default();
281                        //                 let runtime_start = if stats.is_comiler_target {
282                        //                     stats.build_finished_time
283                        //                 } else {
284                        //                     stats.start_time
285                        //                 };
286                        //                 let end_time = handle.result.end_time;
287                        //                 (stats, runtime_start, end_time)
288                        //             } else {
289                        //                 // If we can't lock, fallback to defaults
290                        //                 (Default::default(), None, None)
291                        //             }
292                        //         } else {
293                        //             // If process handle not found, fallback to defaults
294                        //             (Default::default(), None, None)
295                        //         };
296                        //     let status_display = if !cli.no_status_lines {
297                        //         ProcessManager::format_process_status(
298                        //             pid,
299                        //             runtime_start,
300                        //             &target,
301                        //             (idx + 1, targets_len),
302                        //         )
303                        //     } else {
304                        //         String::new()
305                        //     };
306                        //     (stats, runtime_start, end_time, status_display)
307                        // };
308
309                        // if cli.filter && !cli.no_status_lines {
310                        //     // let mut system_guard = system.lock().unwrap();
311                        //     // system_guard.refresh_processes_specifics(
312                        //     //     ProcessesToUpdate::All,
313                        //     //     true,
314                        //     //     ProcessRefreshKind::nothing().with_cpu(),
315                        //     // );
316                        //     // drop(system_guard);
317                        //     ProcessManager::update_status_line(&status_display, true).ok();
318                        // }
319                        // if runtime_start.is_some() {
320                        //     // let mut start_guard = start_for_callback.lock().unwrap();
321                        //     // if start_guard.is_none() {
322                        //     //     *start_guard = Some(Instant::now());
323                        //     // }
324                        //     if let Some(start_time) = *start_for_callback.lock().unwrap() {
325                        //         if start_time.elapsed() >= timeout {
326                        //             println!(
327                        //                 "\nTimeout reached for target {} after {:.2?}. Killing child process {}.",
328                        //                 target.name,
329                        //                 start_time.elapsed(),
330                        //                 pid
331                        //             );
332                        //             manager.e_window_kill(pid);
333                        //             manager.remove(pid);
334                        //             manager.kill_by_pid(pid).ok();
335                        //             break;
336                        //         }
337                        //     }
338                        //     // std::thread::sleep(Duration::from_millis(500));
339                        // } else if end_time.is_some() {
340                        //     println!("Process finished naturally.");
341                        //     manager.e_window_kill(pid);
342                        //     manager.remove(pid);
343                        //     break;
344                        // }
345                        std::thread::sleep(Duration::from_millis(100));
346                    }
347                }
348
349                // Wait for the timeout thread to finish
350                // let _ = timeout_thread.join();
351
352                if let Some(original) = maybe_backup {
353                    fs::write(&target.manifest_path, original)
354                        .context("Failed to restore patched manifest")?;
355                }
356                manager.generate_report(cli.gist);
357
358                Ok(())
359                // --- End: original per-target logic ---
360            });
361            if user_requested_quit.load(Ordering::SeqCst) {
362                break;
363            }
364            handles.push(handle);
365        }
366        // Check if the user requested to quit.
367        if user_requested_quit.load(Ordering::SeqCst) {
368            break;
369        }
370        // Wait for all threads in this chunk to finish
371        for handle in handles {
372            let _ = handle.join();
373        }
374        manager.e_window_kill_all();
375        idx += chunk_size;
376    }
377
378    Ok(Arc::clone(&user_requested_quit).load(Ordering::SeqCst))
379}
380
381// pub fn run_all_examples(cli: &Cli, filtered_targets: &[CargoTarget]) -> Result<()> {
382//     // If --quiet was provided, adjust RUSTFLAGS.
383//     set_rustflags_if_quiet(cli.quiet);
384
385//     // Factor out the prebuild logic.
386//     if cli.pre_build {
387//         crate::e_prebuild::prebuild_examples(filtered_targets)
388//             .context("Prebuild of targets failed")?;
389//     }
390//     let mut targets = filtered_targets.to_vec();
391//     targets.sort_by(|a, b| a.display_name.cmp(&b.display_name));
392//     // For each filtered target, run it with child process management.
393//     for target in targets {
394//         // Clear the screen before running each target.
395
396//         // use crossterm::{execute, terminal::{Clear, ClearType}};
397//         // use std::io::{stdout, Write};
398//         //         execute!(stdout(), Clear(ClearType::All), crossterm::cursor::MoveTo(0, 0))?;
399//         // std::io::Write::flush(&mut std::io::stdout()).unwrap();
400//         println!("Running target: {}", target.name);
401
402//         // Retrieve the current package name (or binary name) at compile time.
403//         let current_bin = env!("CARGO_PKG_NAME");
404//         // Avoid running our own binary if the target's name is the same.
405//         if target.kind == TargetKind::Binary && target.name == current_bin {
406//             continue;
407//         }
408
409//         // Determine the run flag and whether we need to pass the manifest path.
410//         let (run_flag, needs_manifest) = match target.kind {
411//             TargetKind::Example => ("--example", false),
412//             TargetKind::ExtendedExample => ("--example", true),
413//             TargetKind::Binary => ("--bin", false),
414//             TargetKind::ExtendedBinary => ("--bin", true),
415//             TargetKind::ManifestTauri => ("", true),
416//             TargetKind::ManifestTauriExample => ("", true),
417//             TargetKind::Test => ("--test", true),
418//             TargetKind::Manifest => ("", true),
419//             TargetKind::ManifestDioxus => ("", true),
420//             TargetKind::ManifestDioxusExample => ("", true),
421//             TargetKind::Bench => ("", true),
422//         };
423//         let mut cmd_parts = vec!["cargo".to_string()];
424//         cmd_parts.push("run".to_string());
425//         if cli.release {
426//             cmd_parts.push("--release".to_string());
427//         }
428//         // Pass --quiet if requested.
429//         if cli.quiet {
430//             cmd_parts.push("--quiet".to_string());
431//         }
432//         cmd_parts.push(run_flag.to_string());
433//         cmd_parts.push(target.name.clone());
434//         if needs_manifest {
435//             cmd_parts.push("--manifest-path".to_string());
436//             cmd_parts.push(
437//                 target
438//                     .manifest_path
439//                     .clone()
440//                     .to_str()
441//                     .unwrap_or_default()
442//                     .to_owned(),
443//             );
444//         }
445//         cmd_parts.extend(cli.extra.clone());
446
447//         // // Build a vector of command parts for logging.
448//         // let mut cmd_parts = vec!["cargo".to_string(), "run".to_string(), run_flag.to_string(), target.name.clone()];
449//         // if needs_manifest {
450//         //     cmd_parts.push("--manifest-path".to_string());
451//         //     cmd_parts.push(target.manifest_path.clone());
452//         // }
453//         // // Append any extra CLI arguments.
454//         // cmd_parts.extend(cli.extra.clone());
455
456//         // Print out the full command that will be run.
457//         let key = prompt(&format!("Full command: {}", cmd_parts.join(" ")), 2)?;
458//         if let Some('q') = key {
459//             println!("User requested quit.");
460//             break;
461//         }
462
463//         // Clear the screen before running each target.
464//         //println!("\x1B[2J\x1B[H");
465
466//         // Build the command for execution.
467//         let mut command = Command::new("cargo");
468//         command.arg("run");
469//         if cli.release {
470//             command.arg("--release");
471//         }
472//         if cli.quiet {
473//             command.arg("--quiet");
474//         }
475//         command.arg(run_flag).arg(&target.name);
476//         if needs_manifest {
477//             command.args(&[
478//                 "--manifest-path",
479//                 &target.manifest_path.to_str().unwrap_or_default().to_owned(),
480//             ]);
481//         }
482
483//         // --- Inject required-features support using our helper ---
484//         if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
485//             std::path::Path::new(&target.manifest_path),
486//             &target.kind,
487//             &target.name,
488//         ) {
489//             command.args(&["--features", &features]);
490//         }
491//         // --- End required-features support ---
492
493//         // Append any extra CLI arguments.
494//         command.args(&cli.extra);
495
496//         // Spawn the child process.
497//         let child = command
498//             .spawn()
499//             .with_context(|| format!("Failed to spawn cargo run for target {}", target.name))?;
500//         {
501//             let mut global = crate::e_runner::GLOBAL_CHILD.lock().unwrap();
502//             *global = Some(child);
503//         }
504//         // Let the target run for the specified duration.
505//         let run_duration = Duration::from_secs(cli.wait);
506//         thread::sleep(run_duration);
507
508//         // Kill the process (ignoring errors if it already terminated).
509
510//         // Decide on the run duration per target and use it accordingly:
511//         // Determine behavior based on the run_all flag:
512//         let output = {
513//             let mut global = crate::e_runner::GLOBAL_CHILD.lock().unwrap();
514//             if let Some(mut child) = global.take() {
515//                 match cli.run_all {
516//                     RunAll::Timeout(timeout_secs) => {
517//                         let message = format!(
518//                             "Press any key to continue (timeout in {} seconds)...",
519//                             timeout_secs
520//                         );
521//                         let key = prompt(&message, timeout_secs)?;
522//                         if let Some('q') = key {
523//                             println!("User requested quit.");
524//                             // Terminate the process and break out of the loop.
525//                             child.kill().ok();
526//                             break;
527//                         }
528//                         child.kill().ok();
529//                         child.wait_with_output().with_context(|| {
530//                             format!("Failed to wait on cargo run for target {}", target.name)
531//                         })?
532//                     }
533//                     RunAll::Forever => {
534//                         let key = prompt(&"", 0)?;
535//                         if let Some('q') = key {
536//                             println!("User requested quit.");
537//                             // Terminate the process and break out of the loop.
538//                             child.kill().ok();
539//                             break;
540//                         } // Run until natural termination.
541//                         child.wait_with_output().with_context(|| {
542//                             format!("Failed to wait on cargo run for target {}", target.name)
543//                         })?
544//                     }
545//                     RunAll::NotSpecified => {
546//                         let key = prompt(&"", cli.wait)?;
547//                         if let Some('q') = key {
548//                             println!("User requested quit.");
549//                             // Terminate the process and break out of the loop.
550//                             child.kill().ok();
551//                             break;
552//                         }
553//                         child.kill().ok();
554//                         child.wait_with_output().with_context(|| {
555//                             format!("Failed to wait on cargo run for target {}", target.name)
556//                         })?
557//                     }
558//                 }
559//             } else {
560//                 return Err(anyhow::anyhow!("No child process found"));
561//             }
562//         };
563
564//         if !output.stderr.is_empty() {
565//             eprintln!(
566//                 "Target '{}' produced errors:\n{}",
567//                 target.name,
568//                 String::from_utf8_lossy(&output.stderr)
569//             );
570//         }
571//     }
572//     Ok(())
573// }
574
575use std::{env, fs};
576
577/// If quiet mode is enabled, ensure that RUSTFLAGS contains "-Awarnings".
578/// If RUSTFLAGS is already set, and it does not contain "-Awarnings", then append it.
579pub fn set_rustflags_if_quiet(quiet: bool) {
580    if quiet {
581        let current_flags = env::var("RUSTFLAGS").unwrap_or_else(|_| "".to_string());
582        if !current_flags.contains("-Awarnings") {
583            let new_flags = if current_flags.trim().is_empty() {
584                "-Awarnings".to_string()
585            } else {
586                format!("{} -Awarnings", current_flags)
587            };
588            env::set_var("RUSTFLAGS", new_flags);
589        }
590    }
591}