ronantakizawa/codereview-bench huggingface dataset:
Repository: sxyazi/yazi
File: yazi-plugin/src/utils/text.rs (Rust)

Code before:
				Some(true) => yazi_shared::shell::escape_unix(s.as_ref()),
				Some(false) => yazi_shared::shell::escape_windows(s.as_ref()),
				None => yazi_shared::shell::escape_native(s.as_ref()),
			};
			lua.create_string(s.as_ref())
		})
	}

	pub(super) fn truncate(lua: &Lua) -> mlua::Result<Function> {
		fn traverse(
			it: impl Iterator<Item = (usize, char)>,
			max: usize,
		) -> (Option<usize>, usize, bool) {
			let (mut adv, mut last) = (0, 0);
			let idx = it
				.take_while(|&(_, c)| {
					(last, adv) = (adv, adv + c.width().unwrap_or(0));
					adv <= max
				})
				.map(|(i, _)| i)
				.last();
			(idx, last, adv > max)
		}

		lua.create_function(|lua, (s, t): (mlua::String, Table)| {
			let b = s.as_bytes();
			if b.is_empty() {
				return Ok(s);
			}

			let max = t.raw_get("max")?;
			if b.len() <= max {
				return Ok(s);
			} else if max < 1 {
				return lua.create_string("");
			}

			let lossy = String::from_utf8_lossy(&b);
			let rtl = t.raw_get("rtl").unwrap_or(false);
			let (idx, width, remain) = if rtl {
				traverse(lossy.char_indices().rev(), max)
			} else {
				traverse(lossy.char_indices(), max)
			};

			let Some(idx) = idx else { return lua.create_string("…") };
			if !remain {
				return Ok(s);
			}

			let result: Vec<_> = match (rtl, width == max) {

Review comment (suggestion):
The deprecation message includes a '{}' placeholder but no argument is provided, causing a formatting error at runtime. Either supply the missing context value or remove the placeholder.
```suggestion
			deprecate!(lua, "`ya.truncate()` is deprecated, use `ui.truncate()` instead.\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");
```

Code after:
				Some(true) => yazi_shared::shell::escape_unix(s.as_ref()),
				Some(false) => yazi_shared::shell::escape_windows(s.as_ref()),
				None => yazi_shared::shell::escape_native(s.as_ref()),
			};
			lua.create_string(s.as_ref())
		})
	}

	pub(super) fn truncate(lua: &Lua) -> mlua::Result<Function> {
		fn traverse(
			it: impl Iterator<Item = (usize, char)>,
			max: usize,
		) -> (Option<usize>, usize, bool) {
			let (mut adv, mut last) = (0, 0);
			let idx = it
				.take_while(|&(_, c)| {
					(last, adv) = (adv, adv + c.width().unwrap_or(0));
					adv <= max
				})
				.map(|(i, _)| i)
				.last();
			(idx, last, adv > max)
		}

		lua.create_function(|lua, (s, t): (mlua::String, Table)| {
			deprecate!(lua, "`ya.truncate()` is deprecated, use `ui.truncate()` instead, in your {}\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");

			let b = s.as_bytes();
			if b.is_empty() {
				return Ok(s);
			}

			let max = t.raw_get("max")?;
			if b.len() <= max {
				return Ok(s);
			} else if max < 1 {
				return lua.create_string("");
			}

			let lossy = String::from_utf8_lossy(&b);
			let rtl = t.raw_get("rtl").unwrap_or(false);
			let (idx, width, remain) = if rtl {
				traverse(lossy.char_indices().rev(), max)
			} else {
				traverse(lossy.char_indices(), max)
			};

			let Some(idx) = idx else { return lua.create_string("…") };
			if !remain {
				return Ok(s);
			}
Repository: sxyazi/yazi
File: yazi-plugin/src/utils/call.rs (Rust)

Code before:
use mlua::{Function, Lua, Table};
use yazi_dds::Sendable;
use yazi_macro::{emit, render};
use yazi_shared::{Layer, event::Cmd};

use super::Utils;

impl Utils {
	pub(super) fn render(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, ()| {
			render!();
			Ok(())
		})
	}

	pub(super) fn emit(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (name, args): (String, Table)| {
			let mut cmd = Cmd::new_or(name, Layer::Mgr)?;
			cmd.args = Sendable::table_to_args(args)?;
			Ok(emit!(Call(cmd)))
		})
	}

	pub(super) fn mgr_emit(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (name, args): (String, Table)| {
			emit!(Call(Cmd {
				name:  name.into(),
				args:  Sendable::table_to_args(args)?,
				layer: Layer::Mgr,
			}));
			Ok(())
		})
	}
}


