basic-cli
basic-cli copied to clipboard
Add `check_command_available` functionality for basic-cli
Here is an example rust implementation from roc-lang/roc/crates/utils/command/src/lib.rs.
This will be useful for scripts to check a command exists before trying to run it.
fn check_command_available(command_name: &str) -> bool {
if cfg!(target_family = "unix") {
let unparsed_path = match std::env::var("PATH") {
Ok(var) => var,
Err(VarError::NotPresent) => return false,
Err(VarError::NotUnicode(_)) => {
panic!("found PATH, but it included invalid unicode data!")
}
};
std::env::split_paths(&unparsed_path).any(|dir| dir.join(command_name).exists())
} else if cfg!(target = "windows") {
let mut cmd = Command::new("Get-Command");
cmd.args([command_name]);
let cmd_str = format!("{cmd:?}");
let cmd_out = cmd.output().unwrap_or_else(|err| {
panic!(
"Failed to execute `{cmd_str}` to check if {command_name} is available:\n {err}"
)
});
cmd_out.status.success()
} else {
// We're in uncharted waters, best not to panic if
// things may end up working out down the line.
true
}
}