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 td { text-align: center; }
13 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
14 th, td { white-space: nowrap; }
15 th { text-align: left; font-weight: normal; }
16 table { border-collapse: collapse }
17 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
18 tr.key > th > div { width: 1em; }
19 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
20 td { border: thin solid gray; }
21 td.yes { border: thin solid gray; background-color: #ddd; }
22 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
23 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
26 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } }
27 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } }
28 function h2(a, b) { highlight(a); highlight(b); }
29 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
36 const FOOTER: &str = " </tbody>
41 #[derive(PartialEq, Eq, Debug)]
42 pub struct HTML(String);
44 fn escape(value: &str) -> HTML {
45 let mut escaped: String = String::new();
46 for c in value.chars() {
48 '>' => escaped.push_str(">"),
49 '<' => escaped.push_str("<"),
50 '\'' => escaped.push_str("'"),
51 '"' => escaped.push_str("""),
52 '&' => escaped.push_str("&"),
53 ok_c => escaped.push(ok_c),
59 impl From<&str> for HTML {
60 fn from(value: &str) -> HTML {
61 HTML(String::from(value))
64 impl FromIterator<HTML> for HTML {
65 fn from_iter<T>(iter: T) -> HTML
67 T: IntoIterator<Item = HTML>,
69 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
72 impl std::fmt::Display for HTML {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 write!(f, "{}", self.0)
78 #[derive(Debug, PartialEq, Eq, Hash)]
81 instance: Option<String>,
83 impl From<&str> for Entry {
84 fn from(value: &str) -> Entry {
85 match value.split_once(':') {
87 col: String::from(value),
90 Some((col, instance)) => Entry {
91 col: String::from(col.trim()),
92 instance: Some(String::from(instance.trim())),
98 #[derive(Debug, PartialEq, Eq)]
104 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
105 input: std::iter::Enumerate<Input>,
106 row: Option<RowInput>,
108 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
109 fn new(input: Input) -> Self {
111 input: input.enumerate(),
116 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
117 type Item = Result<RowInput, std::io::Error>;
118 fn next(&mut self) -> Option<Self::Item> {
123 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
125 None => return Ok(std::mem::take(&mut self.row)).transpose(),
126 Some((_, Err(e))) => return Some(Err(e)),
127 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
128 return Ok(std::mem::take(&mut self.row)).transpose()
130 Some((_, Ok(line))) if line.is_empty() => {}
131 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
133 return Some(Err(std::io::Error::other(format!(
134 "{}: Entry with no header",
138 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
140 Some((_, Ok(line))) => {
141 let prev = std::mem::take(&mut self.row);
142 self.row = Some(RowInput {
147 return Ok(prev).transpose();
155 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
156 Reader::new(std::io::BufReader::new(input).lines())
159 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
160 let mut counts: Vec<_> = rows
166 .collect::<HashSet<_>>()
169 .fold(HashMap::new(), |mut cs, col| {
170 cs.entry(String::from(col))
171 .and_modify(|n| *n += 1)
176 .map(|(col, n)| (n, col))
178 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
181 fn column_order(rows: &[RowInput]) -> Vec<String> {
188 fn render_instance(entry: &Entry) -> HTML {
189 match &entry.instance {
190 None => HTML::from("✓"),
191 Some(instance) => HTML::escape(instance.as_ref()),
195 fn render_cell(col: &str, row: &RowInput) -> HTML {
196 let row_label = HTML::escape(row.label.as_ref());
197 let col_label = HTML::escape(col);
198 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
199 let class = HTML::from(if entries.is_empty() { "" } else { "yes" });
200 let all_empty = entries.iter().all(|e| e.instance.is_none());
201 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
203 } else if all_empty {
204 HTML(format!("{}", entries.len()))
209 .map(|i| render_instance(i))
210 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
215 HTML(format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col_label}')\" onmouseout=\"ch2('{row_label}','{col_label}')\">{contents}</td>"))
218 fn render_row(columns: &[String], row: &RowInput) -> HTML {
219 // This is O(n^2) & doesn't need to be
220 let row_label = HTML::escape(row.label.as_ref());
222 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
225 .map(|col| render_cell(col, row))
230 fn render_column_headers(columns: &[String]) -> HTML {
232 String::from("<tr class=\"key\"><th></th>")
233 + &columns.iter().fold(String::new(), |mut acc, col| {
234 let col_header = HTML::escape(col.as_ref());
237 "<th id=\"{col_header}\"><div><div>{col_header}</div></div></th>"
248 /// Will return `Err` if
249 /// * there's an i/o error while reading `input`
250 /// * the log has invalid syntax:
251 /// * an indented line with no preceding non-indented line
252 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
253 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
254 let columns = column_order(&rows);
256 "{HEADER}{}{}{FOOTER}",
257 render_column_headers(&columns),
259 .map(|r| render_row(&columns, &r))
269 fn test_parse_entry() {
273 col: String::from("foo"),
278 Entry::from("foo:bar"),
280 col: String::from("foo"),
281 instance: Some(String::from("bar"))
285 Entry::from("foo: bar"),
287 col: String::from("foo"),
288 instance: Some(String::from("bar"))
294 fn test_read_rows() {
296 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
298 label: String::from("foo"),
303 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
305 label: String::from("bar"),
310 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
313 label: String::from("foo"),
317 label: String::from("bar"),
323 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
325 label: String::from("foo"),
326 entries: vec![Entry::from("bar")]
330 read_rows(&b"foo\n bar\n baz\n"[..])
332 .collect::<Vec<_>>(),
334 label: String::from("foo"),
335 entries: vec![Entry::from("bar"), Entry::from("baz")]
339 read_rows(&b"foo\n\nbar\n"[..])
341 .collect::<Vec<_>>(),
344 label: String::from("foo"),
348 label: String::from("bar"),
354 read_rows(&b"foo\n \nbar\n"[..])
356 .collect::<Vec<_>>(),
359 label: String::from("foo"),
363 label: String::from("bar"),
369 read_rows(&b"foo \n bar \n"[..])
371 .collect::<Vec<_>>(),
373 label: String::from("foo"),
374 entries: vec![Entry::from("bar")]
378 let bad = read_rows(&b" foo"[..]).next().unwrap();
379 assert!(bad.is_err());
380 assert!(format!("{bad:?}").contains("1: Entry with no header"));
382 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
383 assert!(bad2.is_err());
384 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
388 fn test_column_counts() {
391 &read_rows(&b"foo\n bar\n baz\n"[..])
392 .collect::<Result<Vec<_>, _>>()
395 vec![(1, String::from("bar")), (1, String::from("baz"))]
399 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
400 .collect::<Result<Vec<_>, _>>()
403 vec![(2, String::from("baz")), (1, String::from("bar"))]
407 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
408 .collect::<Result<Vec<_>, _>>()
411 vec![(2, String::from("baz")), (1, String::from("bar"))]
415 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
416 .collect::<Result<Vec<_>, _>>()
419 vec![(2, String::from("baz")), (1, String::from("bar"))]
424 fn test_render_cell() {
429 label: String::from("nope"),
433 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
439 label: String::from("nope"),
440 entries: vec![Entry::from("bar")]
443 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
449 label: String::from("nope"),
450 entries: vec![Entry::from("foo")]
453 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
459 label: String::from("nope"),
460 entries: vec![Entry::from("foo"), Entry::from("foo")]
463 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
469 label: String::from("nope"),
470 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
473 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
479 label: String::from("nope"),
480 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
483 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")
489 label: String::from("nope"),
490 entries: vec![Entry::from("heart: <3")]
493 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','heart')\" onmouseout=\"ch2('nope','heart')\"><3</td>")
499 label: String::from("bob's"),
500 entries: vec![Entry::from("foo")]
503 HTML::from("<td class=\"yes\" onmouseover=\"h2('bob's','foo')\" onmouseout=\"ch2('bob's','foo')\"></td>")