Review comment (suggestion):
The '{}' placeholder in this deprecation message is never supplied, which will trigger a formatting panic. Either pass the missing value or drop the placeholder.
```suggestion
			deprecate!(lua, "`ya.render()` is deprecated, use `ui.render()` instead, in your function `render`\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");
```

Code after:
use mlua::{Function, Lua, Table};
use yazi_dds::Sendable;
use yazi_macro::{emit, render};
use yazi_shared::{Layer, event::Cmd};

use super::Utils;
use crate::deprecate;

impl Utils {
	pub(super) fn render(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|lua, ()| {
			deprecate!(lua, "`ya.render()` is deprecated, use `ui.render()` instead, in your {}\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");

			render!();
			Ok(())
		})
	}

	pub(super) fn emit(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (name, args): (String, Table)| {
			let mut cmd = Cmd::new_or(name, Layer::Mgr)?;
			cmd.args = Sendable::table_to_args(args)?;
			Ok(emit!(Call(cmd)))
		})
	}

	pub(super) fn mgr_emit(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, (name, args): (String, Table)| {
			emit!(Call(Cmd {
				name:  name.into(),
				args:  Sendable::table_to_args(args)?,
				layer: Layer::Mgr,
			}));
			Ok(())
		})
	}
}
Repository: sxyazi/yazi
File: yazi-plugin/src/utils/app.rs (Rust)

Code before:
use mlua::{AnyUserData, ExternalError, Function, Lua};
use yazi_binding::Id;
use yazi_proxy::{AppProxy, HIDER};

use super::Utils;
use crate::bindings::{Permit, PermitRef};

impl Utils {
	pub(super) fn id(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, r#type: mlua::String| {
			Ok(Id(match r#type.as_bytes().as_ref() {
				b"app" => *yazi_dds::ID,
				b"ft" => yazi_fs::FILES_TICKET.next(),
				_ => Err("Invalid id type".into_lua_err())?,
			}))
		})
	}

	pub(super) fn hide(lua: &Lua) -> mlua::Result<Function> {
		lua.create_async_function(|lua, ()| async move {
			if lua.named_registry_value::<PermitRef<fn()>>("HIDE_PERMIT").is_ok_and(|h| h.is_some()) {
				return Err("Cannot hide while already hidden".into_lua_err());
			}

			let permit = HIDER.acquire().await.unwrap();
			AppProxy::stop().await;

			lua.set_named_registry_value("HIDE_PERMIT", Permit::new(permit, AppProxy::resume as fn()))?;
			lua.named_registry_value::<AnyUserData>("HIDE_PERMIT")
		})
	}
}


Review comment (bug):
This deprecation call includes an unpopulated '{}' placeholder and will fail at runtime. Provide the argument or remove the placeholder.
```suggestion
			deprecate!(lua, "`ya.hide()` is deprecated, use `ui.hide()` instead, in your script.\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");
```

Code after:
use mlua::{AnyUserData, ExternalError, Function, Lua};
use yazi_binding::Id;
use yazi_proxy::{AppProxy, HIDER};

use super::Utils;
use crate::{bindings::{Permit, PermitRef}, deprecate};

