use std::{
env,
ffi::{OsStr, OsString},
fs,
path::{Path, PathBuf},
process::Command,
};
use anyhow::{Context as _, bail};
pub(crate) const IOS_SIMULATOR_TRIPLE: &str = if cfg!(target_arch = "x86_64") {
"x86_64-apple-ios"
} else {
"aarch64-apple-ios-sim"
};
pub(crate) const MAC_CATALYST_TRIPLE: &str = if cfg!(target_arch = "x86_64") {
"x86_64-apple-ios-macabi"
} else {
"aarch64-apple-ios-macabi"
};
#[derive(Debug, Clone, Copy)]
pub(crate) enum Platform {
IphoneOs,
IphoneSimulator,
MacCatalyst,
Linux,
MacOs,
Windows,
Gpui,
Tui,
}
impl Platform {
fn dir(self) -> &'static str {
match self {
Platform::IphoneOs => "ios/iphoneos",
Platform::IphoneSimulator => "ios/iphonesimulator",
Platform::MacCatalyst => "ios/maccatalyst",
Platform::Linux => "linux",
Platform::MacOs => "macos",
Platform::Windows => "windows",
Platform::Gpui => "gpui",
Platform::Tui => "tui",
}
}
fn component(self) -> Option<&'static str> {
match self {
Platform::IphoneOs | Platform::IphoneSimulator | Platform::MacCatalyst => Some("ios"),
Platform::Gpui => Some("gpui"),
Platform::Tui => Some("tui"),
Platform::Linux | Platform::MacOs | Platform::Windows => None,
}
}
pub(crate) fn triple(self) -> Option<&'static str> {
match self {
Platform::IphoneOs => Some("aarch64-apple-ios"),
Platform::IphoneSimulator => Some(IOS_SIMULATOR_TRIPLE),
Platform::MacCatalyst => Some(MAC_CATALYST_TRIPLE),
Platform::Windows if !cfg!(windows) => Some(WINDOWS_TRIPLE),
Platform::Linux
| Platform::MacOs
| Platform::Windows
| Platform::Gpui
| Platform::Tui => None,
}
}
pub(crate) fn binary(self, runner: bool) -> &'static str {
match (self, runner) {
(Platform::Linux, false) => "nsh-linux-host",
(Platform::Linux, true) => "nsh-linux-app",
(Platform::MacOs, false) => "nsh-macos-host",
(Platform::MacOs, true) => "nsh-macos-app",
(Platform::Windows, false) => "nsh-windows-host",
(Platform::Windows, true) => "nsh-windows-app",
(Platform::Tui, false) => "nsh-tui-host",
(Platform::Tui, true) => "nsh-tui-app",
(Platform::Gpui, false) => "nsh-gpui-host",
(Platform::Gpui, true) => unreachable!("GPUI apps are embedded, never packaged"),
(_, false) => "nsh-ios-host",
(_, true) => "nsh-ios-app",
}
}
pub(crate) fn file_name(self, runner: bool, triple: Option<&str>) -> String {
format!("{}{}", self.binary(runner), exe_suffix(triple))
}
pub(crate) fn host(self, runner: bool) -> String {
let what = if runner {
"release runner"
} else {
"development host"
};
let platform = match self {
Platform::IphoneOs => "iOS devices",
Platform::IphoneSimulator => "the iOS simulator",
Platform::MacCatalyst => "Mac Catalyst",
Platform::Linux => "Linux",
Platform::MacOs => "macOS",
Platform::Windows => "Windows",
Platform::Gpui => "GPUI",
Platform::Tui => "the terminal",
};
format!("the {what} for {platform}")
}
}
fn add_component(name: &str, missing: &Path) -> anyhow::Result<bool> {
let Some(root) = crate::component::distribution() else {
return Ok(false);
};
crate::component::ensure(&root, name, missing)?;
Ok(true)
}
fn distribution_current(name: &str) -> bool {
let Some(root) = crate::component::distribution() else {
return true;
};
if !root
.join("components")
.join(format!("{name}.json"))
.exists()
{
return true;
}
crate::component::current(&root, name)
}
pub(crate) fn cli_exe() -> std::io::Result<PathBuf> {
let exe = env::current_exe()?;
if cfg!(windows) {
return Ok(exe);
}
Ok(exe.canonicalize().unwrap_or(exe))
}
pub(crate) fn android(dev: bool, abis: &[String]) -> anyhow::Result<PathBuf> {
let prebuilt = prebuilt_android(dev)?;
match crate::rust_app::current() {
Some(app) => app.android(&prebuilt, dev, abis),
None => Ok(prebuilt),
}
}
pub(crate) fn test_android(abis: &[String]) -> anyhow::Result<PathBuf> {
let prebuilt = prebuilt_android(true)?;
match crate::rust_app::current() {
Some(app) => app.test_android(&prebuilt, abis),
None => Ok(prebuilt),
}
}
fn prebuilt_android(dev: bool) -> anyhow::Result<PathBuf> {
let variant = if dev { "dev" } else { "release" };
if let Some(root) = env::var_os("NSH_RUNTIME") {
return android_existing(PathBuf::from(root).join("android").join(variant), dev);
}
let exe = cli_exe()?;
let bin = exe.parent().context("cli has no parent directory")?;
let dist = bin.join("../runtime/android").join(variant);
if dist.join("classes.dex").exists() && distribution_current("android") {
return Ok(dist);
}
if add_component("android", &dist.join("classes.dex"))? {
return Ok(dist);
}
let build = cli_build();
let bin = build.map_or(bin, |build| build.bin.as_path());
let profile = bin
.file_name()
.context("cli profile dir")?
.to_string_lossy();
if let Some(CheckoutBuild { root, .. }) = build {
let mut args = vec!["xtask", "android"];
if profile == "release" {
args.push("--release");
}
if dev {
args.push("--dev");
}
let what = if dev {
"the Android runtime with development support"
} else {
"the Android runtime"
};
cargo(root, &args, what)?;
}
let name = if dev {
format!("{profile}-dev")
} else {
profile.into_owned()
};
let built = bin
.parent()
.context("cli is not in a target directory")?
.join("android")
.join(name);
android_existing(built, dev)
}
fn android_existing(dir: PathBuf, dev: bool) -> anyhow::Result<PathBuf> {
if dir.join("classes.dex").exists() {
return Ok(dir);
}
bail!(
"the Android runtime is not at {}\nin a nsh checkout, build it with: cargo xtask android{}",
dir.display(),
if dev { " --dev" } else { "" }
)
}
pub(crate) struct WebRuntime {
pub(crate) wasm: PathBuf,
pub(crate) js: PathBuf,
pub(crate) glue: Option<PathBuf>,
pub(crate) syntaxes: Option<PathBuf>,
}
pub(crate) const SYNTAXES: &str = "nsh-syntaxes.bin";
pub(crate) fn syntaxes_in(dir: &Path) -> Option<PathBuf> {
Some(dir.join(SYNTAXES)).filter(|path| path.exists())
}
pub(crate) fn write_syntaxes(manifest: &Path, dir: &Path) -> anyhow::Result<PathBuf> {
let to = dir.join(SYNTAXES);
let modified = |path: &Path| fs::metadata(path).and_then(|m| m.modified()).ok();
if let (Some(copy), Some(lock)) = (
modified(&to),
modified(&manifest.with_file_name("Cargo.lock")),
) && copy > lock
{
return Ok(to);
}
let package = package_dir(manifest, "two-face", None)?;
let dump = package.join("generated/syntaxes-fancy-newlines.bin");
let bytes = fs::read(&dump).with_context(|| format!("read {}", dump.display()))?;
fs::write(&to, bytes).with_context(|| format!("write {}", to.display()))?;
Ok(to)
}
pub(crate) fn package_dir(
manifest: &Path,
name: &str,
version: Option<&str>,
) -> anyhow::Result<PathBuf> {
let cargo = env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo"));
let output = Command::new(cargo)
.args(["metadata", "--format-version", "1", "--manifest-path"])
.arg(manifest)
.output()
.context("run cargo metadata")?;
if !output.status.success() {
bail!(
"cargo metadata of {}:\n{}",
manifest.display(),
String::from_utf8_lossy(&output.stderr).trim()
);
}
let metadata: serde_json::Value =
serde_json::from_slice(&output.stdout).context("cargo metadata's output")?;
let mut found = metadata["packages"]
.as_array()
.into_iter()
.flatten()
.filter(|p| p["name"].as_str() == Some(name))
.filter(|p| version.is_none_or(|v| p["version"].as_str() == Some(v)));
let package = found.next();
if found.next().is_some() {
bail!("{} resolves several versions of {name}", manifest.display());
}
package
.and_then(|p| {
Path::new(p["manifest_path"].as_str()?)
.parent()
.map(Path::to_path_buf)
})
.with_context(|| match version {
Some(version) => format!("{} resolves no {name} {version}", manifest.display()),
None => format!("{} resolves no {name}", manifest.display()),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WebKind {
Browser,
Dev,
}
impl WebKind {
pub(crate) fn file(self) -> &'static str {
match self {
WebKind::Browser => "nsh-browser.wasm",
WebKind::Dev => "nsh-dev.wasm",
}
}
pub(crate) fn features(self) -> &'static [&'static str] {
match self {
WebKind::Browser => &["--no-default-features", "--features", "browser,linkable"],
WebKind::Dev => &["--no-default-features", "--features", "dev"],
}
}
}
pub(crate) fn package_web() -> anyhow::Result<WebRuntime> {
web(WebKind::Browser, true)?.context("no web runtime")
}
pub(crate) fn test_web() -> anyhow::Result<WebRuntime> {
match crate::rust_app::current() {
Some(app) => app.test_web(),
None => web(WebKind::Dev, true)?.context("no web runtime"),
}
}
pub(crate) fn web(kind: WebKind, build: bool) -> anyhow::Result<Option<WebRuntime>> {
const WASM: &str = "wasm32-unknown-unknown";
if let Some(app) = crate::rust_app::current() {
return app.web(kind, build);
}
let found = |dir: PathBuf| {
let runtime = WebRuntime {
wasm: dir.join(kind.file()),
js: dir.join("nsh.js"),
glue: None,
syntaxes: syntaxes_in(&dir),
};
(runtime.wasm.exists() && runtime.js.exists()).then_some(runtime)
};
if let Some(root) = env::var_os("NSH_RUNTIME") {
let dir = PathBuf::from(root).join("web");
return match found(dir.clone()) {
Some(runtime) => Ok(Some(runtime)),
None if build => bail!("the web runtime is not in {}", dir.display()),
None => Ok(None),
};
}
let exe = cli_exe()?;
let bin = exe.parent().context("cli has no parent directory")?;
if let Some(runtime) = found(bin.join("../runtime/web"))
&& (!build || distribution_current("web"))
{
return Ok(Some(runtime));
}
if build && add_component("web", &bin.join("../runtime/web").join(kind.file()))? {
return found(bin.join("../runtime/web"))
.map(Some)
.context("the component `web` holds no web runtime");
}
let Some(CheckoutBuild { root, bin }) = cli_build() else {
if build {
bail!(
"the web runtime is not at {}",
bin.join("../runtime/web").display()
);
}
return Ok(None);
};
let out = bin
.parent()
.context("cli is not in a target directory")?
.join(WASM)
.join("web");
let features = kind.features();
if build {
let cargo = env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo"));
let mut command = Command::new(&cargo);
command
.args(["build", "--profile", "web", "-p", "nsh-platform-web"])
.args(features)
.args(["--target", WASM])
.current_dir(root);
web_build_flags(&mut command);
let ar = format!("AR_{}", WASM.replace('-', "_"));
if env::var_os(&ar).is_none() && env::var_os("AR").is_none() {
command.env(&ar, "llvm-ar");
}
crate::ui::cargo(&mut command, "the web runtime")?;
let built = out.join("nsh_platform_web.wasm");
fs::copy(&built, out.join(kind.file()))
.with_context(|| format!("copy {}", built.display()))?;
write_syntaxes(&root.join("Cargo.toml"), &out)?;
}
let runtime = WebRuntime {
wasm: out.join(kind.file()),
js: root.join("crates/nsh-platform-web/web/nsh.js"),
glue: None,
syntaxes: syntaxes_in(&out),
};
if runtime.wasm.exists() {
return Ok(Some(runtime));
}
if build {
bail!("the web runtime is not at {}", runtime.wasm.display());
}
Ok(None)
}
pub(crate) fn test_host(platform: Platform) -> anyhow::Result<PathBuf> {
match crate::rust_app::current() {
Some(app) => app.test_host(platform),
None => file(platform, false),
}
}
pub(crate) fn file(platform: Platform, runner: bool) -> anyhow::Result<PathBuf> {
file_for(platform, runner, platform.triple())
}
pub(crate) fn file_for(
platform: Platform,
runner: bool,
triple: Option<&'static str>,
) -> anyhow::Result<PathBuf> {
locate(platform, runner, triple).map(|file| file.path)
}
pub(crate) struct RuntimeFile {
pub(crate) path: PathBuf,
pub(crate) built: bool,
}
pub(crate) fn locate(
platform: Platform,
runner: bool,
triple: Option<&'static str>,
) -> anyhow::Result<RuntimeFile> {
if let Some(app) = crate::rust_app::current() {
return Ok(RuntimeFile {
path: app.runtime(platform, runner, triple)?,
built: true,
});
}
let prebuilt = |path| RuntimeFile { path, built: false };
let name = platform.binary(runner);
let file_name = platform.file_name(runner, triple);
if let Some(root) = env::var_os("NSH_RUNTIME") {
return existing(
PathBuf::from(root).join(platform.dir()).join(&file_name),
platform,
name,
triple,
)
.map(prebuilt);
}
let exe = cli_exe()?;
let bin = exe.parent().context("cli has no parent directory")?;
let dist = bin.join("../runtime").join(platform.dir()).join(&file_name);
if dist.exists() && platform.component().is_none_or(distribution_current) {
return Ok(prebuilt(dist));
}
if let Some(component) = platform.component()
&& add_component(component, &dist)?
{
return Ok(prebuilt(dist));
}
let build = cli_build();
let bin = build.map_or(bin, |build| build.bin.as_path());
let profile = bin.file_name().context("cli profile dir")?;
let mut host_target = None;
let mut triple = triple;
let root = build.map(|build| build.root.clone());
if let Some(root) = &root {
let mut args = vec!["build", "-p", name];
if matches!(platform, Platform::Linux) && !runner && !linux_web_views() {
args.push("--no-default-features");
}
let workspace = if matches!(platform, Platform::Gpui) {
args.extend(gpui_features());
root.join("crates/gpui")
} else {
root.clone()
};
triple = build_target(platform, triple, Some(&workspace))?;
if let Some(triple) = triple {
args.extend(["--target", triple]);
}
match profile.to_str() {
Some("debug") => {}
Some("release") => args.push("--release"),
Some(other) => args.extend(["--profile", other]),
None => bail!("cli profile dir is not UTF-8"),
}
let what = match profile.to_str() {
Some("release") => platform.host(runner),
Some(other) => format!("{} ({other} build)", platform.host(runner)),
None => platform.host(runner),
};
let what = format!("{what}{}", other_triple(platform, triple));
cargo(&workspace, &args, &what)?;
if matches!(platform, Platform::Gpui) {
host_target = Some(
crate::rust_app::cargo_target_directory(&workspace)
.context("Cargo did not report the GPUI workspace's target directory")?,
);
}
}
let mut built = host_target.unwrap_or(
bin.parent()
.context("cli is not in a target directory")?
.to_path_buf(),
);
if let Some(triple) = triple {
built.push(triple);
}
built.push(profile);
built.push(&file_name);
let path = existing(built, platform, name, triple)?;
let path = match &root {
Some(root) if cfg!(target_os = "macos") && triple.is_none() => stable_copy(
&path,
&root.join(".nsh/hosts").join(profile).join(&file_name),
)?,
_ => path,
};
Ok(RuntimeFile {
path,
built: root.is_some(),
})
}
fn stable_copy(built: &Path, copy: &Path) -> anyhow::Result<PathBuf> {
let source = fs::metadata(built).with_context(|| format!("read {}", built.display()))?;
let fresh = fs::metadata(copy).is_ok_and(|copied| {
copied.len() == source.len() && copied.modified().ok() == source.modified().ok()
});
if !fresh {
if let Some(dir) = copy.parent() {
fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
}
let _ = fs::remove_file(copy);
fs::copy(built, copy).with_context(|| format!("copy {}", built.display()))?;
let modified = source.modified().context("modification time")?;
fs::File::options()
.write(true)
.open(copy)
.and_then(|file| file.set_modified(modified))
.with_context(|| format!("stamp {}", copy.display()))?;
}
Ok(copy.to_path_buf())
}
pub(crate) fn gpui_features() -> &'static [&'static str] {
if !metal_toolchain_missing() {
return &[];
}
crate::ui::note(
"no Metal Toolchain: GPUI compiles its shaders when the app starts \
(`xcodebuild -downloadComponent MetalToolchain` installs one to precompile them)",
);
&["--features", "nsh-platform-gpui/runtime-shaders"]
}
fn metal_toolchain_missing() -> bool {
cfg!(target_os = "macos")
&& !Command::new("xcrun")
.args(["metal", "--version"])
.output()
.is_ok_and(|out| out.status.success())
}
pub(crate) fn cli_checkout() -> Option<PathBuf> {
cli_build().map(|build| build.root.clone())
}
#[derive(Debug, PartialEq, Eq)]
struct CheckoutBuild {
root: PathBuf,
bin: PathBuf,
}
fn cli_build() -> Option<&'static CheckoutBuild> {
static BUILD: std::sync::OnceLock<Option<CheckoutBuild>> = std::sync::OnceLock::new();
BUILD
.get_or_init(|| {
let exe = env::current_exe().ok()?;
let invoked = env::args_os().next().and_then(|arg0| {
invoked_path(
&arg0,
&env::current_dir().ok()?,
env::var_os("PATH").as_deref(),
)
});
match find_build(&exe, invoked.as_deref()) {
FoundBuild::Checkout(build) => Some(build),
FoundBuild::Outside(bin) => {
note_build_outside_checkout(&bin);
None
}
FoundBuild::Other => None,
}
})
.as_ref()
}
#[derive(Debug, PartialEq, Eq)]
enum FoundBuild {
Checkout(CheckoutBuild),
Outside(PathBuf),
Other,
}
fn find_build(exe: &Path, invoked: Option<&Path>) -> FoundBuild {
if let Some(build) = exe_paths(exe, invoked)
.iter()
.find_map(|path| checkout_build(path))
{
return FoundBuild::Checkout(build);
}
dunce::canonicalize(exe)
.ok()
.and_then(|real| real.parent().map(Path::to_owned))
.filter(|bin| cargo_profile_dir(bin))
.map_or(FoundBuild::Other, FoundBuild::Outside)
}
const MAX_LINKS: usize = 40;
fn exe_paths(exe: &Path, invoked: Option<&Path>) -> Vec<PathBuf> {
let real = dunce::canonicalize(exe).ok();
let mut paths: Vec<PathBuf> = Vec::new();
for start in [Some(exe), invoked].into_iter().flatten() {
if start != exe && (real.is_none() || dunce::canonicalize(start).ok() != real) {
continue;
}
let mut path = start.to_owned();
for _ in 0..MAX_LINKS {
if !paths.contains(&path) {
paths.push(path.clone());
}
let Ok(target) = fs::read_link(&path) else {
break;
};
path = match path.parent() {
Some(dir) => dir.join(target),
None => target,
};
}
}
if let Some(real) = real
&& !paths.contains(&real)
{
paths.push(real);
}
paths
}
fn invoked_path(arg0: &OsStr, cwd: &Path, path: Option<&OsStr>) -> Option<PathBuf> {
let arg0 = Path::new(arg0);
if arg0.as_os_str().is_empty() {
return None;
}
if arg0.is_absolute() || arg0.components().count() > 1 {
return Some(cwd.join(arg0));
}
let mut names = vec![arg0.to_owned()];
if !env::consts::EXE_SUFFIX.is_empty() && arg0.extension().is_none() {
let mut name = arg0.as_os_str().to_owned();
name.push(env::consts::EXE_SUFFIX);
names.push(PathBuf::from(name));
}
env::split_paths(path?).find_map(|dir| {
names
.iter()
.map(|name| cwd.join(&dir).join(name))
.find(|file| file.is_file())
})
}
fn checkout_build(exe: &Path) -> Option<CheckoutBuild> {
let bin = exe.parent()?;
if !cargo_profile_dir(bin) {
return None;
}
let root = bin.parent()?.parent()?;
if !root.join("crates/nsh-ios-host/Cargo.toml").exists() {
return None;
}
Some(CheckoutBuild {
root: dunce::canonicalize(root).unwrap_or_else(|_| root.to_owned()),
bin: bin.to_owned(),
})
}
fn cargo_profile_dir(dir: &Path) -> bool {
dir.join(".cargo-lock").is_file()
}
fn note_build_outside_checkout(bin: &Path) {
let Ok(source) = dunce::canonicalize(Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."))
else {
return;
};
if !source.join("crates/nsh-ios-host/Cargo.toml").exists() {
return;
}
crate::ui::note(format!(
"this nsh was built from {} into {}, outside it, so apps use nsh's released crates and \
runtimes, not the checkout's; run it from the checkout's target directory, or build it \
there, to use them",
crate::ui::path(&source),
crate::ui::path(bin),
));
}
pub(crate) fn web_build_flags(command: &mut Command) {
append_web_flags(
command,
env::var_os("CARGO_ENCODED_RUSTFLAGS"),
env::var_os("RUSTFLAGS")
.or_else(|| env::var_os("CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS")),
);
}
fn append_web_flags(command: &mut Command, encoded: Option<OsString>, plain: Option<OsString>) {
if let Some(mut flags) = encoded {
if !flags.is_empty() {
flags.push("\x1f");
}
flags.push("--cfg\x1fgetrandom_backend=\"custom\"");
command.env("CARGO_ENCODED_RUSTFLAGS", flags);
} else if let Some(mut flags) = plain {
flags.push(" --cfg getrandom_backend=\"custom\"");
command.env("RUSTFLAGS", flags);
} else {
command.args([
"--config",
r#"target.wasm32-unknown-unknown.rustflags=["--cfg", "getrandom_backend=\"custom\""]"#,
]);
}
}
pub(crate) const WINDOWS_TRIPLE: &str = "x86_64-pc-windows-msvc";
pub(crate) fn exe_suffix(triple: Option<&str>) -> &'static str {
match triple {
None => env::consts::EXE_SUFFIX,
Some(triple) if triple.contains("-windows-") => ".exe",
Some(_) => "",
}
}
pub(crate) fn cross_build(cmd: &mut Command, triple: Option<&str>) -> anyhow::Result<()> {
if cfg!(windows) || triple != Some(WINDOWS_TRIPLE) {
return Ok(());
}
let program = cmd.get_program().to_owned();
let found = Command::new(&program)
.args(["xwin", "--version"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success());
if !found {
bail!(
"building for Windows on this machine needs cargo-xwin and the {WINDOWS_TRIPLE} target:\n cargo install --locked cargo-xwin\n rustup target add {WINDOWS_TRIPLE}\nor set NSH_RUNTIME to a runtime with a Windows release runner"
);
}
cmd.arg("xwin").env(
"CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS",
"-C target-feature=+crt-static",
);
Ok(())
}
fn cargo(root: &Path, args: &[&str], what: &str) -> anyhow::Result<()> {
let cargo = env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo"));
let mut cmd = Command::new(&cargo);
let triple = args
.iter()
.position(|arg| *arg == "--target")
.and_then(|i| args.get(i + 1).copied());
cross_build(&mut cmd, triple)?;
crate::ui::cargo(cmd.args(args).current_dir(root), what)
}
pub(crate) fn other_triple(platform: Platform, triple: Option<&str>) -> String {
match triple {
Some(triple) if Some(triple) != platform.triple() => format!(" for {triple}"),
_ => String::new(),
}
}
pub(crate) fn rustc_host(dir: Option<&Path>) -> Option<String> {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
let mut command = Command::new(rustc);
command.arg("-vV");
if let Some(dir) = dir {
command.current_dir(dir);
}
let output = command.output().ok()?;
let text = String::from_utf8(output.stdout).ok()?;
text.lines()
.find_map(|line| line.strip_prefix("host: "))
.map(str::to_owned)
}
pub(crate) fn build_target<'a>(
platform: Platform,
triple: Option<&'a str>,
dir: Option<&Path>,
) -> anyhow::Result<Option<&'a str>> {
let Some(other) = triple.filter(|triple| Some(*triple) != platform.triple()) else {
return Ok(triple);
};
let target = cross_target(other, rustc_host(dir).as_deref());
if let Some(target) = target {
require_target(dir, target)?;
}
Ok(target)
}
fn cross_target<'a>(triple: &'a str, host: Option<&str>) -> Option<&'a str> {
(Some(triple) != host).then_some(triple)
}
pub(crate) fn require_target(dir: Option<&Path>, triple: &str) -> anyhow::Result<()> {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
let mut command = Command::new(rustc);
command.args(["--print", "target-libdir", "--target", triple]);
if let Some(dir) = dir {
command.current_dir(dir);
}
let Ok(output) = command.output() else {
return Ok(());
};
if !output.status.success() {
return Ok(());
}
let libdir = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
if has_core(&libdir) {
return Ok(());
}
bail!("the Rust target {triple} is not installed; add it with: rustup target add {triple}")
}
fn has_core(libdir: &Path) -> bool {
fs::read_dir(libdir).is_ok_and(|entries| {
entries
.flatten()
.any(|entry| entry.file_name().to_string_lossy().starts_with("libcore-"))
})
}
fn existing(
path: PathBuf,
platform: Platform,
name: &str,
triple: Option<&str>,
) -> anyhow::Result<PathBuf> {
if path.exists() {
return Ok(path);
}
let target = triple
.map(|triple| format!(" --target {triple}"))
.unwrap_or_default();
bail!(
"{name} for {} not found at {}\nin a nsh checkout, build it with: cargo build -p {name}{target}",
platform.dir(),
path.display(),
)
}
pub(crate) fn copy_browser_host(source: &Path, target: &Path) -> anyhow::Result<()> {
let from = source.join("browser");
let to = target.join("browser");
fs::create_dir_all(&to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
if entry
.path()
.extension()
.is_some_and(|ext| ext == "js" || ext == "txt")
{
fs::copy(entry.path(), to.join(entry.file_name()))?;
}
}
Ok(())
}
pub(crate) fn linux_web_views() -> bool {
static FOUND: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*FOUND.get_or_init(|| {
let found = std::process::Command::new("pkg-config")
.args(["--exists", "webkitgtk-6.0"])
.status()
.map_or(true, |s| s.success());
if !found {
crate::ui::warn(
"WebKitGTK 6.0 is not installed (webkitgtk-6.0 / libwebkitgtk-6.0-dev): \
the development host builds without web views, which show a placeholder",
);
}
found
})
}
#[cfg(test)]
mod tests {
use super::Platform;
#[cfg(unix)]
struct Layout {
dir: std::path::PathBuf,
checkout: std::path::PathBuf,
cache: std::path::PathBuf,
}
#[cfg(unix)]
impl Layout {
fn new(name: &str) -> Self {
use std::fs;
let dir = std::env::temp_dir().join(format!("nsh-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let dir = dunce::canonicalize(&dir).unwrap();
let checkout = dir.join("checkout");
fs::create_dir_all(checkout.join("crates/nsh-ios-host")).unwrap();
fs::write(checkout.join("crates/nsh-ios-host/Cargo.toml"), "").unwrap();
let cache = dir.join("cache");
for profile in ["debug", "release"] {
fs::create_dir_all(cache.join(profile)).unwrap();
fs::write(cache.join(profile).join(".cargo-lock"), "").unwrap();
fs::write(cache.join(profile).join("nsh"), "").unwrap();
}
std::os::unix::fs::symlink(&cache, checkout.join("target")).unwrap();
Self {
dir,
checkout,
cache,
}
}
fn build(
&self,
exe: &std::path::Path,
invoked: Option<&std::path::Path>,
) -> super::FoundBuild {
super::find_build(exe, invoked)
}
fn expected(&self, profile: &str) -> super::FoundBuild {
super::FoundBuild::Checkout(super::CheckoutBuild {
root: self.checkout.clone(),
bin: self.checkout.join("target").join(profile),
})
}
}
#[cfg(unix)]
impl Drop for Layout {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
#[cfg(unix)]
#[test]
fn a_checkout_build_is_found_through_a_linked_target() {
let layout = Layout::new("linked-target");
let run_as = layout.checkout.join("target/debug/nsh");
let resolved = layout.cache.join("debug/nsh");
assert_eq!(layout.build(&run_as, None), layout.expected("debug"));
assert_eq!(
layout.build(&resolved, Some(&run_as)),
layout.expected("debug")
);
assert_eq!(
layout.build(&resolved, None),
super::FoundBuild::Outside(layout.cache.join("debug"))
);
}
#[cfg(unix)]
#[test]
fn a_link_to_a_source_build_reaches_its_checkout() {
use std::{fs, os::unix::fs::symlink};
let layout = Layout::new("linked-source");
let home = layout.dir.join("home");
fs::create_dir_all(home.join(".local/bin")).unwrap();
fs::create_dir_all(home.join(".nsh/bin")).unwrap();
symlink(
layout.checkout.join("target/release/nsh"),
home.join(".nsh/bin/nsh"),
)
.unwrap();
symlink("../../.nsh/bin/nsh", home.join(".local/bin/nsh")).unwrap();
let run_as = home.join(".local/bin/nsh");
let resolved = layout.cache.join("release/nsh");
assert_eq!(layout.build(&run_as, None), layout.expected("release"));
assert_eq!(
layout.build(&resolved, Some(&run_as)),
layout.expected("release")
);
}
#[cfg(unix)]
#[test]
fn only_a_cargo_build_of_this_file_is_a_checkout_build() {
use std::{fs, os::unix::fs::symlink};
let layout = Layout::new("not-checkout-build");
let dist = layout.dir.join("dist");
fs::create_dir_all(dist.join("bin")).unwrap();
fs::create_dir_all(dist.join("runtime")).unwrap();
fs::write(dist.join("bin/nsh"), "").unwrap();
fs::create_dir_all(layout.checkout.join("tools/bin")).unwrap();
symlink(dist.join("bin/nsh"), layout.checkout.join("tools/bin/nsh")).unwrap();
let linked = layout.checkout.join("tools/bin/nsh");
assert_eq!(layout.build(&linked, None), super::FoundBuild::Other);
assert_eq!(
layout.build(&dist.join("bin/nsh"), Some(&linked)),
super::FoundBuild::Other
);
let other = layout.checkout.join("target/debug/nsh");
assert_eq!(
layout.build(&dist.join("bin/nsh"), Some(&other)),
super::FoundBuild::Other
);
}
#[cfg(unix)]
#[test]
fn a_build_outside_the_checkout_is_where_it_resolves() {
use std::{fs, os::unix::fs::symlink};
let layout = Layout::new("outside-checkout");
let elsewhere = layout.dir.join("elsewhere/release");
fs::create_dir_all(&elsewhere).unwrap();
fs::write(elsewhere.join(".cargo-lock"), "").unwrap();
fs::write(elsewhere.join("nsh"), "").unwrap();
let home = layout.dir.join("home");
fs::create_dir_all(home.join(".local/bin")).unwrap();
fs::create_dir_all(home.join(".nsh/bin")).unwrap();
symlink(elsewhere.join("nsh"), home.join(".nsh/bin/nsh")).unwrap();
symlink("../../.nsh/bin/nsh", home.join(".local/bin/nsh")).unwrap();
let run_as = home.join(".local/bin/nsh");
let outside = super::FoundBuild::Outside(elsewhere.clone());
assert_eq!(layout.build(&elsewhere.join("nsh"), Some(&run_as)), outside);
assert_eq!(layout.build(&run_as, Some(&run_as)), outside);
assert_eq!(layout.build(&run_as, None), outside);
}
#[cfg(unix)]
#[test]
fn the_path_run_as_follows_the_shell() {
use std::{ffi::OsStr, fs};
let layout = Layout::new("invoked-path");
let cwd = &layout.checkout;
assert_eq!(
super::invoked_path(OsStr::new("./target/debug/nsh"), cwd, None),
Some(cwd.join("./target/debug/nsh"))
);
let bin = layout.dir.join("bin");
fs::create_dir_all(&bin).unwrap();
fs::write(bin.join("nsh"), "").unwrap();
let path = std::env::join_paths([layout.dir.join("empty"), bin.clone()]).unwrap();
assert_eq!(
super::invoked_path(OsStr::new("nsh"), cwd, Some(&path)),
Some(bin.join("nsh"))
);
assert_eq!(super::invoked_path(OsStr::new("nsh"), cwd, None), None);
assert_eq!(super::invoked_path(OsStr::new(""), cwd, Some(&path)), None);
}
#[cfg(unix)]
#[test]
fn a_stable_copy_changes_only_with_the_build() {
use std::{fs, os::unix::fs::MetadataExt as _};
let dir = std::env::temp_dir().join(format!("nsh-stable-copy-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let built = dir.join("host");
let copy = dir.join("copies/host");
fs::write(&built, b"one").unwrap();
super::stable_copy(&built, ©).unwrap();
let first = fs::metadata(©).unwrap().ino();
fs::hard_link(&built, dir.join("again")).unwrap();
super::stable_copy(&built, ©).unwrap();
assert_eq!(fs::metadata(©).unwrap().ino(), first);
fs::remove_file(&built).unwrap();
fs::write(&built, b"three").unwrap();
super::stable_copy(&built, ©).unwrap();
assert_eq!(fs::read(©).unwrap(), b"three");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn only_the_toolchains_host_builds_without_a_target() {
const ARM64: &str = "aarch64-apple-darwin";
const X86_64: &str = "x86_64-apple-darwin";
for host in [ARM64, X86_64] {
let other = if host == ARM64 { X86_64 } else { ARM64 };
assert_eq!(super::cross_target(host, Some(host)), None);
assert_eq!(super::cross_target(other, Some(host)), Some(other));
}
assert_eq!(super::cross_target(X86_64, None), Some(X86_64));
let ios = Platform::IphoneOs.triple();
assert_eq!(
super::build_target(Platform::IphoneOs, ios, None).unwrap(),
ios
);
assert_eq!(
super::build_target(Platform::MacOs, None, None).unwrap(),
None
);
}
#[test]
fn a_target_is_installed_when_its_library_has_core() {
use std::fs;
let dir = std::env::temp_dir().join(format!("nsh-target-libdir-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
assert!(!super::has_core(&dir));
fs::create_dir_all(&dir).unwrap();
assert!(!super::has_core(&dir));
fs::write(dir.join("libstd-0123.rlib"), b"").unwrap();
assert!(!super::has_core(&dir));
fs::write(dir.join("libcore-0123.rlib"), b"").unwrap();
assert!(super::has_core(&dir));
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn published_runtime_variants_use_browser_execution() {
use super::WebKind;
assert_eq!(
WebKind::Browser.features(),
["--no-default-features", "--features", "browser,linkable"]
);
assert_eq!(WebKind::Browser.file(), "nsh-browser.wasm");
}
#[test]
fn web_entropy_flags_preserve_existing_rustflags() {
use std::{ffi::OsString, process::Command};
for (encoded, plain, key, expected) in [
(
Some("-C\x1flink-arg=-zstack-size=8388608"),
None,
"CARGO_ENCODED_RUSTFLAGS",
"-C\x1flink-arg=-zstack-size=8388608\x1f--cfg\x1fgetrandom_backend=\"custom\"",
),
(
None,
Some("-C link-arg=-zstack-size=8388608"),
"RUSTFLAGS",
"-C link-arg=-zstack-size=8388608 --cfg getrandom_backend=\"custom\"",
),
] {
let mut command = Command::new("cargo");
super::append_web_flags(
&mut command,
encoded.map(OsString::from),
plain.map(OsString::from),
);
assert_eq!(
command
.get_envs()
.find(|(name, _)| *name == key)
.unwrap()
.1
.unwrap(),
expected
);
}
let mut command = Command::new("cargo");
super::append_web_flags(&mut command, None, None);
let args: Vec<_> = command.get_args().collect();
assert_eq!(args[0], "--config");
assert!(args[1].to_str().unwrap().contains("getrandom_backend"));
assert!(command.get_envs().next().is_none());
}
#[test]
fn gpui_runtimes_are_built_for_this_machine() {
assert_eq!(Platform::Gpui.dir(), "gpui");
assert_eq!(Platform::Gpui.triple(), None);
assert_eq!(Platform::Gpui.binary(false), "nsh-gpui-host");
assert_eq!(
Platform::Gpui.file_name(false, Platform::Gpui.triple()),
format!("nsh-gpui-host{}", std::env::consts::EXE_SUFFIX)
);
assert_eq!(Platform::Gpui.host(false), "the development host for GPUI");
}
#[test]
fn syntaxes_newer_than_the_lock_file_are_kept() {
use std::{
fs,
time::{Duration, SystemTime},
};
let dir = std::env::temp_dir().join(format!("nsh-syntaxes-kept-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let touch = |name: &str, contents: &str, secs: u64| {
let path = dir.join(name);
fs::write(&path, contents).unwrap();
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(secs);
fs::File::options()
.write(true)
.open(&path)
.unwrap()
.set_modified(time)
.unwrap();
};
let manifest = dir.join("Cargo.toml");
touch("Cargo.lock", "", 1_000);
touch(super::SYNTAXES, "kept", 2_000);
let path = super::write_syntaxes(&manifest, &dir).unwrap();
assert_eq!(fs::read_to_string(path).unwrap(), "kept");
touch("Cargo.lock", "", 3_000);
assert!(super::write_syntaxes(&manifest, &dir).is_err());
let _ = fs::remove_dir_all(&dir);
}
}