aidaemon_tools/
platform_shell.rs1use tokio::process::Command;
8
9pub const POWERSHELL_EXIT_EPILOGUE: &str =
13 "\nif (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }\n";
14
15pub 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
36pub 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}