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 HEADER: &str = r#"<!DOCTYPE html>
38 <meta charset="utf-8">
39 <meta name="viewport" content="width=device-width, initial-scale=1">
41 td { text-align: center; }
42 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
43 th, td { white-space: nowrap; }
44 th { text-align: left; font-weight: normal; }
45 th.spacer_row { height: .3em; }
46 .spacer_col { border: none; width: .2em; }
47 table { border-collapse: collapse }
48 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
49 tr.key > th > div { width: 1em; }
50 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
51 td { border: thin solid gray; }
52 td.leftover { text-align: left; border: none; padding-left: .4em; }
53 td.yes { border: thin solid gray; background-color: #ddd; }
54 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
55 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
58 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
59 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
60 function h2(a, b) { highlight(a); highlight(b); }
61 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
68 const FOOTER: &str = " </tbody>
73 #[derive(PartialEq, Eq, Debug)]
74 pub struct HTML(String);
76 fn escape(value: &str) -> HTML {
77 let mut escaped: String = String::new();
78 for c in value.chars() {
80 '>' => escaped.push_str(">"),
81 '<' => escaped.push_str("<"),
82 '\'' => escaped.push_str("'"),
83 '"' => escaped.push_str("""),
84 '&' => escaped.push_str("&"),
85 ok_c => escaped.push(ok_c),
91 impl From<&str> for HTML {
92 fn from(value: &str) -> HTML {
93 HTML(String::from(value))
96 impl FromIterator<HTML> for HTML {
97 fn from_iter<T>(iter: T) -> HTML
99 T: IntoIterator<Item = HTML>,
101 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
104 impl std::fmt::Display for HTML {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 write!(f, "{}", self.0)
110 #[derive(Debug, PartialEq, Eq)]
114 Entry(&'a str, Option<&'a str>),
117 impl<'a> From<&'a str> for InputLine<'a> {
118 fn from(value: &'a str) -> InputLine<'a> {
119 let trimmed = value.trim_end();
120 if trimmed.is_empty() {
122 } else if let Some(cmd) = trimmed.strip_prefix('!') {
123 InputLine::Command(cmd)
124 } else if !trimmed.starts_with(' ') {
125 InputLine::RowHeader(value.trim())
127 match value.split_once(':') {
128 None => InputLine::Entry(value.trim(), None),
129 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
135 #[derive(Debug, PartialEq, Eq)]
138 entries: HashMap<String, Vec<Option<String>>>,
141 #[derive(Debug, PartialEq, Eq)]
147 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
148 input: std::iter::Enumerate<Input>,
150 config: &'cfg mut Config,
152 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
153 fn new(config: &'cfg mut Config, input: Input) -> Self {
155 input: input.enumerate(),
161 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
162 for Reader<'cfg, Input>
164 type Item = Result<Rowlike, std::io::Error>;
165 fn next(&mut self) -> Option<Self::Item> {
167 match self.input.next() {
168 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
169 Some((_, Err(e))) => return Some(Err(e)),
170 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
171 InputLine::Command(cmd) => {
172 if let Err(e) = self.config.apply_command(n + 1, cmd) {
176 InputLine::Blank if self.row.is_some() => {
177 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
179 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
180 InputLine::Entry(col, instance) => match &mut self.row {
182 return Some(Err(std::io::Error::other(format!(
183 "line {}: Entry with no header",
187 Some(ref mut row) => {
189 .entry(col.to_owned())
190 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
191 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
194 InputLine::RowHeader(row) => {
195 let prev = std::mem::take(&mut self.row);
196 self.row = Some(Row {
197 label: row.to_owned(),
198 entries: HashMap::new(),
201 return Ok(prev.map(Rowlike::Row)).transpose();
210 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
211 let mut config = Config {
213 static_columns: vec![],
215 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
217 .collect::<Result<Vec<_>, _>>()
218 .map(|rows| (rows, config))
221 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
222 let empty = HashMap::new();
223 let mut counts: Vec<_> = rows
225 .flat_map(|rl| match rl {
226 Rowlike::Row(r) => r.entries.keys(),
227 Rowlike::Spacer => empty.keys(),
229 .fold(HashMap::new(), |mut cs, col| {
230 cs.entry(col.to_owned())
231 .and_modify(|n| *n += 1)
236 .map(|(col, n)| (n, col))
238 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
241 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
242 let static_columns: HashSet<&str> = config
246 .map(std::string::String::as_str)
250 .filter_map(|(n, col)| {
251 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
256 fn render_one_instance(instance: &Option<String>) -> HTML {
258 None => HTML::from("✓"),
259 Some(instance) => HTML::escape(instance.as_ref()),
263 fn render_instances(instances: &[Option<String>]) -> HTML {
264 let all_empty = instances.iter().all(Option::is_none);
265 if all_empty && instances.len() == 1 {
267 } else if all_empty {
268 HTML(format!("{}", instances.len()))
273 .map(render_one_instance)
274 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
281 fn render_cell(col: &str, row: &mut Row) -> HTML {
282 let row_label = HTML::escape(row.label.as_ref());
283 let col_label = HTML::escape(col);
284 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
285 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
286 let contents = match instances {
287 None => HTML::from(""),
288 Some(is) => render_instances(is),
290 row.entries.remove(col);
292 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
296 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
297 let label = HTML::escape(notcol);
298 let rest = render_instances(instances);
299 if rest == HTML::from("") {
300 HTML(format!("{label}"))
302 HTML(format!("{label}: {rest}"))
306 fn render_all_leftovers(row: &Row) -> HTML {
307 let mut order: Vec<_> = row.entries.keys().collect();
308 order.sort_unstable();
312 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
313 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
319 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
321 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
322 Rowlike::Row(row) => {
323 let row_label = HTML::escape(row.label.as_ref());
324 let static_cells = config
327 .map(|ocol| match ocol {
328 Some(col) => render_cell(col, row),
329 None => HTML::from(r#"<td class="spacer_col"></td>"#),
332 let dynamic_cells = columns
334 .map(|col| render_cell(col, row))
336 let leftovers = render_all_leftovers(row);
338 "<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"
344 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
345 let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
346 let dynamic_columns = columns.iter().map(Some);
348 String::from(r#"<tr class="key"><th></th>"#)
350 .chain(dynamic_columns)
351 .fold(String::new(), |mut acc, ocol| {
354 let col_header = HTML::escape(col);
357 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
360 None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
371 /// Will return `Err` if
372 /// * there's an i/o error while reading `input`
373 /// * the log has invalid syntax:
374 /// * an indented line with no preceding non-indented line
375 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
376 let (rows, config) = read_input(input)?;
377 let columns = column_order(&config, &rows);
379 "{HEADER}{}{}{FOOTER}",
380 render_column_headers(&config, &columns),
382 .map(|mut r| render_row(&config, &columns, &mut r))
392 fn test_parse_line() {
393 assert_eq!(InputLine::from(""), InputLine::Blank);
394 assert_eq!(InputLine::from(" "), InputLine::Blank);
395 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
396 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
397 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
399 InputLine::from(" foo:bar"),
400 InputLine::Entry("foo", Some("bar"))
403 InputLine::from(" foo: bar"),
404 InputLine::Entry("foo", Some("bar"))
407 InputLine::from(" foo: bar "),
408 InputLine::Entry("foo", Some("bar"))
411 InputLine::from(" foo: bar "),
412 InputLine::Entry("foo", Some("bar"))
415 InputLine::from(" foo : bar "),
416 InputLine::Entry("foo", Some("bar"))
420 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
421 read_input(input).map(|(rows, _)| rows)
423 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
424 read_input(input).map(|(_, config)| config)
427 fn test_read_rows() {
429 read_rows(&b"foo"[..]).unwrap(),
430 vec![Rowlike::Row(Row {
431 label: "foo".to_owned(),
432 entries: HashMap::new(),
436 read_rows(&b"bar"[..]).unwrap(),
437 vec![Rowlike::Row(Row {
438 label: "bar".to_owned(),
439 entries: HashMap::new(),
443 read_rows(&b"foo\nbar\n"[..]).unwrap(),
446 label: "foo".to_owned(),
447 entries: HashMap::new(),
450 label: "bar".to_owned(),
451 entries: HashMap::new(),
456 read_rows(&b"foo\n bar\n"[..]).unwrap(),
457 vec![Rowlike::Row(Row {
458 label: "foo".to_owned(),
459 entries: HashMap::from([("bar".to_owned(), vec![None])]),
463 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
464 vec![Rowlike::Row(Row {
465 label: "foo".to_owned(),
466 entries: HashMap::from([
467 ("bar".to_owned(), vec![None]),
468 ("baz".to_owned(), vec![None])
473 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
476 label: "foo".to_owned(),
477 entries: HashMap::new(),
480 label: "bar".to_owned(),
481 entries: HashMap::new(),
486 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
489 label: "foo".to_owned(),
490 entries: HashMap::new(),
494 label: "bar".to_owned(),
495 entries: HashMap::new(),
500 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
503 label: "foo".to_owned(),
504 entries: HashMap::new(),
507 label: "bar".to_owned(),
508 entries: HashMap::new(),
513 read_rows(&b"foo \n bar \n"[..]).unwrap(),
514 vec![Rowlike::Row(Row {
515 label: "foo".to_owned(),
516 entries: HashMap::from([("bar".to_owned(), vec![None])]),
520 let bad = read_rows(&b" foo"[..]);
521 assert!(bad.is_err());
522 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
524 let bad2 = read_rows(&b"foo\n\n bar"[..]);
525 assert!(bad2.is_err());
526 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
530 fn test_read_config() {
532 read_config(&b"!col_threshold 10"[..])
538 read_config(&b"!col foo"[..]).unwrap().static_columns,
539 vec![Some("foo".to_owned())]
542 let bad_command = read_config(&b"!no such command"[..]);
543 assert!(bad_command.is_err());
544 assert!(format!("{bad_command:?}").contains("line 1: Unknown command"));
546 let bad_num = read_config(&b"!col_threshold foo"[..]);
547 assert!(bad_num.is_err());
548 assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric"));
552 fn test_column_counts() {
554 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
555 vec![(1, String::from("bar")), (1, String::from("baz"))]
558 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
559 vec![(2, String::from("baz")), (1, String::from("bar"))]
562 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
563 vec![(2, String::from("baz")), (1, String::from("bar"))]
567 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
569 vec![(2, String::from("baz")), (1, String::from("bar"))]
574 fn test_render_cell() {
579 label: "nope".to_owned(),
580 entries: HashMap::new(),
584 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
591 label: "nope".to_owned(),
592 entries: HashMap::from([("bar".to_owned(), vec![None])]),
596 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
603 label: "nope".to_owned(),
604 entries: HashMap::from([("foo".to_owned(), vec![None])]),
608 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
615 label: "nope".to_owned(),
616 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
620 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
627 label: "nope".to_owned(),
628 entries: HashMap::from([(
630 vec![Some("5".to_owned()), Some("10".to_owned())]
635 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
642 label: "nope".to_owned(),
643 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
647 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
654 label: "nope".to_owned(),
655 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
659 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
666 label: "bob's".to_owned(),
667 entries: HashMap::from([("foo".to_owned(), vec![None])]),
671 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
675 label: "nope".to_owned(),
676 entries: HashMap::from([
677 ("foo".to_owned(), vec![None]),
678 ("baz".to_owned(), vec![None]),
681 assert_eq!(r.entries.len(), 2);
682 render_cell("foo", &mut r);
683 assert_eq!(r.entries.len(), 1);
684 render_cell("bar", &mut r);
685 assert_eq!(r.entries.len(), 1);
686 render_cell("baz", &mut r);
687 assert_eq!(r.entries.len(), 0);
691 fn test_render_leftovers() {
693 render_all_leftovers(&Row {
694 label: "nope".to_owned(),
695 entries: HashMap::from([("foo".to_owned(), vec![None])]),
700 render_all_leftovers(&Row {
701 label: "nope".to_owned(),
702 entries: HashMap::from([
703 ("foo".to_owned(), vec![None]),
704 ("bar".to_owned(), vec![None])
707 HTML::from("bar, foo")
710 render_all_leftovers(&Row {
711 label: "nope".to_owned(),
712 entries: HashMap::from([
713 ("foo".to_owned(), vec![None]),
714 ("bar".to_owned(), vec![None, None])
717 HTML::from("bar: 2, foo")
722 fn test_render_row() {
727 static_columns: vec![],
730 &mut Rowlike::Row(Row {
731 label: "nope".to_owned(),
732 entries: HashMap::from([("bar".to_owned(), vec![None])]),
736 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>
744 static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())],
747 &mut Rowlike::Row(Row {
748 label: "nope".to_owned(),
749 entries: HashMap::from([
750 ("bar".to_owned(), vec![Some("r".to_owned())]),
751 ("baz".to_owned(), vec![Some("z".to_owned())]),
752 ("foo".to_owned(), vec![Some("f".to_owned())]),
757 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>
765 static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())],
768 &mut Rowlike::Row(Row {
769 label: "nope".to_owned(),
770 entries: HashMap::from([
771 ("bar".to_owned(), vec![Some("r".to_owned())]),
772 ("foo".to_owned(), vec![Some("f".to_owned())]),
777 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>