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.yes { border: thin solid gray; background-color: #ddd; }
21 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
22 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
25 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } }
26 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } }
27 function h2(a, b) { highlight(a); highlight(b); }
28 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
35 const FOOTER: &str = " </tbody>
40 #[derive(Debug, PartialEq, Eq, Hash)]
43 instance: Option<String>,
45 impl From<&str> for Entry {
46 fn from(value: &str) -> Entry {
47 match value.split_once(':') {
49 col: String::from(value),
52 Some((col, instance)) => Entry {
53 col: String::from(col.trim()),
54 instance: Some(String::from(instance.trim())),
60 #[derive(Debug, PartialEq, Eq)]
66 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
67 input: std::iter::Enumerate<Input>,
68 row: Option<RowInput>,
70 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
71 fn new(input: Input) -> Self {
73 input: input.enumerate(),
78 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
79 type Item = Result<RowInput, std::io::Error>;
80 fn next(&mut self) -> Option<Self::Item> {
85 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
87 None => return Ok(std::mem::take(&mut self.row)).transpose(),
88 Some((_, Err(e))) => return Some(Err(e)),
89 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
90 return Ok(std::mem::take(&mut self.row)).transpose()
92 Some((_, Ok(line))) if line.is_empty() => {}
93 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
95 return Some(Err(std::io::Error::other(format!(
96 "{}: Entry with no header",
100 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
102 Some((_, Ok(line))) => {
103 let prev = std::mem::take(&mut self.row);
104 self.row = Some(RowInput {
109 return Ok(prev).transpose();
117 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
118 Reader::new(std::io::BufReader::new(input).lines())
121 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
122 let mut counts: Vec<_> = rows
128 .collect::<HashSet<_>>()
131 .fold(HashMap::new(), |mut cs, col| {
132 cs.entry(String::from(col))
133 .and_modify(|n| *n += 1)
138 .map(|(col, n)| (n, col))
143 fn column_order(rows: &[RowInput]) -> Vec<String> {
150 fn render_instance(entry: &Entry) -> String {
151 match &entry.instance {
152 None => String::from("✓ "),
153 Some(instance) => String::from(instance) + " ",
157 fn render_cell(col: &str, row: &RowInput) -> String {
158 // TODO: Escape HTML special characters
159 let row_label = &row.label;
160 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
161 let class = if entries.is_empty() { "" } else { "yes" };
162 let all_empty = entries.iter().all(|e| e.instance.is_none());
163 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
165 } else if all_empty {
166 format!("{}", entries.len())
170 .map(|i| render_instance(i))
173 format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col}')\" onmouseout=\"ch2('{row_label}','{col}')\">{}</td>", contents.trim())
176 fn render_row(columns: &[String], row: &RowInput) -> String {
177 // This is O(n^2) & doesn't need to be
178 // TODO: Escape HTML special characters
179 let row_label = &row.label;
181 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
184 .map(|col| render_cell(col, row))
189 fn render_column_headers(columns: &[String]) -> String {
190 // TODO: Escape HTML special characters
191 String::from("<tr class=\"key\"><th></th>")
192 + &columns.iter().fold(String::new(), |mut acc, c| {
193 write!(&mut acc, "<th id=\"{c}\"><div><div>{c}</div></div></th>").unwrap();
201 /// Will return `Err` if
202 /// * there's an i/o error while reading `input`
203 /// * the log has invalid syntax:
204 /// * an indented line with no preceding non-indented line
205 pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> {
206 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
207 let columns = column_order(&rows);
208 Ok(String::from(HEADER)
209 + &render_column_headers(&columns)
212 .map(|r| render_row(&columns, &r))
222 fn test_parse_entry() {
226 col: String::from("foo"),
231 Entry::from("foo:bar"),
233 col: String::from("foo"),
234 instance: Some(String::from("bar"))
238 Entry::from("foo: bar"),
240 col: String::from("foo"),
241 instance: Some(String::from("bar"))
247 fn test_read_rows() {
249 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
251 label: String::from("foo"),
256 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
258 label: String::from("bar"),
263 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
266 label: String::from("foo"),
270 label: String::from("bar"),
276 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
278 label: String::from("foo"),
279 entries: vec![Entry::from("bar")]
283 read_rows(&b"foo\n bar\n baz\n"[..])
285 .collect::<Vec<_>>(),
287 label: String::from("foo"),
288 entries: vec![Entry::from("bar"), Entry::from("baz")]
292 read_rows(&b"foo\n\nbar\n"[..])
294 .collect::<Vec<_>>(),
297 label: String::from("foo"),
301 label: String::from("bar"),
307 read_rows(&b"foo\n \nbar\n"[..])
309 .collect::<Vec<_>>(),
312 label: String::from("foo"),
316 label: String::from("bar"),
322 read_rows(&b"foo \n bar \n"[..])
324 .collect::<Vec<_>>(),
326 label: String::from("foo"),
327 entries: vec![Entry::from("bar")]
331 let bad = read_rows(&b" foo"[..]).next().unwrap();
332 assert!(bad.is_err());
333 assert!(format!("{bad:?}").contains("1: Entry with no header"));
335 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
336 assert!(bad2.is_err());
337 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
341 fn test_column_counts() {
344 &read_rows(&b"foo\n bar\n baz\n"[..])
345 .collect::<Result<Vec<_>, _>>()
348 vec![(1, String::from("bar")), (1, String::from("baz"))]
352 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
353 .collect::<Result<Vec<_>, _>>()
356 vec![(1, String::from("bar")), (2, String::from("baz"))]
360 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
361 .collect::<Result<Vec<_>, _>>()
364 vec![(1, String::from("bar")), (2, String::from("baz"))]
368 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
369 .collect::<Result<Vec<_>, _>>()
372 vec![(1, String::from("bar")), (2, String::from("baz"))]
377 fn test_render_cell() {
382 label: String::from("nope"),
386 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
392 label: String::from("nope"),
393 entries: vec![Entry::from("bar")]
396 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
402 label: String::from("nope"),
403 entries: vec![Entry::from("foo")]
406 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
412 label: String::from("nope"),
413 entries: vec![Entry::from("foo"), Entry::from("foo")]
416 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
422 label: String::from("nope"),
423 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
426 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
432 label: String::from("nope"),
433 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
436 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")