artifactize-tools 0.27.2

Portable scoped tools and safe file access for artifactize.
Documentation
//! Unix desktop handoff and WSL opener status policy.

use std::{
    ffi::OsStr,
    io,
    process::{ExitStatus, Stdio},
    time::Duration,
};

/// The desktop's own opener program: `open` on macOS; `xdg-open` elsewhere, WSL included.
#[cfg(target_os = "macos")]
const OPENER: &str = "open";
#[cfg(not(target_os = "macos"))]
const OPENER: &str = "xdg-open";

/// Run the desktop opener with the target as its one argument, never through a shell.
pub(crate) async fn open_desktop(
    target: &OsStr,
    deadline: Duration,
    cancellation: &tokio_util::sync::CancellationToken,
) -> io::Result<()> {
    let cwd = std::env::current_dir()?;
    let program = crate::program::resolve(std::path::Path::new(OPENER), &cwd)?;
    let mut command = tokio::process::Command::new(program);
    command
        .arg(target)
        .env_clear()
        .envs(crate::environment::user())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    let status = crate::platform::process::handoff(&mut command, deadline, cancellation).await?;
    if !opened(&status, is_wsl()) {
        return Err(io::Error::other(format!(
            "Desktop opener exited with {status}."
        )));
    }
    Ok(())
}

/// On WSL, xdg-utils opens files with `explorer.exe`, which exits 1 even after opening the
/// file, and xdg-open then reports "the action failed" with this status (#210).
const WSL_EXPLORER_STATUS: i32 = 4;

/// Whether the opener's exit status means the target was handed to the desktop.
fn opened(status: &ExitStatus, wsl: bool) -> bool {
    status.success() || (wsl && status.code() == Some(WSL_EXPLORER_STATUS))
}

/// Whether this is WSL, by the test xdg-open itself uses: `microsoft` in `/proc/version`.
fn is_wsl() -> bool {
    cfg!(target_os = "linux")
        && std::fs::read_to_string("/proc/version")
            .is_ok_and(|version| version.contains("microsoft"))
}

// The opener's exit status exists only where an opener process runs: Unix, WSL included.
// Windows hands the target to ShellExecute instead.
#[cfg(test)]
mod tests;