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}"),
34 impl Default for Config {
35 fn default() -> Self {
38 static_columns: vec![],
43 const HEADER: &str = r#"<!DOCTYPE html>
46 <meta charset="utf-8">
47 <meta name="viewport" content="width=device-width, initial-scale=1">
49 td { text-align: center; }
50 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
51 th, td { white-space: nowrap; }
52 th { text-align: left; font-weight: normal; }
53 th.spacer_row { height: .3em; }
54 .spacer_col { border: none; width: .2em; }
55 table { border-collapse: collapse }
56 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
57 tr.key > th > div { width: 1em; }
58 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
59 td { border: thin solid gray; }
60 td.leftover { text-align: left; border: none; padding-left: .4em; }
61 td.yes { border: thin solid gray; background-color: #ddd; }
62 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
63 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
66 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
67 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
68 function h2(a, b) { highlight(a); highlight(b); }
69 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
76 const FOOTER: &str = " </tbody>
81 #[derive(PartialEq, Eq, Debug)]
82 pub struct HTML(String);
84 fn escape(value: &str) -> HTML {
85 let mut escaped: String = String::new();
86 for c in value.chars() {
88 '>' => escaped.push_str(">"),
89 '<' => escaped.push_str("<"),
90 '\'' => escaped.push_str("'"),
91 '"' => escaped.push_str("""),
92 '&' => escaped.push_str("&"),
93 ok_c => escaped.push(ok_c),
99 impl From<&str> for HTML {
100 fn from(value: &str) -> HTML {
101 HTML(String::from(value))
104 impl FromIterator<HTML> for HTML {
105 fn from_iter<T>(iter: T) -> HTML
107 T: IntoIterator<Item = HTML>,
109 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
112 impl std::fmt::Display for HTML {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 write!(f, "{}", self.0)
118 #[derive(Debug, PartialEq, Eq)]
122 Entry(&'a str, Option<&'a str>),
125 impl<'a> From<&'a str> for InputLine<'a> {
126 fn from(value: &'a str) -> InputLine<'a> {
127 let trimmed = value.trim_end();
128 if trimmed.is_empty() {
130 } else if let Some(cmd) = trimmed.strip_prefix('!') {
131 InputLine::Command(cmd)
132 } else if !trimmed.starts_with(' ') {
133 InputLine::RowHeader(value.trim())
135 match value.split_once(':') {
136 None => InputLine::Entry(value.trim(), None),
137 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
143 #[derive(Debug, PartialEq, Eq)]
146 entries: HashMap<String, Vec<Option<String>>>,
149 #[derive(Debug, PartialEq, Eq)]
155 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
156 input: std::iter::Enumerate<Input>,
158 config: &'cfg mut Config,
160 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
161 fn new(config: &'cfg mut Config, input: Input) -> Self {
163 input: input.enumerate(),
169 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
170 for Reader<'cfg, Input>
172 type Item = Result<Rowlike, std::io::Error>;
173 fn next(&mut self) -> Option<Self::Item> {
175 match self.input.next() {
176 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
177 Some((_, Err(e))) => return Some(Err(e)),
178 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
179 InputLine::Command(cmd) => {
180 if let Err(e) = self.config.apply_command(n + 1, cmd) {
184 InputLine::Blank if self.row.is_some() => {
185 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
187 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
188 InputLine::Entry(col, instance) => match &mut self.row {
190 return Some(Err(std::io::Error::other(format!(
191 "line {}: Entry with no header",
195 Some(ref mut row) => {
197 .entry(col.to_owned())
198 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
199 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
202 InputLine::RowHeader(row) => {
203 let prev = std::mem::take(&mut self.row);
204 self.row = Some(Row {
205 label: row.to_owned(),
206 entries: HashMap::new(),
209 return Ok(prev.map(Rowlike::Row)).transpose();
218 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
219 let mut config = Config::default();
220 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
222 .collect::<Result<Vec<_>, _>>()
223 .map(|rows| (rows, config))
226 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
227 let empty = HashMap::new();
228 let mut counts: Vec<_> = rows
230 .flat_map(|rl| match rl {
231 Rowlike::Row(r) => r.entries.keys(),
232 Rowlike::Spacer => empty.keys(),
234 .fold(HashMap::new(), |mut cs, col| {
235 cs.entry(col.to_owned())
236 .and_modify(|n| *n += 1)
241 .map(|(col, n)| (n, col))
243 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
246 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
247 let static_columns: HashSet<&str> = config
251 .map(std::string::String::as_str)
255 .filter_map(|(n, col)| {
256 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
261 fn render_one_instance(instance: &Option<String>) -> HTML {
263 None => HTML::from("✓"),
264 Some(instance) => HTML::escape(instance.as_ref()),
268 fn render_instances(instances: &[Option<String>]) -> HTML {
269 let all_empty = instances.iter().all(Option::is_none);
270 if all_empty && instances.len() == 1 {
272 } else if all_empty {
273 HTML(format!("{}", instances.len()))
278 .map(render_one_instance)
279 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
286 fn render_cell(col: &str, row: &mut Row) -> HTML {
287 let row_label = HTML::escape(row.label.as_ref());
288 let col_label = HTML::escape(col);
289 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
290 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
291 let contents = match instances {
292 None => HTML::from(""),
293 Some(is) => render_instances(is),
295 row.entries.remove(col);
297 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
301 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
302 let label = HTML::escape(notcol);
303 let rest = render_instances(instances);
304 if rest == HTML::from("") {
305 HTML(format!("{label}"))
307 HTML(format!("{label}: {rest}"))
311 fn render_all_leftovers(row: &Row) -> HTML {
312 let mut order: Vec<_> = row.entries.keys().collect();
313 order.sort_unstable();
317 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
318 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
324 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
326 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
327 Rowlike::Row(row) => {
328 let row_label = HTML::escape(row.label.as_ref());
329 let static_cells = config
332 .map(|ocol| match ocol {
333 Some(col) => render_cell(col, row),
334 None => HTML::from(r#"<td class="spacer_col"></td>"#),
337 let dynamic_cells = columns
339 .map(|col| render_cell(col, row))
341 let leftovers = render_all_leftovers(row);
343 "<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"
349 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
350 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
351 let dynamic_columns = columns.iter().map(Some);
353 String::from(r#"<tr class="key"><th></th>"#)
355 .chain(dynamic_columns)
356 .fold(String::new(), |mut acc, ocol| {
359 let col_header = HTML::escape(col);
362 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
365 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
376 /// Will return `Err` if
377 /// * there's an i/o error while reading `input`
378 /// * the log has invalid syntax:
379 /// * an indented line with no preceding non-indented line
380 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
381 let (rows, config) = read_input(input)?;
382 let columns = column_order(&config, &rows);
384 "{HEADER}{}{}{FOOTER}",
385 render_column_headers(&config, &columns),
387 .map(|mut r| render_row(&config, &columns, &mut r))
397 fn test_parse_line() {
398 assert_eq!(InputLine::from(""), InputLine::Blank);
399 assert_eq!(InputLine::from(" "), InputLine::Blank);
400 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
401 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
402 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
404 InputLine::from(" foo:bar"),
405 InputLine::Entry("foo", Some("bar"))
408 InputLine::from(" foo: bar"),
409 InputLine::Entry("foo", Some("bar"))
412 InputLine::from(" foo: bar "),
413 InputLine::Entry("foo", Some("bar"))
416 InputLine::from(" foo: bar "),
417 InputLine::Entry("foo", Some("bar"))
420 InputLine::from(" foo : bar "),
421 InputLine::Entry("foo", Some("bar"))
425 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
426 read_input(input).map(|(rows, _)| rows)
428 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
429 read_input(input).map(|(_, config)| config)
432 fn test_read_rows() {
434 read_rows(&b"foo"[..]).unwrap(),
435 vec![Rowlike::Row(Row {
436 label: "foo".to_owned(),
437 entries: HashMap::new(),
441 read_rows(&b"bar"[..]).unwrap(),
442 vec![Rowlike::Row(Row {
443 label: "bar".to_owned(),
444 entries: HashMap::new(),
448 read_rows(&b"foo\nbar\n"[..]).unwrap(),
451 label: "foo".to_owned(),
452 entries: HashMap::new(),
455 label: "bar".to_owned(),
456 entries: HashMap::new(),
461 read_rows(&b"foo\n bar\n"[..]).unwrap(),
462 vec![Rowlike::Row(Row {
463 label: "foo".to_owned(),
464 entries: HashMap::from([("bar".to_owned(), vec![None])]),
468 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
469 vec![Rowlike::Row(Row {
470 label: "foo".to_owned(),
471 entries: HashMap::from([
472 ("bar".to_owned(), vec![None]),
473 ("baz".to_owned(), vec![None])
478 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
481 label: "foo".to_owned(),
482 entries: HashMap::new(),
485 label: "bar".to_owned(),
486 entries: HashMap::new(),
491 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
494 label: "foo".to_owned(),
495 entries: HashMap::new(),
499 label: "bar".to_owned(),
500 entries: HashMap::new(),
505 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
508 label: "foo".to_owned(),
509 entries: HashMap::new(),
512 label: "bar".to_owned(),
513 entries: HashMap::new(),
518 read_rows(&b"foo \n bar \n"[..]).unwrap(),
519 vec![Rowlike::Row(Row {
520 label: "foo".to_owned(),
521 entries: HashMap::from([("bar".to_owned(), vec![None])]),
525 let bad = read_rows(&b" foo"[..]);
526 assert!(bad.is_err());
527 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
529 let bad2 = read_rows(&b"foo\n\n bar"[..]);
530 assert!(bad2.is_err());
531 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
535 fn test_read_config() {
537 read_config(&b"!col_threshold 10"[..])
543 read_config(&b"!col foo"[..]).unwrap().static_columns,
544 vec![Some("foo".to_owned())]
547 let bad_command = read_config(&b"!no such command"[..]);
548 assert!(bad_command.is_err());
549 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
551 let bad_num = read_config(&b"!col_threshold foo"[..]);
552 assert!(bad_num.is_err());
553 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
557 fn test_column_counts() {
559 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
560 vec![(1, String::from("bar")), (1, String::from("baz"))]
563 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
564 vec![(2, String::from("baz")), (1, String::from("bar"))]
567 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
568 vec![(2, String::from("baz")), (1, String::from("bar"))]
572 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
574 vec![(2, String::from("baz")), (1, String::from("bar"))]
579 fn test_render_cell() {
584 label: "nope".to_owned(),
585 entries: HashMap::new(),
589 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
596 label: "nope".to_owned(),
597 entries: HashMap::from([("bar".to_owned(), vec![None])]),
601 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
608 label: "nope".to_owned(),
609 entries: HashMap::from([("foo".to_owned(), vec![None])]),
613 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
620 label: "nope".to_owned(),
621 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
625 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
632 label: "nope".to_owned(),
633 entries: HashMap::from([(
635 vec![Some("5".to_owned()), Some("10".to_owned())]
640 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
647 label: "nope".to_owned(),
648 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
652 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
659 label: "nope".to_owned(),
660 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
664 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
671 label: "bob's".to_owned(),
672 entries: HashMap::from([("foo".to_owned(), vec![None])]),
676 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
680 label: "nope".to_owned(),
681 entries: HashMap::from([
682 ("foo".to_owned(), vec![None]),
683 ("baz".to_owned(), vec![None]),
686 assert_eq!(r.entries.len(), 2);
687 render_cell("foo", &mut r);
688 assert_eq!(r.entries.len(), 1);
689 render_cell("bar", &mut r);
690 assert_eq!(r.entries.len(), 1);
691 render_cell("baz", &mut r);
692 assert_eq!(r.entries.len(), 0);
696 fn test_render_leftovers() {
698 render_all_leftovers(&Row {
699 label: "nope".to_owned(),
700 entries: HashMap::from([("foo".to_owned(), vec![None])]),
705 render_all_leftovers(&Row {
706 label: "nope".to_owned(),
707 entries: HashMap::from([
708 ("foo".to_owned(), vec![None]),
709 ("bar".to_owned(), vec![None])
712 HTML::from("bar, foo")
715 render_all_leftovers(&Row {
716 label: "nope".to_owned(),
717 entries: HashMap::from([
718 ("foo".to_owned(), vec![None]),
719 ("bar".to_owned(), vec![None, None])
722 HTML::from("bar: 2, foo")
727 fn test_render_row() {
732 &mut Rowlike::Row(Row {
733 label: "nope".to_owned(),
734 entries: HashMap::from([("bar".to_owned(), vec![None])]),
738 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>
746 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
749 &mut Rowlike::Row(Row {
750 label: "nope".to_owned(),
751 entries: HashMap::from([
752 ("bar".to_owned(), vec![Some("r".to_owned())]),
753 ("baz".to_owned(), vec![Some("z".to_owned())]),
754 ("foo".to_owned(), vec![Some("f".to_owned())]),
759 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>
767 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
770 &mut Rowlike::Row(Row {
771 label: "nope".to_owned(),
772 entries: HashMap::from([
773 ("bar".to_owned(), vec![Some("r".to_owned())]),
774 ("foo".to_owned(), vec![Some("f".to_owned())]),
779 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>