use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use tokio::process::Command;
#[derive(Debug, Clone)]
pub struct CommandOutput {
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
pub duration_ms: u128,
}
impl CommandOutput {
pub fn success(&self) -> bool {
self.exit_code == Some(0)
}
}
static PATH_INDEX: OnceLock<HashMap<String, Vec<String>>> = OnceLock::new();
fn build_path_index() -> HashMap<String, Vec<String>> {
let mut index: HashMap<String, Vec<String>> = HashMap::new();
let Some(path_var) = std::env::var_os("PATH") else {
return index;
};
let pathext: Vec<String> = if cfg!(windows) {
std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD;.PS1".to_string())
.split(';')
.filter(|s| !s.is_empty())
.map(|s| s.to_ascii_lowercase())
.collect()
} else {
Vec::new()
};
let mut seen_paths = HashSet::new();
for dir in std::env::split_paths(&path_var) {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
let mut dir_files: Vec<(String, String)> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let Some(fname) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
let full = path.to_string_lossy().into_owned();
if seen_paths.insert(full.to_ascii_lowercase()) {
dir_files.push((fname.to_ascii_lowercase(), full));
}
}
if cfg!(windows) {
dir_files.sort_by_key(|(fname, _)| {
pathext
.iter()
.position(|ext| fname.ends_with(ext))
.unwrap_or(usize::MAX)
});
}
for (fname, full) in dir_files {
let stem = if cfg!(windows) {
pathext
.iter()
.find_map(|ext| fname.strip_suffix(ext))
.unwrap_or(&fname)
.to_string()
} else {
fname.clone()
};
index.entry(stem).or_default().push(full.clone());
index.entry(fname).or_default().push(full);
}
}
index
}
pub fn find_executable(names: &[&str]) -> Option<String> {
let index = PATH_INDEX.get_or_init(build_path_index);
for name in names {
let key = name.to_ascii_lowercase();
if let Some(paths) = index.get(&key) {
if let Some(first) = paths.first() {
return Some(first.clone());
}
}
}
None
}
pub fn find_all_executables(name: &str) -> Vec<String> {
let index = PATH_INDEX.get_or_init(build_path_index);
let key = name.to_ascii_lowercase();
index.get(&key).cloned().unwrap_or_default()
}
pub fn build_command(program: &str, args: &[String]) -> Command {
let lower = program.to_ascii_lowercase();
if cfg!(windows) && (lower.ends_with(".cmd") || lower.ends_with(".bat")) {
let mut cmd = Command::new("cmd.exe");
cmd.arg("/C").arg(program).args(args);
cmd
} else if cfg!(windows) && lower.ends_with(".ps1") {
let mut cmd = Command::new("powershell.exe");
cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", program])
.args(args);
cmd
} else {
let mut cmd = Command::new(program);
cmd.args(args);
cmd
}
}
pub async fn run_command(
program: &str,
args: &[String],
timeout_secs: u64,
) -> Result<CommandOutput, String> {
let started = Instant::now();
let mut cmd = build_command(program, args);
cmd.stdin(std::process::Stdio::null());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let child = cmd
.spawn()
.map_err(|e| format!("failed to spawn '{}': {e}", PathBuf::from(program).display()))?;
let waited = tokio::time::timeout(
Duration::from_secs(timeout_secs),
child.wait_with_output(),
)
.await;
match waited {
Ok(Ok(output)) => Ok(CommandOutput {
exit_code: output.status.code(),
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
duration_ms: started.elapsed().as_millis(),
}),
Ok(Err(e)) => Err(format!("failed waiting for '{program}': {e}")),
Err(_) => Err(format!(
"command '{program} {}' timed out after {timeout_secs}s",
args.join(" ")
)),
}
}
pub fn first_non_empty_line(text: &str) -> Option<String> {
text.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(ToString::to_string)
}
pub fn strip_ansi(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
if matches!(chars.peek(), Some('[')) {
chars.next();
while let Some(&next) = chars.peek() {
chars.next();
if ('@'..='~').contains(&next) {
break;
}
}
}
} else {
out.push(c);
}
}
out
}
pub async fn run_command_streaming<F>(
program: &str,
args: &[String],
timeout_secs: u64,
mut on_line: F,
) -> Result<CommandOutput, String>
where
F: FnMut(&'static str, &str),
{
use tokio::io::{AsyncBufReadExt, BufReader};
let started = Instant::now();
let mut cmd = build_command(program, args);
cmd.stdin(std::process::Stdio::null());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut child = cmd
.spawn()
.map_err(|e| format!("failed to spawn '{}': {e}", PathBuf::from(program).display()))?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let mut out_lines = stdout.map(|s| BufReader::new(s).lines());
let mut err_lines = stderr.map(|s| BufReader::new(s).lines());
let mut collected_out = String::new();
let mut collected_err = String::new();
let deadline = tokio::time::sleep(Duration::from_secs(timeout_secs));
tokio::pin!(deadline);
loop {
let out_done = out_lines.is_none();
let err_done = err_lines.is_none();
if out_done && err_done {
break;
}
tokio::select! {
_ = &mut deadline => {
let _ = child.kill().await;
return Err(format!("command '{program} {}' timed out after {timeout_secs}s", args.join(" ")));
}
res = async {
match out_lines.as_mut() {
Some(r) => r.next_line().await,
None => std::future::pending().await,
}
}, if out_lines.is_some() => {
match res {
Ok(Some(line)) => {
on_line("stdout", &line);
collected_out.push_str(&line);
collected_out.push('\n');
}
_ => out_lines = None,
}
}
res = async {
match err_lines.as_mut() {
Some(r) => r.next_line().await,
None => std::future::pending().await,
}
}, if err_lines.is_some() => {
match res {
Ok(Some(line)) => {
on_line("stderr", &line);
collected_err.push_str(&line);
collected_err.push('\n');
}
_ => err_lines = None,
}
}
}
}
let status = child
.wait()
.await
.map_err(|e| format!("failed waiting for '{program}': {e}"))?;
Ok(CommandOutput {
exit_code: status.code(),
stdout: collected_out,
stderr: collected_err,
duration_ms: started.elapsed().as_millis(),
})
}