evobench_tools/utillib/
get_terminal_width.rs

1//! Hack to get terminal width to allow making older Clap versions
2//! auto-adapt to the current width.
3
4use std::{fs::File, os::fd::AsRawFd};
5
6use terminal_size::{Height, Width, terminal_size, terminal_size_using_fd};
7
8/// Unlike `terminal_size::terminal_size()` which uses stdout, this
9/// opens `/dev/tty` if possible, then falls back to the former.
10pub fn terminal_size_using_tty() -> Option<(Width, Height)> {
11    if let Ok(file) = File::open("/dev/tty") {
12        terminal_size_using_fd(file.as_raw_fd())
13    } else {
14        terminal_size()
15    }
16}
17
18/// Always return a width, fall back to a default value of 120.
19pub fn get_terminal_width(right_margin: usize) -> usize {
20    let default = 120;
21    if let Some((terminal_size::Width(width), _height)) = terminal_size_using_tty() {
22        usize::from(width)
23            .checked_sub(right_margin)
24            .unwrap_or(default)
25    } else {
26        default
27    }
28}