impl Utils {
	pub(super) fn id(lua: &Lua) -> mlua::Result<Function> {
		lua.create_function(|_, r#type: mlua::String| {
			Ok(Id(match r#type.as_bytes().as_ref() {
				b"app" => *yazi_dds::ID,
				b"ft" => yazi_fs::FILES_TICKET.next(),
				_ => Err("Invalid id type".into_lua_err())?,
			}))
		})
	}

	pub(super) fn hide(lua: &Lua) -> mlua::Result<Function> {
		lua.create_async_function(|lua, ()| async move {
			deprecate!(lua, "`ya.hide()` is deprecated, use `ui.hide()` instead, in your {}\nSee #2939 for more details: https://github.com/sxyazi/yazi/pull/2939");

			if lua.named_registry_value::<PermitRef<fn()>>("HIDE_PERMIT").is_ok_and(|h| h.is_some()) {
				return Err("Cannot hide while already hidden".into_lua_err());
			}

			let permit = HIDER.acquire().await.unwrap();
			AppProxy::stop().await;

			lua.set_named_registry_value("HIDE_PERMIT", Permit::new(permit, AppProxy::resume as fn()))?;
			lua.named_registry_value::<AnyUserData>("HIDE_PERMIT")
		})
	}
}
Repository: sxyazi/yazi
File: yazi-core/src/cmp/commands/trigger.rs (Rust)

Code before:
use std::{ffi::OsString, mem, path::{MAIN_SEPARATOR_STR, Path, PathBuf}};

use tokio::fs;
use yazi_fs::{CWD, expand_path};
use yazi_macro::{emit, render};
use yazi_parser::cmp::TriggerOpt;
use yazi_proxy::options::CmpItem;
use yazi_shared::{event::Cmd, natsort};

use crate::cmp::Cmp;

