1 use std::collections::{HashMap, HashSet};
4 use std::iter::Iterator;
6 const HEADER: &str = "<!DOCTYPE html>
9 <meta charset=\"utf-8\">
10 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
12 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
13 th, td { white-space: nowrap; }
14 th { text-align: left; font-weight: normal; }
15 table { border-collapse: collapse }
16 tr.key > th { height: 8em; vertical-align: bottom; line-height: 1 }
17 tr.key > th > div { width: 1em; }
18 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
19 td { border: thin solid gray; }
20 td.numeric { text-align: right; }
21 td.yes { border: thin solid gray; background-color: gray; }
22 td.spacer { border: none; }
23 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
24 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
25 img { height: 1.2em; }
28 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } }
29 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } }
30 function h2(a, b) { highlight(a); highlight(b); }
31 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
38 const FOOTER: &str = " </tbody>
43 #[derive(Debug, PartialEq, Eq, Hash)]
46 instance: Option<String>,
48 impl From<&str> for Entry {
49 fn from(value: &str) -> Entry {
50 match value.split_once(':') {
52 col: String::from(value),
55 Some((col, instance)) => Entry {
56 col: String::from(col.trim()),
57 instance: Some(String::from(instance.trim())),
63 #[derive(Debug, PartialEq, Eq)]
69 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
70 input: std::iter::Enumerate<Input>,
71 row: Option<RowInput>,
73 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
74 fn new(input: Input) -> Self {
76 input: input.enumerate(),
81 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
82 type Item = Result<RowInput, std::io::Error>;
83 fn next(&mut self) -> Option<Self::Item> {
88 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
90 None => return Ok(std::mem::take(&mut self.row)).transpose(),
91 Some((_, Err(e))) => return Some(Err(e)),
92 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
93 return Ok(std::mem::take(&mut self.row)).transpose()
95 Some((_, Ok(line))) if line.is_empty() => {}
96 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
98 return Some(Err(std::io::Error::other(format!(
99 "{}: Entry with no header",
103 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
105 Some((_, Ok(line))) => {
106 let prev = std::mem::take(&mut self.row);
107 self.row = Some(RowInput {
112 return Ok(prev).transpose();
120 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
121 Reader::new(std::io::BufReader::new(input).lines())
124 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
125 let mut counts: Vec<_> = rows
131 .collect::<HashSet<_>>()
134 .fold(HashMap::new(), |mut cs, col| {
135 cs.entry(String::from(col))
136 .and_modify(|n| *n += 1)
141 .map(|(col, n)| (n, col))
146 fn column_order(rows: &[RowInput]) -> Vec<String> {
153 fn render_instance(entry: &Entry) -> String {
154 match &entry.instance {
155 None => String::from("✓ "),
156 Some(instance) => String::from(instance) + " ",
160 fn render_cell(col: &str, row: &RowInput) -> String {
161 // TODO: Escape HTML special characters
162 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
163 let class = if entries.is_empty() { "" } else { "yes" };
164 let all_empty = entries.iter().all(|e| e.instance.is_none());
165 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
167 } else if all_empty {
168 format!("{}", entries.len())
172 .map(|i| render_instance(i))
175 format!("<td class=\"{class}\">{}</td>", contents.trim())
178 fn render_row(columns: &[String], row: &RowInput) -> String {
179 // This is O(n^2) & doesn't need to be
180 // TODO: Escape HTML special characters
182 "<tr><th>{}</th>{}</tr>\n",
186 .map(|col| render_cell(col, row))
191 fn render_column_headers(columns: &[String]) -> String {
192 // TODO: Escape HTML special characters
193 String::from("<th></th>")
194 + &columns.iter().fold(String::new(), |mut acc, c| {
195 write!(&mut acc, "<th>{c}</th>").unwrap();
203 /// Will return `Err` if
204 /// * there's an i/o error while reading `input`
205 /// * the log has invalid syntax:
206 /// * an indented line with no preceding non-indented line
207 pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> {
208 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
209 let columns = column_order(&rows);
210 Ok(String::from(HEADER)
211 + &render_column_headers(&columns)
214 .map(|r| render_row(&columns, &r))
224 fn test_parse_entry() {
228 col: String::from("foo"),
233 Entry::from("foo:bar"),
235 col: String::from("foo"),
236 instance: Some(String::from("bar"))
240 Entry::from("foo: bar"),
242 col: String::from("foo"),
243 instance: Some(String::from("bar"))
249 fn test_read_rows() {
251 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
253 label: String::from("foo"),
258 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
260 label: String::from("bar"),
265 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
268 label: String::from("foo"),
272 label: String::from("bar"),
278 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
280 label: String::from("foo"),
281 entries: vec![Entry::from("bar")]
285 read_rows(&b"foo\n bar\n baz\n"[..])
287 .collect::<Vec<_>>(),
289 label: String::from("foo"),
290 entries: vec![Entry::from("bar"), Entry::from("baz")]
294 read_rows(&b"foo\n\nbar\n"[..])
296 .collect::<Vec<_>>(),
299 label: String::from("foo"),
303 label: String::from("bar"),
309 read_rows(&b"foo\n \nbar\n"[..])
311 .collect::<Vec<_>>(),
314 label: String::from("foo"),
318 label: String::from("bar"),
324 read_rows(&b"foo \n bar \n"[..])
326 .collect::<Vec<_>>(),
328 label: String::from("foo"),
329 entries: vec![Entry::from("bar")]
333 let bad = read_rows(&b" foo"[..]).next().unwrap();
334 assert!(bad.is_err());
335 assert!(format!("{bad:?}").contains("1: Entry with no header"));
337 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
338 assert!(bad2.is_err());
339 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
343 fn test_column_counts() {
346 &read_rows(&b"foo\n bar\n baz\n"[..])
347 .collect::<Result<Vec<_>, _>>()
350 vec![(1, String::from("bar")), (1, String::from("baz"))]
354 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
355 .collect::<Result<Vec<_>, _>>()
358 vec![(1, String::from("bar")), (2, String::from("baz"))]
362 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
363 .collect::<Result<Vec<_>, _>>()
366 vec![(1, String::from("bar")), (2, String::from("baz"))]
370 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
371 .collect::<Result<Vec<_>, _>>()
374 vec![(1, String::from("bar")), (2, String::from("baz"))]
379 fn test_render_cell() {
384 label: String::from("nope"),
388 String::from("<td class=\"\"></td>")
394 label: String::from("nope"),
395 entries: vec![Entry::from("bar")]
398 String::from("<td class=\"\"></td>")
404 label: String::from("nope"),
405 entries: vec![Entry::from("foo")]
408 String::from("<td class=\"yes\"></td>")
414 label: String::from("nope"),
415 entries: vec![Entry::from("foo"), Entry::from("foo")]
418 String::from("<td class=\"yes\">2</td>")
424 label: String::from("nope"),
425 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
428 String::from("<td class=\"yes\">5 10</td>")
434 label: String::from("nope"),
435 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
438 String::from("<td class=\"yes\">5 ✓</td>")