1use std::ffi::OsString;
7use std::path::Path;
8use std::process::Command;
9
10use crate::Env;
11
12pub fn command(exe: &Path, args: &[OsString], env: &Env, root: &Path) -> Command {
17 let mut command = Command::new(exe);
18 command
19 .args(args)
20 .env_clear()
21 .envs(env.vars())
22 .current_dir(root);
23 command
24}
25
26pub fn shown<'a>(path: &'a Path, cwd: &Path) -> &'a Path {
29 path.strip_prefix(cwd).unwrap_or(path)
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use crate::NameCase;
36 use std::ffi::OsStr;
37
38 #[test]
44 fn a_program_runs_in_the_root_with_the_environment_given() {
45 let env = Env::from_pairs([("ONLY".into(), "1".into())], NameCase::Insensitive);
46 let args = [OsString::from("--exact"), OsString::from("t")];
47 let cmd = command(Path::new("C:/p/app.exe"), &args, &env, Path::new("C:/p"));
48 assert_eq!(cmd.get_program(), OsStr::new("C:/p/app.exe"));
49 assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--exact", "t"]);
50 assert_eq!(cmd.get_current_dir(), Some(Path::new("C:/p")));
51 let vars: Vec<_> = cmd.get_envs().collect();
52 assert_eq!(vars, [(OsStr::new("ONLY"), Some(OsStr::new("1")))]);
53 let (shell, list): (OsString, &[&str]) = match std::env::var_os("ComSpec") {
56 Some(cmd) => (cmd, &["/C", "set"]),
57 None => ("/usr/bin/env".into(), &[]),
58 };
59 let list: Vec<OsString> = list.iter().map(OsString::from).collect();
60 let printed = command(Path::new(&shell), &list, &env, &std::env::temp_dir())
61 .output()
62 .unwrap()
63 .stdout;
64 let printed = String::from_utf8_lossy(&printed);
65 assert!(printed.contains("ONLY=1"), "{printed}");
66 assert!(!printed.contains("CARGO_PKG_NAME="), "{printed}");
67 }
68
69 #[test]
75 fn a_program_is_shown_relative_to_the_current_directory() {
76 let cwd = Path::new("C:/p");
77 assert_eq!(
78 shown(Path::new("C:/p/target/debug/app.exe"), cwd),
79 Path::new("target/debug/app.exe")
80 );
81 assert_eq!(
82 shown(Path::new("D:/other/app.exe"), cwd),
83 Path::new("D:/other/app.exe")
84 );
85 }
86}