Skip to main content

aidaemon_tools/
platform_shell.rs

1//! The shell a command line runs in: `sh -c` on Unix, Windows PowerShell on
2//! Windows (always present, unlike `sh`). The command-effect checks are
3//! written for POSIX shells and fail closed: a PowerShell line they cannot
4//! read as a known observation or local work is treated as unknown, so it
5//! asks first.
6
7use tokio::process::Command;
8
9/// Appended to every PowerShell script so the shell exits as `sh` does:
10/// with the last program's own exit code. `-Command` alone turns any
11/// failing last step into 1, so `python x.py` exiting 7 read as 1.
12pub const POWERSHELL_EXIT_EPILOGUE: &str =
13    "\nif (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }\n";
14
15/// `script` run by this platform's shell.
16pub fn shell_command(script: &str) -> Command {
17    if cfg!(windows) {
18        let mut command = Command::new("powershell.exe");
19        command.args([
20            "-NoLogo",
21            "-NoProfile",
22            "-NonInteractive",
23            "-ExecutionPolicy",
24            "Bypass",
25            "-Command",
26            &format!("{script}{POWERSHELL_EXIT_EPILOGUE}"),
27        ]);
28        command
29    } else {
30        let mut command = Command::new("sh");
31        command.arg("-c").arg(script);
32        command
33    }
34}
35
36/// Whether this platform's shell is there to run commands.
37pub fn shell_available() -> bool {
38    if cfg!(windows) {
39        true
40    } else {
41        std::path::Path::new("/bin/sh").exists()
42    }
43}
44
45#[cfg(all(test, windows))]
46mod tests {
47    use super::*;
48
49    async fn exit_code(script: &str) -> Option<i32> {
50        shell_command(script).output().await.unwrap().status.code()
51    }
52
53    #[tokio::test]
54    async fn the_last_programs_exit_code_comes_through() {
55        assert_eq!(exit_code("cmd /c exit 7").await, Some(7));
56        assert_eq!(
57            exit_code("Get-Item C:/synthetic-missing-path").await,
58            Some(1)
59        );
60        assert_eq!(
61            exit_code("cmd /c exit 3; Write-Output after").await,
62            Some(0)
63        );
64        assert_eq!(exit_code("Write-Output ok").await, Some(0));
65    }
66}