rpi-tools 0.36.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
Documentation
//! Windows shell resolution + output encoding, exercised against the real
//! host.
//!
//! The reported bug: on a machine with Git for Windows outside
//! `%ProgramFiles%`, discovery fell through to `where bash.exe`, whose first
//! hit on a stock machine is `C:\Windows\System32\bash.exe` — the WSL
//! launcher. That stub exits 1 and writes its message in UTF-16LE, so the
//! `bash` tool reported a failed command whose text was garbage (NUL bytes
//! stripped, non-ASCII decoded as the console code page).
//!
//! These checks are behavioural on purpose: the resolved path is private, but
//! a real Git Bash is distinguishable from the WSL launcher (`uname -s` is
//! `MINGW*`/`MSYS*`, Windows cwd is reachable, output is UTF-8).

#![cfg(windows)]

use std::sync::Arc;

use rpi_tools::{ExecutionErrorCode, OsExecutionEnv, Shell, ShellExecOptions};

/// Skip (do not fail) when this machine has no usable bash: the crate keeps
/// passing on a host without Git for Windows.
macro_rules! shell_or_skip {
    ($env:expr) => {
        match $env.exec("true", ShellExecOptions::default()).await {
            Ok(_) => {}
            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => {
                eprintln!("skipping: no usable bash on this host ({error})");
                return;
            }
            Err(error) => panic!("unexpected shell error: {error:?}"),
        }
    };
}

#[tokio::test]
async fn resolves_git_bash_with_utf8_output_and_host_cwd() {
    let temp = tempfile::tempdir().unwrap();
    std::fs::write(temp.path().join("marker.txt"), "cwd-reached").unwrap();
    let environment = std::env::vars()
        .filter(|(name, _)| {
            let name = name.to_ascii_uppercase();
            name != "LANG" && !name.starts_with("LC_")
        })
        .collect();
    let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf()).with_environment(environment);
    shell_or_skip!(env);

    let out = env
        .exec("uname -s", ShellExecOptions::default())
        .await
        .expect("bash runs");
    let uname = out.stdout.trim();
    assert!(
        uname.starts_with("MINGW") || uname.starts_with("MSYS"),
        "expected Git Bash/MSYS, got {uname:?} — the WSL launcher or cmd was used"
    );

    // cwd: the Windows temp directory must be the shell's working directory.
    let out = env
        .exec("cat marker.txt", ShellExecOptions::default())
        .await
        .expect("cwd is reachable from the shell");
    assert_eq!(
        out.stdout.trim(),
        "cwd-reached",
        "wrong cwd: {:?}",
        out.stdout
    );

    // UTF-8: a Chinese command argument must come back as the same characters
    // (the command arrives as UTF-8 and the child must echo UTF-8).
    let out = env
        .exec(r#"printf '中文输出\n'"#, ShellExecOptions::default())
        .await
        .expect("utf-8 output");
    assert_eq!(out.stdout, "中文输出\n");
    assert!(
        !out.stdout.contains('\u{fffd}'),
        "output was decoded with the wrong encoding: {:?}",
        out.stdout
    );

    // The defaults that make the above encoding stable.
    let out = env
        .exec(
            r#"printf '%s|%s' "${LANG:-}" "${LC_ALL:-}""#,
            ShellExecOptions::default(),
        )
        .await
        .expect("locale");
    assert_eq!(out.stdout, "C.UTF-8|");
    let out = env
        .exec(
            r#"printf '%s|%s' "${LANG:-}" "${LC_ALL:-}""#,
            ShellExecOptions {
                env: Some([("LANG".to_string(), "C".to_string())].into()),
                ..Default::default()
            },
        )
        .await
        .expect("explicit locale");
    assert_eq!(out.stdout, "C|");
}

/// Native Windows programs run from bash still write the console code page
/// (GBK on a Chinese system). The decoder must fall back to it rather than
/// emit replacement characters.
#[tokio::test]
async fn non_utf8_output_decodes_with_the_console_code_page() {
    if rpi_tools::output_decode::console_encoding() != encoding_rs::GBK {
        eprintln!("skipping: console code page is not GBK (936) on this host");
        return;
    }
    let temp = tempfile::tempdir().unwrap();
    let env = Arc::new(OsExecutionEnv::with_cwd(temp.path().to_path_buf()));
    match env.exec("true", ShellExecOptions::default()).await {
        Ok(_) => {}
        Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => {
            eprintln!("skipping: no usable bash on this host ({error})");
            return;
        }
        Err(error) => panic!("unexpected shell error: {error:?}"),
    }

    // `\326\320\316\304` is "中文" in GBK, emitted as raw bytes like a native
    // tool would.
    let out = env
        .exec(
            r#"printf '\326\320\316\304\n'"#,
            ShellExecOptions::default(),
        )
        .await
        .expect("legacy output");
    assert_eq!(out.stdout, "中文\n");
}