1 use std::borrow::ToOwned;
2 use std::collections::HashMap;
5 use std::iter::Iterator;
8 pub column_threshold: usize,
11 const HEADER: &str = r#"<!DOCTYPE html>
14 <meta charset="utf-8">
15 <meta name="viewport" content="width=device-width, initial-scale=1">
17 td { text-align: center; }
18 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
19 th, td { white-space: nowrap; }
20 th { text-align: left; font-weight: normal; }
21 table { border-collapse: collapse }
22 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
23 tr.key > th > div { width: 1em; }
24 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
25 td { border: thin solid gray; }
26 td.leftover { text-align: left; border: none; padding-left: .4em; }
27 td.yes { border: thin solid gray; background-color: #ddd; }
28 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
29 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
32 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
33 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
34 function h2(a, b) { highlight(a); highlight(b); }
35 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
42 const FOOTER: &str = " </tbody>
47 #[derive(PartialEq, Eq, Debug)]
48 pub struct HTML(String);
50 fn escape(value: &str) -> HTML {
51 let mut escaped: String = String::new();
52 for c in value.chars() {
54 '>' => escaped.push_str(">"),
55 '<' => escaped.push_str("<"),
56 '\'' => escaped.push_str("'"),
57 '"' => escaped.push_str("""),
58 '&' => escaped.push_str("&"),
59 ok_c => escaped.push(ok_c),
65 impl From<&str> for HTML {
66 fn from(value: &str) -> HTML {
67 HTML(String::from(value))
70 impl FromIterator<HTML> for HTML {
71 fn from_iter<T>(iter: T) -> HTML
73 T: IntoIterator<Item = HTML>,
75 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
78 impl std::fmt::Display for HTML {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 write!(f, "{}", self.0)
84 #[derive(Debug, PartialEq, Eq)]
88 Entry(&'a str, Option<&'a str>),
90 impl<'a> From<&'a str> for InputLine<'a> {
91 fn from(value: &'a str) -> InputLine<'a> {
92 let trimmed = value.trim_end();
93 if trimmed.is_empty() {
95 } else if !trimmed.starts_with(' ') {
96 InputLine::RowHeader(value.trim())
98 match value.split_once(':') {
99 None => InputLine::Entry(value.trim(), None),
100 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
106 #[derive(Debug, PartialEq, Eq)]
109 entries: HashMap<String, Vec<Option<String>>>,
112 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
113 input: std::iter::Enumerate<Input>,
116 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
117 fn new(input: Input) -> Self {
119 input: input.enumerate(),
124 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
125 type Item = Result<Row, std::io::Error>;
126 fn next(&mut self) -> Option<Self::Item> {
128 match self.input.next() {
129 None => return Ok(std::mem::take(&mut self.row)).transpose(),
130 Some((_, Err(e))) => return Some(Err(e)),
131 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
132 InputLine::Blank if self.row.is_some() => {
133 return Ok(std::mem::take(&mut self.row)).transpose()
135 InputLine::Blank => {}
136 InputLine::Entry(col, instance) => match &mut self.row {
138 return Some(Err(std::io::Error::other(format!(
139 "{}: Entry with no header",
143 Some(ref mut row) => {
145 .entry(col.to_owned())
146 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
147 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
150 InputLine::RowHeader(row) => {
151 let prev = std::mem::take(&mut self.row);
152 self.row = Some(Row {
153 label: row.to_owned(),
154 entries: HashMap::new(),
157 return Ok(prev).transpose();
166 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<Row, std::io::Error>> {
167 Reader::new(std::io::BufReader::new(input).lines())
170 fn column_counts(rows: &[Row]) -> Vec<(usize, String)> {
171 let mut counts: Vec<_> = rows
173 .flat_map(|r| r.entries.keys())
174 .fold(HashMap::new(), |mut cs, col| {
175 cs.entry(col.to_owned())
176 .and_modify(|n| *n += 1)
181 .map(|(col, n)| (n, col))
183 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
186 fn column_order(config: &Config, rows: &[Row]) -> Vec<String> {
189 .filter_map(|(n, col)| (n >= config.column_threshold).then_some(col))
193 fn render_one_instance(instance: &Option<String>) -> HTML {
195 None => HTML::from("✓"),
196 Some(instance) => HTML::escape(instance.as_ref()),
200 fn render_instances(instances: &[Option<String>]) -> HTML {
201 let all_empty = instances.iter().all(Option::is_none);
202 if all_empty && instances.len() == 1 {
204 } else if all_empty {
205 HTML(format!("{}", instances.len()))
210 .map(render_one_instance)
211 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
218 fn render_cell(col: &str, row: &mut Row) -> HTML {
219 let row_label = HTML::escape(row.label.as_ref());
220 let col_label = HTML::escape(col);
221 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
222 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
223 let contents = match instances {
224 None => HTML::from(""),
225 Some(is) => render_instances(is),
227 row.entries.remove(col);
229 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
233 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
234 let label = HTML::escape(notcol);
235 let rest = render_instances(instances);
236 if rest == HTML::from("") {
237 HTML(format!("{label}"))
239 HTML(format!("{label}: {rest}"))
243 fn render_all_leftovers(row: &Row) -> HTML {
244 let mut order: Vec<_> = row.entries.keys().collect();
245 order.sort_unstable();
249 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
250 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
256 fn render_row(columns: &[String], row: &mut Row) -> HTML {
257 let row_label = HTML::escape(row.label.as_ref());
260 .map(|col| render_cell(col, row))
262 let leftovers = render_all_leftovers(row);
264 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
268 fn render_column_headers(columns: &[String]) -> HTML {
270 String::from(r#"<tr class="key"><th></th>"#)
271 + &columns.iter().fold(String::new(), |mut acc, col| {
272 let col_header = HTML::escape(col.as_ref());
275 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
286 /// Will return `Err` if
287 /// * there's an i/o error while reading `input`
288 /// * the log has invalid syntax:
289 /// * an indented line with no preceding non-indented line
290 pub fn tablify(config: &Config, input: impl std::io::Read) -> Result<HTML, std::io::Error> {
291 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
292 let columns = column_order(config, &rows);
294 "{HEADER}{}{}{FOOTER}",
295 render_column_headers(&columns),
297 .map(|mut r| render_row(&columns, &mut r))
307 fn test_parse_line() {
308 assert_eq!(InputLine::from(""), InputLine::Blank);
309 assert_eq!(InputLine::from(" "), InputLine::Blank);
310 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
311 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
312 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
314 InputLine::from(" foo:bar"),
315 InputLine::Entry("foo", Some("bar"))
318 InputLine::from(" foo: bar"),
319 InputLine::Entry("foo", Some("bar"))
322 InputLine::from(" foo: bar "),
323 InputLine::Entry("foo", Some("bar"))
326 InputLine::from(" foo: bar "),
327 InputLine::Entry("foo", Some("bar"))
330 InputLine::from(" foo : bar "),
331 InputLine::Entry("foo", Some("bar"))
336 fn test_read_rows() {
338 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
340 label: "foo".to_owned(),
341 entries: HashMap::new(),
345 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
347 label: "bar".to_owned(),
348 entries: HashMap::new(),
352 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
355 label: "foo".to_owned(),
356 entries: HashMap::new(),
359 label: "bar".to_owned(),
360 entries: HashMap::new(),
365 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
367 label: "foo".to_owned(),
368 entries: HashMap::from([("bar".to_owned(), vec![None])]),
372 read_rows(&b"foo\n bar\n baz\n"[..])
374 .collect::<Vec<_>>(),
376 label: "foo".to_owned(),
377 entries: HashMap::from([
378 ("bar".to_owned(), vec![None]),
379 ("baz".to_owned(), vec![None])
384 read_rows(&b"foo\n\nbar\n"[..])
386 .collect::<Vec<_>>(),
389 label: "foo".to_owned(),
390 entries: HashMap::new(),
393 label: "bar".to_owned(),
394 entries: HashMap::new(),
399 read_rows(&b"foo\n \nbar\n"[..])
401 .collect::<Vec<_>>(),
404 label: "foo".to_owned(),
405 entries: HashMap::new(),
408 label: "bar".to_owned(),
409 entries: HashMap::new(),
414 read_rows(&b"foo \n bar \n"[..])
416 .collect::<Vec<_>>(),
418 label: "foo".to_owned(),
419 entries: HashMap::from([("bar".to_owned(), vec![None])]),
423 let bad = read_rows(&b" foo"[..]).next().unwrap();
424 assert!(bad.is_err());
425 assert!(format!("{bad:?}").contains("1: Entry with no header"));
427 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
428 assert!(bad2.is_err());
429 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
433 fn test_column_counts() {
436 &read_rows(&b"foo\n bar\n baz\n"[..])
437 .collect::<Result<Vec<_>, _>>()
440 vec![(1, String::from("bar")), (1, String::from("baz"))]
444 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
445 .collect::<Result<Vec<_>, _>>()
448 vec![(2, String::from("baz")), (1, String::from("bar"))]
452 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
453 .collect::<Result<Vec<_>, _>>()
456 vec![(2, String::from("baz")), (1, String::from("bar"))]
460 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
461 .collect::<Result<Vec<_>, _>>()
464 vec![(2, String::from("baz")), (1, String::from("bar"))]
469 fn test_render_cell() {
474 label: "nope".to_owned(),
475 entries: HashMap::new(),
479 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
486 label: "nope".to_owned(),
487 entries: HashMap::from([("bar".to_owned(), vec![None])]),
491 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
498 label: "nope".to_owned(),
499 entries: HashMap::from([("foo".to_owned(), vec![None])]),
503 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
510 label: "nope".to_owned(),
511 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
515 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
522 label: "nope".to_owned(),
523 entries: HashMap::from([(
525 vec![Some("5".to_owned()), Some("10".to_owned())]
530 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
537 label: "nope".to_owned(),
538 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
542 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
549 label: "nope".to_owned(),
550 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
554 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
561 label: "bob's".to_owned(),
562 entries: HashMap::from([("foo".to_owned(), vec![None])]),
566 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
570 label: "nope".to_owned(),
571 entries: HashMap::from([
572 ("foo".to_owned(), vec![None]),
573 ("baz".to_owned(), vec![None]),
576 assert_eq!(r.entries.len(), 2);
577 render_cell("foo", &mut r);
578 assert_eq!(r.entries.len(), 1);
579 render_cell("bar", &mut r);
580 assert_eq!(r.entries.len(), 1);
581 render_cell("baz", &mut r);
582 assert_eq!(r.entries.len(), 0);
586 fn test_render_leftovers() {
588 render_all_leftovers(&Row {
589 label: "nope".to_owned(),
590 entries: HashMap::from([("foo".to_owned(), vec![None])]),
595 render_all_leftovers(&Row {
596 label: "nope".to_owned(),
597 entries: HashMap::from([
598 ("foo".to_owned(), vec![None]),
599 ("bar".to_owned(), vec![None])
602 HTML::from("bar, foo")
605 render_all_leftovers(&Row {
606 label: "nope".to_owned(),
607 entries: HashMap::from([
608 ("foo".to_owned(), vec![None]),
609 ("bar".to_owned(), vec![None, None])
612 HTML::from("bar: 2, foo")
617 fn test_render_row() {
622 label: "nope".to_owned(),
623 entries: HashMap::from([("bar".to_owned(), vec![None])]),
627 r#"<tr><th id="nope">nope</th><td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')">bar</td></tr>