1use std::ffi::{OsStr, OsString};
5
6use base64::Engine;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Shell {
11 Sh,
13 PowerShell,
15}
16
17impl Shell {
18 pub fn host() -> Self {
20 if cfg!(windows) { Self::PowerShell } else { Self::Sh }
21 }
22
23 pub fn describe(self) -> &'static str {
25 match self {
26 Self::Sh => "`sh -c`",
27 Self::PowerShell => "PowerShell",
28 }
29 }
30
31 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
46fn 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
61fn 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}