From d6108e5bc0d431df274a32696d6c6eb60b47d750 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 17 Dec 2025 17:25:56 +0000 Subject: [PATCH] Refactor `common::is_console_session` - Use nix::unistd::ttyname - Simplify logic with pattern matching Closes #12179 --- Cargo.toml | 1 + src/common.rs | 35 ++++++++++++++--------------------- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 09b1a895f..4ece75a83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ nix = { version = "0.30.1", default-features = false, features = [ "inotify", "resource", "fs", + "term", ] } num-traits = "0.2.19" once_cell = "1.19.0" diff --git a/src/common.rs b/src/common.rs index c60d5cc50..f6476f4d4 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1833,27 +1833,20 @@ pub fn is_console_session() -> bool { static IS_CONSOLE_SESSION: OnceCell = OnceCell::new(); // TODO(terminal-workaround) *IS_CONSOLE_SESSION.get_or_init(|| { - const PATH_MAX: usize = libc::PATH_MAX as usize; - let mut tty_name = [0u8; PATH_MAX]; - unsafe { - if libc::ttyname_r(STDIN_FILENO, tty_name.as_mut_ptr().cast(), tty_name.len()) != 0 { - return false; - } - } - // Check if the tty matches /dev/(console|dcons|tty[uv\d]) - const LEN: usize = b"/dev/tty".len(); - ( - ( - tty_name.starts_with(b"/dev/tty") && - ([b'u', b'v'].contains(&tty_name[LEN]) || tty_name[LEN].is_ascii_digit()) - ) || - tty_name.starts_with(b"/dev/dcons\0") || - tty_name.starts_with(b"/dev/console\0")) - // and that $TERM is simple, e.g. `xterm` or `vt100`, not `xterm-something` or `sun-color`. - && match env::var_os("TERM") { - Some(term) => !term.as_bytes().contains(&b'-'), - None => true, - } + nix::unistd::ttyname(unsafe { std::os::fd::BorrowedFd::borrow_raw(STDIN_FILENO) }) + .is_ok_and(|buf| { + // Check if the tty matches /dev/(console|dcons|tty[uv\d]) + let is_console_tty = match buf.as_os_str().as_bytes() { + b"/dev/console" => true, + b"/dev/dcons" => true, + bytes => bytes.strip_prefix(b"/dev/tty").is_some_and(|rest| { + matches!(rest.first(), Some(b'u' | b'v' | b'0'..=b'9')) + }), + }; + + // and that $TERM is simple, e.g. `xterm` or `vt100`, not `xterm-something` or `sun-color`. + is_console_tty && env::var_os("TERM").is_none_or(|t| !t.as_bytes().contains(&b'-')) + }) }) }