impl Cmp {
	#[yazi_codegen::command]
	pub fn trigger(&mut self, opt: TriggerOpt) {
		if opt.ticket < self.ticket {
			return;
		}

		self.ticket = opt.ticket;
		let Some((parent, word)) = Self::split_path(&opt.word) else {
			return self.close(false);
		};

		if self.caches.contains_key(&parent) {
			return self.show(
				Cmd::default().with_any("cache-name", parent).with("word", word).with("ticket", opt.ticket),
			);
		}

		let ticket = self.ticket;
		tokio::spawn(async move {
			let mut dir = fs::read_dir(&parent).await?;
			let mut cache = vec![];

			// "/" is both a directory separator and the root directory per se
			// As there's no parent directory for the FS root, it is a special case
			if parent == Path::new("/") {
				cache.push(CmpItem { name: OsString::new(), is_dir: true });
			}

Review comment (suggestion):
[nitpick] The `None` case for `opt.ticket` is implicitly skipped; adding a comment or explicit branch could help clarify why missing tickets should bypass update logic.
```suggestion
	pub fn trigger(&mut self, opt: TriggerOpt) {
		// If `opt.ticket` is `None`, we bypass the update logic as no ticket is provided.
```

Code after:
use std::{ffi::OsString, mem, path::{MAIN_SEPARATOR_STR, Path, PathBuf}};

use tokio::fs;
use yazi_fs::{CWD, expand_path};
use yazi_macro::{emit, render};
use yazi_parser::cmp::TriggerOpt;
use yazi_proxy::options::CmpItem;
use yazi_shared::{event::Cmd, natsort};

use crate::cmp::Cmp;

impl Cmp {
	#[yazi_codegen::command]
	pub fn trigger(&mut self, opt: TriggerOpt) {
		if let Some(t) = opt.ticket {
			if t < self.ticket {
				return;
			}
			self.ticket = t;
		}

		let Some((parent, word)) = Self::split_path(&opt.word) else {
			return self.close(false);
		};

		if self.caches.contains_key(&parent) {
			return self.show(
				Cmd::default()
					.with_any("cache-name", parent)
					.with("word", word)
					.with("ticket", self.ticket),
			);
		}

		let ticket = self.ticket;
		tokio::spawn(async move {
			let mut dir = fs::read_dir(&parent).await?;
			let mut cache = vec![];
Repository: sxyazi/yazi
File: yazi-dds/src/body/yank.rs (Rust)

Code before:
use std::{borrow::Cow, collections::HashSet};

use mlua::{IntoLua, Lua, MetaMethod, UserData, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::Url;

use super::Body;

#[derive(Debug, Serialize, Deserialize)]
pub struct BodyYank<'a> {
	pub cut:  bool,
	pub urls: Cow<'a, HashSet<Url>>,
	#[serde(skip)]
	dummy:    bool,
}

impl<'a> BodyYank<'a> {
	#[inline]
	pub fn borrowed(cut: bool, urls: &'a HashSet<Url>) -> Body<'a> {
		Self { cut, urls: Cow::Borrowed(urls), dummy: false }.into()
	}
}

impl BodyYank<'static> {
	#[inline]
	pub fn dummy() -> Body<'static> {
		Self { cut: false, urls: Default::default(), dummy: true }.into()
	}
}

impl<'a> From<BodyYank<'a>> for Body<'a> {
	fn from(value: BodyYank<'a>) -> Self { Self::Yank(value) }
}

impl IntoLua for BodyYank<'static> {
	fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
		if let Some(Cow::Owned(urls)) = Some(self.urls).filter(|_| !self.dummy) {
			BodyYankIter { cut: self.cut, urls: urls.into_iter().collect() }.into_lua(lua)
		} else {
			lua.create_table()?.into_lua(lua)
		}
	}
}

// --- Iterator
#[derive(Clone)]
pub struct BodyYankIter {
	pub cut:  bool,

Review comment (suggestion):
[nitpick] Consider re-adding `#[inline]` on simple one-line constructors like `owned` to preserve cross-crate inlining and reduce potential call overhead.
```suggestion
impl BodyYank<'static> {
	#[inline]
```

Code after:
use std::{borrow::Cow, collections::HashSet};

use mlua::{IntoLua, Lua, MetaMethod, UserData, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::Url;

use super::Body;

#[derive(Debug, Serialize, Deserialize)]
pub struct BodyYank<'a> {
	pub cut:  bool,
	pub urls: Cow<'a, HashSet<Url>>,
	#[serde(skip)]
	dummy:    bool,
}

impl<'a> BodyYank<'a> {
	pub fn borrowed(cut: bool, urls: &'a HashSet<Url>) -> Body<'a> {
		Self { cut, urls: Cow::Borrowed(urls), dummy: false }.into()
	}
}

impl BodyYank<'static> {
	pub fn owned(cut: bool, _: &HashSet<Url>) -> Body<'static> {
		Self { cut, urls: Default::default(), dummy: true }.into()
	}
}

impl<'a> From<BodyYank<'a>> for Body<'a> {
	fn from(value: BodyYank<'a>) -> Self { Self::Yank(value) }
}

impl IntoLua for BodyYank<'static> {
	fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
		if let Some(Cow::Owned(urls)) = Some(self.urls).filter(|_| !self.dummy) {
			BodyYankIter { cut: self.cut, urls: urls.into_iter().collect() }.into_lua(lua)
		} else {
			lua.create_table()?.into_lua(lua)
		}
	}
}

// --- Iterator
#[derive(Clone)]
pub struct BodyYankIter {
	pub cut:  bool,
	pub urls: Vec<Url>,
}
Repository: sxyazi/yazi
File: yazi-fm/src/app/commands/plugin.rs (Rust)

Code before:
			return self.plugin_do(opt);
		}

		tokio::spawn(async move {
			match LOADER.ensure(&opt.id, |_| ()).await {
				Ok(()) => AppProxy::plugin_do(opt),
				Err(e) => AppProxy::notify_error("Plugin load failed", e),
			}
		});
		succ!();
	}

