use std::ffi::OsStr;
use std::process::{Child, Command};
pub fn hidden_command(program: impl AsRef<OsStr>) -> Command {
#[allow(unused_mut)]
let mut command = Command::new(program);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
command
}
pub fn reap_in_background(mut child: Child) {
let _ = std::thread::Builder::new()
.name("symforge-child-reaper".to_owned())
.spawn(move || {
let _ = child.wait();
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_no_raw_command_spawns_outside_hidden_command() {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let mut offenders: Vec<String> = Vec::new();
for tree in ["src", "tests"] {
let tree_root = manifest.join(tree);
let mut stack = vec![tree_root.clone()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).expect("read source dir") {
let entry = entry.expect("dir entry");
let path = entry.path();
if path.is_dir() {
if tree == "tests"
&& path.file_name().is_some_and(|name| name == "fixtures")
{
continue;
}
stack.push(path);
continue;
}
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
continue;
}
let relative = path
.strip_prefix(&tree_root)
.expect("under tree root")
.to_string_lossy()
.replace('\\', "/");
if tree == "src" && relative == "process_util.rs" {
continue; }
let contents = std::fs::read_to_string(&path).expect("read source file");
let mut hits = 0usize;
for (number, line) in contents.lines().enumerate() {
let trimmed = line.trim_start();
if trimmed.starts_with("//") || trimmed.starts_with("//!") {
continue; }
if line.contains("Command::new(") {
hits += 1;
offenders.push(format!("{tree}/{relative}:{}", number + 1));
}
}
if tree == "src" && relative == "daemon.rs" && hits == 1 {
offenders.pop();
}
}
}
}
assert!(
offenders.is_empty(),
"raw Command::new( spawns found — route them through \
process_util::hidden_command so no console window can ever open: {offenders:?}"
);
}
#[test]
fn test_hidden_command_runs_and_captures_output() {
#[cfg(windows)]
let output = hidden_command("cmd")
.args(["/C", "echo hidden-ok"])
.output()
.expect("hidden_command should spawn");
#[cfg(not(windows))]
let output = hidden_command("sh")
.args(["-c", "echo hidden-ok"])
.output()
.expect("hidden_command should spawn");
assert!(output.status.success());
assert!(String::from_utf8_lossy(&output.stdout).contains("hidden-ok"));
}
}