nsh-cli 0.8.0

The nsh command line tool: build, package and run apps.
//! An app's own release runner linked from the prebuilt runner's objects
//! (#1644), with no Rust, Visual Studio or Xcode on the machine: the parts
//! of `nsh/base` the app does not import are left out of the executable.
//!
//! The release runner (Windows x86_64, macOS arm64, Linux x86_64) reaches each part but
//! the core only through its gate, `nsh_part_<name>`, which its build
//! resolves to the part (`-alternatename:nsh_part_<name>=nsh_have_<name>`
//! on Windows, `-alias _nsh_have_<name> _nsh_part_<name>` on macOS, see the
//! runners' `build.rs`). Next to the runner, its link kit
//! `<runner>.link/` holds what linking it took: `link.rsp`, the linker's
//! arguments with `${KIT}` for the kit's own directory, and the objects
//! and libraries they name, rustc's metadata taken out (on macOS also
//! `sdk/`, stubs of the system libraries the runner imports, so that no
//! SDK is needed). Linking again with the gates of the parts nothing
//! imports resolved to `nsh_part_none` makes the linker drop those parts'
//! code. The kit's linker (`rust-lld`) is a component of the distribution
//! (`windows-linker`, `macos-linker`, `linux-linker`), added the first time
//! an app is packaged.
//!
//! The Linux runner's gates are `--defsym=nsh_part_<name>=nsh_have_<name>`
//! (`crates/nsh-linux-app/build.rs`), and its kit `nsh-linux-app.link/`
//! is made the same way (`crates/nsh-linux-app/script/link-kit.js`): it
//! holds glibc's start files and `libc_nonshared.a`, and names the system
//! libraries by their runtime file (`-l:libgtk-4.so.1`), which the link
//! finds in this machine's library directories, so no `-dev` package is
//! needed. Its linker, `linker/bin/ld.lld` with the LLVM library it loads, is
//! the component `linux-linker`; without it, a system `ld.lld` will do.

use std::{
    fs,
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::Context as _;

/// The system a link kit links a runner for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Os {
    Windows,
    Macos,
    Linux,
}

impl Os {
    /// `rust-lld`'s flavor for the system's linker.
    fn flavor(self) -> &'static str {
        match self {
            Os::Windows => "gnu",
            Os::Macos => "darwin",
            Os::Linux => "gnu",
        }
    }

    /// The component that holds the kit's linker.
    fn component(self) -> &'static str {
        match self {
            Os::Windows => "windows-linker",
            Os::Macos => "macos-linker",
            Os::Linux => "linux-linker",
        }
    }

    /// The kit's own linker.
    fn own_linker(self, kit: &Path) -> PathBuf {
        match self {
            Os::Windows => kit.join("bin").join("ld.lld.exe"),
            // Next to `lib/libLLVM.dylib`, which it loads.
            Os::Macos => kit.join("linker/bin/rust-lld"),
            // With the LLVM library it loads, in `linker/lib`.
            Os::Linux => kit.join("linker/bin/ld.lld"),
        }
    }

    /// A Rust toolchain's `rust-lld` for the system, under its sysroot.
    fn toolchain_linker(self) -> &'static str {
        match self {
            Os::Windows => "lib/rustlib/x86_64-pc-windows-msvc/bin/rust-lld.exe",
            Os::Macos => "lib/rustlib/aarch64-apple-darwin/bin/rust-lld",
            Os::Linux => "lib/rustlib/x86_64-unknown-linux-gnu/bin/rust-lld",
        }
    }
}

/// The arguments' file of a link kit.
const ARGS: &str = "link.rsp";

/// The link kit of `runner`, when it has one.
pub(crate) fn kit_for(runner: &Path) -> Option<PathBuf> {
    let stem = runner.file_stem()?;
    let kit = runner.with_file_name(format!("{}.link", stem.to_string_lossy()));
    kit.join(ARGS).is_file().then_some(kit)
}

/// Links `kit`'s runner to `out` with the parts whose gates are in `gates`
/// ([`crate::web::linked_gates`]) and none of the others.
pub(crate) fn link(
    os: Os,
    kit: &Path,
    gates: &[String],
    out: &Path,
) -> anyhow::Result<Vec<String>> {
    let template = fs::read_to_string(kit.join(ARGS))
        .with_context(|| format!("read {}", kit.join(ARGS).display()))?;
    let (args, left_out) = args(&template, &slashes(kit), gates, &slashes(out));
    let rsp = out.with_extension("rsp");
    fs::write(
        &rsp,
        args.iter().map(|a| quote(a)).collect::<Vec<_>>().join("\n"),
    )?;
    let lld = linker(os, kit)?;
    let mut command = Command::new(&lld);
    command.args(["-flavor", os.flavor()]);
    if os == Os::Linux {
        for dir in system_library_dirs() {
            command.arg(format!("-L{dir}"));
        }
    }
    let output = command
        .arg(format!("@{}", rsp.display()))
        .output()
        .with_context(|| format!("run {}", lld.display()))?;
    let _ = fs::remove_file(&rsp);
    anyhow::ensure!(
        output.status.success(),
        "linking the runner failed: {}",
        String::from_utf8_lossy(&output.stderr).trim()
    );
    Ok(left_out)
}

