1 use std::borrow::ToOwned;
2 use std::collections::HashMap;
5 use std::iter::Iterator;
9 const HEADER: &str = r#"<!DOCTYPE html>
12 <meta charset="utf-8">
13 <meta name="viewport" content="width=device-width, initial-scale=1">
15 td { text-align: center; }
16 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
17 th, td { white-space: nowrap; }
18 th { text-align: left; font-weight: normal; }
19 table { border-collapse: collapse }
20 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
21 tr.key > th > div { width: 1em; }
22 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
23 td { border: thin solid gray; }
24 td.yes { border: thin solid gray; background-color: #ddd; }
25 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
26 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
29 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
30 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
31 function h2(a, b) { highlight(a); highlight(b); }
32 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
39 const FOOTER: &str = " </tbody>
44 #[derive(PartialEq, Eq, Debug)]
45 pub struct HTML(String);
47 fn escape(value: &str) -> HTML {
48 let mut escaped: String = String::new();
49 for c in value.chars() {
51 '>' => escaped.push_str(">"),
52 '<' => escaped.push_str("<"),
53 '\'' => escaped.push_str("'"),
54 '"' => escaped.push_str("""),
55 '&' => escaped.push_str("&"),
56 ok_c => escaped.push(ok_c),
62 impl From<&str> for HTML {
63 fn from(value: &str) -> HTML {
64 HTML(String::from(value))
67 impl FromIterator<HTML> for HTML {
68 fn from_iter<T>(iter: T) -> HTML
70 T: IntoIterator<Item = HTML>,
72 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
75 impl std::fmt::Display for HTML {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 write!(f, "{}", self.0)
81 #[derive(Debug, PartialEq, Eq)]
85 Entry(&'a str, Option<&'a str>),
87 impl<'a> From<&'a str> for InputLine<'a> {
88 fn from(value: &'a str) -> InputLine<'a> {
89 let trimmed = value.trim_end();
90 if trimmed.is_empty() {
92 } else if !trimmed.starts_with(' ') {
93 InputLine::RowHeader(value.trim())
95 match value.split_once(':') {
96 None => InputLine::Entry(value.trim(), None),
97 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
103 #[derive(Debug, PartialEq, Eq)]
106 entries: HashMap<String, Vec<Option<String>>>,
109 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
110 input: std::iter::Enumerate<Input>,
113 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
114 fn new(input: Input) -> Self {
116 input: input.enumerate(),
121 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
122 type Item = Result<Row, std::io::Error>;
123 fn next(&mut self) -> Option<Self::Item> {
125 match self.input.next() {
126 None => return Ok(std::mem::take(&mut self.row)).transpose(),
127 Some((_, Err(e))) => return Some(Err(e)),
128 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
129 InputLine::Blank if self.row.is_some() => {
130 return Ok(std::mem::take(&mut self.row)).transpose()
132 InputLine::Blank => {}
133 InputLine::Entry(col, instance) => match &mut self.row {
135 return Some(Err(std::io::Error::other(format!(
136 "{}: Entry with no header",
140 Some(ref mut row) => {
142 .entry(col.to_owned())
143 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
144 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
147 InputLine::RowHeader(row) => {
148 let prev = std::mem::take(&mut self.row);
149 self.row = Some(Row {
150 label: row.to_owned(),
151 entries: HashMap::new(),
154 return Ok(prev).transpose();
163 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<Row, std::io::Error>> {
164 Reader::new(std::io::BufReader::new(input).lines())
167 fn column_counts(rows: &[Row]) -> Vec<(usize, String)> {
168 let mut counts: Vec<_> = rows
170 .flat_map(|r| r.entries.keys())
171 .fold(HashMap::new(), |mut cs, col| {
172 cs.entry(col.to_owned())
173 .and_modify(|n| *n += 1)
178 .map(|(col, n)| (n, col))
180 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
183 fn column_order(rows: &[Row]) -> Vec<String> {
190 fn render_one_instance(instance: &Option<String>) -> HTML {
192 None => HTML::from("✓"),
193 Some(instance) => HTML::escape(instance.as_ref()),
197 fn render_instances(instances: &[Option<String>]) -> HTML {
198 let all_empty = instances.iter().all(Option::is_none);
199 if all_empty && instances.len() == 1 {
201 } else if all_empty {
202 HTML(format!("{}", instances.len()))
207 .map(render_one_instance)
208 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
215 fn render_cell(col: &str, row: &mut Row) -> HTML {
216 let row_label = HTML::escape(row.label.as_ref());
217 let col_label = HTML::escape(col);
218 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
219 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
220 let contents = match instances {
221 None => HTML::from(""),
222 Some(is) => render_instances(is),
224 row.entries.remove(col);
226 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
230 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
231 let label = HTML::escape(notcol);
232 let rest = render_instances(instances);
233 if rest == HTML::from("") {
234 HTML(format!("{label}"))
236 HTML(format!("{label}: {rest}"))
240 fn render_all_leftovers(row: &Row) -> HTML {
241 let mut order: Vec<_> = row.entries.keys().collect();
242 order.sort_unstable();
246 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
247 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
253 fn render_row(columns: &[String], row: &mut Row) -> HTML {
254 let row_label = HTML::escape(row.label.as_ref());
257 .map(|col| render_cell(col, row))
259 let leftovers = render_all_leftovers(row);
261 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}<td onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
265 fn render_column_headers(columns: &[String]) -> HTML {
267 String::from(r#"<tr class="key"><th></th>"#)
268 + &columns.iter().fold(String::new(), |mut acc, col| {
269 let col_header = HTML::escape(col.as_ref());
272 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
283 /// Will return `Err` if
284 /// * there's an i/o error while reading `input`
285 /// * the log has invalid syntax:
286 /// * an indented line with no preceding non-indented line
287 pub fn tablify(config: &Config, input: impl std::io::Read) -> Result<HTML, std::io::Error> {
288 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
289 let columns = column_order(&rows);
291 "{HEADER}{}{}{FOOTER}",
292 render_column_headers(&columns),
294 .map(|mut r| render_row(&columns, &mut r))
304 fn test_parse_line() {
305 assert_eq!(InputLine::from(""), InputLine::Blank);
306 assert_eq!(InputLine::from(" "), InputLine::Blank);
307 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
308 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
309 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
311 InputLine::from(" foo:bar"),
312 InputLine::Entry("foo", Some("bar"))
315 InputLine::from(" foo: bar"),
316 InputLine::Entry("foo", Some("bar"))
319 InputLine::from(" foo: bar "),
320 InputLine::Entry("foo", Some("bar"))
323 InputLine::from(" foo: bar "),
324 InputLine::Entry("foo", Some("bar"))
327 InputLine::from(" foo : bar "),
328 InputLine::Entry("foo", Some("bar"))
333 fn test_read_rows() {
335 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
337 label: "foo".to_owned(),
338 entries: HashMap::new(),
342 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
344 label: "bar".to_owned(),
345 entries: HashMap::new(),
349 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
352 label: "foo".to_owned(),
353 entries: HashMap::new(),
356 label: "bar".to_owned(),
357 entries: HashMap::new(),
362 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
364 label: "foo".to_owned(),
365 entries: HashMap::from([("bar".to_owned(), vec![None])]),
369 read_rows(&b"foo\n bar\n baz\n"[..])
371 .collect::<Vec<_>>(),
373 label: "foo".to_owned(),
374 entries: HashMap::from([
375 ("bar".to_owned(), vec![None]),
376 ("baz".to_owned(), vec![None])
381 read_rows(&b"foo\n\nbar\n"[..])
383 .collect::<Vec<_>>(),
386 label: "foo".to_owned(),
387 entries: HashMap::new(),
390 label: "bar".to_owned(),
391 entries: HashMap::new(),
396 read_rows(&b"foo\n \nbar\n"[..])
398 .collect::<Vec<_>>(),
401 label: "foo".to_owned(),
402 entries: HashMap::new(),
405 label: "bar".to_owned(),
406 entries: HashMap::new(),
411 read_rows(&b"foo \n bar \n"[..])
413 .collect::<Vec<_>>(),
415 label: "foo".to_owned(),
416 entries: HashMap::from([("bar".to_owned(), vec![None])]),
420 let bad = read_rows(&b" foo"[..]).next().unwrap();
421 assert!(bad.is_err());
422 assert!(format!("{bad:?}").contains("1: Entry with no header"));
424 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
425 assert!(bad2.is_err());
426 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
430 fn test_column_counts() {
433 &read_rows(&b"foo\n bar\n baz\n"[..])
434 .collect::<Result<Vec<_>, _>>()
437 vec![(1, String::from("bar")), (1, String::from("baz"))]
441 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
442 .collect::<Result<Vec<_>, _>>()
445 vec![(2, String::from("baz")), (1, String::from("bar"))]
449 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
450 .collect::<Result<Vec<_>, _>>()
453 vec![(2, String::from("baz")), (1, String::from("bar"))]
457 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
458 .collect::<Result<Vec<_>, _>>()
461 vec![(2, String::from("baz")), (1, String::from("bar"))]
466 fn test_render_cell() {
471 label: "nope".to_owned(),
472 entries: HashMap::new(),
476 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
483 label: "nope".to_owned(),
484 entries: HashMap::from([("bar".to_owned(), vec![None])]),
488 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
495 label: "nope".to_owned(),
496 entries: HashMap::from([("foo".to_owned(), vec![None])]),
500 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
507 label: "nope".to_owned(),
508 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
512 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
519 label: "nope".to_owned(),
520 entries: HashMap::from([(
522 vec![Some("5".to_owned()), Some("10".to_owned())]
527 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
534 label: "nope".to_owned(),
535 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
539 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
546 label: "nope".to_owned(),
547 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
551 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
558 label: "bob's".to_owned(),
559 entries: HashMap::from([("foo".to_owned(), vec![None])]),
563 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
567 label: "nope".to_owned(),
568 entries: HashMap::from([
569 ("foo".to_owned(), vec![None]),
570 ("baz".to_owned(), vec![None]),
573 assert_eq!(r.entries.len(), 2);
574 render_cell("foo", &mut r);
575 assert_eq!(r.entries.len(), 1);
576 render_cell("bar", &mut r);
577 assert_eq!(r.entries.len(), 1);
578 render_cell("baz", &mut r);
579 assert_eq!(r.entries.len(), 0);
583 fn test_render_leftovers() {
585 render_all_leftovers(&Row {
586 label: "nope".to_owned(),
587 entries: HashMap::from([("foo".to_owned(), vec![None])]),
592 render_all_leftovers(&Row {
593 label: "nope".to_owned(),
594 entries: HashMap::from([
595 ("foo".to_owned(), vec![None]),
596 ("bar".to_owned(), vec![None])
599 HTML::from("bar, foo")
602 render_all_leftovers(&Row {
603 label: "nope".to_owned(),
604 entries: HashMap::from([
605 ("foo".to_owned(), vec![None]),
606 ("bar".to_owned(), vec![None, None])
609 HTML::from("bar: 2, foo")
614 fn test_render_row() {
619 label: "nope".to_owned(),
620 entries: HashMap::from([("bar".to_owned(), vec![None])]),
624 r#"<tr><th id="nope">nope</th><td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td><td onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')">bar</td></tr>