	pub(crate) fn plugin_do(&mut self, opt: PluginOpt) -> Result<Data> {
		let loader = LOADER.read();
		let Some(chunk) = loader.get(opt.id.as_ref()) else {
			succ!(warn!("plugin `{}` not found", opt.id));
		};

		if let Err(e) = Loader::compatible_or_error(&opt.id, chunk) {
			succ!(AppProxy::notify_error("Incompatible plugin", e));
		}

		if opt.mode.auto_then(chunk.sync_entry) != PluginMode::Sync {
			succ!(self.core.tasks.plugin_micro(opt));
		}

		match runtime_mut!(LUA) {
			Ok(mut r) => r.push(&opt.id),
			Err(e) => succ!(warn!("{e}")),
		}
		defer! { _ = runtime_mut!(LUA).map(|mut r| r.pop()) }

		let plugin = match LOADER.load_with(&LUA, &opt.id, chunk) {
			Ok(t) => t,
			Err(e) => succ!(warn!("{e}")),
		};
		drop(loader);

		let result = Lives::scope(&self.core, || {
			if let Some(cb) = opt.cb {
				cb(&LUA, plugin)
			} else {
				let job = LUA.create_table_from([("args", Sendable::args_to_table(&LUA, opt.args)?)])?;
				plugin.call_method("entry", job)
			}
		});
		if let Err(ref e) = result {
			error!("Sync plugin `{}` failed: {e}", opt.id);
		}
		succ!(result?);
	}

Review comment (bug):
The error handling change removes the warning log that was previously displayed when LUA runtime access failed. This could make debugging more difficult as errors will now propagate up instead of being logged and handled gracefully.
```suggestion

		if let Err(e) = runtime_mut!(LUA) {
			warn!("Failed to access LUA runtime: {e}");
			return Err(e);
		}
```

Code after:
			return self.plugin_do(opt);
		}

		tokio::spawn(async move {
			match LOADER.ensure(&opt.id, |_| ()).await {
				Ok(()) => AppProxy::plugin_do(opt),
				Err(e) => AppProxy::notify_error("Plugin load failed", e),
			}
		});
		succ!();
	}

	pub(crate) fn plugin_do(&mut self, opt: PluginOpt) -> Result<Data> {
		let loader = LOADER.read();
		let Some(chunk) = loader.get(opt.id.as_ref()) else {
			succ!(warn!("plugin `{}` not found", opt.id));
		};

		if let Err(e) = Loader::compatible_or_error(&opt.id, chunk) {
			succ!(AppProxy::notify_error("Incompatible plugin", e));
		}

		if opt.mode.auto_then(chunk.sync_entry) != PluginMode::Sync {
			succ!(self.core.tasks.plugin_micro(opt));
		}

		runtime_mut!(LUA)?.push(&opt.id);
		defer! { _ = runtime_mut!(LUA).map(|mut r| r.pop()) }

		let plugin = match LOADER.load_with(&LUA, &opt.id, chunk) {
			Ok(t) => t,
			Err(e) => succ!(warn!("{e}")),
		};
		drop(loader);

		let result = Lives::scope(&self.core, || {
			if let Some(cb) = opt.cb {
				cb(&LUA, plugin)
			} else {
				let job = LUA.create_table_from([("args", Sendable::args_to_table(&LUA, opt.args)?)])?;
				plugin.call_method("entry", job)
			}
		});
		if let Err(ref e) = result {
			error!("Sync plugin `{}` failed: {e}", opt.id);
		}
		succ!(result?);
	}
}
Repository: sxyazi/yazi
File: yazi-fm/src/executor.rs (Rust)

Code before:
			($name:ident) => {
				if cmd.name == stringify!($name) {
					return act!($name, self.app, cmd);
				}
			};
		}

		on!(accept_payload);
		on!(notify);
		on!(plugin);
		on!(plugin_do);
		on!(update_notify);
		on!(update_progress);
		on!(resize);
		on!(stop);
		on!(resume);
		on!(deprecate);

		succ!();
	}

	fn mgr(&mut self, cmd: CmdCow) -> Result<Data> {
		let cx = &mut Ctx::new(&mut self.app.core, &cmd)?;

		macro_rules! on {
			($name:ident) => {
				if cmd.name == stringify!($name) {
					return act!(mgr:$name, cx, cmd);
				}
			};
		}

		on!(cd);
		on!(update_tasks);
		on!(update_yanked);

		on!(update_files);
		on!(update_mimes);
		on!(update_paged);
		on!(watch);
		on!(peek);
		on!(seek);
		on!(spot);
		on!(refresh);
		on!(quit);
		on!(close);
		on!(suspend);
		on!(escape);
		on!(update_peeked);
		on!(update_spotted);


Review comment (suggestion):
The FIXME comment indicates technical debt where DDS logic should be moved to the appropriate module. This mixing of concerns may affect maintainability.

Code after:
		macro_rules! on {
			($name:ident) => {
				if cmd.name == stringify!($name) {
					return act!($name, self.app, cmd);
				}
			};
		}

		on!(accept_payload);
		on!(notify);
		on!(plugin);
		on!(plugin_do);
		on!(update_notify);
		on!(update_progress);
		on!(resize);
		on!(stop);
		on!(resume);
		on!(deprecate);

		succ!();
	}

	fn mgr(&mut self, cmd: CmdCow) -> Result<Data> {
		let cx = &mut Ctx::new(&mut self.app.core, &cmd)?;

		// FIXME: move the DDS part to `yazi-actor`
		macro_rules! on {
			($name:ident) => {
				if cmd.name == stringify!($name) {
					let opt = <act!(mgr:$name) as Actor>::Options::try_from(cmd)?;
					return if let Ok(body) = Body::try_from(&opt) && App::accept_payload2(cx.core, body)? == true {
						succ!()
					} else {
						act!(mgr:$name, cx, opt)
					};
				}
			};
		}

		on!(cd);
		on!(update_tasks);
		on!(update_yanked);

		on!(update_files);
		on!(update_mimes);
		on!(update_paged);
		on!(watch);
		on!(peek);
		on!(seek);
		on!(spot);
		on!(refresh);
Repository: sxyazi/yazi
File: yazi-shared/src/os.rs (Rust)

Code before:
#[cfg(unix)]
pub static USERS_CACHE: crate::RoCell<uzers::UsersCache> = crate::RoCell::new();

#[cfg(unix)]
pub fn hostname() -> Option<&'static str> {
	static CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

	CACHE.get_or_init(|| hostname_impl().ok()).as_deref()
}

