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.yes { border: thin solid gray; background-color: #ddd; }
27 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
28 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
31 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
32 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
33 function h2(a, b) { highlight(a); highlight(b); }
34 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
41 const FOOTER: &str = " </tbody>
46 #[derive(PartialEq, Eq, Debug)]
47 pub struct HTML(String);
49 fn escape(value: &str) -> HTML {
50 let mut escaped: String = String::new();
51 for c in value.chars() {
53 '>' => escaped.push_str(">"),
54 '<' => escaped.push_str("<"),
55 '\'' => escaped.push_str("'"),
56 '"' => escaped.push_str("""),
57 '&' => escaped.push_str("&"),
58 ok_c => escaped.push(ok_c),
64 impl From<&str> for HTML {
65 fn from(value: &str) -> HTML {
66 HTML(String::from(value))
69 impl FromIterator<HTML> for HTML {
70 fn from_iter<T>(iter: T) -> HTML
72 T: IntoIterator<Item = HTML>,
74 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
77 impl std::fmt::Display for HTML {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 write!(f, "{}", self.0)
83 #[derive(Debug, PartialEq, Eq)]
87 Entry(&'a str, Option<&'a str>),
89 impl<'a> From<&'a str> for InputLine<'a> {
90 fn from(value: &'a str) -> InputLine<'a> {
91 let trimmed = value.trim_end();
92 if trimmed.is_empty() {
94 } else if !trimmed.starts_with(' ') {
95 InputLine::RowHeader(value.trim())
97 match value.split_once(':') {
98 None => InputLine::Entry(value.trim(), None),
99 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
105 #[derive(Debug, PartialEq, Eq)]
108 entries: HashMap<String, Vec<Option<String>>>,
111 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
112 input: std::iter::Enumerate<Input>,
115 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
116 fn new(input: Input) -> Self {
118 input: input.enumerate(),
123 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
124 type Item = Result<Row, std::io::Error>;
125 fn next(&mut self) -> Option<Self::Item> {
127 match self.input.next() {
128 None => return Ok(std::mem::take(&mut self.row)).transpose(),
129 Some((_, Err(e))) => return Some(Err(e)),
130 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
131 InputLine::Blank if self.row.is_some() => {
132 return Ok(std::mem::take(&mut self.row)).transpose()
134 InputLine::Blank => {}
135 InputLine::Entry(col, instance) => match &mut self.row {
137 return Some(Err(std::io::Error::other(format!(
138 "{}: Entry with no header",
142 Some(ref mut row) => {
144 .entry(col.to_owned())
145 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
146 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
149 InputLine::RowHeader(row) => {
150 let prev = std::mem::take(&mut self.row);
151 self.row = Some(Row {
152 label: row.to_owned(),
153 entries: HashMap::new(),
156 return Ok(prev).transpose();
165 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<Row, std::io::Error>> {
166 Reader::new(std::io::BufReader::new(input).lines())
169 fn column_counts(rows: &[Row]) -> Vec<(usize, String)> {
170 let mut counts: Vec<_> = rows
172 .flat_map(|r| r.entries.keys())
173 .fold(HashMap::new(), |mut cs, col| {
174 cs.entry(col.to_owned())
175 .and_modify(|n| *n += 1)
180 .map(|(col, n)| (n, col))
182 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
185 fn column_order(config: &Config, rows: &[Row]) -> Vec<String> {
188 .filter_map(|(n, col)| (n >= config.column_threshold).then_some(col))
192 fn render_one_instance(instance: &Option<String>) -> HTML {
194 None => HTML::from("✓"),
195 Some(instance) => HTML::escape(instance.as_ref()),
199 fn render_instances(instances: &[Option<String>]) -> HTML {
200 let all_empty = instances.iter().all(Option::is_none);
201 if all_empty && instances.len() == 1 {
203 } else if all_empty {
204 HTML(format!("{}", instances.len()))
209 .map(render_one_instance)
210 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
217 fn render_cell(col: &str, row: &mut Row) -> HTML {
218 let row_label = HTML::escape(row.label.as_ref());
219 let col_label = HTML::escape(col);
220 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
221 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
222 let contents = match instances {
223 None => HTML::from(""),
224 Some(is) => render_instances(is),
226 row.entries.remove(col);
228 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
232 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
233 let label = HTML::escape(notcol);
234 let rest = render_instances(instances);
235 if rest == HTML::from("") {
236 HTML(format!("{label}"))
238 HTML(format!("{label}: {rest}"))
242 fn render_all_leftovers(row: &Row) -> HTML {
243 let mut order: Vec<_> = row.entries.keys().collect();
244 order.sort_unstable();
248 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
249 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
255 fn render_row(columns: &[String], row: &mut Row) -> HTML {
256 let row_label = HTML::escape(row.label.as_ref());
259 .map(|col| render_cell(col, row))
261 let leftovers = render_all_leftovers(row);
263 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}<td onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
267 fn render_column_headers(columns: &[String]) -> HTML {
269 String::from(r#"<tr class="key"><th></th>"#)
270 + &columns.iter().fold(String::new(), |mut acc, col| {
271 let col_header = HTML::escape(col.as_ref());
274 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
285 /// Will return `Err` if
286 /// * there's an i/o error while reading `input`
287 /// * the log has invalid syntax:
288 /// * an indented line with no preceding non-indented line
289 pub fn tablify(config: &Config, input: impl std::io::Read) -> Result<HTML, std::io::Error> {
290 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
291 let columns = column_order(config, &rows);
293 "{HEADER}{}{}{FOOTER}",
294 render_column_headers(&columns),
296 .map(|mut r| render_row(&columns, &mut r))
306 fn test_parse_line() {
307 assert_eq!(InputLine::from(""), InputLine::Blank);
308 assert_eq!(InputLine::from(" "), InputLine::Blank);
309 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
310 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
311 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
313 InputLine::from(" foo:bar"),
314 InputLine::Entry("foo", Some("bar"))
317 InputLine::from(" foo: bar"),
318 InputLine::Entry("foo", Some("bar"))
321 InputLine::from(" foo: bar "),
322 InputLine::Entry("foo", Some("bar"))
325 InputLine::from(" foo: bar "),
326 InputLine::Entry("foo", Some("bar"))
329 InputLine::from(" foo : bar "),
330 InputLine::Entry("foo", Some("bar"))
335 fn test_read_rows() {
337 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
339 label: "foo".to_owned(),
340 entries: HashMap::new(),
344 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
346 label: "bar".to_owned(),
347 entries: HashMap::new(),
351 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
354 label: "foo".to_owned(),
355 entries: HashMap::new(),
358 label: "bar".to_owned(),
359 entries: HashMap::new(),
364 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
366 label: "foo".to_owned(),
367 entries: HashMap::from([("bar".to_owned(), vec![None])]),
371 read_rows(&b"foo\n bar\n baz\n"[..])
373 .collect::<Vec<_>>(),
375 label: "foo".to_owned(),
376 entries: HashMap::from([
377 ("bar".to_owned(), vec![None]),
378 ("baz".to_owned(), vec![None])
383 read_rows(&b"foo\n\nbar\n"[..])
385 .collect::<Vec<_>>(),
388 label: "foo".to_owned(),
389 entries: HashMap::new(),
392 label: "bar".to_owned(),
393 entries: HashMap::new(),
398 read_rows(&b"foo\n \nbar\n"[..])
400 .collect::<Vec<_>>(),
403 label: "foo".to_owned(),
404 entries: HashMap::new(),
407 label: "bar".to_owned(),
408 entries: HashMap::new(),
413 read_rows(&b"foo \n bar \n"[..])
415 .collect::<Vec<_>>(),
417 label: "foo".to_owned(),
418 entries: HashMap::from([("bar".to_owned(), vec![None])]),
422 let bad = read_rows(&b" foo"[..]).next().unwrap();
423 assert!(bad.is_err());
424 assert!(format!("{bad:?}").contains("1: Entry with no header"));
426 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
427 assert!(bad2.is_err());
428 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
432 fn test_column_counts() {
435 &read_rows(&b"foo\n bar\n baz\n"[..])
436 .collect::<Result<Vec<_>, _>>()
439 vec![(1, String::from("bar")), (1, String::from("baz"))]
443 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
444 .collect::<Result<Vec<_>, _>>()
447 vec![(2, String::from("baz")), (1, String::from("bar"))]
451 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
452 .collect::<Result<Vec<_>, _>>()
455 vec![(2, String::from("baz")), (1, String::from("bar"))]
459 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
460 .collect::<Result<Vec<_>, _>>()
463 vec![(2, String::from("baz")), (1, String::from("bar"))]
468 fn test_render_cell() {
473 label: "nope".to_owned(),
474 entries: HashMap::new(),
478 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
485 label: "nope".to_owned(),
486 entries: HashMap::from([("bar".to_owned(), vec![None])]),
490 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
497 label: "nope".to_owned(),
498 entries: HashMap::from([("foo".to_owned(), vec![None])]),
502 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
509 label: "nope".to_owned(),
510 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
514 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
521 label: "nope".to_owned(),
522 entries: HashMap::from([(
524 vec![Some("5".to_owned()), Some("10".to_owned())]
529 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
536 label: "nope".to_owned(),
537 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
541 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
548 label: "nope".to_owned(),
549 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
553 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
560 label: "bob's".to_owned(),
561 entries: HashMap::from([("foo".to_owned(), vec![None])]),
565 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
569 label: "nope".to_owned(),
570 entries: HashMap::from([
571 ("foo".to_owned(), vec![None]),
572 ("baz".to_owned(), vec![None]),
575 assert_eq!(r.entries.len(), 2);
576 render_cell("foo", &mut r);
577 assert_eq!(r.entries.len(), 1);
578 render_cell("bar", &mut r);
579 assert_eq!(r.entries.len(), 1);
580 render_cell("baz", &mut r);
581 assert_eq!(r.entries.len(), 0);
585 fn test_render_leftovers() {
587 render_all_leftovers(&Row {
588 label: "nope".to_owned(),
589 entries: HashMap::from([("foo".to_owned(), vec![None])]),
594 render_all_leftovers(&Row {
595 label: "nope".to_owned(),
596 entries: HashMap::from([
597 ("foo".to_owned(), vec![None]),
598 ("bar".to_owned(), vec![None])
601 HTML::from("bar, foo")
604 render_all_leftovers(&Row {
605 label: "nope".to_owned(),
606 entries: HashMap::from([
607 ("foo".to_owned(), vec![None]),
608 ("bar".to_owned(), vec![None, None])
611 HTML::from("bar: 2, foo")
616 fn test_render_row() {
621 label: "nope".to_owned(),
622 entries: HashMap::from([("bar".to_owned(), vec![None])]),
626 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>