use std::ffi::OsString;
use std::path::Path;
use std::process::Command;
use crate::Env;
pub fn command(exe: &Path, args: &[OsString], env: &Env, root: &Path) -> Command {
let mut command = Command::new(exe);
command
.args(args)
.env_clear()
.envs(env.vars())
.current_dir(root);
command
}
pub fn shown<'a>(path: &'a Path, cwd: &Path) -> &'a Path {
path.strip_prefix(cwd).unwrap_or(path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::NameCase;
use std::ffi::OsStr;
#[test]
fn a_program_runs_in_the_root_with_the_environment_given() {
let env = Env::from_pairs([("ONLY".into(), "1".into())], NameCase::Insensitive);
let args = [OsString::from("--exact"), OsString::from("t")];
let cmd = command(Path::new("C:/p/app.exe"), &args, &env, Path::new("C:/p"));
assert_eq!(cmd.get_program(), OsStr::new("C:/p/app.exe"));
assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--exact", "t"]);
assert_eq!(cmd.get_current_dir(), Some(Path::new("C:/p")));
let vars: Vec<_> = cmd.get_envs().collect();
assert_eq!(vars, [(OsStr::new("ONLY"), Some(OsStr::new("1")))]);
let (shell, list): (OsString, &[&str]) = match std::env::var_os("ComSpec") {
Some(cmd) => (cmd, &["/C", "set"]),
None => ("/usr/bin/env".into(), &[]),
};
let list: Vec<OsString> = list.iter().map(OsString::from).collect();
let printed = command(Path::new(&shell), &list, &env, &std::env::temp_dir())
.output()
.unwrap()
.stdout;
let printed = String::from_utf8_lossy(&printed);
assert!(printed.contains("ONLY=1"), "{printed}");
assert!(!printed.contains("CARGO_PKG_NAME="), "{printed}");
}
#[test]
fn a_program_is_shown_relative_to_the_current_directory() {
let cwd = Path::new("C:/p");
assert_eq!(
shown(Path::new("C:/p/target/debug/app.exe"), cwd),
Path::new("target/debug/app.exe")
);
assert_eq!(
shown(Path::new("D:/other/app.exe"), cwd),
Path::new("D:/other/app.exe")
);
}
}