Skip to content

Commit

Permalink
feat: new host_name() API (#550)
Browse files Browse the repository at this point in the history
  • Loading branch information
sxyazi committed Jan 21, 2024
1 parent 93dc1b7 commit 74bcae0
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 1 deletion.
14 changes: 13 additions & 1 deletion yazi-plugin/src/utils/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))?)?;

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

Expand Down
2 changes: 2 additions & 0 deletions yazi-plugin/src/utils/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 2 additions & 0 deletions yazi-shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod layer;
mod mime;
mod natsort;
mod number;
mod os;
mod ro_cell;
pub mod term;
mod throttle;
Expand All @@ -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::*;
19 changes: 19 additions & 0 deletions yazi-shared/src/os.rs
Original file line number Diff line number Diff line change
@@ -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())
}

0 comments on commit 74bcae0

Please sign in to comment.