From 74bcae037b43c840698a8335c17afa7f3778001f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E9=9B=85=20=C2=B7=20Misaki=20Masa?= Date: Sun, 21 Jan 2024 08:57:59 +0800 Subject: [PATCH] feat: new `host_name()` API (#550) --- yazi-plugin/src/utils/user.rs | 14 +++++++++++++- yazi-plugin/src/utils/utils.rs | 2 ++ yazi-shared/src/lib.rs | 2 ++ yazi-shared/src/os.rs | 19 +++++++++++++++++++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 yazi-shared/src/os.rs diff --git a/yazi-plugin/src/utils/user.rs b/yazi-plugin/src/utils/user.rs index 216b09acf..ca5f271c8 100644 --- a/yazi-plugin/src/utils/user.rs +++ b/yazi-plugin/src/utils/user.rs @@ -6,8 +6,9 @@ impl Utils { #[cfg(unix)] pub(super) fn user(lua: &Lua, ya: &Table) -> mlua::Result<()> { use uzers::{Groups, Users}; + use yazi_shared::hostname; - use crate::utils::USERS_CACHE; + use crate::utils::{HOSTNAME_CACHE, USERS_CACHE}; ya.set("uid", lua.create_function(|_, ()| Ok(USERS_CACHE.get_current_uid()))?)?; @@ -33,6 +34,17 @@ impl Utils { })?, )?; + ya.set( + "host_name", + lua.create_function(|lua, ()| { + HOSTNAME_CACHE + .get_or_init(|| hostname().ok()) + .as_ref() + .map(|s| lua.create_string(s)) + .transpose() + })?, + )?; + Ok(()) } diff --git a/yazi-plugin/src/utils/utils.rs b/yazi-plugin/src/utils/utils.rs index ffe1be50c..1552437c0 100644 --- a/yazi-plugin/src/utils/utils.rs +++ b/yazi-plugin/src/utils/utils.rs @@ -3,6 +3,8 @@ use mlua::{Lua, Table}; #[cfg(unix)] pub(super) static USERS_CACHE: yazi_shared::RoCell = yazi_shared::RoCell::new(); +pub(super) static HOSTNAME_CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + pub(super) struct Utils; pub fn init() { diff --git a/yazi-shared/src/lib.rs b/yazi-shared/src/lib.rs index 27fb956c5..e655e8656 100644 --- a/yazi-shared/src/lib.rs +++ b/yazi-shared/src/lib.rs @@ -12,6 +12,7 @@ mod layer; mod mime; mod natsort; mod number; +mod os; mod ro_cell; pub mod term; mod throttle; @@ -27,6 +28,7 @@ pub use layer::*; pub use mime::*; pub use natsort::*; pub use number::*; +pub use os::*; pub use ro_cell::*; pub use throttle::*; pub use time::*; diff --git a/yazi-shared/src/os.rs b/yazi-shared/src/os.rs new file mode 100644 index 000000000..9bcc1d2d5 --- /dev/null +++ b/yazi-shared/src/os.rs @@ -0,0 +1,19 @@ +#[cfg(unix)] +pub fn hostname() -> Result { + use std::io::{Error, ErrorKind}; + + use libc::{gethostname, strlen}; + + let mut s = [0; 256]; + let len = unsafe { + if gethostname(s.as_mut_ptr() as *mut _, 255) == -1 { + return Err(std::io::Error::last_os_error()); + } + + strlen(s.as_ptr() as *const _) + }; + + std::str::from_utf8(&s[..len]) + .map_err(|_| Error::new(ErrorKind::Other, "invalid hostname")) + .map(|s| s.to_owned()) +}