use anyhow::Result;
use std::path::Path;
use std::time::Duration;
pub struct CommandOutput {
pub status: std::process::ExitStatus,
pub stdout: String,
pub stderr: String,
}
pub struct CommandOutputBytes {
pub status: std::process::ExitStatus,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
#[cfg(unix)]
fn configure_process_group(command: &mut std::process::Command) {
use std::os::unix::process::CommandExt;
unsafe {
command.pre_exec(|| {
if libc::setpgid(0, 0) == -1 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
});
}
}
#[cfg(not(unix))]
fn configure_process_group(_command: &mut std::process::Command) {}
fn terminate_child(child: &mut std::process::Child) {
#[cfg(unix)]
{
let _ = unsafe { libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL) };
}
let _ = child.kill();
let _ = child.wait();
}
pub fn run_with_timeout_bytes(
cmd: &str,
args: &[&str],
cwd: &Path,
timeout: Duration,
) -> Result<CommandOutputBytes> {
use std::io::Read;
let mut command = std::process::Command::new(cmd);
command.args(args);
command.current_dir(cwd);
command.stdout(std::process::Stdio::piped());
command.stderr(std::process::Stdio::piped());
configure_process_group(&mut command);
let start = std::time::Instant::now();
let mut child = command.spawn()?;
let mut stdout_pipe = child.stdout.take().unwrap();
let mut stderr_pipe = child.stderr.take().unwrap();
let stdout_handle = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout_pipe.read_to_end(&mut buf);
buf
});
let stderr_handle = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stderr_pipe.read_to_end(&mut buf);
buf
});
loop {
let status = match child.try_wait() {
Ok(status) => status,
Err(error) => {
terminate_child(&mut child);
let _ = stdout_handle.join();
let _ = stderr_handle.join();
return Err(error.into());
}
};
if let Some(status) = status {
let stdout_bytes = stdout_handle.join().unwrap_or_default();
let stderr_bytes = stderr_handle.join().unwrap_or_default();
return Ok(CommandOutputBytes {
status,
stdout: stdout_bytes,
stderr: stderr_bytes,
});
}
if start.elapsed() > timeout {
terminate_child(&mut child);
let _ = stdout_handle.join();
let _ = stderr_handle.join();
return Ok(CommandOutputBytes {
status: std::process::ExitStatus::default(),
stdout: Vec::new(),
stderr: b"timeout".to_vec(),
});
}
std::thread::sleep(Duration::from_millis(10));
}
}
pub fn run_with_timeout(
cmd: &str,
args: &[&str],
cwd: &Path,
timeout: Duration,
) -> Result<CommandOutput> {
let output = run_with_timeout_bytes(cmd, args, cwd, timeout)?;
Ok(CommandOutput {
status: output.status,
stdout: String::from_utf8_lossy(&output.stdout).to_string(),
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
})
}
pub fn run_with_timeout_stdout(cmd: &str, args: &[&str], timeout: Duration) -> Result<String> {
use std::io::Read;
let mut command = std::process::Command::new(cmd);
command.args(args);
command.stdout(std::process::Stdio::piped());
command.stderr(std::process::Stdio::null());
configure_process_group(&mut command);
let start = std::time::Instant::now();
let mut child = command.spawn()?;
let mut stdout_pipe = child.stdout.take().unwrap();
let stdout_handle = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout_pipe.read_to_end(&mut buf);
buf
});
loop {
let status = match child.try_wait() {
Ok(status) => status,
Err(error) => {
terminate_child(&mut child);
let _ = stdout_handle.join();
return Err(error.into());
}
};
if status.is_some() {
let stdout_bytes = stdout_handle.join().unwrap_or_default();
return Ok(String::from_utf8_lossy(&stdout_bytes).to_string());
}
if start.elapsed() > timeout {
terminate_child(&mut child);
let _ = stdout_handle.join();
return Ok(String::new());
}
std::thread::sleep(Duration::from_millis(10));
}
}
pub fn env_flag(name: &str) -> bool {
std::env::var(name).is_ok_and(|value| value == "1")
}
pub fn feature_enabled(config_enabled: bool, enable_var: &str, disable_var: &str) -> bool {
if env_flag(disable_var) {
false
} else if env_flag(enable_var) {
true
} else {
config_enabled
}
}
pub fn direct_feature_enabled(config_enabled: bool, enable_var: &str, disable_var: &str) -> bool {
if env_flag(disable_var) {
false
} else {
config_enabled && env_flag(enable_var)
}
}
pub const SKIP_DIRS: &[&str] = &[
"node_modules",
"target",
".git",
"dist",
"build",
"vendor",
".next",
"__pycache__",
".venv",
"venv",
".svelte-kit",
".vite",
".pi",
".pi-glla",
".opencode",
".claude",
".cursor",
".roo",
".windsurf",
".augment",
".amazonq",
".kiro",
".trae",
".deepseek",
".gemini",
".qwen",
".dracon",
".cache",
".trash",
];
pub const BINARY_EXTS: &[&str] = &[
"exe", "bin", "o", "so", "dll", "dylib", "a", "lib", "obj", "pdb", "png", "jpg", "jpeg", "gif",
"webp", "ico", "svg", "bmp", "tiff", "mp3", "mp4", "avi", "mkv", "mov", "webm", "flac", "wav",
"ogg", "zip", "tar", "gz", "bz2", "xz", "7z", "rar", "tgz", "woff", "woff2", "ttf", "eot",
"pdf", "doc", "docx", "xls", "xlsx", "sqlite", "sqlite3", "db",
"lock", ];
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_run_with_timeout_success() {
let tmp = TempDir::new().unwrap();
let result = run_with_timeout("echo", &["hello"], tmp.path(), Duration::from_secs(5));
assert!(result.is_ok());
let output = result.unwrap();
assert!(output.stdout.contains("hello"));
}
#[test]
fn test_run_with_timeout_timeout() {
let tmp = TempDir::new().unwrap();
let result = run_with_timeout("sleep", &["10"], tmp.path(), Duration::from_millis(50));
assert!(result.is_ok());
let output = result.unwrap();
assert_eq!(output.stderr, "timeout");
}
#[test]
fn test_run_with_timeout_stdout() {
let result = run_with_timeout_stdout("echo", &["test"], Duration::from_secs(5));
assert!(result.is_ok());
assert!(result.unwrap().contains("test"));
}
#[test]
fn test_skip_dirs_constant() {
assert!(SKIP_DIRS.contains(&"node_modules"));
assert!(SKIP_DIRS.contains(&"target"));
assert!(SKIP_DIRS.contains(&".git"));
assert!(SKIP_DIRS.contains(&"__pycache__"));
assert!(SKIP_DIRS.contains(&".svelte-kit"));
assert!(SKIP_DIRS.contains(&".pi"));
assert!(SKIP_DIRS.contains(&".opencode"));
assert!(SKIP_DIRS.contains(&".claude"));
assert!(SKIP_DIRS.contains(&".cursor"));
assert!(SKIP_DIRS.contains(&".dracon"));
assert!(SKIP_DIRS.contains(&".cache"));
}
#[test]
fn test_binary_exts_constant() {
assert!(BINARY_EXTS.contains(&"png"));
assert!(BINARY_EXTS.contains(&"jpg"));
assert!(BINARY_EXTS.contains(&"mp4"));
assert!(BINARY_EXTS.contains(&"lock"));
}
#[test]
fn test_feature_flag_defaults_to_config() {
assert!(feature_enabled(
true,
"FAB_TEST_MISSING_ENABLE",
"FAB_TEST_MISSING_DISABLE"
));
assert!(!feature_enabled(
false,
"FAB_TEST_MISSING_ENABLE",
"FAB_TEST_MISSING_DISABLE"
));
assert!(!direct_feature_enabled(
true,
"FAB_TEST_MISSING_ENABLE",
"FAB_TEST_MISSING_DISABLE"
));
}
}