prs_lib/util/tty.rs
1use std::path::{Path, PathBuf};
2
3/// Maximum symlink resolving depth.
4const SYMLINK_DEPTH_MAX: u8 = 31;
5
6/// Local TTY path.
7const LOCAL_TTY_PATH: &str = "/dev/stdin";
8
9/// Get TTY path for this process.
10///
11/// Returns `None` if not in a TTY. Always returns `None` if not Linux, FreeBSD or OpenBSD.
12pub fn get_tty() -> Option<PathBuf> {
13 // None on unsupported platforms
14 if cfg!(not(any(
15 target_os = "linux",
16 target_os = "freebsd",
17 target_os = "openbsd",
18 ))) {
19 return None;
20 }
21
22 let path = PathBuf::from(LOCAL_TTY_PATH);
23 resolve_symlink(&path, 0)
24}
25
26/// Resolve symlink to the final accessible path.
27///
28/// Returns `None` if the given link could not be read (and `depth` is 0).
29///
30/// # Panics
31///
32/// Panics if a depth of `SYMLINK_DEPTH_MAX` is reached to prevent infinite loops.
33fn resolve_symlink(path: &Path, depth: u8) -> Option<PathBuf> {
34 // Panic if we're getting too deep
35 if depth >= SYMLINK_DEPTH_MAX {
36 // TODO: do not panic, return last unique path or return error
37 panic!("failed to resolve symlink because it is too deep, possible loop?");
38 }
39
40 // Read symlink path, recursively find target
41 match path.read_link() {
42 Ok(path) => resolve_symlink(&path, depth + 1),
43 Err(_) if depth == 0 => None,
44 Err(_) => Some(path.into()),
45 }
46}