use std::path::{Path, PathBuf};
const SYMLINK_DEPTH_MAX: u8 = 31;
const LOCAL_TTY_PATH: &str = "/dev/stdin";
pub fn get_tty() -> Option<PathBuf> {
if cfg!(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd",
))) {
return None;
}
let path = PathBuf::from(LOCAL_TTY_PATH);
resolve_symlink(&path, 0)
}
fn resolve_symlink(path: &Path, depth: u8) -> Option<PathBuf> {
if depth >= SYMLINK_DEPTH_MAX {
panic!("failed to resolve symlink because it is too deep, possible loop?");
}
match path.read_link() {
Ok(path) => resolve_symlink(&path, depth + 1),
Err(_) if depth == 0 => None,
Err(_) => Some(path.into()),
}
}