aboutsummaryrefslogtreecommitdiff
path: root/libs/nak/src/runtime_wrap.rs
blob: 9b5ff8990235a341b2a234a1176ee704c334d9bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::env;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;

fn env_flag(name: &str) -> bool {
    matches!(
        env::var(name)
            .unwrap_or_default()
            .trim()
            .to_ascii_lowercase()
            .as_str(),
        "1" | "true" | "yes" | "on"
    )
}

pub fn use_steam_run() -> bool {
    env_flag("NAK_USE_STEAM_RUN")
}

pub fn use_umu_for_prefix() -> bool {
    env_flag("NAK_USE_UMU_FOR_PREFIX")
}

pub fn prefer_system_umu() -> bool {
    env_flag("NAK_PREFER_SYSTEM_UMU")
}

fn find_in_path(binary: &str) -> Option<PathBuf> {
    let path = env::var_os("PATH")?;
    env::split_paths(&path)
        .map(|entry| entry.join(binary))
        .find(|candidate| candidate.exists())
}

pub fn resolve_umu_run() -> Option<PathBuf> {
    let bundled = env::var("NAK_BUNDLED_UMU_RUN")
        .ok()
        .map(PathBuf::from)
        .filter(|p| p.exists());
    let system = find_in_path("umu-run");

    if prefer_system_umu() {
        system.or(bundled)
    } else {
        bundled.or(system)
    }
}

/// Build a command to run `exe` with the given environment variables.
///
/// In steam-run mode, the command is wrapped with `steam-run`.
/// Otherwise the command runs directly.
pub fn build_command<S: AsRef<OsStr>>(
    exe: impl AsRef<OsStr>,
    envs: &[(&str, S)],
) -> Command {
    if use_steam_run() {
        let mut cmd = Command::new("steam-run");
        cmd.arg(exe.as_ref());
        for (key, value) in envs {
            cmd.env(key, value.as_ref());
        }
        return cmd;
    }
    let mut cmd = Command::new(exe);
    for (key, value) in envs {
        cmd.env(key, value.as_ref());
    }
    cmd
}

/// Build a command with no extra environment variables.
pub fn command_for(exe: impl AsRef<OsStr>) -> Command {
    build_command::<&str>(exe, &[])
}

pub fn bundled_umu_path_from_appdir(appdir: &Path) -> Option<PathBuf> {
    let path = appdir.join("umu-run");
    if path.exists() {
        Some(path)
    } else {
        None
    }
}