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, line_num: usize, cmd: &str) -> Result<(), std::io::Error> {
14 if let Some(threshold) = cmd.strip_prefix("col_threshold ") {
15 self.column_threshold = threshold.parse().map_err(|e| {
17 std::io::ErrorKind::InvalidInput,
18 format!("line {line_num}: col_threshold must be numeric: {e}"),
21 } else if let Some(col) = cmd.strip_prefix("col ") {
22 self.static_columns.push(col.to_owned());
24 return Err(std::io::Error::new(
25 std::io::ErrorKind::InvalidInput,
26 format!("line {line_num}: Unknown command: {cmd}"),
33 const HEADER: &str = r#"<!DOCTYPE html>
36 <meta charset="utf-8">
37 <meta name="viewport" content="width=device-width, initial-scale=1">
39 td { text-align: center; }
40 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
41 th, td { white-space: nowrap; }
42 th { text-align: left; font-weight: normal; }
43 th.spacer_row { height: .3em; }
44 table { border-collapse: collapse }
45 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
46 tr.key > th > div { width: 1em; }
47 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
48 td { border: thin solid gray; }
49 td.leftover { text-align: left; border: none; padding-left: .4em; }
50 td.yes { border: thin solid gray; background-color: #ddd; }
51 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
52 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
55 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
56 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
57 function h2(a, b) { highlight(a); highlight(b); }
58 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
65 const FOOTER: &str = " </tbody>
70 #[derive(PartialEq, Eq, Debug)]
71 pub struct HTML(String);
73 fn escape(value: &str) -> HTML {
74 let mut escaped: String = String::new();
75 for c in value.chars() {
77 '>' => escaped.push_str(">"),
78 '<' => escaped.push_str("<"),
79 '\'' => escaped.push_str("'"),
80 '"' => escaped.push_str("""),
81 '&' => escaped.push_str("&"),
82 ok_c => escaped.push(ok_c),
88 impl From<&str> for HTML {
89 fn from(value: &str) -> HTML {
90 HTML(String::from(value))
93 impl FromIterator<HTML> for HTML {
94 fn from_iter<T>(iter: T) -> HTML
96 T: IntoIterator<Item = HTML>,
98 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
101 impl std::fmt::Display for HTML {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 write!(f, "{}", self.0)
107 #[derive(Debug, PartialEq, Eq)]
111 Entry(&'a str, Option<&'a str>),
114 impl<'a> From<&'a str> for InputLine<'a> {
115 fn from(value: &'a str) -> InputLine<'a> {
116 let trimmed = value.trim_end();
117 if trimmed.is_empty() {
119 } else if let Some(cmd) = trimmed.strip_prefix('!') {
120 InputLine::Command(cmd)
121 } else if !trimmed.starts_with(' ') {
122 InputLine::RowHeader(value.trim())
124 match value.split_once(':') {
125 None => InputLine::Entry(value.trim(), None),
126 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
132 #[derive(Debug, PartialEq, Eq)]
135 entries: HashMap<String, Vec<Option<String>>>,
138 #[derive(Debug, PartialEq, Eq)]
144 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
145 input: std::iter::Enumerate<Input>,
147 config: &'cfg mut Config,
149 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
150 fn new(config: &'cfg mut Config, input: Input) -> Self {
152 input: input.enumerate(),
158 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
159 for Reader<'cfg, Input>
161 type Item = Result<Rowlike, std::io::Error>;
162 fn next(&mut self) -> Option<Self::Item> {
164 match self.input.next() {
165 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
166 Some((_, Err(e))) => return Some(Err(e)),
167 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
168 InputLine::Command(cmd) => {
169 if let Err(e) = self.config.apply_command(n + 1, cmd) {
173 InputLine::Blank if self.row.is_some() => {
174 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
176 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
177 InputLine::Entry(col, instance) => match &mut self.row {
179 return Some(Err(std::io::Error::other(format!(
180 "line {}: Entry with no header",
184 Some(ref mut row) => {
186 .entry(col.to_owned())
187 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
188 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
191 InputLine::RowHeader(row) => {
192 let prev = std::mem::take(&mut self.row);
193 self.row = Some(Row {
194 label: row.to_owned(),
195 entries: HashMap::new(),
198 return Ok(prev.map(Rowlike::Row)).transpose();
207 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
208 let mut config = Config {
210 static_columns: vec![],
212 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
214 .collect::<Result<Vec<_>, _>>()
215 .map(|rows| (rows, config))
218 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
219 let empty = HashMap::new();
220 let mut counts: Vec<_> = rows
222 .flat_map(|rl| match rl {
223 Rowlike::Row(r) => r.entries.keys(),
224 Rowlike::Spacer => empty.keys(),
226 .fold(HashMap::new(), |mut cs, col| {
227 cs.entry(col.to_owned())
228 .and_modify(|n| *n += 1)
233 .map(|(col, n)| (n, col))
235 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
238 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
239 let static_columns: HashSet<&str> = config
242 .map(std::string::String::as_str)
246 .filter_map(|(n, col)| {
247 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
252 fn render_one_instance(instance: &Option<String>) -> HTML {
254 None => HTML::from("✓"),
255 Some(instance) => HTML::escape(instance.as_ref()),
259 fn render_instances(instances: &[Option<String>]) -> HTML {
260 let all_empty = instances.iter().all(Option::is_none);
261 if all_empty && instances.len() == 1 {
263 } else if all_empty {
264 HTML(format!("{}", instances.len()))
269 .map(render_one_instance)
270 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
277 fn render_cell(col: &str, row: &mut Row) -> HTML {
278 let row_label = HTML::escape(row.label.as_ref());
279 let col_label = HTML::escape(col);
280 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
281 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
282 let contents = match instances {
283 None => HTML::from(""),
284 Some(is) => render_instances(is),
286 row.entries.remove(col);
288 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
292 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
293 let label = HTML::escape(notcol);
294 let rest = render_instances(instances);
295 if rest == HTML::from("") {
296 HTML(format!("{label}"))
298 HTML(format!("{label}: {rest}"))
302 fn render_all_leftovers(row: &Row) -> HTML {
303 let mut order: Vec<_> = row.entries.keys().collect();
304 order.sort_unstable();
308 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
309 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
315 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
317 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
318 Rowlike::Row(row) => {
319 let row_label = HTML::escape(row.label.as_ref());
320 let static_cells = config
323 .map(|col| render_cell(col, row))
325 let dynamic_cells = columns
327 .map(|col| render_cell(col, row))
329 let leftovers = render_all_leftovers(row);
331 "<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"
337 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
339 String::from(r#"<tr class="key"><th></th>"#)
340 + &config.static_columns.iter().chain(columns.iter()).fold(
343 let col_header = HTML::escape(col.as_ref());
346 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
358 /// Will return `Err` if
359 /// * there's an i/o error while reading `input`
360 /// * the log has invalid syntax:
361 /// * an indented line with no preceding non-indented line
362 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
363 let (rows, config) = read_input(input)?;
364 let columns = column_order(&config, &rows);
366 "{HEADER}{}{}{FOOTER}",
367 render_column_headers(&config, &columns),
369 .map(|mut r| render_row(&config, &columns, &mut r))
379 fn test_parse_line() {
380 assert_eq!(InputLine::from(""), InputLine::Blank);
381 assert_eq!(InputLine::from(" "), InputLine::Blank);
382 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
383 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
384 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
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"))
398 InputLine::from(" foo: bar "),
399 InputLine::Entry("foo", Some("bar"))
402 InputLine::from(" foo : bar "),
403 InputLine::Entry("foo", Some("bar"))
407 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
408 read_input(input).map(|(rows, _)| rows)
410 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
411 read_input(input).map(|(_, config)| config)
414 fn test_read_rows() {
416 read_rows(&b"foo"[..]).unwrap(),
417 vec![Rowlike::Row(Row {
418 label: "foo".to_owned(),
419 entries: HashMap::new(),
423 read_rows(&b"bar"[..]).unwrap(),
424 vec![Rowlike::Row(Row {
425 label: "bar".to_owned(),
426 entries: HashMap::new(),
430 read_rows(&b"foo\nbar\n"[..]).unwrap(),
433 label: "foo".to_owned(),
434 entries: HashMap::new(),
437 label: "bar".to_owned(),
438 entries: HashMap::new(),
443 read_rows(&b"foo\n bar\n"[..]).unwrap(),
444 vec![Rowlike::Row(Row {
445 label: "foo".to_owned(),
446 entries: HashMap::from([("bar".to_owned(), vec![None])]),
450 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
451 vec![Rowlike::Row(Row {
452 label: "foo".to_owned(),
453 entries: HashMap::from([
454 ("bar".to_owned(), vec![None]),
455 ("baz".to_owned(), vec![None])
460 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
463 label: "foo".to_owned(),
464 entries: HashMap::new(),
467 label: "bar".to_owned(),
468 entries: HashMap::new(),
473 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
476 label: "foo".to_owned(),
477 entries: HashMap::new(),
481 label: "bar".to_owned(),
482 entries: HashMap::new(),
487 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
490 label: "foo".to_owned(),
491 entries: HashMap::new(),
494 label: "bar".to_owned(),
495 entries: HashMap::new(),
500 read_rows(&b"foo \n bar \n"[..]).unwrap(),
501 vec![Rowlike::Row(Row {
502 label: "foo".to_owned(),
503 entries: HashMap::from([("bar".to_owned(), vec![None])]),
507 let bad = read_rows(&b" foo"[..]);
508 assert!(bad.is_err());
509 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
511 let bad2 = read_rows(&b"foo\n\n bar"[..]);
512 assert!(bad2.is_err());
513 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
517 fn test_read_config() {
519 read_config(&b"!col_threshold 10"[..])
525 read_config(&b"!col foo"[..]).unwrap().static_columns,
526 vec!["foo".to_owned()]
529 let bad_command = read_config(&b"!no such command"[..]);
530 assert!(bad_command.is_err());
531 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
533 let bad_num = read_config(&b"!col_threshold foo"[..]);
534 assert!(bad_num.is_err());
535 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
539 fn test_column_counts() {
541 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
542 vec![(1, String::from("bar")), (1, String::from("baz"))]
545 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
546 vec![(2, String::from("baz")), (1, String::from("bar"))]
549 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
550 vec![(2, String::from("baz")), (1, String::from("bar"))]
554 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
556 vec![(2, String::from("baz")), (1, String::from("bar"))]
561 fn test_render_cell() {
566 label: "nope".to_owned(),
567 entries: HashMap::new(),
571 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
578 label: "nope".to_owned(),
579 entries: HashMap::from([("bar".to_owned(), vec![None])]),
583 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
590 label: "nope".to_owned(),
591 entries: HashMap::from([("foo".to_owned(), vec![None])]),
595 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
602 label: "nope".to_owned(),
603 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
607 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
614 label: "nope".to_owned(),
615 entries: HashMap::from([(
617 vec![Some("5".to_owned()), Some("10".to_owned())]
622 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
629 label: "nope".to_owned(),
630 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
634 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
641 label: "nope".to_owned(),
642 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
646 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
653 label: "bob's".to_owned(),
654 entries: HashMap::from([("foo".to_owned(), vec![None])]),
658 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
662 label: "nope".to_owned(),
663 entries: HashMap::from([
664 ("foo".to_owned(), vec![None]),
665 ("baz".to_owned(), vec![None]),
668 assert_eq!(r.entries.len(), 2);
669 render_cell("foo", &mut r);
670 assert_eq!(r.entries.len(), 1);
671 render_cell("bar", &mut r);
672 assert_eq!(r.entries.len(), 1);
673 render_cell("baz", &mut r);
674 assert_eq!(r.entries.len(), 0);
678 fn test_render_leftovers() {
680 render_all_leftovers(&Row {
681 label: "nope".to_owned(),
682 entries: HashMap::from([("foo".to_owned(), vec![None])]),
687 render_all_leftovers(&Row {
688 label: "nope".to_owned(),
689 entries: HashMap::from([
690 ("foo".to_owned(), vec![None]),
691 ("bar".to_owned(), vec![None])
694 HTML::from("bar, foo")
697 render_all_leftovers(&Row {
698 label: "nope".to_owned(),
699 entries: HashMap::from([
700 ("foo".to_owned(), vec![None]),
701 ("bar".to_owned(), vec![None, None])
704 HTML::from("bar: 2, foo")
709 fn test_render_row() {
714 static_columns: vec![],
717 &mut Rowlike::Row(Row {
718 label: "nope".to_owned(),
719 entries: HashMap::from([("bar".to_owned(), vec![None])]),
723 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>
731 static_columns: vec!["foo".to_owned(), "bar".to_owned()],
734 &mut Rowlike::Row(Row {
735 label: "nope".to_owned(),
736 entries: HashMap::from([
737 ("bar".to_owned(), vec![Some("r".to_owned())]),
738 ("baz".to_owned(), vec![Some("z".to_owned())]),
739 ("foo".to_owned(), vec![Some("f".to_owned())]),
744 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>