/// The linker's arguments from `template` (one per line), for the kit in
/// `kit` and the executable `out`; and the parts left out, those whose
/// gate is not in `gates`.
fn args(template: &str, kit: &str, gates: &[String], out: &str) -> (Vec<String>, Vec<String>) {
    let kept = |part: &str| gates.iter().any(|g| *g == format!("nsh_part_{part}"));
    let mut left_out = Vec::new();
    let mut args: Vec<String> = template
        .lines()
        .map(|line| unquote(line.trim()))
        .filter(|line| !line.is_empty())
        .map(|line| line.replace("${KIT}", kit))
        .collect();
    for i in 0..args.len() {
        // Windows: `...alternatename:nsh_part_<part>=nsh_have_<part>`,
        // Linux: `--defsym=nsh_part_<part>=nsh_have_<part>`.
        if let Some(part) = part_of_gate(&args[i]).map(str::to_owned) {
            if !kept(&part) {
                args[i] = args[i].replace(&format!("=nsh_have_{part}"), "=nsh_part_none");
                left_out.push(part);
            }
            continue;
        }
        // macOS: `-alias _nsh_have_<part> _nsh_part_<part>`.
        if args[i] == "-alias"
            && let Some(part) = args
                .get(i + 2)
                .and_then(|gate| gate.strip_prefix("_nsh_part_"))
                .map(str::to_owned)
            && args[i + 1] == format!("_nsh_have_{part}")
            && !kept(&part)
        {
            args[i + 1] = "_nsh_part_none".to_owned();
            left_out.push(part);
        }
    }
    args.extend(["-o".to_owned(), out.to_owned()]);
    (args, left_out)
}

/// The directories of this machine's shared libraries, where the Linux
/// kit's `-l:<runtime file>` are found (none elsewhere: the Windows and
/// macOS kits have their own libraries and stubs).
fn system_library_dirs() -> Vec<String> {
    if !cfg!(target_os = "linux") {
        return Vec::new();
    }
    [
        "/lib/x86_64-linux-gnu",
        "/usr/lib/x86_64-linux-gnu",
        "/lib64",
        "/usr/lib64",
        "/lib",
        "/usr/lib",
    ]
    .into_iter()
    .filter(|dir| Path::new(dir).is_dir())
    .map(str::to_owned)
    .collect()
}

/// The part whose gate the argument resolves (Windows: `...alternatename:
/// nsh_part_<part>=nsh_have_<part>`, Linux: `--defsym=nsh_part_<part>=
/// nsh_have_<part>`).
fn part_of_gate(arg: &str) -> Option<&str> {
    let (_, alias) = arg
        .split_once("alternatename:nsh_part_")
        .or_else(|| arg.split_once("--defsym=nsh_part_"))?;
    let (part, have) = alias.split_once('=')?;
    (have == format!("nsh_have_{part}")).then_some(part)
}

/// Adds the kit's linker, the component `windows-linker`, `macos-linker`
/// or `linux-linker`, when `kit` is an installed distribution's and has no
/// linker yet: the linker (`rust-lld`) comes with the first app packaged,
/// not with nsh.
pub(crate) fn ensure_linker(os: Os, kit: &Path) -> anyhow::Result<()> {
    let own = os.own_linker(kit);
    if own.is_file() || std::env::var_os("NSH_LLD").is_some() {
        return Ok(());
    }
    match crate::component::distribution() {
        Some(root) if kit.starts_with(root.join("runtime")) => {
            crate::component::ensure(&root, os.component(), &own)
        }
        _ => Ok(()),
    }
}

