1 use std::borrow::ToOwned;
2 use std::collections::{HashMap, HashSet};
5 use std::iter::Iterator;
7 #[derive(PartialEq, Eq, Debug)]
9 column_threshold: usize,
10 static_columns: Vec<String>,
13 fn apply_command(&mut self, cmd: &str) -> Result<(), std::io::Error> {
14 if let Some(threshold) = cmd.strip_prefix("col_threshold ") {
15 self.column_threshold = threshold
17 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
18 } else if let Some(col) = cmd.strip_prefix("col ") {
19 self.static_columns.push(col.to_owned());
25 const HEADER: &str = r#"<!DOCTYPE html>
28 <meta charset="utf-8">
29 <meta name="viewport" content="width=device-width, initial-scale=1">
31 td { text-align: center; }
32 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
33 th, td { white-space: nowrap; }
34 th { text-align: left; font-weight: normal; }
35 th.spacer_row { height: .3em; }
36 table { border-collapse: collapse }
37 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
38 tr.key > th > div { width: 1em; }
39 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
40 td { border: thin solid gray; }
41 td.leftover { text-align: left; border: none; padding-left: .4em; }
42 td.yes { border: thin solid gray; background-color: #ddd; }
43 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
44 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
47 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
48 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
49 function h2(a, b) { highlight(a); highlight(b); }
50 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
57 const FOOTER: &str = " </tbody>
62 #[derive(PartialEq, Eq, Debug)]
63 pub struct HTML(String);
65 fn escape(value: &str) -> HTML {
66 let mut escaped: String = String::new();
67 for c in value.chars() {
69 '>' => escaped.push_str(">"),
70 '<' => escaped.push_str("<"),
71 '\'' => escaped.push_str("'"),
72 '"' => escaped.push_str("""),
73 '&' => escaped.push_str("&"),
74 ok_c => escaped.push(ok_c),
80 impl From<&str> for HTML {
81 fn from(value: &str) -> HTML {
82 HTML(String::from(value))
85 impl FromIterator<HTML> for HTML {
86 fn from_iter<T>(iter: T) -> HTML
88 T: IntoIterator<Item = HTML>,
90 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
93 impl std::fmt::Display for HTML {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 write!(f, "{}", self.0)
99 #[derive(Debug, PartialEq, Eq)]
103 Entry(&'a str, Option<&'a str>),
106 impl<'a> From<&'a str> for InputLine<'a> {
107 fn from(value: &'a str) -> InputLine<'a> {
108 let trimmed = value.trim_end();
109 if trimmed.is_empty() {
111 } else if let Some(cmd) = trimmed.strip_prefix('!') {
112 InputLine::Command(cmd)
113 } else if !trimmed.starts_with(' ') {
114 InputLine::RowHeader(value.trim())
116 match value.split_once(':') {
117 None => InputLine::Entry(value.trim(), None),
118 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
124 #[derive(Debug, PartialEq, Eq)]
127 entries: HashMap<String, Vec<Option<String>>>,
130 #[derive(Debug, PartialEq, Eq)]
136 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
137 input: std::iter::Enumerate<Input>,
139 config: &'cfg mut Config,
141 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
142 fn new(config: &'cfg mut Config, input: Input) -> Self {
144 input: input.enumerate(),
150 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
151 for Reader<'cfg, Input>
153 type Item = Result<Rowlike, std::io::Error>;
154 fn next(&mut self) -> Option<Self::Item> {
156 match self.input.next() {
157 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
158 Some((_, Err(e))) => return Some(Err(e)),
159 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
160 InputLine::Command(cmd) => {
161 if let Err(e) = self.config.apply_command(cmd) {
165 InputLine::Blank if self.row.is_some() => {
166 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
168 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
169 InputLine::Entry(col, instance) => match &mut self.row {
171 return Some(Err(std::io::Error::other(format!(
172 "{}: Entry with no header",
176 Some(ref mut row) => {
178 .entry(col.to_owned())
179 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
180 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
183 InputLine::RowHeader(row) => {
184 let prev = std::mem::take(&mut self.row);
185 self.row = Some(Row {
186 label: row.to_owned(),
187 entries: HashMap::new(),
190 return Ok(prev.map(Rowlike::Row)).transpose();
199 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
200 let mut config = Config {
202 static_columns: vec![],
204 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
206 .collect::<Result<Vec<_>, _>>()
207 .map(|rows| (rows, config))
210 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
211 let empty = HashMap::new();
212 let mut counts: Vec<_> = rows
214 .flat_map(|rl| match rl {
215 Rowlike::Row(r) => r.entries.keys(),
216 Rowlike::Spacer => empty.keys(),
218 .fold(HashMap::new(), |mut cs, col| {
219 cs.entry(col.to_owned())
220 .and_modify(|n| *n += 1)
225 .map(|(col, n)| (n, col))
227 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
230 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
231 let static_columns: HashSet<&str> = config
234 .map(std::string::String::as_str)
238 .filter_map(|(n, col)| {
239 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
244 fn render_one_instance(instance: &Option<String>) -> HTML {
246 None => HTML::from("✓"),
247 Some(instance) => HTML::escape(instance.as_ref()),
251 fn render_instances(instances: &[Option<String>]) -> HTML {
252 let all_empty = instances.iter().all(Option::is_none);
253 if all_empty && instances.len() == 1 {
255 } else if all_empty {
256 HTML(format!("{}", instances.len()))
261 .map(render_one_instance)
262 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
269 fn render_cell(col: &str, row: &mut Row) -> HTML {
270 let row_label = HTML::escape(row.label.as_ref());
271 let col_label = HTML::escape(col);
272 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
273 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
274 let contents = match instances {
275 None => HTML::from(""),
276 Some(is) => render_instances(is),
278 row.entries.remove(col);
280 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
284 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
285 let label = HTML::escape(notcol);
286 let rest = render_instances(instances);
287 if rest == HTML::from("") {
288 HTML(format!("{label}"))
290 HTML(format!("{label}: {rest}"))
294 fn render_all_leftovers(row: &Row) -> HTML {
295 let mut order: Vec<_> = row.entries.keys().collect();
296 order.sort_unstable();
300 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
301 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
307 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
309 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
310 Rowlike::Row(row) => {
311 let row_label = HTML::escape(row.label.as_ref());
312 let static_cells = config
315 .map(|col| render_cell(col, row))
317 let dynamic_cells = columns
319 .map(|col| render_cell(col, row))
321 let leftovers = render_all_leftovers(row);
323 "<tr><th id=\"{row_label}\">{row_label}</th>{static_cells}{dynamic_cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
329 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
331 String::from(r#"<tr class="key"><th></th>"#)
332 + &config.static_columns.iter().chain(columns.iter()).fold(
335 let col_header = HTML::escape(col.as_ref());
338 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
350 /// Will return `Err` if
351 /// * there's an i/o error while reading `input`
352 /// * the log has invalid syntax:
353 /// * an indented line with no preceding non-indented line
354 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
355 let (rows, config) = read_input(input)?;
356 let columns = column_order(&config, &rows);
358 "{HEADER}{}{}{FOOTER}",
359 render_column_headers(&config, &columns),
361 .map(|mut r| render_row(&config, &columns, &mut r))
371 fn test_parse_line() {
372 assert_eq!(InputLine::from(""), InputLine::Blank);
373 assert_eq!(InputLine::from(" "), InputLine::Blank);
374 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
375 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
376 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
378 InputLine::from(" foo:bar"),
379 InputLine::Entry("foo", Some("bar"))
382 InputLine::from(" foo: bar"),
383 InputLine::Entry("foo", Some("bar"))
386 InputLine::from(" foo: bar "),
387 InputLine::Entry("foo", Some("bar"))
390 InputLine::from(" foo: bar "),
391 InputLine::Entry("foo", Some("bar"))
394 InputLine::from(" foo : bar "),
395 InputLine::Entry("foo", Some("bar"))
399 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
400 read_input(input).map(|(rows, _)| rows)
402 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
403 read_input(input).map(|(_, config)| config)
406 fn test_read_rows() {
408 read_rows(&b"foo"[..]).unwrap(),
409 vec![Rowlike::Row(Row {
410 label: "foo".to_owned(),
411 entries: HashMap::new(),
415 read_rows(&b"bar"[..]).unwrap(),
416 vec![Rowlike::Row(Row {
417 label: "bar".to_owned(),
418 entries: HashMap::new(),
422 read_rows(&b"foo\nbar\n"[..]).unwrap(),
425 label: "foo".to_owned(),
426 entries: HashMap::new(),
429 label: "bar".to_owned(),
430 entries: HashMap::new(),
435 read_rows(&b"foo\n bar\n"[..]).unwrap(),
436 vec![Rowlike::Row(Row {
437 label: "foo".to_owned(),
438 entries: HashMap::from([("bar".to_owned(), vec![None])]),
442 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
443 vec![Rowlike::Row(Row {
444 label: "foo".to_owned(),
445 entries: HashMap::from([
446 ("bar".to_owned(), vec![None]),
447 ("baz".to_owned(), vec![None])
452 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
455 label: "foo".to_owned(),
456 entries: HashMap::new(),
459 label: "bar".to_owned(),
460 entries: HashMap::new(),
465 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
468 label: "foo".to_owned(),
469 entries: HashMap::new(),
473 label: "bar".to_owned(),
474 entries: HashMap::new(),
479 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
482 label: "foo".to_owned(),
483 entries: HashMap::new(),
486 label: "bar".to_owned(),
487 entries: HashMap::new(),
492 read_rows(&b"foo \n bar \n"[..]).unwrap(),
493 vec![Rowlike::Row(Row {
494 label: "foo".to_owned(),
495 entries: HashMap::from([("bar".to_owned(), vec![None])]),
499 let bad = read_rows(&b" foo"[..]);
500 assert!(bad.is_err());
501 assert!(format!("{bad:?}").contains("1: Entry with no header"));
503 let bad2 = read_rows(&b"foo\n\n bar"[..]);
504 assert!(bad2.is_err());
505 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
509 fn test_read_config() {
511 read_config(&b"!col_threshold 10"[..])
517 read_config(&b"!col foo"[..]).unwrap().static_columns,
518 vec!["foo".to_owned()]
521 let bad_num = read_config(&b"!col_threshold foo"[..]);
522 assert!(bad_num.is_err());
523 assert!(format!("{bad_num:?}").contains("Parse"));
527 fn test_column_counts() {
529 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
530 vec![(1, String::from("bar")), (1, String::from("baz"))]
533 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
534 vec![(2, String::from("baz")), (1, String::from("bar"))]
537 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
538 vec![(2, String::from("baz")), (1, String::from("bar"))]
542 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
544 vec![(2, String::from("baz")), (1, String::from("bar"))]
549 fn test_render_cell() {
554 label: "nope".to_owned(),
555 entries: HashMap::new(),
559 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
566 label: "nope".to_owned(),
567 entries: HashMap::from([("bar".to_owned(), vec![None])]),
571 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
578 label: "nope".to_owned(),
579 entries: HashMap::from([("foo".to_owned(), vec![None])]),
583 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
590 label: "nope".to_owned(),
591 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
595 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
602 label: "nope".to_owned(),
603 entries: HashMap::from([(
605 vec![Some("5".to_owned()), Some("10".to_owned())]
610 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
617 label: "nope".to_owned(),
618 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
622 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
629 label: "nope".to_owned(),
630 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
634 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
641 label: "bob's".to_owned(),
642 entries: HashMap::from([("foo".to_owned(), vec![None])]),
646 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
650 label: "nope".to_owned(),
651 entries: HashMap::from([
652 ("foo".to_owned(), vec![None]),
653 ("baz".to_owned(), vec![None]),
656 assert_eq!(r.entries.len(), 2);
657 render_cell("foo", &mut r);
658 assert_eq!(r.entries.len(), 1);
659 render_cell("bar", &mut r);
660 assert_eq!(r.entries.len(), 1);
661 render_cell("baz", &mut r);
662 assert_eq!(r.entries.len(), 0);
666 fn test_render_leftovers() {
668 render_all_leftovers(&Row {
669 label: "nope".to_owned(),
670 entries: HashMap::from([("foo".to_owned(), vec![None])]),
675 render_all_leftovers(&Row {
676 label: "nope".to_owned(),
677 entries: HashMap::from([
678 ("foo".to_owned(), vec![None]),
679 ("bar".to_owned(), vec![None])
682 HTML::from("bar, foo")
685 render_all_leftovers(&Row {
686 label: "nope".to_owned(),
687 entries: HashMap::from([
688 ("foo".to_owned(), vec![None]),
689 ("bar".to_owned(), vec![None, None])
692 HTML::from("bar: 2, foo")
697 fn test_render_row() {
702 static_columns: vec![],
705 &mut Rowlike::Row(Row {
706 label: "nope".to_owned(),
707 entries: HashMap::from([("bar".to_owned(), vec![None])]),
711 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>
719 static_columns: vec!["foo".to_owned(), "bar".to_owned()],
722 &mut Rowlike::Row(Row {
723 label: "nope".to_owned(),
724 entries: HashMap::from([
725 ("bar".to_owned(), vec![Some("r".to_owned())]),
726 ("baz".to_owned(), vec![Some("z".to_owned())]),
727 ("foo".to_owned(), vec![Some("f".to_owned())]),
732 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="yes" onmouseover="h2('nope','baz')" onmouseout="ch2('nope','baz')">z</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>