use std::io::IsTerminal;
pub fn color_enabled() -> bool {
std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none()
}
pub fn paint(text: &str, code: &str) -> String {
if color_enabled() {
format!("\x1b[{code}m{text}\x1b[0m")
} else {
text.to_string()
}
}
pub fn bold_cyan(text: &str) -> String {
paint(text, "1;36")
}
pub fn green(text: &str) -> String {
paint(text, "32")
}
pub fn yellow(text: &str) -> String {
paint(text, "33")
}
pub fn magenta(text: &str) -> String {
paint(text, "35")
}
pub fn dim(text: &str) -> String {
paint(text, "2")
}
#[derive(Debug, PartialEq, Eq)]
pub enum JsonLine {
Structural,
KeyValue(usize),
Plain,
}
pub fn classify_json_line(line: &str) -> JsonLine {
let trimmed = line.trim();
if !trimmed.is_empty() && trimmed.chars().all(|c| matches!(c, '{' | '}' | '[' | ']' | ',')) {
return JsonLine::Structural;
}
if line.trim_start().starts_with('"') {
if let Some(colon) = line.find(':') {
return JsonLine::KeyValue(colon + 1);
}
}
JsonLine::Plain
}
pub fn humanize_secs(secs: u64) -> String {
let days = secs / 86_400;
let hours = (secs % 86_400) / 3_600;
let mins = (secs % 3_600) / 60;
if days > 0 {
format!("{days}d{hours}h")
} else if hours > 0 {
format!("{hours}h{mins:02}m")
} else if mins > 0 {
format!("{mins}m")
} else {
format!("{secs}s")
}
}
pub fn table<R: AsRef<[String]>>(headers: &[&str], rows: &[R]) -> String {
let n = headers.len();
let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
for row in rows {
for (i, cell) in row.as_ref().iter().enumerate() {
widths[i] = widths[i].max(cell.len());
}
}
let header_row: Vec<String> = headers.iter().map(|h| h.to_string()).collect();
let mut out = String::new();
for row in std::iter::once(header_row.as_slice()).chain(rows.iter().map(AsRef::as_ref)) {
for (i, cell) in row.iter().enumerate() {
if i > 0 {
out.push_str(" ");
}
out.push_str(cell);
if i + 1 < n {
out.extend(std::iter::repeat(' ').take(widths[i] - cell.len()));
}
}
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classify_json_lines_by_kind() {
assert_eq!(classify_json_line(" \"Id\": \"abc\","), JsonLine::KeyValue(9));
assert_eq!(classify_json_line(" {"), JsonLine::Structural);
assert_eq!(classify_json_line("],"), JsonLine::Structural);
assert_eq!(classify_json_line(" \"abc\""), JsonLine::Plain);
assert_eq!(classify_json_line(""), JsonLine::Plain);
assert_eq!(classify_json_line("not json"), JsonLine::Plain);
}
#[test]
fn table_aligns_and_never_pads_last_column() {
let rows = vec![
["devsandbox-repo".to_string(), "node:22".to_string(), "Up 3 minutes".to_string()],
["devsandbox-x".to_string(), "alpine".to_string(), "running".to_string()],
];
assert_eq!(
table(&["NAME", "IMAGE", "STATUS"], &rows),
"NAME IMAGE STATUS\n\
devsandbox-repo node:22 Up 3 minutes\n\
devsandbox-x alpine running\n"
);
}
}