feat: new host_name() API

This commit is contained in:
sxyazi 2024-01-20 16:35:47 +08:00
parent 97a7eb7d47
commit 22dfd726dc
No known key found for this signature in database
4 changed files with 31 additions and 1 deletions

View file

@ -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(())
}

View file

@ -3,6 +3,8 @@ use mlua::{Lua, Table};
#[cfg(unix)]
pub(super) static USERS_CACHE: yazi_shared::RoCell<uzers::UsersCache> = yazi_shared::RoCell::new();
pub(super) static HOSTNAME_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
pub(super) struct Utils;
pub fn init() {

View file

@ -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::*;

14
yazi-shared/src/os.rs Normal file
View file

@ -0,0 +1,14 @@
#[cfg(unix)]
pub fn hostname() -> Result<String, std::io::Error> {
use libc::{gethostname, strlen};
let mut s = Vec::<u8>::with_capacity(256);
unsafe {
if gethostname(s.as_mut_ptr() as *mut _, 255) == -1 {
return Err(std::io::Error::last_os_error());
}
s.set_len(strlen(s.as_ptr() as *const _));
Ok(String::from_utf8_unchecked(s))
}
}