goat_cli/
output.rs

1//! Output formats (`--format tsv|csv|json`) and a small table type that the
2//! CLI builds itself (e.g. for `count`, `lookup`, `record` and reports) and
3//! can write in any format.
4
5use std::io::Write;
6
7use serde_json::{Map, Value};
8
9use crate::error::Result;
10
11/// The output format, chosen with `--format`.
12//
13// No doc comments on the variants: clap would show them as help for each
14// value, which switches every command's `--help` to its long layout.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
16pub enum Format {
17    // Tab separated values.
18    #[default]
19    Tsv,
20    // Comma separated values.
21    Csv,
22    // JSON.
23    Json,
24}
25
26impl Format {
27    /// The `Accept` header to request this format from GoaT's `/search`.
28    pub fn accept(self) -> &'static str {
29        match self {
30            Format::Tsv => "text/tab-separated-values",
31            Format::Csv => "text/csv",
32            Format::Json => "application/json",
33        }
34    }
35}
36
37/// A table of values, written as TSV, CSV, or a JSON array of objects.
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Table {
40    /// The column names.
41    pub header: Vec<String>,
42    /// The rows; each has one cell per column.
43    pub rows: Vec<Vec<Value>>,
44}
45
46impl Table {
47    /// A table with the given column names and no rows.
48    pub fn new(header: &[&str]) -> Self {
49        Self {
50            header: header.iter().map(|h| h.to_string()).collect(),
51            rows: Vec::new(),
52        }
53    }
54
55    /// Add a row. Panics if it has the wrong number of cells, which is a
56    /// programming error.
57    pub fn push(&mut self, row: Vec<Value>) {
58        assert_eq!(row.len(), self.header.len(), "row length must match header");
59        self.rows.push(row);
60    }
61
62    /// Write the table to `out` in `format`.
63    pub fn write(&self, format: Format, out: &mut impl Write) -> Result<()> {
64        match format {
65            Format::Tsv | Format::Csv => {
66                let line = |cells: Vec<String>| -> String {
67                    match format {
68                        Format::Csv => cells.iter().map(|c| csv_escape(c)).collect::<Vec<_>>().join(","),
69                        _ => cells.iter().map(|c| tsv_escape(c)).collect::<Vec<_>>().join("\t"),
70                    }
71                };
72                writeln!(out, "{}", line(self.header.clone()))?;
73                for row in &self.rows {
74                    writeln!(out, "{}", line(row.iter().map(cell_text).collect()))?;
75                }
76            }
77            Format::Json => {
78                let objects = self
79                    .rows
80                    .iter()
81                    .map(|row| {
82                        Value::Object(
83                            self.header.iter().cloned().zip(row.iter().cloned()).collect::<Map<_, _>>(),
84                        )
85                    })
86                    .collect::<Vec<_>>();
87                writeln!(out, "{}", serde_json::to_string_pretty(&Value::Array(objects))?)?;
88            }
89        }
90        Ok(())
91    }
92
93    /// Write the table to stdout.
94    pub fn print(&self, format: Format) -> Result<()> {
95        let mut out = std::io::BufWriter::new(std::io::stdout().lock());
96        self.write(format, &mut out)?;
97        out.flush()?;
98        Ok(())
99    }
100}
101
102/// How a cell is shown in TSV/CSV: strings as is, lists joined with `;`
103/// (as GoaT does), and null as empty.
104pub fn cell_text(value: &Value) -> String {
105    match value {
106        Value::Null => String::new(),
107        Value::String(s) => s.clone(),
108        Value::Array(values) => values.iter().map(cell_text).collect::<Vec<_>>().join(";"),
109        other => other.to_string(),
110    }
111}
112
113/// TSV has no quoting, so tabs and newlines in a value become spaces.
114fn tsv_escape(text: &str) -> String {
115    text.replace(['\t', '\n', '\r'], " ")
116}
117
118/// Quote a CSV field if needed (RFC 4180).
119fn csv_escape(text: &str) -> String {
120    if text.contains([',', '"', '\n', '\r']) {
121        format!("\"{}\"", text.replace('"', "\"\""))
122    } else {
123        text.to_string()
124    }
125}
126
127/// Format milliseconds since the Unix epoch (as GoaT uses for dates in
128/// reports) as `yyyy-mm-dd`.
129pub fn epoch_millis_to_date(millis: i64) -> String {
130    // days since 1970-01-01, then Howard Hinnant's civil_from_days
131    let z = millis.div_euclid(86_400_000) + 719_468;
132    let era = z.div_euclid(146_097);
133    let doe = z - era * 146_097;
134    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
135    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
136    let mp = (5 * doy + 2) / 153;
137    let day = doy - (153 * mp + 2) / 5 + 1;
138    let month = if mp < 10 { mp + 3 } else { mp - 9 };
139    let year = yoe + era * 400 + i64::from(month <= 2);
140    format!("{:04}-{:02}-{:02}", year, month, day)
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use serde_json::json;
147
148    fn sample() -> Table {
149        let mut table = Table::new(&["name", "count", "tags"]);
150        table.push(vec![json!("Homo sapiens"), json!(3), json!(["a", "b"])]);
151        table.push(vec![json!("comma, \"quote\""), Value::Null, json!([])]);
152        table
153    }
154
155    fn render(table: &Table, format: Format) -> String {
156        let mut out = Vec::new();
157        table.write(format, &mut out).unwrap();
158        String::from_utf8(out).unwrap()
159    }
160
161    #[test]
162    fn test_tsv() {
163        assert_eq!(
164            render(&sample(), Format::Tsv),
165            "name\tcount\ttags\nHomo sapiens\t3\ta;b\ncomma, \"quote\"\t\t\n"
166        );
167    }
168
169    #[test]
170    fn test_csv_quotes_when_needed() {
171        assert_eq!(
172            render(&sample(), Format::Csv),
173            "name,count,tags\nHomo sapiens,3,a;b\n\"comma, \"\"quote\"\"\",,\n"
174        );
175    }
176
177    #[test]
178    fn test_json_objects_keep_types() {
179        let parsed: Value = serde_json::from_str(&render(&sample(), Format::Json)).unwrap();
180        assert_eq!(parsed[0], json!({"name": "Homo sapiens", "count": 3, "tags": ["a", "b"]}));
181        assert_eq!(parsed[1]["count"], Value::Null);
182    }
183
184    #[test]
185    fn test_tsv_replaces_tabs_and_newlines() {
186        let mut table = Table::new(&["x"]);
187        table.push(vec![json!("a\tb\nc")]);
188        assert_eq!(render(&table, Format::Tsv), "x\na b c\n");
189    }
190
191    #[test]
192    fn test_epoch_millis_to_date() {
193        assert_eq!(epoch_millis_to_date(0), "1970-01-01");
194        assert_eq!(epoch_millis_to_date(1_293_840_000_000), "2011-01-01");
195        assert_eq!(epoch_millis_to_date(951_782_400_000), "2000-02-29");
196        assert_eq!(epoch_millis_to_date(-86_400_000), "1969-12-31");
197    }
198}