1use std::io::Write;
4
5use anyhow::Result;
6use serde_json::{Map, Value};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
10pub enum Format {
11 Json,
13 Jsonl,
15 Csv,
17 Table,
19}
20
21#[derive(Clone, Debug, Default)]
23pub struct Table {
24 pub columns: Vec<String>,
25 pub rows: Vec<Vec<Value>>,
26}
27
28impl Table {
29 pub fn new(columns: Vec<String>) -> Self {
30 Self {
31 columns,
32 rows: Vec::new(),
33 }
34 }
35
36 pub fn push(&mut self, row: Vec<Value>) {
37 self.rows.push(row);
38 }
39
40 pub fn objects(&self) -> Vec<Value> {
42 self.rows
43 .iter()
44 .map(|row| {
45 let mut object = Map::new();
46 for (column, value) in self.columns.iter().zip(row.iter()) {
47 object.insert(column.clone(), value.clone());
48 }
49 Value::Object(object)
50 })
51 .collect()
52 }
53}
54
55pub fn write_table(out: &mut impl Write, table: &Table, format: Format) -> Result<()> {
57 match format {
58 Format::Json => {
59 let objects = table.objects();
60 serde_json::to_writer_pretty(&mut *out, &objects)?;
61 writeln!(out)?;
62 }
63 Format::Jsonl => {
64 for object in table.objects() {
65 serde_json::to_writer(&mut *out, &object)?;
66 writeln!(out)?;
67 }
68 }
69 Format::Csv => {
70 writeln!(out, "{}", table.columns.join(","))?;
71 for row in &table.rows {
72 let cells: Vec<String> = row.iter().map(csv_cell).collect();
73 writeln!(out, "{}", cells.join(","))?;
74 }
75 }
76 Format::Table => {
77 write_aligned(out, table)?;
78 }
79 }
80 Ok(())
81}
82
83pub fn write_aligned(out: &mut impl Write, table: &Table) -> Result<()> {
85 let mut cells: Vec<Vec<String>> = Vec::with_capacity(table.rows.len());
86 for row in &table.rows {
87 cells.push(row.iter().map(display_cell).collect());
88 }
89 let widths: Vec<usize> = table
90 .columns
91 .iter()
92 .enumerate()
93 .map(|(i, column)| {
94 let longest = cells
95 .iter()
96 .filter_map(|row| row.get(i))
97 .map(|cell| cell.chars().count())
98 .max()
99 .unwrap_or(0);
100 column.chars().count().max(longest)
101 })
102 .collect();
103
104 let mut write_row = |row: &[String]| -> Result<()> {
105 let mut line = String::new();
106 for (i, cell) in row.iter().enumerate() {
107 if i > 0 {
108 line.push_str(" ");
109 }
110 let pad = widths[i].saturating_sub(cell.chars().count());
111 line.push_str(cell);
112 line.push_str(&" ".repeat(pad));
113 }
114 writeln!(out, "{}", line.trim_end())?;
115 Ok(())
116 };
117
118 write_row(&table.columns)?;
119 for row in &cells {
120 write_row(row)?;
121 }
122 Ok(())
123}
124
125pub fn display_cell(value: &Value) -> String {
127 match value {
128 Value::Null => "NULL".into(),
129 Value::String(s) => s.clone(),
130 other => other.to_string(),
131 }
132}
133
134fn csv_cell(value: &Value) -> String {
136 match value {
137 Value::Null => String::new(),
138 Value::String(s) => {
139 if s.contains([',', '"', '\n', '\r']) {
140 format!("\"{}\"", s.replace('"', "\"\""))
141 } else {
142 s.clone()
143 }
144 }
145 other => other.to_string(),
146 }
147}