#[cfg(unix)]
fn hostname_impl() -> Result<String, std::io::Error> {
	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(|_| std::io::Error::other("invalid hostname"))
		.map(|s| s.to_owned())
}


Review comment (suggestion):
The `session_leader()` function lacks documentation. Add a docstring explaining what it does, when it returns true/false, and its purpose in the suspension context.
```suggestion
#[cfg(unix)]
/// Determines if the current process is the session leader.
///
/// A session leader is a process that created a new session using the `setsid` system call.
/// This function checks if the session ID of the current process (obtained via `getsid(0)`)
/// matches its process ID (obtained via `getpid`). If they match, the process is the session leader.
///
/// # Returns
/// - `true` if the current process is the session leader.
/// - `false` otherwise.
///
/// # Safety
/// This function uses unsafe code to call low-level system functions. It is intended for use
/// in Unix-like environments where such system calls are available.
///
/// # Purpose
/// This function is useful in contexts where it is necessary to determine the role of the
/// current process in process management, such as when handling process suspension or
/// termination.
```

Code after:
#[cfg(unix)]
pub fn hostname() -> Option<&'static str> {
	static CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

	CACHE.get_or_init(|| hostname_impl().ok()).as_deref()
}

#[cfg(unix)]
fn hostname_impl() -> Result<String, std::io::Error> {
	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(|_| std::io::Error::other("invalid hostname"))
		.map(|s| s.to_owned())
}

#[cfg(unix)]
pub fn session_leader() -> bool { unsafe { libc::getsid(0) == libc::getpid() } }
Repository: sxyazi/yazi
File: yazi-shared/src/os.rs (Rust)

Code before:
#[cfg(unix)]
pub static USERS_CACHE: crate::RoCell<uzers::UsersCache> = crate::RoCell::new();

#[cfg(unix)]
pub fn hostname() -> Option<&'static str> {
	static CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

	CACHE.get_or_init(|| hostname_impl().ok()).as_deref()
}

#[cfg(unix)]
fn hostname_impl() -> Result<String, std::io::Error> {
	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(|_| std::io::Error::other("invalid hostname"))
		.map(|s| s.to_owned())
}


Review comment (suggestion):
[nitpick] Consider formatting this function across multiple lines for better readability, especially given the unsafe block usage.
```suggestion
pub fn session_leader() -> bool {
    unsafe {
        libc::getsid(0) == libc::getpid()
    }
}
```

Code after:
pub fn hostname() -> Option<&'static str> {
	static CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

	CACHE.get_or_init(|| hostname_impl().ok()).as_deref()
}

#[cfg(unix)]
fn hostname_impl() -> Result<String, std::io::Error> {
	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(|_| std::io::Error::other("invalid hostname"))
		.map(|s| s.to_owned())
}

#[cfg(unix)]
pub fn session_leader() -> bool { unsafe { libc::getsid(0) == libc::getpid() } }