#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
use crate::element::{JsError, System, codes, module};
pub(crate) const SYSTEM: &str = if cfg!(target_env = "ohos") {
"harmonyos"
} else {
std::env::consts::OS
};
#[module]
#[derive(Default)]
#[non_exhaustive]
pub(crate) struct Os;
#[module(flat, default)]
impl Os {
pub(crate) const EOL: &'static str = if cfg!(windows) { "\r\n" } else { "\n" };
pub(crate) fn platform() -> String {
SYSTEM.to_owned()
}
pub(crate) fn arch() -> String {
std::env::consts::ARCH.to_owned()
}
pub(crate) fn homedir(sys: System) -> Result<String, JsError> {
if !sys.access.allows_home_dir() {
return Err(JsError::access_denied(
"os.homedir() is not granted: add `\"homeDir\": true` to capabilities in nsh.json",
"homeDir",
"",
));
}
let none = || {
JsError::Error("os.homedir(): no absolute native home directory is configured".into())
.with_code(codes::UNAVAILABLE)
};
#[cfg(target_arch = "wasm32")]
{
Err(none())
}
#[cfg(not(target_arch = "wasm32"))]
{
["HOME", "USERPROFILE"]
.into_iter()
.filter_map(std::env::var_os)
.map(PathBuf::from)
.find(|path| path.is_absolute())
.map(|path| path.to_string_lossy().into_owned())
.ok_or_else(none)
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::access::{Access, Capabilities};
fn sys(declared: Capabilities) -> System {
System::new(
std::sync::Arc::new(Access {
declared,
granted: None,
}),
None,
Default::default(),
Default::default(),
)
}
#[test]
fn metadata_matches_native_values_without_surface_context() {
assert_eq!(Os::platform(), std::env::consts::OS);
assert_eq!(Os::arch(), std::env::consts::ARCH);
assert_eq!(Os::EOL, if cfg!(windows) { "\r\n" } else { "\n" });
if let Ok(home) = Os::homedir(sys(Capabilities::all())) {
assert!(PathBuf::from(home).is_absolute());
}
}
#[test]
fn the_home_directory_is_a_capability() {
let Err(error) = Os::homedir(sys(Default::default())) else {
panic!("os.homedir() without capabilities.homeDir");
};
assert_eq!(error.code(), Some(codes::ACCESS_DENIED));
assert!(error.message().contains("homeDir"), "{}", error.message());
let granted = Capabilities {
home_dir: true,
..Default::default()
};
let denied =
|r: Result<String, JsError>| r.is_err_and(|e| e.code() == Some(codes::ACCESS_DENIED));
assert!(!denied(Os::homedir(sys(granted))));
}
#[test]
fn registry_generates_os_signatures_from_typed_functions() {
let registry = crate::runtime::registries()
.iter()
.find(|registry| registry.specifier() == Some("os"))
.unwrap();
let modules = registry.module_specs();
let os = modules.iter().find(|module| module.name == "Os").unwrap();
assert!(os.flat);
assert_eq!(os.functions.len(), 3);
for name in ["platform", "arch", "homedir"] {
let function = os
.functions
.iter()
.find(|function| function.name == name)
.unwrap();
assert!(function.params.is_empty());
assert_eq!(function.returns.as_deref(), Some("string"));
assert_eq!(function.kind, crate::element::FunctionKind::Sync);
}
let declarations = crate::element::declarations(registry, &[]);
for name in ["platform", "arch", "homedir"] {
assert!(
declarations.contains(&format!("function {name}(): string")),
"{declarations}"
);
}
assert!(declarations.contains("EOL"), "{declarations}");
assert!(declarations.contains("default"), "{declarations}");
}
}