use std::collections::HashSet;
use std::fmt::Write as _;
use std::io::IsTerminal;
use coip_format::Value;
use unicode_width::UnicodeWidthStr;
const ANSI_BOLD_GREEN: &str = "\x1b[1;32m";
const ANSI_LIGHT_CYAN: &str = "\x1b[96m";
const ANSI_BLUE: &str = "\x1b[34m";
const ANSI_RESET: &str = "\x1b[0m";
#[derive(Debug, Clone, Copy, Default)]
pub struct TableOptions {
pub color: bool,
}
impl TableOptions {
pub fn auto() -> Self {
let no_color = std::env::var_os("NO_COLOR")
.map(|v| !v.is_empty())
.unwrap_or(false);
let force = std::env::var_os("CLICOLOR_FORCE")
.map(|v| !v.is_empty() && v != "0")
.unwrap_or(false);
let dumb_term = std::env::var_os("TERM")
.map(|v| v == "dumb")
.unwrap_or(false);
let color = if no_color {
false
} else if force {
true
} else {
!dumb_term && std::io::stdout().is_terminal()
};
Self { color }
}
#[cfg(test)]
pub fn plain() -> Self {
Self { color: false }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Align {
Left,
Right,
Center,
}
#[derive(Debug, Clone)]
struct StyledLine {
text: String,
width: usize,
}
#[derive(Debug, Clone)]
struct CellBlock {
lines: Vec<StyledLine>,
max_width: usize,
align: Align,
is_table: bool,
}
impl CellBlock {
fn from_lines(lines: Vec<StyledLine>, align: Align, is_table: bool) -> Self {
let max_width = lines.iter().map(|l| l.width).max().unwrap_or(0);
Self {
lines,
max_width,
align,
is_table,
}
}
fn single(text: &str, style: Option<&str>, align: Align) -> Self {
let lines = text_to_styled_lines(text, style);
Self::from_lines(lines, align, false)
}
fn empty() -> Self {
Self {
lines: vec![StyledLine {
text: String::new(),
width: 0,
}],
max_width: 0,
align: Align::Left,
is_table: false,
}
}
}
pub fn render_value(val: &Value, opts: TableOptions) -> String {
let block = match val {
Value::Null => render_single_box("null", None),
Value::Map(m) if m.is_empty() => render_single_box("empty record", None),
Value::Map(m) => render_record_entries(m.iter().map(|(k, v)| (k.as_str(), v)), opts),
Value::Array(a) if a.is_empty() => render_single_box("empty list", None),
Value::Array(a) => render_array(a, opts),
other => {
let cell = render_cell(other, opts, false);
render_grid(None, vec![vec![cell]], 1)
}
};
join_block(&block)
}
pub fn render_entries(entries: &[(String, Value)], opts: TableOptions) -> String {
let block = if entries.is_empty() {
render_single_box("empty record", None)
} else {
render_record_entries(entries.iter().map(|(k, v)| (k.as_str(), v)), opts)
};
join_block(&block)
}
fn join_block(block: &CellBlock) -> String {
let mut out = String::new();
for (i, line) in block.lines.iter().enumerate() {
if i > 0 {
out.push('\n');
}
out.push_str(&line.text);
}
out
}
fn render_single_box(text: &str, style: Option<&str>) -> CellBlock {
render_grid(
None,
vec![vec![CellBlock::single(text, style, Align::Left)]],
1,
)
}
fn render_record_entries<'a>(
entries: impl IntoIterator<Item = (&'a str, &'a Value)>,
opts: TableOptions,
) -> CellBlock {
let key_style = opts.color.then_some(ANSI_BOLD_GREEN);
let mut rows = Vec::new();
for (key, val) in entries {
let val_cell = render_cell(val, opts, false);
let mut key_lines = text_to_styled_lines(key, key_style);
if val_cell.is_table {
key_lines.insert(
0,
StyledLine {
text: String::new(),
width: 0,
},
);
}
let key_cell = CellBlock::from_lines(key_lines, Align::Left, false);
rows.push(vec![key_cell, val_cell]);
}
render_grid(None, rows, 2)
}
fn render_array(items: &[Value], opts: TableOptions) -> CellBlock {
let header_style = opts.color.then_some(ANSI_BOLD_GREEN);
if items.iter().all(|v| matches!(v, Value::Map(_))) {
let mut columns: Vec<&str> = Vec::new();
let mut seen: HashSet<&str> = HashSet::new();
for item in items {
if let Value::Map(m) = item {
for k in m.keys() {
if seen.insert(k.as_str()) {
columns.push(k.as_str());
}
}
}
}
if !columns.is_empty() {
let missing_style = opts.color.then_some(ANSI_BLUE);
let mut headers = Vec::with_capacity(columns.len() + 1);
headers.push(CellBlock::single("#", header_style, Align::Center));
for &col in &columns {
headers.push(CellBlock::single(col, header_style, Align::Center));
}
let mut rows = Vec::with_capacity(items.len());
for (idx, item) in items.iter().enumerate() {
let mut row = Vec::with_capacity(columns.len() + 1);
row.push(CellBlock::single(
&idx.to_string(),
header_style,
Align::Right,
));
if let Value::Map(m) = item {
for &col in &columns {
match m.get(col) {
Some(v) => row.push(render_cell(v, opts, true)),
None => row.push(CellBlock::single("❎", missing_style, Align::Center)),
}
}
}
rows.push(row);
}
return render_grid(Some(headers), rows, columns.len() + 1);
}
}
let mut rows = Vec::with_capacity(items.len());
for (idx, item) in items.iter().enumerate() {
let idx_cell = CellBlock::single(&idx.to_string(), header_style, Align::Right);
let val_cell = render_cell(item, opts, true);
rows.push(vec![idx_cell, val_cell]);
}
render_grid(None, rows, 2)
}
fn render_cell(val: &Value, opts: TableOptions, align_numbers_right: bool) -> CellBlock {
let num_align = if align_numbers_right {
Align::Right
} else {
Align::Left
};
match val {
Value::Null => CellBlock::empty(),
Value::Bool(b) => {
let style = opts.color.then_some(ANSI_LIGHT_CYAN);
CellBlock::single(if *b { "true" } else { "false" }, style, Align::Left)
}
Value::U8(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::U16(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::U32(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::U64(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::U128(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::I32(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::I64(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::F32(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::F64(n) => CellBlock::single(&n.to_string(), None, num_align),
Value::Utf8(s) => CellBlock::single(s, None, Align::Left),
Value::Bytes(bytes) => CellBlock::single(&format_bytes_hex(bytes), None, Align::Left),
Value::Array(a) if a.is_empty() => CellBlock::single("[list 0 items]", None, Align::Left),
Value::Array(a) => render_array(a, opts),
Value::Map(m) if m.is_empty() => CellBlock::single("{record 0 fields}", None, Align::Left),
Value::Map(m) => render_record_entries(m.iter().map(|(k, v)| (k.as_str(), v)), opts),
}
}
fn format_bytes_hex(bytes: &[u8]) -> String {
if bytes.is_empty() {
return String::from("0x[]");
}
let mut out = String::with_capacity(bytes.len() * 3 + 3);
out.push_str("0x[");
for (i, b) in bytes.iter().enumerate() {
if i > 0 {
out.push(' ');
}
let _ = write!(out, "{b:02x}");
}
out.push(']');
out
}
fn text_to_styled_lines(text: &str, style: Option<&str>) -> Vec<StyledLine> {
text.split('\n')
.map(|raw| {
let clean = sanitize_line(raw);
let width = UnicodeWidthStr::width(clean.as_str());
let styled = match style {
Some(code) if !clean.is_empty() => format!("{code}{clean}{ANSI_RESET}"),
_ => clean,
};
StyledLine {
text: styled,
width,
}
})
.collect()
}
fn sanitize_line(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'\t' => out.push_str(" "),
'\r' => {}
c if c.is_control() => {
let _ = write!(out, "\\u{{{:04x}}}", c as u32);
}
c => out.push(c),
}
}
out
}
fn render_grid(
headers: Option<Vec<CellBlock>>,
rows: Vec<Vec<CellBlock>>,
num_cols: usize,
) -> CellBlock {
debug_assert!(num_cols > 0);
let mut col_widths = vec![0usize; num_cols];
if let Some(ref hdrs) = headers {
for (c, cell) in hdrs.iter().enumerate() {
col_widths[c] = col_widths[c].max(cell.max_width);
}
}
for row in &rows {
for (c, cell) in row.iter().enumerate() {
col_widths[c] = col_widths[c].max(cell.max_width);
}
}
let total_width: usize = 1 + col_widths.iter().map(|&w| w + 3).sum::<usize>();
let mut out_lines = Vec::new();
out_lines.push(border_line('╭', '┬', '╮', &col_widths, total_width));
if let Some(ref hdrs) = headers {
push_row_lines(&mut out_lines, hdrs, &col_widths, total_width);
out_lines.push(border_line('├', '┼', '┤', &col_widths, total_width));
}
for row in &rows {
push_row_lines(&mut out_lines, row, &col_widths, total_width);
}
out_lines.push(border_line('╰', '┴', '╯', &col_widths, total_width));
CellBlock::from_lines(out_lines, Align::Left, true)
}
fn border_line(
left: char,
mid: char,
right: char,
col_widths: &[usize],
total_width: usize,
) -> StyledLine {
let mut s = String::with_capacity(total_width * 3);
s.push(left);
for (i, &w) in col_widths.iter().enumerate() {
if i > 0 {
s.push(mid);
}
for _ in 0..(w + 2) {
s.push('─');
}
}
s.push(right);
StyledLine {
text: s,
width: total_width,
}
}
fn push_row_lines(
out: &mut Vec<StyledLine>,
row: &[CellBlock],
col_widths: &[usize],
total_width: usize,
) {
let height = row.iter().map(|c| c.lines.len()).max().unwrap_or(1).max(1);
for line_idx in 0..height {
let mut s = String::with_capacity(total_width + 16);
s.push('│');
for (c, &col_w) in col_widths.iter().enumerate() {
s.push(' ');
if let Some(cell) = row.get(c)
&& let Some(line) = cell.lines.get(line_idx)
{
let pad = col_w.saturating_sub(line.width);
match cell.align {
Align::Left => {
s.push_str(&line.text);
push_spaces(&mut s, pad);
}
Align::Right => {
push_spaces(&mut s, pad);
s.push_str(&line.text);
}
Align::Center => {
let left_pad = pad / 2;
let right_pad = pad - left_pad;
push_spaces(&mut s, left_pad);
s.push_str(&line.text);
push_spaces(&mut s, right_pad);
}
}
} else {
push_spaces(&mut s, col_w);
}
s.push(' ');
s.push('│');
}
out.push(StyledLine {
text: s,
width: total_width,
});
}
}
fn push_spaces(out: &mut String, count: usize) {
for _ in 0..count {
out.push(' ');
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
fn map(pairs: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
let mut m = BTreeMap::new();
for (k, v) in pairs {
m.insert(k.to_owned(), v);
}
Value::Map(m)
}
#[test]
fn test_nested_record_with_cjk_matches_nushell() {
let rec = map([
(
"country",
map([
("geoname_id", Value::U32(6252001)),
("is_in_european_union", Value::Bool(false)),
("iso_code", Value::Utf8("US".into())),
(
"names",
map([
("de", Value::Utf8("USA".into())),
("en", Value::Utf8("United States".into())),
("ja", Value::Utf8("アメリカ合衆国".into())),
("zh-CN", Value::Utf8("美国".into())),
]),
),
]),
),
(
"location",
map([
("accuracy_radius", Value::U16(1000)),
("latitude", Value::F64(37.7510123)),
("longitude", Value::F64(-97.8220456)),
("time_zone", Value::Utf8("America/Chicago".into())),
]),
),
("traits", map([("is_anycast", Value::Bool(false))])),
]);
let expected = "\
╭──────────┬───────────────────────────────────────────────────────╮
│ │ ╭──────────────────────┬────────────────────────────╮ │
│ country │ │ geoname_id │ 6252001 │ │
│ │ │ is_in_european_union │ false │ │
│ │ │ iso_code │ US │ │
│ │ │ │ ╭───────┬────────────────╮ │ │
│ │ │ names │ │ de │ USA │ │ │
│ │ │ │ │ en │ United States │ │ │
│ │ │ │ │ ja │ アメリカ合衆国 │ │ │
│ │ │ │ │ zh-CN │ 美国 │ │ │
│ │ │ │ ╰───────┴────────────────╯ │ │
│ │ ╰──────────────────────┴────────────────────────────╯ │
│ │ ╭─────────────────┬─────────────────╮ │
│ location │ │ accuracy_radius │ 1000 │ │
│ │ │ latitude │ 37.7510123 │ │
│ │ │ longitude │ -97.8220456 │ │
│ │ │ time_zone │ America/Chicago │ │
│ │ ╰─────────────────┴─────────────────╯ │
│ │ ╭────────────┬───────╮ │
│ traits │ │ is_anycast │ false │ │
│ │ ╰────────────┴───────╯ │
╰──────────┴───────────────────────────────────────────────────────╯";
assert_eq!(render_value(&rec, TableOptions::plain()), expected);
}
#[test]
fn test_array_of_records_and_scalars_and_empty() {
let rec = map([
(
"subdivisions",
Value::Array(vec![
map([
("iso_code", Value::Utf8("CA".into())),
(
"names",
map([
("en", Value::Utf8("California".into())),
("zh-CN", Value::Utf8("加利福尼亚".into())),
]),
),
]),
map([
("iso_code", Value::Utf8("SF".into())),
("names", map([("en", Value::Utf8("San Francisco".into()))])),
]),
]),
),
(
"tags",
Value::Array(vec![
Value::Utf8("cdn".into()),
Value::Utf8("anycast".into()),
]),
),
("empty_arr", Value::Array(vec![])),
("empty_obj", Value::Map(BTreeMap::new())),
("nothing", Value::Null),
]);
let expected = "\
╭──────────────┬───────────────────────────────────────────╮
│ empty_arr │ [list 0 items] │
│ empty_obj │ {record 0 fields} │
│ nothing │ │
│ │ ╭───┬──────────┬────────────────────────╮ │
│ subdivisions │ │ # │ iso_code │ names │ │
│ │ ├───┼──────────┼────────────────────────┤ │
│ │ │ 0 │ CA │ ╭───────┬────────────╮ │ │
│ │ │ │ │ │ en │ California │ │ │
│ │ │ │ │ │ zh-CN │ 加利福尼亚 │ │ │
│ │ │ │ │ ╰───────┴────────────╯ │ │
│ │ │ 1 │ SF │ ╭────┬───────────────╮ │ │
│ │ │ │ │ │ en │ San Francisco │ │ │
│ │ │ │ │ ╰────┴───────────────╯ │ │
│ │ ╰───┴──────────┴────────────────────────╯ │
│ │ ╭───┬─────────╮ │
│ tags │ │ 0 │ cdn │ │
│ │ │ 1 │ anycast │ │
│ │ ╰───┴─────────╯ │
╰──────────────┴───────────────────────────────────────────╯";
assert_eq!(render_value(&rec, TableOptions::plain()), expected);
}
#[test]
fn test_sparse_table_missing_cells_and_alignment() {
let arr = Value::Array(vec![
map([("a", Value::U32(1)), ("b", Value::Utf8("x".into()))]),
Value::Map(BTreeMap::new()),
map([("a", Value::U32(2)), ("c", Value::Bool(true))]),
]);
let expected = "\
╭───┬────┬────┬──────╮
│ # │ a │ b │ c │
├───┼────┼────┼──────┤
│ 0 │ 1 │ x │ ❎ │
│ 1 │ ❎ │ ❎ │ ❎ │
│ 2 │ 2 │ ❎ │ true │
╰───┴────┴────┴──────╯";
assert_eq!(render_value(&arr, TableOptions::plain()), expected);
}
#[test]
fn test_root_null_and_empty_containers() {
assert_eq!(
render_value(&Value::Null, TableOptions::plain()),
"╭──────╮\n│ null │\n╰──────╯"
);
assert_eq!(
render_value(&Value::Map(BTreeMap::new()), TableOptions::plain()),
"╭──────────────╮\n│ empty record │\n╰──────────────╯"
);
assert_eq!(
render_value(&Value::Array(vec![]), TableOptions::plain()),
"╭────────────╮\n│ empty list │\n╰────────────╯"
);
}
#[test]
fn test_multiline_string_and_bytes() {
let rec = map([
("bin", Value::Bytes(vec![0xde, 0xad, 0xbe, 0xef])),
("note", Value::Utf8("line1\nline2".into())),
]);
let expected = "\
╭──────┬─────────────────╮
│ bin │ 0x[de ad be ef] │
│ note │ line1 │
│ │ line2 │
╰──────┴─────────────────╯";
assert_eq!(render_value(&rec, TableOptions::plain()), expected);
}
#[test]
fn test_ansi_color_preserves_alignment() {
let rec = map([
("flag", Value::Bool(true)),
("name", Value::Utf8("US".into())),
]);
let colored = render_value(&rec, TableOptions { color: true });
assert!(colored.contains(ANSI_BOLD_GREEN));
assert!(colored.contains(ANSI_LIGHT_CYAN));
let stripped = strip_ansi(&colored);
assert_eq!(stripped, render_value(&rec, TableOptions::plain()));
}
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\x1b' {
for next in chars.by_ref() {
if next == 'm' {
break;
}
}
} else {
out.push(c);
}
}
out
}
}