use std::{
env,
ffi::OsStr,
io::{self, IsTerminal},
};
use crate::cli::Color;
pub(crate) const HEADER: &str = "\x1b[1;38;5;220m";
pub(crate) const COMMAND: &str = "\x1b[1;38;5;81m";
pub(crate) const DIM: &str = "\x1b[2m";
pub(crate) const RESET: &str = "\x1b[0m";
const GOOD: &str = "\x1b[32m";
const PENDING: &str = "\x1b[33m";
const BAD: &str = "\x1b[31m";
const MUTED: &str = "\x1b[2m";
const GOOD_GLYPH: &str = "✓";
const PENDING_GLYPH: &str = "•";
const BAD_GLYPH: &str = "✗";
const GAP: &str = " ";
const DEFAULT_COLUMNS: u16 = 80;
const COLUMNS_VARIABLE: &str = "COLUMNS";
pub(crate) const OUTPUT_MODE_VARIABLE: &str = "TROLL_OUTPUT";
pub(crate) const AGENT_MARKERS: [&str; 4] = ["CLAUDECODE", "GEMINI_CLI", "CURSOR_AGENT", "CI"];
pub(crate) const NO_COLOR_FLAGS: [&str; 3] = ["--no-color", "--no-colors", "--no-ansi-colors"];
pub(crate) fn is_no_color_flag(token: &str) -> bool {
NO_COLOR_FLAGS.contains(&token)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Stream {
Stdout,
#[allow(dead_code)]
Stderr,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum OutputMode {
#[default]
Auto,
Plain,
Human,
}
impl OutputMode {
pub(crate) fn parse(value: Option<&OsStr>) -> Self {
match value.and_then(OsStr::to_str).map(str::trim) {
Some(value) if value.eq_ignore_ascii_case("plain") => Self::Plain,
Some(value) if value.eq_ignore_ascii_case("human") => Self::Human,
_ => Self::Auto,
}
}
}
pub(crate) fn agent_marker(
lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Option<&'static str> {
AGENT_MARKERS.into_iter().find(|name| {
lookup(name).is_some_and(|value| {
let value = value.to_string_lossy();
let value = value.trim();
!(value.is_empty() || value == "0" || value.eq_ignore_ascii_case("false"))
})
})
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct TerminalFacts {
pub(crate) is_terminal: bool,
pub(crate) no_color_env: bool,
pub(crate) dumb_term: bool,
pub(crate) mode: OutputMode,
pub(crate) agent: bool,
pub(crate) columns: Option<u16>,
}
impl TerminalFacts {
pub(crate) fn of(stream: Stream) -> Self {
let is_terminal = match stream {
Stream::Stdout => io::stdout().is_terminal(),
Stream::Stderr => io::stderr().is_terminal(),
};
Self {
is_terminal,
no_color_env: env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()),
dumb_term: env::var_os("TERM").as_deref() == Some(OsStr::new("dumb")),
mode: OutputMode::parse(env::var_os(OUTPUT_MODE_VARIABLE).as_deref()),
agent: agent_marker(|name| env::var_os(name)).is_some(),
columns: is_terminal.then(|| {
columns_from(env::var_os(COLUMNS_VARIABLE).as_deref()).unwrap_or(DEFAULT_COLUMNS)
}),
}
}
}
pub(crate) fn columns_from(value: Option<&OsStr>) -> Option<u16> {
value?
.to_str()?
.trim()
.parse::<u16>()
.ok()
.filter(|columns| *columns > 0)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Style {
human: bool,
color: bool,
columns: Option<u16>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Tone {
Good,
Pending,
Bad,
Muted,
Neutral,
}
impl Style {
#[cfg(test)]
pub(crate) const PLAIN: Self = Self {
human: false,
color: false,
columns: None,
};
#[cfg(test)]
pub(crate) const COLOR: Self = Self {
human: true,
color: true,
columns: None,
};
pub(crate) fn detect(stream: Stream, choice: Color, json: bool) -> Self {
Self::decide(TerminalFacts::of(stream), choice, json)
}
pub(crate) fn decide(facts: TerminalFacts, choice: Color, json: bool) -> Self {
if json {
return Self {
human: false,
color: false,
columns: None,
};
}
let wanted_human = match facts.mode {
OutputMode::Plain => false,
OutputMode::Human => true,
OutputMode::Auto => !facts.agent,
};
let human = match choice {
Color::Always => true,
Color::Never => facts.is_terminal && wanted_human,
Color::Auto => facts.is_terminal && wanted_human,
};
let color = match choice {
Color::Always => true,
Color::Never => false,
Color::Auto => human && !facts.no_color_env && !facts.dumb_term,
};
Self {
human,
color,
columns: facts.columns.filter(|_| human),
}
}
pub(crate) fn is_human(self) -> bool {
self.human
}
pub(crate) fn has_color(self) -> bool {
self.color
}
#[allow(dead_code)]
pub(crate) fn columns(self) -> Option<usize> {
self.columns.map(usize::from)
}
pub(crate) fn paint(self, code: &str, text: &str) -> String {
if self.color {
format!("{code}{text}{RESET}")
} else {
text.to_owned()
}
}
pub(crate) fn heading(self, text: &str) -> String {
self.paint(HEADER, text)
}
pub(crate) fn accent(self, text: &str) -> String {
self.paint(COMMAND, text)
}
pub(crate) fn dim(self, text: &str) -> String {
self.paint(DIM, text)
}
pub(crate) fn status_cell(self, word: &str) -> Cell {
if !self.human {
return Cell::plain(display(word));
}
let (glyph, code) = match tone(word) {
Tone::Good => (GOOD_GLYPH, GOOD),
Tone::Pending => (PENDING_GLYPH, PENDING),
Tone::Bad => (BAD_GLYPH, BAD),
Tone::Muted => (PENDING_GLYPH, MUTED),
Tone::Neutral => return Cell::plain(display(word)),
};
let text = format!("{glyph} {}", display(word));
Cell::styled(&text, self.paint(code, &text))
}
pub(crate) fn status_text(self, word: &str) -> String {
self.status_cell(word).into()
}
}
pub(crate) fn tone(word: &str) -> Tone {
match word {
"listening" | "ok" | "active" | "free" | "enabled" => Tone::Good,
"warning" | "overdue" | "expiring" | "claimed" | "in use" | "unknown" => Tone::Pending,
"failed" | "reclaimable" | "conflict" => Tone::Bad,
"silent" | "disabled" => Tone::Muted,
_ => Tone::Neutral,
}
}
pub(crate) fn display(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for character in raw.chars() {
match character {
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
ch if ch.is_control() || is_bidi_control(ch) => {
out.push_str(&format!("\\u{{{:x}}}", u32::from(ch)));
}
other => out.push(other),
}
}
out
}
fn is_bidi_control(ch: char) -> bool {
matches!(
ch,
'\u{061C}'
| '\u{200E}'..='\u{200F}'
| '\u{202A}'..='\u{202E}'
| '\u{2066}'..='\u{2069}'
)
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Cell {
width: usize,
shown: String,
}
impl Cell {
pub(crate) fn plain(text: impl Into<String>) -> Self {
let shown = text.into();
Self {
width: shown.chars().count(),
shown,
}
}
pub(crate) fn styled(text: &str, shown: String) -> Self {
Self {
width: text.chars().count(),
shown,
}
}
}
impl From<Cell> for String {
fn from(cell: Cell) -> Self {
cell.shown
}
}
#[derive(Debug)]
pub(crate) struct Table {
headers: Vec<String>,
rows: Vec<Vec<Cell>>,
}
impl Table {
pub(crate) fn new(headers: &[&str]) -> Self {
Self {
headers: headers.iter().map(|header| (*header).to_owned()).collect(),
rows: Vec::new(),
}
}
pub(crate) fn row(&mut self, mut cells: Vec<Cell>) -> &mut Self {
cells.resize_with(self.headers.len().max(cells.len()), || Cell::plain(""));
self.rows.push(cells);
self
}
pub(crate) fn render(&self, style: Style, indent: &str) -> String {
let columns = self.headers.len();
let mut widths: Vec<usize> = self
.headers
.iter()
.map(|header| header.chars().count())
.collect();
for row in &self.rows {
for (index, cell) in row.iter().enumerate().take(columns) {
widths[index] = widths[index].max(cell.width);
}
}
let mut out = String::new();
let header: Vec<Cell> = self
.headers
.iter()
.map(|text| Cell::styled(text, style.dim(text)))
.collect();
for row in std::iter::once(&header).chain(&self.rows) {
out.push_str(indent);
for (index, cell) in row.iter().enumerate() {
out.push_str(&cell.shown);
if index + 1 < row.len() {
let width = widths.get(index).copied().unwrap_or(cell.width);
out.push_str(&" ".repeat(width.saturating_sub(cell.width)));
out.push_str(GAP);
}
}
let trimmed = out.trim_end_matches(' ').len();
out.truncate(trimmed);
out.push('\n');
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn style_gives_ansi_to_human_terminals_and_raw_text_to_pipes_and_agents() {
let tty = TerminalFacts {
is_terminal: true,
..TerminalFacts::default()
};
assert!(Style::decide(tty, Color::Auto, false).has_color());
assert!(Style::decide(tty, Color::Auto, false).is_human());
let piped = TerminalFacts::default();
assert!(!Style::decide(piped, Color::Auto, false).has_color());
assert!(!Style::decide(piped, Color::Auto, false).is_human());
let agent = TerminalFacts {
is_terminal: true,
agent: true,
..TerminalFacts::default()
};
assert!(!Style::decide(agent, Color::Auto, false).has_color());
assert!(!Style::decide(agent, Color::Auto, false).is_human());
let forced_human = TerminalFacts {
mode: OutputMode::Human,
..agent
};
assert!(Style::decide(forced_human, Color::Auto, false).has_color());
let forced_plain = TerminalFacts {
mode: OutputMode::Plain,
..tty
};
assert!(!Style::decide(forced_plain, Color::Auto, false).is_human());
assert!(!Style::decide(forced_plain, Color::Auto, false).has_color());
let dumb = TerminalFacts {
dumb_term: true,
..tty
};
assert!(Style::decide(dumb, Color::Auto, false).is_human());
assert!(!Style::decide(dumb, Color::Auto, false).has_color());
let no_color = TerminalFacts {
no_color_env: true,
..tty
};
assert!(Style::decide(no_color, Color::Auto, false).is_human());
assert!(!Style::decide(no_color, Color::Auto, false).has_color());
assert!(!Style::decide(tty, Color::Always, true).has_color());
assert!(Style::decide(piped, Color::Always, false).has_color());
}
#[test]
fn display_escapes_control_and_bidi_override_characters() {
assert_eq!(display("safe-name"), "safe-name");
assert_eq!(
display("a\x1b[31mb\u{202e}c\nd"),
"a\\u{1b}[31mb\\u{202e}c\\nd"
);
}
#[test]
fn table_aligns_visible_widths_ignoring_ansi_codes() {
let mut table = Table::new(&["PORT", "STATUS"]);
table.row(vec![
Cell::styled("8123", Style::COLOR.accent("8123")),
Style::COLOR.status_cell("listening"),
]);
let rendered = table.render(Style::COLOR, " ");
assert!(rendered.contains("\x1b["));
assert!(rendered.contains("✓ listening"));
let plain = table.render(Style::PLAIN, " ");
assert!(plain.contains("8123"));
}
}