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