use std::io::Write;
use anyhow::Result;
use serde_json::{Map, Value};
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Format {
Json,
Jsonl,
Csv,
Table,
}
#[derive(Clone, Debug, Default)]
pub struct Table {
pub columns: Vec<String>,
pub rows: Vec<Vec<Value>>,
}
impl Table {
pub fn new(columns: Vec<String>) -> Self {
Self {
columns,
rows: Vec::new(),
}
}
pub fn push(&mut self, row: Vec<Value>) {
self.rows.push(row);
}
pub fn objects(&self) -> Vec<Value> {
self.rows
.iter()
.map(|row| {
let mut object = Map::new();
for (column, value) in self.columns.iter().zip(row.iter()) {
object.insert(column.clone(), value.clone());
}
Value::Object(object)
})
.collect()
}
}
pub fn write_table(out: &mut impl Write, table: &Table, format: Format) -> Result<()> {
match format {
Format::Json => {
let objects = table.objects();
serde_json::to_writer_pretty(&mut *out, &objects)?;
writeln!(out)?;
}
Format::Jsonl => {
for object in table.objects() {
serde_json::to_writer(&mut *out, &object)?;
writeln!(out)?;
}
}
Format::Csv => {
writeln!(out, "{}", table.columns.join(","))?;
for row in &table.rows {
let cells: Vec<String> = row.iter().map(csv_cell).collect();
writeln!(out, "{}", cells.join(","))?;
}
}
Format::Table => {
write_aligned(out, table)?;
}
}
Ok(())
}
pub fn write_aligned(out: &mut impl Write, table: &Table) -> Result<()> {
let mut cells: Vec<Vec<String>> = Vec::with_capacity(table.rows.len());
for row in &table.rows {
cells.push(row.iter().map(display_cell).collect());
}
let widths: Vec<usize> = table
.columns
.iter()
.enumerate()
.map(|(i, column)| {
let longest = cells
.iter()
.filter_map(|row| row.get(i))
.map(|cell| cell.chars().count())
.max()
.unwrap_or(0);
column.chars().count().max(longest)
})
.collect();
let mut write_row = |row: &[String]| -> Result<()> {
let mut line = String::new();
for (i, cell) in row.iter().enumerate() {
if i > 0 {
line.push_str(" ");
}
let pad = widths[i].saturating_sub(cell.chars().count());
line.push_str(cell);
line.push_str(&" ".repeat(pad));
}
writeln!(out, "{}", line.trim_end())?;
Ok(())
};
write_row(&table.columns)?;
for row in &cells {
write_row(row)?;
}
Ok(())
}
pub fn display_cell(value: &Value) -> String {
match value {
Value::Null => "NULL".into(),
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
fn csv_cell(value: &Value) -> String {
match value {
Value::Null => String::new(),
Value::String(s) => {
if s.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.clone()
}
}
other => other.to_string(),
}
}