use std::ffi::{OsStr, OsString};
use buildl::report::{Mode, Paint};
use crate::cli::Color;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Terminal {
pub interactive: bool,
pub term: Option<OsString>,
pub no_color: Option<OsString>,
}
impl Terminal {
pub(crate) fn mode(&self) -> Mode {
if self.redraws() {
Mode::Live
} else {
Mode::Plain
}
}
pub(crate) fn paint(&self, color: Color) -> Paint {
let coloured = match color {
Color::Always => true,
Color::Never => false,
Color::Auto => self.redraws() && !set(self.no_color.as_deref()),
};
if coloured { Paint::Ansi } else { Paint::Plain }
}
fn redraws(&self) -> bool {
self.interactive
&& set(self.term.as_deref())
&& self.term.as_deref() != Some(OsStr::new("dumb"))
}
}
fn set(value: Option<&OsStr>) -> bool {
value.is_some_and(|value| !value.is_empty())
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use buildl::report::{Mode, Paint};
use super::Terminal;
use crate::cli::Color;
fn on_a_terminal(term: Option<&str>, no_color: Option<&str>) -> Terminal {
Terminal {
interactive: true,
term: term.map(OsString::from),
no_color: no_color.map(OsString::from),
}
}
fn into_a_pipe(term: Option<&str>, no_color: Option<&str>) -> Terminal {
Terminal {
interactive: false,
term: term.map(OsString::from),
no_color: no_color.map(OsString::from),
}
}
#[test]
fn a_terminal_gets_a_status_line_and_colour() {
let terminal = on_a_terminal(Some("xterm-256color"), None);
assert_eq!(terminal.mode(), Mode::Live);
assert_eq!(terminal.paint(Color::Auto), Paint::Ansi);
}
#[test]
fn a_pipe_is_plain() {
let pipe = into_a_pipe(Some("xterm-256color"), None);
assert_eq!(pipe.mode(), Mode::Plain);
assert_eq!(pipe.paint(Color::Auto), Paint::Plain);
}
#[test]
fn a_dumb_terminal_is_plain() {
for term in [Some("dumb"), Some(""), None] {
let terminal = on_a_terminal(term, None);
assert_eq!(terminal.mode(), Mode::Plain, "TERM is {term:?}");
assert_eq!(
terminal.paint(Color::Auto),
Paint::Plain,
"TERM is {term:?}"
);
}
}
#[test]
fn no_color_turns_colour_off_and_keeps_the_status_line() {
let terminal = on_a_terminal(Some("xterm"), Some("1"));
assert_eq!(terminal.mode(), Mode::Live);
assert_eq!(terminal.paint(Color::Auto), Paint::Plain);
let empty = on_a_terminal(Some("xterm"), Some(""));
assert_eq!(empty.paint(Color::Auto), Paint::Ansi);
}
#[test]
fn always_colours_a_pipe() {
let pipe = into_a_pipe(None, Some("1"));
assert_eq!(pipe.paint(Color::Always), Paint::Ansi);
assert_eq!(pipe.mode(), Mode::Plain);
}
#[test]
fn never_leaves_a_terminal_uncoloured() {
let terminal = on_a_terminal(Some("xterm"), None);
assert_eq!(terminal.paint(Color::Never), Paint::Plain);
assert_eq!(terminal.mode(), Mode::Live);
}
}