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 )
116 .with_target(&target)
117 .with_cli(&cli)
118 .with_extra_args(&cli.extra);
119
120 builder.print_command();
121
122 let maybe_backup =
123 crate::e_manifest::maybe_patch_manifest_for_run(&target.manifest_path)
124 .context("Failed to patch manifest for run")?;
125
126 // let system = Arc::new(Mutex::new(System::new_all()));
127 // std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
128 // let mut system_guard = system.lock().unwrap();
129 // system_guard.refresh_processes_specifics(
130 // ProcessesToUpdate::All,
131 // true,
132 // ProcessRefreshKind::nothing().with_cpu(),
133 // );
134 // drop(system_guard);
135
136 let start = Arc::new(std::sync::Mutex::new(None));
137 let start_for_callback = Arc::clone(&start);
138 let pid = Arc::new(builder).run({
139 let manager_ref = Arc::clone(&manager);
140 let t = target.clone();
141 let len = targets_len;
142 let start = Arc::clone(&start_for_callback);
143 // let system_clone = system.clone();
144 move |pid, handle| {
145 let stats = handle.stats.lock().unwrap().clone();
146 let runtime_start = if stats.is_comiler_target {
147 stats.build_finished_time
148 } else {
149 stats.start_time
150 };
151 let mut start_guard = start.lock().unwrap();
152 if start_guard.is_none() {
153 *start_guard = Some(Instant::now());
154 }
155 if !cli.no_status_lines {
156 let status_display = ProcessManager::format_process_status(
157 pid,
158 runtime_start,
159 &t,
160 (idx + 1, len),
161 );
162 ProcessManager::update_status_line(&status_display, true).ok();
163 }
164 manager_ref.register(handle);
165 }
166 })?;
167
168 let timeout = match cli.run_all {
169 RunAll::Timeout(secs) => Duration::from_secs(secs),
170 RunAll::Forever => Duration::from_secs(u64::MAX),
171 RunAll::NotSpecified => Duration::from_secs(cli.wait),
172 };
173
174 // Use an Arc<Mutex<Option<Instant>>> so it can be set in the run callback and accessed in the main loop.
175 let start_for_callback = Arc::clone(&start);
176 let target_name_for_timeout = target.name.clone();
177 // let timeout_thread = std::thread::spawn({
178 // let manager = Arc::clone(&manager);
179 // let pid = pid.clone();
180 // move || {
181 // // Wait until `start` is Some, i.e., the process has started running
182 // while start.is_none() {
183 // println!(
184 // "Waiting for process {} to start before applying timeout...",
185 // pid
186 // );
187 // std::thread::sleep(Duration::from_millis(50));
188 // }
189 // let start_time = start.expect("start should have been set");
190 // while start_time.elapsed() < timeout {
191 // std::thread::sleep(Duration::from_millis(500));
192 // if manager.try_wait(pid).is_ok() {
193 // return; // Process finished naturally
194 // }
195 // println!(
196 // "Process {} is still running, waiting for timeout...",
197 // pid
198 // );
199 // }
200 // // Timeout reached, kill the process
201 // println!(
202 // "\nTimeout reached for target {}. Killing child process {}.",
203 // target_name_for_timeout, pid
204 // );
205 // manager.kill_by_pid(pid).ok();
206 // manager.remove(pid);
207 // }
208 // });
209
210 // Main thread continues to monitor the process
211 loop {
212 if manager.is_alive(pid) {
213 println!(
214 "Monitoring process {} for target {} ({} of {})...",
215 pid, target.name, idx + 1, targets_len
216 );
217 match manager.try_wait(pid) {
218 Ok(Some(status)) => {
219 println!("Process {} finished naturally. {:?}", pid,status);
220 // manager.e_window_kill(pid);
221 // manager.remove(pid);
222 break;
223 }
224 _ => {
225 // Process is still running.
226 // We can check for timeout here as well.
227 if let Ok(start_guard) = start_for_callback.lock() {
228 if let Some(start_time) = *start_guard {
229 if start_time.elapsed() >= timeout {
230 println!(
231 "\nTimeout reached for target {}. Killing child process {}.",
232 target.name,pid);
233 manager.kill_by_pid(pid).ok();
234 // manager.remove(pid);
235 // user_requested_kill_thread.store(true, Ordering::SeqCst);
236 // pids_to_kill_thread.lock().push(pid);
237 break;
238 }
239 }
240 }
241 std::thread::sleep(Duration::from_millis(100));
242 }
243 }
244 if manager.has_signalled() > 0 {
245 println!("Detected Ctrl+C. {}", manager.has_signalled());
246 manager.remove(pid); // Clean up the process handle
247
248 if manager.has_signalled() > 1 {
249 if let Some(dur) = manager.time_between_signals() {
250 if dur < Duration::from_millis(350) {
251 println!("User requested quit two times quickly (<350ms).");
252 user_requested_quit_thread.store(true, Ordering::SeqCst);
253 break;
254 }
255 }
256 }
257 println!("Dectected Ctrl+C, coninuing to next target.");
258 manager.reset_signalled();
259 break;
260 }
261
262 // let (_stats, runtime_start, end_time, status_display) = {
263 // let (stats, runtime_start, end_time) =
264 // if let Some(process_handle) = manager.get(pid) {
265 // if let Ok(handle) = process_handle.lock() {
266 // let stats =
267 // handle.stats.lock().map(|s| s.clone()).unwrap_or_default();
268 // let runtime_start = if stats.is_comiler_target {
269 // stats.build_finished_time
270 // } else {
271 // stats.start_time
272 // };
273 // let end_time = handle.result.end_time;
274 // (stats, runtime_start, end_time)
275 // } else {
276 // // If we can't lock, fallback to defaults
277 // (Default::default(), None, None)
278 // }
279 // } else {
280 // // If process handle not found, fallback to defaults
281 // (Default::default(), None, None)
282 // };
283 // let status_display = if !cli.no_status_lines {
284 // ProcessManager::format_process_status(
285 // pid,
286 // runtime_start,
287 // &target,
288 // (idx + 1, targets_len),
289 // )
290 // } else {
291 // String::new()
292 // };
293 // (stats, runtime_start, end_time, status_display)
294 // };
295
296 // if cli.filter && !cli.no_status_lines {
297 // // let mut system_guard = system.lock().unwrap();
298 // // system_guard.refresh_processes_specifics(
299 // // ProcessesToUpdate::All,
300 // // true,
301 // // ProcessRefreshKind::nothing().with_cpu(),
302 // // );
303 // // drop(system_guard);
304 // ProcessManager::update_status_line(&status_display, true).ok();
305 // }
306 // if runtime_start.is_some() {
307 // // let mut start_guard = start_for_callback.lock().unwrap();
308 // // if start_guard.is_none() {
309 // // *start_guard = Some(Instant::now());
310 // // }
311 // if let Some(start_time) = *start_for_callback.lock().unwrap() {
312 // if start_time.elapsed() >= timeout {
313 // println!(
314 // "\nTimeout reached for target {} after {:.2?}. Killing child process {}.",
315 // target.name,
316 // start_time.elapsed(),
317 // pid
318 // );
319 // manager.e_window_kill(pid);
320 // manager.remove(pid);
321 // manager.kill_by_pid(pid).ok();
322 // break;
323 // }
324 // }
325 // // std::thread::sleep(Duration::from_millis(500));
326 // } else if end_time.is_some() {
327 // println!("Process finished naturally.");
328 // manager.e_window_kill(pid);
329 // manager.remove(pid);
330 // break;
331 // }
332 std::thread::sleep(Duration::from_millis(100));
333 }
334
335 }
336
337 // Wait for the timeout thread to finish
338 // let _ = timeout_thread.join();
339
340 if let Some(original) = maybe_backup {
341 fs::write(&target.manifest_path, original)
342 .context("Failed to restore patched manifest")?;
343 }
344 manager.generate_report(cli.gist);
345
346 Ok(())
347 // --- End: original per-target logic ---
348 });
349 if user_requested_quit.load(Ordering::SeqCst) {
350 break;
351 }
352 handles.push(handle);
353 }
354 // Check if the user requested to quit.
355 if user_requested_quit.load(Ordering::SeqCst) {
356 break;
357 }
358 // Wait for all threads in this chunk to finish
359 for handle in handles {
360 let _ = handle.join();
361 }
362 manager.e_window_kill_all();
363 idx += chunk_size;
364 }
365
366 Ok(Arc::clone(&user_requested_quit).load(Ordering::SeqCst))
367}
368
369// pub fn run_all_examples(cli: &Cli, filtered_targets: &[CargoTarget]) -> Result<()> {
370// // If --quiet was provided, adjust RUSTFLAGS.
371// set_rustflags_if_quiet(cli.quiet);
372
373// // Factor out the prebuild logic.
374// if cli.pre_build {
375// crate::e_prebuild::prebuild_examples(filtered_targets)
376// .context("Prebuild of targets failed")?;
377// }
378// let mut targets = filtered_targets.to_vec();
379// targets.sort_by(|a, b| a.display_name.cmp(&b.display_name));
380// // For each filtered target, run it with child process management.
381// for target in targets {
382// // Clear the screen before running each target.
383
384// // use crossterm::{execute, terminal::{Clear, ClearType}};
385// // use std::io::{stdout, Write};
386// // execute!(stdout(), Clear(ClearType::All), crossterm::cursor::MoveTo(0, 0))?;
387// // std::io::Write::flush(&mut std::io::stdout()).unwrap();
388// println!("Running target: {}", target.name);
389
390// // Retrieve the current package name (or binary name) at compile time.
391// let current_bin = env!("CARGO_PKG_NAME");
392// // Avoid running our own binary if the target's name is the same.
393// if target.kind == TargetKind::Binary && target.name == current_bin {
394// continue;
395// }
396
397// // Determine the run flag and whether we need to pass the manifest path.
398// let (run_flag, needs_manifest) = match target.kind {
399// TargetKind::Example => ("--example", false),
400// TargetKind::ExtendedExample => ("--example", true),
401// TargetKind::Binary => ("--bin", false),
402// TargetKind::ExtendedBinary => ("--bin", true),
403// TargetKind::ManifestTauri => ("", true),
404// TargetKind::ManifestTauriExample => ("", true),
405// TargetKind::Test => ("--test", true),
406// TargetKind::Manifest => ("", true),
407// TargetKind::ManifestDioxus => ("", true),
408// TargetKind::ManifestDioxusExample => ("", true),
409// TargetKind::Bench => ("", true),
410// };
411// let mut cmd_parts = vec!["cargo".to_string()];
412// cmd_parts.push("run".to_string());
413// if cli.release {
414// cmd_parts.push("--release".to_string());
415// }
416// // Pass --quiet if requested.
417// if cli.quiet {
418// cmd_parts.push("--quiet".to_string());
419// }
420// cmd_parts.push(run_flag.to_string());
421// cmd_parts.push(target.name.clone());
422// if needs_manifest {
423// cmd_parts.push("--manifest-path".to_string());
424// cmd_parts.push(
425// target
426// .manifest_path
427// .clone()
428// .to_str()
429// .unwrap_or_default()
430// .to_owned(),
431// );
432// }
433// cmd_parts.extend(cli.extra.clone());
434
435// // // Build a vector of command parts for logging.
436// // let mut cmd_parts = vec!["cargo".to_string(), "run".to_string(), run_flag.to_string(), target.name.clone()];
437// // if needs_manifest {
438// // cmd_parts.push("--manifest-path".to_string());
439// // cmd_parts.push(target.manifest_path.clone());
440// // }
441// // // Append any extra CLI arguments.
442// // cmd_parts.extend(cli.extra.clone());
443
444// // Print out the full command that will be run.
445// let key = prompt(&format!("Full command: {}", cmd_parts.join(" ")), 2)?;
446// if let Some('q') = key {
447// println!("User requested quit.");
448// break;
449// }
450
451// // Clear the screen before running each target.
452// //println!("\x1B[2J\x1B[H");
453
454// // Build the command for execution.
455// let mut command = Command::new("cargo");
456// command.arg("run");
457// if cli.release {
458// command.arg("--release");
459// }
460// if cli.quiet {
461// command.arg("--quiet");
462// }
463// command.arg(run_flag).arg(&target.name);
464// if needs_manifest {
465// command.args(&[
466// "--manifest-path",
467// &target.manifest_path.to_str().unwrap_or_default().to_owned(),
468// ]);
469// }
470
471// // --- Inject required-features support using our helper ---
472// if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
473// std::path::Path::new(&target.manifest_path),
474// &target.kind,
475// &target.name,
476// ) {
477// command.args(&["--features", &features]);
478// }
479// // --- End required-features support ---
480
481// // Append any extra CLI arguments.
482// command.args(&cli.extra);
483
484// // Spawn the child process.
485// let child = command
486// .spawn()
487// .with_context(|| format!("Failed to spawn cargo run for target {}", target.name))?;
488// {
489// let mut global = crate::e_runner::GLOBAL_CHILD.lock().unwrap();
490// *global = Some(child);
491// }
492// // Let the target run for the specified duration.
493// let run_duration = Duration::from_secs(cli.wait);
494// thread::sleep(run_duration);
495
496// // Kill the process (ignoring errors if it already terminated).
497
498// // Decide on the run duration per target and use it accordingly:
499// // Determine behavior based on the run_all flag:
500// let output = {
501// let mut global = crate::e_runner::GLOBAL_CHILD.lock().unwrap();
502// if let Some(mut child) = global.take() {
503// match cli.run_all {
504// RunAll::Timeout(timeout_secs) => {
505// let message = format!(
506// "Press any key to continue (timeout in {} seconds)...",
507// timeout_secs
508// );
509// let key = prompt(&message, timeout_secs)?;
510// if let Some('q') = key {
511// println!("User requested quit.");
512// // Terminate the process and break out of the loop.
513// child.kill().ok();
514// break;
515// }
516// child.kill().ok();
517// child.wait_with_output().with_context(|| {
518// format!("Failed to wait on cargo run for target {}", target.name)
519// })?
520// }
521// RunAll::Forever => {
522// let key = prompt(&"", 0)?;
523// if let Some('q') = key {
524// println!("User requested quit.");
525// // Terminate the process and break out of the loop.
526// child.kill().ok();
527// break;
528// } // Run until natural termination.
529// child.wait_with_output().with_context(|| {
530// format!("Failed to wait on cargo run for target {}", target.name)
531// })?
532// }
533// RunAll::NotSpecified => {
534// let key = prompt(&"", cli.wait)?;
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// }
541// child.kill().ok();
542// child.wait_with_output().with_context(|| {
543// format!("Failed to wait on cargo run for target {}", target.name)
544// })?
545// }
546// }
547// } else {
548// return Err(anyhow::anyhow!("No child process found"));
549// }
550// };
551
552// if !output.stderr.is_empty() {
553// eprintln!(
554// "Target '{}' produced errors:\n{}",
555// target.name,
556// String::from_utf8_lossy(&output.stderr)
557// );
558// }
559// }
560// Ok(())
561// }
562
563use std::{env, fs};
564
565/// If quiet mode is enabled, ensure that RUSTFLAGS contains "-Awarnings".
566/// If RUSTFLAGS is already set, and it does not contain "-Awarnings", then append it.
567pub fn set_rustflags_if_quiet(quiet: bool) {
568 if quiet {
569 let current_flags = env::var("RUSTFLAGS").unwrap_or_else(|_| "".to_string());
570 if !current_flags.contains("-Awarnings") {
571 let new_flags = if current_flags.trim().is_empty() {
572 "-Awarnings".to_string()
573 } else {
574 format!("{} -Awarnings", current_flags)
575 };
576 env::set_var("RUSTFLAGS", new_flags);
577 }
578 }
579}