/// The linker: the kit's own, else `NSH_LLD`, else the `rust-lld` of a
/// Rust toolchain.
fn linker(os: Os, kit: &Path) -> anyhow::Result<PathBuf> {
    let own = os.own_linker(kit);
    if own.is_file() {
        return Ok(own);
    }
    if let Some(lld) = std::env::var_os("NSH_LLD") {
        return Ok(lld.into());
    }
    if os == Os::Linux
        && let Some(lld) = std::env::var_os("PATH").and_then(|paths| {
            std::env::split_paths(&paths)
                .map(|dir| dir.join("ld.lld"))
                .find(|lld| lld.is_file())
        })
    {
        return Ok(lld);
    }
    let sysroot = Command::new("rustc")
        .args(["--print", "sysroot"])
        .output()
        .ok()
        .filter(|out| out.status.success())
        .context("no linker in the runner's link kit, and no Rust toolchain for rust-lld")?;
    let sysroot = String::from_utf8_lossy(&sysroot.stdout).trim().to_owned();
    let lld = Path::new(&sysroot).join(os.toolchain_linker());
    anyhow::ensure!(lld.is_file(), "no rust-lld in {sysroot}");
    Ok(lld)
}

fn slashes(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn quote(arg: &str) -> String {
    format!("\"{}\"", arg.replace('"', "\\\""))
}

fn unquote(arg: &str) -> String {
    arg.strip_prefix('"')
        .and_then(|a| a.strip_suffix('"'))
        .map_or_else(|| arg.to_owned(), |a| a.replace("\\\"", "\""))
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEMPLATE: &str = "\"-m\"\n\"i386pep\"\n\"${KIT}/lib/libnsh_base.a\"\n\
        \"-Xlink=-alternatename:nsh_part_editor=nsh_have_editor\"\n\
        \"-Xlink=-alternatename:nsh_part_plot=nsh_have_plot\"\n";

    #[test]
    fn the_gates_of_parts_not_imported_resolve_to_none() {
        let gates = ["nsh_part_core".to_owned(), "nsh_part_plot".to_owned()];
        let (args, left_out) = args(TEMPLATE, "C:/kit", &gates, "C:/out/App.exe");
        assert_eq!(
            args,
            [
                "-m",
                "i386pep",
                "C:/kit/lib/libnsh_base.a",
                "-Xlink=-alternatename:nsh_part_editor=nsh_part_none",
                "-Xlink=-alternatename:nsh_part_plot=nsh_have_plot",
                "-o",
                "C:/out/App.exe",
            ]
        );
        assert_eq!(left_out, ["editor"]);
    }

    #[test]
    fn the_linux_gates_of_parts_not_imported_resolve_to_none() {
        let template = "\"${KIT}/lib/Scrt1.o\"\n\"--defsym=nsh_part_editor=nsh_have_editor\"\n\
            \"--defsym=nsh_part_plot=nsh_have_plot\"\n\"-l:libgtk-4.so.1\"\n";
        let gates = ["nsh_part_plot".to_owned()];
        let (args, left_out) = args(template, "/kit", &gates, "/out/app");
        assert_eq!(
            args,
            [
                "/kit/lib/Scrt1.o",
                "--defsym=nsh_part_editor=nsh_part_none",
                "--defsym=nsh_part_plot=nsh_have_plot",
                "-l:libgtk-4.so.1",
                "-o",
                "/out/app",
            ]
        );
        assert_eq!(left_out, ["editor"]);
    }

    #[test]
    fn the_aliases_of_parts_not_imported_resolve_to_none() {
        let template = "\"-syslibroot\"\n\"${KIT}/sdk\"\n\"${KIT}/lib/libnsh_base.a\"\n\
            \"-alias\"\n\"_nsh_have_editor\"\n\"_nsh_part_editor\"\n\
            \"-alias\"\n\"_nsh_have_plot\"\n\"_nsh_part_plot\"\n\
            \"-alias\"\n\"_main_alias\"\n\"_other\"\n";
        let gates = ["nsh_part_core".to_owned(), "nsh_part_plot".to_owned()];
        let (args, left_out) = args(template, "/kit", &gates, "/out/App");
        assert_eq!(
            args,
            [
                "-syslibroot",
                "/kit/sdk",
                "/kit/lib/libnsh_base.a",
                "-alias",
                "_nsh_part_none",
                "_nsh_part_editor",
                "-alias",
                "_nsh_have_plot",
                "_nsh_part_plot",
                "-alias",
                "_main_alias",
                "_other",
                "-o",
                "/out/App",
            ]
        );
        assert_eq!(left_out, ["editor"]);
    }

    #[test]
    fn a_kit_is_found_next_to_its_runner() {
        let dir = std::env::temp_dir().join(format!("nsh-link-kit-{}", std::process::id()));
        let kit = dir.join("nsh-windows-app.link");
        fs::create_dir_all(&kit).unwrap();
        let runner = dir.join("nsh-windows-app.exe");
        assert_eq!(kit_for(&runner), None);
        fs::write(kit.join(ARGS), TEMPLATE).unwrap();
        assert_eq!(kit_for(&runner), Some(kit));
        fs::remove_dir_all(&dir).unwrap();
    }
}