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<Option<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(Some(col.to_owned()));
23 } else if cmd == "colsep" {
24 self.static_columns.push(None);
26 return Err(std::io::Error::new(
27 std::io::ErrorKind::InvalidInput,
28 format!("line {line_num}: Unknown command: {cmd}"),
35 const DEFAULT_CONFIG: Config = Config {
37 static_columns: vec![],
40 const HEADER: &str = r#"<!DOCTYPE html>
43 <meta charset="utf-8">
44 <meta name="viewport" content="width=device-width, initial-scale=1">
46 td { text-align: center; }
47 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
48 th, td { white-space: nowrap; }
49 th { text-align: left; font-weight: normal; }
50 th.spacer_row { height: .3em; }
51 .spacer_col { border: none; width: .2em; }
52 table { border-collapse: collapse }
53 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
54 tr.key > th > div { width: 1em; }
55 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
56 td { border: thin solid gray; }
57 td.leftover { text-align: left; border: none; padding-left: .4em; }
58 td.yes { border: thin solid gray; background-color: #ddd; }
59 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
60 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
63 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
64 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
65 function h2(a, b) { highlight(a); highlight(b); }
66 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
73 const FOOTER: &str = " </tbody>
78 #[derive(PartialEq, Eq, Debug)]
79 pub struct HTML(String);
81 fn escape(value: &str) -> HTML {
82 let mut escaped: String = String::new();
83 for c in value.chars() {
85 '>' => escaped.push_str(">"),
86 '<' => escaped.push_str("<"),
87 '\'' => escaped.push_str("'"),
88 '"' => escaped.push_str("""),
89 '&' => escaped.push_str("&"),
90 ok_c => escaped.push(ok_c),
96 impl From<&str> for HTML {
97 fn from(value: &str) -> HTML {
98 HTML(String::from(value))
101 impl FromIterator<HTML> for HTML {
102 fn from_iter<T>(iter: T) -> HTML
104 T: IntoIterator<Item = HTML>,
106 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
109 impl std::fmt::Display for HTML {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 write!(f, "{}", self.0)
115 #[derive(Debug, PartialEq, Eq)]
119 Entry(&'a str, Option<&'a str>),
122 impl<'a> From<&'a str> for InputLine<'a> {
123 fn from(value: &'a str) -> InputLine<'a> {
124 let trimmed = value.trim_end();
125 if trimmed.is_empty() {
127 } else if let Some(cmd) = trimmed.strip_prefix('!') {
128 InputLine::Command(cmd)
129 } else if !trimmed.starts_with(' ') {
130 InputLine::RowHeader(value.trim())
132 match value.split_once(':') {
133 None => InputLine::Entry(value.trim(), None),
134 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
140 #[derive(Debug, PartialEq, Eq)]
143 entries: HashMap<String, Vec<Option<String>>>,
146 #[derive(Debug, PartialEq, Eq)]
152 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
153 input: std::iter::Enumerate<Input>,
155 config: &'cfg mut Config,
157 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
158 fn new(config: &'cfg mut Config, input: Input) -> Self {
160 input: input.enumerate(),
166 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
167 for Reader<'cfg, Input>
169 type Item = Result<Rowlike, std::io::Error>;
170 fn next(&mut self) -> Option<Self::Item> {
172 match self.input.next() {
173 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
174 Some((_, Err(e))) => return Some(Err(e)),
175 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
176 InputLine::Command(cmd) => {
177 if let Err(e) = self.config.apply_command(n + 1, cmd) {
181 InputLine::Blank if self.row.is_some() => {
182 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
184 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
185 InputLine::Entry(col, instance) => match &mut self.row {
187 return Some(Err(std::io::Error::other(format!(
188 "line {}: Entry with no header",
192 Some(ref mut row) => {
194 .entry(col.to_owned())
195 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
196 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
199 InputLine::RowHeader(row) => {
200 let prev = std::mem::take(&mut self.row);
201 self.row = Some(Row {
202 label: row.to_owned(),
203 entries: HashMap::new(),
206 return Ok(prev.map(Rowlike::Row)).transpose();
215 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
216 let mut config = DEFAULT_CONFIG;
217 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
219 .collect::<Result<Vec<_>, _>>()
220 .map(|rows| (rows, config))
223 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
224 let empty = HashMap::new();
225 let mut counts: Vec<_> = rows
227 .flat_map(|rl| match rl {
228 Rowlike::Row(r) => r.entries.keys(),
229 Rowlike::Spacer => empty.keys(),
231 .fold(HashMap::new(), |mut cs, col| {
232 cs.entry(col.to_owned())
233 .and_modify(|n| *n += 1)
238 .map(|(col, n)| (n, col))
240 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
243 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
244 let static_columns: HashSet<&str> = config
248 .map(std::string::String::as_str)
252 .filter_map(|(n, col)| {
253 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
258 fn render_one_instance(instance: &Option<String>) -> HTML {
260 None => HTML::from("✓"),
261 Some(instance) => HTML::escape(instance.as_ref()),
265 fn render_instances(instances: &[Option<String>]) -> HTML {
266 let all_empty = instances.iter().all(Option::is_none);
267 if all_empty && instances.len() == 1 {
269 } else if all_empty {
270 HTML(format!("{}", instances.len()))
275 .map(render_one_instance)
276 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
283 fn render_cell(col: &str, row: &mut Row) -> HTML {
284 let row_label = HTML::escape(row.label.as_ref());
285 let col_label = HTML::escape(col);
286 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
287 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
288 let contents = match instances {
289 None => HTML::from(""),
290 Some(is) => render_instances(is),
292 row.entries.remove(col);
294 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
298 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
299 let label = HTML::escape(notcol);
300 let rest = render_instances(instances);
301 if rest == HTML::from("") {
302 HTML(format!("{label}"))
304 HTML(format!("{label}: {rest}"))
308 fn render_all_leftovers(row: &Row) -> HTML {
309 let mut order: Vec<_> = row.entries.keys().collect();
310 order.sort_unstable();
314 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
315 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
321 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
323 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
324 Rowlike::Row(row) => {
325 let row_label = HTML::escape(row.label.as_ref());
326 let static_cells = config
329 .map(|ocol| match ocol {
330 Some(col) => render_cell(col, row),
331 None => HTML::from(r#"<td class="spacer_col"></td>"#),
334 let dynamic_cells = columns
336 .map(|col| render_cell(col, row))
338 let leftovers = render_all_leftovers(row);
340 "<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"
346 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
347 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
348 let dynamic_columns = columns.iter().map(Some);
350 String::from(r#"<tr class="key"><th></th>"#)
352 .chain(dynamic_columns)
353 .fold(String::new(), |mut acc, ocol| {
356 let col_header = HTML::escape(col);
359 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
362 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
373 /// Will return `Err` if
374 /// * there's an i/o error while reading `input`
375 /// * the log has invalid syntax:
376 /// * an indented line with no preceding non-indented line
377 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
378 let (rows, config) = read_input(input)?;
379 let columns = column_order(&config, &rows);
381 "{HEADER}{}{}{FOOTER}",
382 render_column_headers(&config, &columns),
384 .map(|mut r| render_row(&config, &columns, &mut r))
394 fn test_parse_line() {
395 assert_eq!(InputLine::from(""), InputLine::Blank);
396 assert_eq!(InputLine::from(" "), InputLine::Blank);
397 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
398 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
399 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
401 InputLine::from(" foo:bar"),
402 InputLine::Entry("foo", Some("bar"))
405 InputLine::from(" foo: bar"),
406 InputLine::Entry("foo", Some("bar"))
409 InputLine::from(" foo: bar "),
410 InputLine::Entry("foo", Some("bar"))
413 InputLine::from(" foo: bar "),
414 InputLine::Entry("foo", Some("bar"))
417 InputLine::from(" foo : bar "),
418 InputLine::Entry("foo", Some("bar"))
422 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
423 read_input(input).map(|(rows, _)| rows)
425 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
426 read_input(input).map(|(_, config)| config)
429 fn test_read_rows() {
431 read_rows(&b"foo"[..]).unwrap(),
432 vec![Rowlike::Row(Row {
433 label: "foo".to_owned(),
434 entries: HashMap::new(),
438 read_rows(&b"bar"[..]).unwrap(),
439 vec![Rowlike::Row(Row {
440 label: "bar".to_owned(),
441 entries: HashMap::new(),
445 read_rows(&b"foo\nbar\n"[..]).unwrap(),
448 label: "foo".to_owned(),
449 entries: HashMap::new(),
452 label: "bar".to_owned(),
453 entries: HashMap::new(),
458 read_rows(&b"foo\n bar\n"[..]).unwrap(),
459 vec![Rowlike::Row(Row {
460 label: "foo".to_owned(),
461 entries: HashMap::from([("bar".to_owned(), vec![None])]),
465 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
466 vec![Rowlike::Row(Row {
467 label: "foo".to_owned(),
468 entries: HashMap::from([
469 ("bar".to_owned(), vec![None]),
470 ("baz".to_owned(), vec![None])
475 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
478 label: "foo".to_owned(),
479 entries: HashMap::new(),
482 label: "bar".to_owned(),
483 entries: HashMap::new(),
488 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
491 label: "foo".to_owned(),
492 entries: HashMap::new(),
496 label: "bar".to_owned(),
497 entries: HashMap::new(),
502 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
505 label: "foo".to_owned(),
506 entries: HashMap::new(),
509 label: "bar".to_owned(),
510 entries: HashMap::new(),
515 read_rows(&b"foo \n bar \n"[..]).unwrap(),
516 vec![Rowlike::Row(Row {
517 label: "foo".to_owned(),
518 entries: HashMap::from([("bar".to_owned(), vec![None])]),
522 let bad = read_rows(&b" foo"[..]);
523 assert!(bad.is_err());
524 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
526 let bad2 = read_rows(&b"foo\n\n bar"[..]);
527 assert!(bad2.is_err());
528 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
532 fn test_read_config() {
534 read_config(&b"!col_threshold 10"[..])
540 read_config(&b"!col foo"[..]).unwrap().static_columns,
541 vec![Some("foo".to_owned())]
544 let bad_command = read_config(&b"!no such command"[..]);
545 assert!(bad_command.is_err());
546 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
548 let bad_num = read_config(&b"!col_threshold foo"[..]);
549 assert!(bad_num.is_err());
550 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
554 fn test_column_counts() {
556 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
557 vec![(1, String::from("bar")), (1, String::from("baz"))]
560 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
561 vec![(2, String::from("baz")), (1, String::from("bar"))]
564 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
565 vec![(2, String::from("baz")), (1, String::from("bar"))]
569 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
571 vec![(2, String::from("baz")), (1, String::from("bar"))]
576 fn test_render_cell() {
581 label: "nope".to_owned(),
582 entries: HashMap::new(),
586 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
593 label: "nope".to_owned(),
594 entries: HashMap::from([("bar".to_owned(), vec![None])]),
598 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
605 label: "nope".to_owned(),
606 entries: HashMap::from([("foo".to_owned(), vec![None])]),
610 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
617 label: "nope".to_owned(),
618 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
622 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
629 label: "nope".to_owned(),
630 entries: HashMap::from([(
632 vec![Some("5".to_owned()), Some("10".to_owned())]
637 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
644 label: "nope".to_owned(),
645 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
649 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
656 label: "nope".to_owned(),
657 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
661 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
668 label: "bob's".to_owned(),
669 entries: HashMap::from([("foo".to_owned(), vec![None])]),
673 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
677 label: "nope".to_owned(),
678 entries: HashMap::from([
679 ("foo".to_owned(), vec![None]),
680 ("baz".to_owned(), vec![None]),
683 assert_eq!(r.entries.len(), 2);
684 render_cell("foo", &mut r);
685 assert_eq!(r.entries.len(), 1);
686 render_cell("bar", &mut r);
687 assert_eq!(r.entries.len(), 1);
688 render_cell("baz", &mut r);
689 assert_eq!(r.entries.len(), 0);
693 fn test_render_leftovers() {
695 render_all_leftovers(&Row {
696 label: "nope".to_owned(),
697 entries: HashMap::from([("foo".to_owned(), vec![None])]),
702 render_all_leftovers(&Row {
703 label: "nope".to_owned(),
704 entries: HashMap::from([
705 ("foo".to_owned(), vec![None]),
706 ("bar".to_owned(), vec![None])
709 HTML::from("bar, foo")
712 render_all_leftovers(&Row {
713 label: "nope".to_owned(),
714 entries: HashMap::from([
715 ("foo".to_owned(), vec![None]),
716 ("bar".to_owned(), vec![None, None])
719 HTML::from("bar: 2, foo")
724 fn test_render_row() {
729 &mut Rowlike::Row(Row {
730 label: "nope".to_owned(),
731 entries: HashMap::from([("bar".to_owned(), vec![None])]),
735 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>
743 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
746 &mut Rowlike::Row(Row {
747 label: "nope".to_owned(),
748 entries: HashMap::from([
749 ("bar".to_owned(), vec![Some("r".to_owned())]),
750 ("baz".to_owned(), vec![Some("z".to_owned())]),
751 ("foo".to_owned(), vec![Some("f".to_owned())]),
756 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>
764 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
767 &mut Rowlike::Row(Row {
768 label: "nope".to_owned(),
769 entries: HashMap::from([
770 ("bar".to_owned(), vec![Some("r".to_owned())]),
771 ("foo".to_owned(), vec![Some("f".to_owned())]),
776 r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="spacer_col"></td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr>