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: #ddd; }
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 row_label = &row.label;
163 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
164 let class = if entries.is_empty() { "" } else { "yes" };
165 let all_empty = entries.iter().all(|e| e.instance.is_none());
166 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
168 } else if all_empty {
169 format!("{}", entries.len())
173 .map(|i| render_instance(i))
176 format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col}')\" onmouseout=\"ch2('{row_label}','{col}')\">{}</td>", contents.trim())
179 fn render_row(columns: &[String], row: &RowInput) -> String {
180 // This is O(n^2) & doesn't need to be
181 // TODO: Escape HTML special characters
182 let row_label = &row.label;
184 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
187 .map(|col| render_cell(col, row))
192 fn render_column_headers(columns: &[String]) -> String {
193 // TODO: Escape HTML special characters
194 String::from("<tr class=\"key\"><th></th>")
195 + &columns.iter().fold(String::new(), |mut acc, c| {
196 write!(&mut acc, "<th id=\"{c}\"><div><div>{c}</div></div></th>").unwrap();
204 /// Will return `Err` if
205 /// * there's an i/o error while reading `input`
206 /// * the log has invalid syntax:
207 /// * an indented line with no preceding non-indented line
208 pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> {
209 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
210 let columns = column_order(&rows);
211 Ok(String::from(HEADER)
212 + &render_column_headers(&columns)
215 .map(|r| render_row(&columns, &r))
225 fn test_parse_entry() {
229 col: String::from("foo"),
234 Entry::from("foo:bar"),
236 col: String::from("foo"),
237 instance: Some(String::from("bar"))
241 Entry::from("foo: bar"),
243 col: String::from("foo"),
244 instance: Some(String::from("bar"))
250 fn test_read_rows() {
252 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
254 label: String::from("foo"),
259 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
261 label: String::from("bar"),
266 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
269 label: String::from("foo"),
273 label: String::from("bar"),
279 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
281 label: String::from("foo"),
282 entries: vec![Entry::from("bar")]
286 read_rows(&b"foo\n bar\n baz\n"[..])
288 .collect::<Vec<_>>(),
290 label: String::from("foo"),
291 entries: vec![Entry::from("bar"), Entry::from("baz")]
295 read_rows(&b"foo\n\nbar\n"[..])
297 .collect::<Vec<_>>(),
300 label: String::from("foo"),
304 label: String::from("bar"),
310 read_rows(&b"foo\n \nbar\n"[..])
312 .collect::<Vec<_>>(),
315 label: String::from("foo"),
319 label: String::from("bar"),
325 read_rows(&b"foo \n bar \n"[..])
327 .collect::<Vec<_>>(),
329 label: String::from("foo"),
330 entries: vec![Entry::from("bar")]
334 let bad = read_rows(&b" foo"[..]).next().unwrap();
335 assert!(bad.is_err());
336 assert!(format!("{bad:?}").contains("1: Entry with no header"));
338 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
339 assert!(bad2.is_err());
340 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
344 fn test_column_counts() {
347 &read_rows(&b"foo\n bar\n baz\n"[..])
348 .collect::<Result<Vec<_>, _>>()
351 vec![(1, String::from("bar")), (1, String::from("baz"))]
355 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
356 .collect::<Result<Vec<_>, _>>()
359 vec![(1, String::from("bar")), (2, String::from("baz"))]
363 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
364 .collect::<Result<Vec<_>, _>>()
367 vec![(1, String::from("bar")), (2, String::from("baz"))]
371 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
372 .collect::<Result<Vec<_>, _>>()
375 vec![(1, String::from("bar")), (2, String::from("baz"))]
380 fn test_render_cell() {
385 label: String::from("nope"),
389 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
395 label: String::from("nope"),
396 entries: vec![Entry::from("bar")]
399 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
405 label: String::from("nope"),
406 entries: vec![Entry::from("foo")]
409 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
415 label: String::from("nope"),
416 entries: vec![Entry::from("foo"), Entry::from("foo")]
419 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
425 label: String::from("nope"),
426 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
429 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
435 label: String::from("nope"),
436 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
439 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")