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 table<const N: usize>(headers: &[&str; N], rows: &[[String; N]]) -> String {
let mut widths = headers.map(str::len);
for row in rows {
for (i, cell) in row.iter().enumerate() {
widths[i] = widths[i].max(cell.len());
}
}
let header_row: [String; N] = headers.map(str::to_string);
let mut out = String::new();
for row in std::iter::once(&header_row).chain(rows) {
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"
);
}
}