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<&'a str>,
83 impl<'a> From<&'a str> for Entry<'a> {
84 fn from(value: &'a str) -> Entry<'a> {
85 match value.split_once(':') {
90 Some((col, instance)) => Entry {
92 instance: Some(instance.trim()),
98 #[derive(Debug, PartialEq, Eq)]
101 entries: Vec<Entry<'a>>,
104 struct Reader<'a, Input: Iterator<Item = Result<String, std::io::Error>>> {
105 input: std::iter::Enumerate<Input>,
106 row: Option<RowInput<'a>>,
108 impl<'a, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'a, Input> {
109 fn new(input: Input) -> Self {
111 input: input.enumerate(),
116 impl<'a, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<'a, Input> {
117 type Item = Result<RowInput<'a>, std::io::Error>;
118 fn next(&mut self) -> Option<Self::Item> {
124 .map(|(n, r)| (n, r.map(|line| String::from(line).leak().trim_end())))
126 None => return Ok(std::mem::take(&mut self.row)).transpose(),
127 Some((_, Err(e))) => return Some(Err(e)),
128 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
129 return Ok(std::mem::take(&mut self.row)).transpose()
131 Some((_, Ok(line))) if line.is_empty() => {}
132 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
134 return Some(Err(std::io::Error::other(format!(
135 "{}: Entry with no header",
139 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
141 Some((_, Ok(line))) => {
142 let prev = std::mem::take(&mut self.row);
143 self.row = Some(RowInput {
148 return Ok(prev).transpose();
157 input: impl std::io::Read,
158 ) -> impl Iterator<Item = Result<RowInput<'static>, std::io::Error>> {
159 Reader::new(std::io::BufReader::new(input).lines())
162 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
163 let mut counts: Vec<_> = rows
169 .collect::<HashSet<_>>()
172 .fold(HashMap::new(), |mut cs, col| {
173 cs.entry(String::from(*col))
174 .and_modify(|n| *n += 1)
179 .map(|(col, n)| (n, col))
181 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
184 fn column_order(rows: &[RowInput]) -> Vec<String> {
191 fn render_instance(entry: &Entry) -> HTML {
192 match &entry.instance {
193 None => HTML::from("✓"),
194 Some(instance) => HTML::escape(instance.as_ref()),
198 fn render_cell(col: &str, row: &RowInput) -> HTML {
199 let row_label = HTML::escape(row.label.as_ref());
200 let col_label = HTML::escape(col);
201 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
202 let class = HTML::from(if entries.is_empty() { "" } else { "yes" });
203 let all_empty = entries.iter().all(|e| e.instance.is_none());
204 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
206 } else if all_empty {
207 HTML(format!("{}", entries.len()))
212 .map(|i| render_instance(i))
213 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
218 HTML(format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col_label}')\" onmouseout=\"ch2('{row_label}','{col_label}')\">{contents}</td>"))
221 fn render_row(columns: &[String], row: &RowInput) -> HTML {
222 // This is O(n^2) & doesn't need to be
223 let row_label = HTML::escape(row.label.as_ref());
225 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
228 .map(|col| render_cell(col, row))
233 fn render_column_headers(columns: &[String]) -> HTML {
235 String::from("<tr class=\"key\"><th></th>")
236 + &columns.iter().fold(String::new(), |mut acc, col| {
237 let col_header = HTML::escape(col.as_ref());
240 "<th id=\"{col_header}\"><div><div>{col_header}</div></div></th>"
251 /// Will return `Err` if
252 /// * there's an i/o error while reading `input`
253 /// * the log has invalid syntax:
254 /// * an indented line with no preceding non-indented line
255 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
256 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
257 let columns = column_order(&rows);
259 "{HEADER}{}{}{FOOTER}",
260 render_column_headers(&columns),
262 .map(|r| render_row(&columns, &r))
272 fn test_parse_entry() {
281 Entry::from("foo:bar"),
284 instance: Some("bar")
288 Entry::from("foo: bar"),
291 instance: Some("bar")
297 fn test_read_rows() {
299 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
306 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
313 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
326 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
329 entries: vec![Entry::from("bar")]
333 read_rows(&b"foo\n bar\n baz\n"[..])
335 .collect::<Vec<_>>(),
338 entries: vec![Entry::from("bar"), Entry::from("baz")]
342 read_rows(&b"foo\n\nbar\n"[..])
344 .collect::<Vec<_>>(),
357 read_rows(&b"foo\n \nbar\n"[..])
359 .collect::<Vec<_>>(),
372 read_rows(&b"foo \n bar \n"[..])
374 .collect::<Vec<_>>(),
377 entries: vec![Entry::from("bar")]
381 let bad = read_rows(&b" foo"[..]).next().unwrap();
382 assert!(bad.is_err());
383 assert!(format!("{bad:?}").contains("1: Entry with no header"));
385 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
386 assert!(bad2.is_err());
387 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
391 fn test_column_counts() {
394 &read_rows(&b"foo\n bar\n baz\n"[..])
395 .collect::<Result<Vec<_>, _>>()
398 vec![(1, String::from("bar")), (1, String::from("baz"))]
402 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
403 .collect::<Result<Vec<_>, _>>()
406 vec![(2, String::from("baz")), (1, String::from("bar"))]
410 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
411 .collect::<Result<Vec<_>, _>>()
414 vec![(2, String::from("baz")), (1, String::from("bar"))]
418 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
419 .collect::<Result<Vec<_>, _>>()
422 vec![(2, String::from("baz")), (1, String::from("bar"))]
427 fn test_render_cell() {
436 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
443 entries: vec![Entry::from("bar")]
446 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
453 entries: vec![Entry::from("foo")]
456 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
463 entries: vec![Entry::from("foo"), Entry::from("foo")]
466 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
473 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
476 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
483 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
486 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")
493 entries: vec![Entry::from("heart: <3")]
496 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','heart')\" onmouseout=\"ch2('nope','heart')\"><3</td>")
503 entries: vec![Entry::from("foo")]
506 HTML::from("<td class=\"yes\" onmouseover=\"h2('bob's','foo')\" onmouseout=\"ch2('bob's','foo')\"></td>")