Skip to main content

cargo_zng/res/built_in/
sh.rs

1use std::process::Command;
2
3use super::*;
4
5const SH_HELP: &str = r#"
6Run a bash script
7
8Script is configured using environment variables (like other tools):
9
10ZR_SOURCE_DIR — Resources directory that is being build.
11ZR_TARGET_DIR — Target directory where resources are being built to.
12ZR_CACHE_DIR — Dir to use for intermediary data for the specific request.
13ZR_WORKSPACE_DIR — Cargo workspace that contains source dir. This is also the working dir.
14ZR_REQUEST — Request file that called the tool ('sh).
15ZR_REQUEST_DD — Parent dir of the request file.
16ZR_TARGET — Target file implied by the request file name.
17ZR_TARGET_DD — Parent dir of the target file.
18
19In a Cargo workspace the `zng::env::about` metadata is also set:
20
21ZR_APP_ID — package.metadata.zng.about.app_id or "qualifier.org.app" in snake_case
22ZR_APP — package.metadata.zng.about.app or package.name
23ZR_ORG — package.metadata.zng.about.org or the first package.authors
24ZR_VERSION — package.version
25ZR_DESCRIPTION — package.description
26ZR_HOMEPAGE — package.homepage
27ZR_LICENSE — package.license
28ZR_PKG_NAME — package.name
29ZR_PKG_AUTHORS — package.authors
30ZR_CRATE_NAME — package.name in snake_case
31ZR_QUALIFIER — package.metadata.zng.about.qualifier or the first components `ZR_APP_ID` except the last two
32ZR_META_* — any other custom string value in package.metadata.zng.about.*
33
34Script can make requests to the resource builder by printing to stdout.
35Current supported requests:
36
37zng-res::warning={msg} — Prints the `{msg}` as a warning after the script exits.
38
39If the script fails the entire stderr is printed and the resource build fails. Scripts run with
40`set -e` by default.
41
42Tries to run on $ZR_SH, $PROGRAMFILES/Git/bin/bash.exe, bash, sh.
43"#;
44pub(super) fn sh() {
45    help(SH_HELP);
46    let script = fs::read_to_string(path(ZR_REQUEST)).unwrap_or_else(|e| fatal!("{e}"));
47    sh_run(script, false, None).unwrap_or_else(|e| fatal!("{e}"));
48}
49
50fn sh_options() -> Vec<std::ffi::OsString> {
51    let mut r = vec![];
52    if let Ok(sh) = env::var("ZR_SH")
53        && !sh.is_empty()
54    {
55        let sh = PathBuf::from(sh);
56        if sh.exists() {
57            r.push(sh.into_os_string());
58        }
59    }
60
61    #[cfg(windows)]
62    if let Ok(pf) = env::var("PROGRAMFILES") {
63        let sh = PathBuf::from(pf).join("Git/bin/bash.exe");
64        if sh.exists() {
65            r.push(sh.into_os_string());
66        }
67    }
68    #[cfg(windows)]
69    if let Ok(c) = env::var("SYSTEMDRIVE") {
70        let sh = PathBuf::from(c).join("Program Files (x86)/Git/bin/bash.exe");
71        if sh.exists() {
72            r.push(sh.into_os_string());
73        }
74    }
75
76    r.push("bash".into());
77    r.push("sh".into());
78
79    r
80}
81pub(crate) fn sh_run(mut script: String, capture: bool, current_dir: Option<&Path>) -> io::Result<String> {
82    script.insert_str(0, "set -e\n");
83
84    for opt in sh_options() {
85        let r = sh_run_try(&opt, &script, capture, current_dir)?;
86        if let Some(r) = r {
87            return Ok(r);
88        }
89    }
90    Err(io::Error::new(
91        io::ErrorKind::NotFound,
92        "cannot find bash, tried $ZR_SH, $PROGRAMFILES/Git/bin/bash.exe, bash, sh",
93    ))
94}
95fn sh_run_try(sh: &std::ffi::OsStr, script: &str, capture: bool, current_dir: Option<&Path>) -> io::Result<Option<String>> {
96    let mut sh = Command::new(sh);
97    if let Some(d) = current_dir {
98        sh.current_dir(d);
99    }
100    sh.arg("-c").arg(script);
101    sh.stdin(std::process::Stdio::null());
102    sh.stderr(std::process::Stdio::inherit());
103    let r = if capture {
104        sh.output().map(|o| (o.status, String::from_utf8_lossy(&o.stdout).into_owned()))
105    } else {
106        sh.stdout(std::process::Stdio::inherit());
107        sh.status().map(|s| (s, String::new()))
108    };
109    match r {
110        Ok((s, o)) => {
111            if !s.success() {
112                return Err(match s.code() {
113                    Some(c) => io::Error::other(format!("script failed, exit code {c}")),
114                    None => io::Error::other("script failed"),
115                });
116            }
117            Ok(Some(o))
118        }
119        Err(e) => {
120            if e.kind() == io::ErrorKind::NotFound {
121                Ok(None)
122            } else {
123                Err(e)
124            }
125        }
126    }
127}