pub(crate) fn term_width() -> usize {
#[cfg(unix)]
{
use std::io::IsTerminal;
if std::io::stdout().is_terminal() {
let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
if unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) } == 0 && ws.ws_col > 0 {
return ws.ws_col as usize;
}
}
}
std::env::var("COLUMNS")
.ok()
.and_then(|c| c.parse().ok())
.filter(|&c: &usize| c >= 40)
.unwrap_or(100)
}
pub(crate) struct Ink(pub(crate) bool);
impl Ink {
pub(crate) fn detect() -> Self {
use std::io::IsTerminal;
Ink(std::io::stdout().is_terminal()
&& std::env::var_os("NO_COLOR").is_none()
&& std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true))
}
pub(crate) fn bold(&self, t: &str) -> String {
if self.0 {
format!("\x1b[1m{t}\x1b[0m")
} else {
t.to_string()
}
}
pub(crate) fn dim(&self, t: &str) -> String {
if self.0 {
format!("\x1b[2m{t}\x1b[0m")
} else {
t.to_string()
}
}
}
pub(crate) fn clip(t: &str, w: usize) -> String {
if t.chars().count() <= w {
return t.to_string();
}
let mut out: String = t.chars().take(w.saturating_sub(1)).collect();
out.push('…');
out
}
pub(crate) fn pad(t: &str, w: usize) -> String {
let t = clip(t, w);
let n = t.chars().count();
format!("{t}{}", " ".repeat(w.saturating_sub(n)))
}
pub(crate) fn rpad(t: &str, w: usize) -> String {
let n = t.chars().count();
format!("{}{t}", " ".repeat(w.saturating_sub(n)))
}
#[cfg(test)]
mod tests {
#[test]
fn columns_clip_and_pad_to_width() {
assert_eq!(super::pad("abc", 5), "abc ");
assert_eq!(super::pad("abcdefgh", 5), "abcd…");
assert_eq!(super::rpad("3.1G", 6), " 3.1G");
assert_eq!(super::clip("short", 10), "short");
}
}