7.6 KiB · text History 2977adf
//! Terminal presentation: colour, tables, times.
//!
//! Colour is ANSI written by hand: off unless stdout is a terminal and
//! `NO_COLOR` is unset.

use chrono::{DateTime, Utc};
use serde::Serialize;
use std::io::IsTerminal;
use std::sync::OnceLock;

// ── colour ───────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
    Good,
    Bad,
    Warn,
    Muted,
    Plain,
}

impl Tone {
    fn ansi(self) -> &'static str {
        match self {
            Tone::Good => "\x1b[32m",
            Tone::Bad => "\x1b[31m",
            Tone::Warn => "\x1b[33m",
            Tone::Muted => "\x1b[90m",
            Tone::Plain => "",
        }
    }
}

fn color_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED
        .get_or_init(|| std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal())
}

pub fn paint(text: &str, tone: Tone) -> String {
    if tone == Tone::Plain || !color_enabled() {
        return text.to_string();
    }
    format!("{}{text}\x1b[0m", tone.ansi())
}

pub fn bold(text: &str) -> String {
    if color_enabled() {
        format!("\x1b[1m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

/// The colour a status word reads in, across issues, monitors and keys.
pub fn status_tone(status: &str) -> Tone {
    match status {
        "resolved" | "ok" | "up" | "active" | "open" => Tone::Good,
        "unresolved" | "error" | "fatal" | "down" | "failing" | "missed" | "timeout" => Tone::Bad,
        "warning" | "pending" | "late" => Tone::Warn,
        _ => Tone::Muted,
    }
}

pub fn status(text: &str) -> String {
    paint(text, status_tone(text))
}

// ── time ─────────────────────────────────────────────────────────────

/// "3m ago" for anything recent, the date once that stops being useful.
/// An unparseable timestamp prints raw rather than vanishing.
pub fn ago(raw: Option<&str>) -> String {
    ago_from(raw, Utc::now())
}

fn ago_from(raw: Option<&str>, now: DateTime<Utc>) -> String {
    let Some(raw) = raw else {
        return "-".to_string();
    };
    let Some(then) = parse_time(raw) else {
        return raw.to_string();
    };

    match (now - then).num_seconds() {
        s if s < 0 => "just now".to_string(),
        s if s < 60 => format!("{s}s ago"),
        s if s < 3600 => format!("{}m ago", s / 60),
        s if s < 86_400 => format!("{}h ago", s / 3600),
        s if s < 86_400 * 30 => format!("{}d ago", s / 86_400),
        _ => then.format("%Y-%m-%d").to_string(),
    }
}

fn parse_time(raw: &str) -> Option<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(raw)
        .map(|t| t.with_timezone(&Utc))
        .ok()
}

// ── tables ───────────────────────────────────────────────────────────

/// A left-aligned table sized to its contents.
pub struct Table {
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
}

impl Table {
    pub fn new<I: IntoIterator<Item = S>, S: Into<String>>(headers: I) -> Self {
        Self {
            headers: headers.into_iter().map(Into::into).collect(),
            rows: Vec::new(),
        }
    }

    pub fn row<I: IntoIterator<Item = S>, S: Into<String>>(&mut self, cells: I) {
        self.rows.push(cells.into_iter().map(Into::into).collect());
    }

    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    pub fn render(&self) -> String {
        let cols = self.headers.len();
        let mut widths: Vec<usize> = self.headers.iter().map(|h| visible_len(h)).collect();
        for row in &self.rows {
            for (i, cell) in row.iter().enumerate().take(cols) {
                widths[i] = widths[i].max(visible_len(cell));
            }
        }

        let mut out = bold(&join_padded(&self.headers, &widths));
        for row in &self.rows {
            out.push('\n');
            out.push_str(&join_padded(row, &widths));
        }
        out
    }

    /// Prints the table, or `empty` (dimmed) when it has no rows.
    pub fn print_or(&self, empty: &str) {
        if self.is_empty() {
            note(empty);
        } else {
            println!("{}", self.render());
        }
    }
}

fn join_padded(cells: &[String], widths: &[usize]) -> String {
    let mut out = String::new();
    for (i, cell) in cells.iter().enumerate() {
        out.push_str(cell);
        if i + 1 < cells.len() {
            let pad = widths[i].saturating_sub(visible_len(cell)) + 2;
            out.push_str(&" ".repeat(pad));
        }
    }
    out.trim_end().to_string()
}

/// Characters, with ANSI escapes discounted, so a coloured cell pads to
/// the same width as a plain one.
fn visible_len(s: &str) -> usize {
    let mut len = 0;
    let mut in_escape = false;
    for c in s.chars() {
        if in_escape {
            in_escape = c != 'm';
        } else if c == '\x1b' {
            in_escape = true;
        } else {
            len += 1;
        }
    }
    len
}

pub fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let kept: String = s.chars().take(max.saturating_sub(1)).collect();
    format!("{}…", kept.trim_end())
}

/// `label    value` lines for a detail view.
pub fn field(label: &str, value: &str) {
    println!("{}  {value}", paint(&format!("{label:<11}"), Tone::Muted));
}

pub fn heading(text: &str) {
    println!("{}", bold(text));
}

pub fn note(text: &str) {
    println!("{}", paint(text, Tone::Muted));
}

pub fn print_json<T: Serialize>(value: &T) -> anyhow::Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tables_pad_to_the_widest_cell() {
        let mut t = Table::new(["SLUG", "NAME"]);
        t.row(["web", "Website"]);
        t.row(["mobile-app", "Mobile"]);
        // Headers are bold on a terminal; compare what's visible.
        let plain = t.render().replace("\x1b[1m", "").replace("\x1b[0m", "");
        assert_eq!(
            plain,
            "SLUG        NAME\nweb         Website\nmobile-app  Mobile"
        );
    }

    #[test]
    fn padding_ignores_ansi() {
        assert_eq!(visible_len("\x1b[32mok\x1b[0m"), 2);
        assert_eq!(
            join_padded(&["\x1b[31mab\x1b[0m".into(), "c".into()], &[4, 1]),
            "\x1b[31mab\x1b[0m    c"
        );
    }

    #[test]
    fn truncates_with_an_ellipsis() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello world", 8), "hello w…");
    }

    #[test]
    fn times_read_as_ages() {
        let now = DateTime::parse_from_rfc3339("2026-12-01T12:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        assert_eq!(ago_from(Some("2026-12-01T11:59:30Z"), now), "30s ago");
        assert_eq!(ago_from(Some("2026-12-01T09:00:00Z"), now), "3h ago");
        assert_eq!(ago_from(Some("2026-11-29T11:00:00.123456Z"), now), "2d ago");
        assert_eq!(ago_from(Some("2026-01-02T00:00:00Z"), now), "2026-01-02");
        assert_eq!(ago_from(None, now), "-");
        assert_eq!(ago_from(Some("yesterday"), now), "yesterday");
    }

    #[test]
    fn statuses_have_tones() {
        assert_eq!(status_tone("resolved"), Tone::Good);
        assert_eq!(status_tone("unresolved"), Tone::Bad);
        assert_eq!(status_tone("ignored"), Tone::Muted);
        assert_eq!(status_tone("pending"), Tone::Warn);
    }
}