feat: new host_name() API (#550)

This commit is contained in:
三咲雅 · Misaki Masa 2024-01-21 08:57:59 +08:00 committed by sxyazi
parent 93dc1b78e2
commit 74bcae037b
No known key found for this signature in database
4 changed files with 36 additions and 1 deletions

View file

@ -6,8 +6,9 @@ impl Utils {
#[cfg(unix)] #[cfg(unix)]
pub(super) fn user(lua: &Lua, ya: &Table) -> mlua::Result<()> { pub(super) fn user(lua: &Lua, ya: &Table) -> mlua::Result<()> {
use uzers::{Groups, Users}; 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()))?)?; 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(()) Ok(())
} }

View file

@ -3,6 +3,8 @@ use mlua::{Lua, Table};
#[cfg(unix)] #[cfg(unix)]
pub(super) static USERS_CACHE: yazi_shared::RoCell<uzers::UsersCache> = yazi_shared::RoCell::new(); 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(super) struct Utils;
pub fn init() { pub fn init() {

View file

@ -12,6 +12,7 @@ mod layer;
mod mime; mod mime;
mod natsort; mod natsort;
mod number; mod number;
mod os;
mod ro_cell; mod ro_cell;
pub mod term; pub mod term;
mod throttle; mod throttle;
@ -27,6 +28,7 @@ pub use layer::*;
pub use mime::*; pub use mime::*;
pub use natsort::*; pub use natsort::*;
pub use number::*; pub use number::*;
pub use os::*;
pub use ro_cell::*; pub use ro_cell::*;
pub use throttle::*; pub use throttle::*;
pub use time::*; pub use time::*;

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

@ -0,0 +1,19 @@
#[cfg(unix)]
pub fn hostname() -> Result<String, std::io::Error> {
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())
}