Skip to main content

byob_exec/
shell.rs

1//! The shell `run_command` hands its command to: `sh -c` on Unix and in containers; on
2//! Windows, PowerShell (`pwsh` when installed, else the Windows PowerShell every Windows has).
3
4use std::ffi::{OsStr, OsString};
5
6use base64::Engine;
7
8/// Which shell runs a command.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Shell {
11    /// `sh -c` (POSIX).
12    Sh,
13    /// PowerShell.
14    PowerShell,
15}
16
17impl Shell {
18    /// The shell for commands on this computer.
19    pub fn host() -> Self {
20        if cfg!(windows) { Self::PowerShell } else { Self::Sh }
21    }
22
23    /// How the tool description names it.
24    pub fn describe(self) -> &'static str {
25        match self {
26            Self::Sh => "`sh -c`",
27            Self::PowerShell => "PowerShell",
28        }
29    }
30
31    /// Program and arguments that run `command`.
32    pub fn argv(self, command: &str) -> (OsString, Vec<OsString>) {
33        match self {
34            Self::Sh => ("sh".into(), vec!["-c".into(), command.into()]),
35            Self::PowerShell => {
36                let program = if byob_sandbox::which(OsStr::new("pwsh")).is_some() { "pwsh" } else { "powershell" };
37                let args = ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand"];
38                let mut v: Vec<OsString> = args.iter().map(OsString::from).collect();
39                v.push(encode(&powershell_script(command)).into());
40                (program.into(), v)
41            }
42        }
43    }
44}
45
46/// `command` with UTF-8 output (Windows PowerShell writes the console code page into pipes
47/// otherwise) and UTF-8 files (its `Set-Content` and `Out-File` write the ANSI code page or
48/// UTF-16, so a `✓` became `?`; 5.1's UTF-8 has a BOM, PowerShell 7's doesn't), no progress
49/// bars, and a failing program's exit code as the script's.
50fn powershell_script(command: &str) -> String {
51    format!(
52        "$ProgressPreference = 'SilentlyContinue'\n\
53         [Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n\
54         $OutputEncoding = [System.Text.Encoding]::UTF8\n\
55         if ($PSVersionTable.PSVersion.Major -lt 6) {{ $PSDefaultParameterValues['*:Encoding'] = 'utf8' }}\n\
56         {command}\n\
57         if ($LASTEXITCODE) {{ exit $LASTEXITCODE }}\n"
58    )
59}
60
61/// `-EncodedCommand` takes base64 of UTF-16LE. Passing the script that way avoids Windows
62/// PowerShell's quote stripping in `-Command` arguments.
63fn encode(script: &str) -> String {
64    let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
65    base64::engine::general_purpose::STANDARD.encode(bytes)
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn sh_takes_the_command_as_is() {
74        let (p, a) = Shell::Sh.argv("echo 'hi' | wc -c");
75        assert_eq!((p, a), ("sh".into(), vec![OsString::from("-c"), "echo 'hi' | wc -c".into()]));
76    }
77
78    #[test]
79    fn powershell_gets_the_command_encoded_with_quotes_intact() {
80        let (p, a) = Shell::PowerShell.argv(r#"Get-ChildItem "my files" | Select-Object -First 2"#);
81        assert!(p == "pwsh" || p == "powershell", "{p:?}");
82        assert_eq!(a.get(a.len() - 2).map(OsString::as_os_str), Some(OsStr::new("-EncodedCommand")));
83        let b64 = a.last().and_then(|s| s.to_str()).unwrap();
84        let raw = base64::engine::general_purpose::STANDARD.decode(b64).unwrap();
85        let units: Vec<u16> = raw.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
86        let script = String::from_utf16(&units).unwrap();
87        assert!(script.contains(r#"Get-ChildItem "my files" | Select-Object -First 2"#), "{script}");
88        assert!(script.contains("$PSDefaultParameterValues['*:Encoding'] = 'utf8'"), "{script}");
89        assert!(script.contains("[Console]::OutputEncoding") && script.trim_end().ends_with("exit $LASTEXITCODE }"), "{script}");
90    }
91
92    #[test]
93    fn the_host_shell_matches_the_os() {
94        assert_eq!(Shell::host(), if cfg!(windows) { Shell::PowerShell } else { Shell::Sh });
95    }
96}