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 #[derive(Debug, PartialEq, Eq)]
118 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
119 input: std::iter::Enumerate<Input>,
122 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
123 fn new(input: Input) -> Self {
125 input: input.enumerate(),
130 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
131 type Item = Result<Rowlike, std::io::Error>;
132 fn next(&mut self) -> Option<Self::Item> {
134 match self.input.next() {
135 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
136 Some((_, Err(e))) => return Some(Err(e)),
137 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
138 InputLine::Blank if self.row.is_some() => {
139 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
141 InputLine::Blank => {}
142 InputLine::Entry(col, instance) => match &mut self.row {
144 return Some(Err(std::io::Error::other(format!(
145 "{}: Entry with no header",
149 Some(ref mut row) => {
151 .entry(col.to_owned())
152 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
153 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
156 InputLine::RowHeader(row) => {
157 let prev = std::mem::take(&mut self.row);
158 self.row = Some(Row {
159 label: row.to_owned(),
160 entries: HashMap::new(),
163 return Ok(prev.map(Rowlike::Row)).transpose();
172 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<Rowlike, std::io::Error>> {
173 Reader::new(std::io::BufReader::new(input).lines())
176 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
177 let empty = HashMap::new();
178 let mut counts: Vec<_> = rows
180 .flat_map(|rl| match rl {
181 Rowlike::Row(r) => r.entries.keys(),
182 Rowlike::Spacer => empty.keys(),
184 .fold(HashMap::new(), |mut cs, col| {
185 cs.entry(col.to_owned())
186 .and_modify(|n| *n += 1)
191 .map(|(col, n)| (n, col))
193 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
196 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
199 .filter_map(|(n, col)| (n >= config.column_threshold).then_some(col))
203 fn render_one_instance(instance: &Option<String>) -> HTML {
205 None => HTML::from("✓"),
206 Some(instance) => HTML::escape(instance.as_ref()),
210 fn render_instances(instances: &[Option<String>]) -> HTML {
211 let all_empty = instances.iter().all(Option::is_none);
212 if all_empty && instances.len() == 1 {
214 } else if all_empty {
215 HTML(format!("{}", instances.len()))
220 .map(render_one_instance)
221 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
228 fn render_cell(col: &str, row: &mut Row) -> HTML {
229 let row_label = HTML::escape(row.label.as_ref());
230 let col_label = HTML::escape(col);
231 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
232 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
233 let contents = match instances {
234 None => HTML::from(""),
235 Some(is) => render_instances(is),
237 row.entries.remove(col);
239 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
243 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
244 let label = HTML::escape(notcol);
245 let rest = render_instances(instances);
246 if rest == HTML::from("") {
247 HTML(format!("{label}"))
249 HTML(format!("{label}: {rest}"))
253 fn render_all_leftovers(row: &Row) -> HTML {
254 let mut order: Vec<_> = row.entries.keys().collect();
255 order.sort_unstable();
259 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
260 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
266 fn render_row(columns: &[String], rowlike: &mut Rowlike) -> HTML {
268 Rowlike::Spacer => HTML::from("<tr><td> </td></tr>"),
269 Rowlike::Row(row) => {
270 let row_label = HTML::escape(row.label.as_ref());
273 .map(|col| render_cell(col, row))
275 let leftovers = render_all_leftovers(row);
277 "<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"
283 fn render_column_headers(columns: &[String]) -> HTML {
285 String::from(r#"<tr class="key"><th></th>"#)
286 + &columns.iter().fold(String::new(), |mut acc, col| {
287 let col_header = HTML::escape(col.as_ref());
290 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
301 /// Will return `Err` if
302 /// * there's an i/o error while reading `input`
303 /// * the log has invalid syntax:
304 /// * an indented line with no preceding non-indented line
305 pub fn tablify(config: &Config, input: impl std::io::Read) -> Result<HTML, std::io::Error> {
306 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
307 let columns = column_order(config, &rows);
309 "{HEADER}{}{}{FOOTER}",
310 render_column_headers(&columns),
312 .map(|mut r| render_row(&columns, &mut r))
322 fn test_parse_line() {
323 assert_eq!(InputLine::from(""), InputLine::Blank);
324 assert_eq!(InputLine::from(" "), InputLine::Blank);
325 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
326 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
327 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
329 InputLine::from(" foo:bar"),
330 InputLine::Entry("foo", Some("bar"))
333 InputLine::from(" foo: bar"),
334 InputLine::Entry("foo", Some("bar"))
337 InputLine::from(" foo: bar "),
338 InputLine::Entry("foo", Some("bar"))
341 InputLine::from(" foo: bar "),
342 InputLine::Entry("foo", Some("bar"))
345 InputLine::from(" foo : bar "),
346 InputLine::Entry("foo", Some("bar"))
351 fn test_read_rows() {
353 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
354 vec![Rowlike::Row(Row {
355 label: "foo".to_owned(),
356 entries: HashMap::new(),
360 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
361 vec![Rowlike::Row(Row {
362 label: "bar".to_owned(),
363 entries: HashMap::new(),
367 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
370 label: "foo".to_owned(),
371 entries: HashMap::new(),
374 label: "bar".to_owned(),
375 entries: HashMap::new(),
380 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
381 vec![Rowlike::Row(Row {
382 label: "foo".to_owned(),
383 entries: HashMap::from([("bar".to_owned(), vec![None])]),
387 read_rows(&b"foo\n bar\n baz\n"[..])
389 .collect::<Vec<_>>(),
390 vec![Rowlike::Row(Row {
391 label: "foo".to_owned(),
392 entries: HashMap::from([
393 ("bar".to_owned(), vec![None]),
394 ("baz".to_owned(), vec![None])
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\n\nbar\n"[..])
416 .collect::<Vec<_>>(),
419 label: "foo".to_owned(),
420 entries: HashMap::new(),
423 label: "bar".to_owned(),
424 entries: HashMap::new(),
429 read_rows(&b"foo\n \nbar\n"[..])
431 .collect::<Vec<_>>(),
434 label: "foo".to_owned(),
435 entries: HashMap::new(),
438 label: "bar".to_owned(),
439 entries: HashMap::new(),
444 read_rows(&b"foo \n bar \n"[..])
446 .collect::<Vec<_>>(),
447 vec![Rowlike::Row(Row {
448 label: "foo".to_owned(),
449 entries: HashMap::from([("bar".to_owned(), vec![None])]),
453 let bad = read_rows(&b" foo"[..]).next().unwrap();
454 assert!(bad.is_err());
455 assert!(format!("{bad:?}").contains("1: Entry with no header"));
457 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
458 assert!(bad2.is_err());
459 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
463 fn test_column_counts() {
466 &read_rows(&b"foo\n bar\n baz\n"[..])
467 .collect::<Result<Vec<_>, _>>()
470 vec![(1, String::from("bar")), (1, String::from("baz"))]
474 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
475 .collect::<Result<Vec<_>, _>>()
478 vec![(2, String::from("baz")), (1, String::from("bar"))]
482 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
483 .collect::<Result<Vec<_>, _>>()
486 vec![(2, String::from("baz")), (1, String::from("bar"))]
490 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
491 .collect::<Result<Vec<_>, _>>()
494 vec![(2, String::from("baz")), (1, String::from("bar"))]
499 fn test_render_cell() {
504 label: "nope".to_owned(),
505 entries: HashMap::new(),
509 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
516 label: "nope".to_owned(),
517 entries: HashMap::from([("bar".to_owned(), vec![None])]),
521 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
528 label: "nope".to_owned(),
529 entries: HashMap::from([("foo".to_owned(), vec![None])]),
533 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
540 label: "nope".to_owned(),
541 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
545 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
552 label: "nope".to_owned(),
553 entries: HashMap::from([(
555 vec![Some("5".to_owned()), Some("10".to_owned())]
560 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
567 label: "nope".to_owned(),
568 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
572 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
579 label: "nope".to_owned(),
580 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
584 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
591 label: "bob's".to_owned(),
592 entries: HashMap::from([("foo".to_owned(), vec![None])]),
596 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
600 label: "nope".to_owned(),
601 entries: HashMap::from([
602 ("foo".to_owned(), vec![None]),
603 ("baz".to_owned(), vec![None]),
606 assert_eq!(r.entries.len(), 2);
607 render_cell("foo", &mut r);
608 assert_eq!(r.entries.len(), 1);
609 render_cell("bar", &mut r);
610 assert_eq!(r.entries.len(), 1);
611 render_cell("baz", &mut r);
612 assert_eq!(r.entries.len(), 0);
616 fn test_render_leftovers() {
618 render_all_leftovers(&Row {
619 label: "nope".to_owned(),
620 entries: HashMap::from([("foo".to_owned(), vec![None])]),
625 render_all_leftovers(&Row {
626 label: "nope".to_owned(),
627 entries: HashMap::from([
628 ("foo".to_owned(), vec![None]),
629 ("bar".to_owned(), vec![None])
632 HTML::from("bar, foo")
635 render_all_leftovers(&Row {
636 label: "nope".to_owned(),
637 entries: HashMap::from([
638 ("foo".to_owned(), vec![None]),
639 ("bar".to_owned(), vec![None, None])
642 HTML::from("bar: 2, foo")
647 fn test_render_row() {
651 &mut Rowlike::Row(Row {
652 label: "nope".to_owned(),
653 entries: HashMap::from([("bar".to_owned(), vec![None])]),
657 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>