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());
21 return Err(std::io::Error::new(
22 std::io::ErrorKind::InvalidInput,
23 format!("Unknown command: {cmd}"),
30 const HEADER: &str = r#"<!DOCTYPE html>
33 <meta charset="utf-8">
34 <meta name="viewport" content="width=device-width, initial-scale=1">
36 td { text-align: center; }
37 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
38 th, td { white-space: nowrap; }
39 th { text-align: left; font-weight: normal; }
40 th.spacer_row { height: .3em; }
41 table { border-collapse: collapse }
42 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
43 tr.key > th > div { width: 1em; }
44 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
45 td { border: thin solid gray; }
46 td.leftover { text-align: left; border: none; padding-left: .4em; }
47 td.yes { border: thin solid gray; background-color: #ddd; }
48 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
49 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
52 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
53 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
54 function h2(a, b) { highlight(a); highlight(b); }
55 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
62 const FOOTER: &str = " </tbody>
67 #[derive(PartialEq, Eq, Debug)]
68 pub struct HTML(String);
70 fn escape(value: &str) -> HTML {
71 let mut escaped: String = String::new();
72 for c in value.chars() {
74 '>' => escaped.push_str(">"),
75 '<' => escaped.push_str("<"),
76 '\'' => escaped.push_str("'"),
77 '"' => escaped.push_str("""),
78 '&' => escaped.push_str("&"),
79 ok_c => escaped.push(ok_c),
85 impl From<&str> for HTML {
86 fn from(value: &str) -> HTML {
87 HTML(String::from(value))
90 impl FromIterator<HTML> for HTML {
91 fn from_iter<T>(iter: T) -> HTML
93 T: IntoIterator<Item = HTML>,
95 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
98 impl std::fmt::Display for HTML {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 write!(f, "{}", self.0)
104 #[derive(Debug, PartialEq, Eq)]
108 Entry(&'a str, Option<&'a str>),
111 impl<'a> From<&'a str> for InputLine<'a> {
112 fn from(value: &'a str) -> InputLine<'a> {
113 let trimmed = value.trim_end();
114 if trimmed.is_empty() {
116 } else if let Some(cmd) = trimmed.strip_prefix('!') {
117 InputLine::Command(cmd)
118 } else if !trimmed.starts_with(' ') {
119 InputLine::RowHeader(value.trim())
121 match value.split_once(':') {
122 None => InputLine::Entry(value.trim(), None),
123 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
129 #[derive(Debug, PartialEq, Eq)]
132 entries: HashMap<String, Vec<Option<String>>>,
135 #[derive(Debug, PartialEq, Eq)]
141 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
142 input: std::iter::Enumerate<Input>,
144 config: &'cfg mut Config,
146 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
147 fn new(config: &'cfg mut Config, input: Input) -> Self {
149 input: input.enumerate(),
155 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
156 for Reader<'cfg, Input>
158 type Item = Result<Rowlike, std::io::Error>;
159 fn next(&mut self) -> Option<Self::Item> {
161 match self.input.next() {
162 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
163 Some((_, Err(e))) => return Some(Err(e)),
164 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
165 InputLine::Command(cmd) => {
166 if let Err(e) = self.config.apply_command(cmd) {
170 InputLine::Blank if self.row.is_some() => {
171 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
173 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
174 InputLine::Entry(col, instance) => match &mut self.row {
176 return Some(Err(std::io::Error::other(format!(
177 "line {}: Entry with no header",
181 Some(ref mut row) => {
183 .entry(col.to_owned())
184 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
185 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
188 InputLine::RowHeader(row) => {
189 let prev = std::mem::take(&mut self.row);
190 self.row = Some(Row {
191 label: row.to_owned(),
192 entries: HashMap::new(),
195 return Ok(prev.map(Rowlike::Row)).transpose();
204 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
205 let mut config = Config {
207 static_columns: vec![],
209 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
211 .collect::<Result<Vec<_>, _>>()
212 .map(|rows| (rows, config))
215 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
216 let empty = HashMap::new();
217 let mut counts: Vec<_> = rows
219 .flat_map(|rl| match rl {
220 Rowlike::Row(r) => r.entries.keys(),
221 Rowlike::Spacer => empty.keys(),
223 .fold(HashMap::new(), |mut cs, col| {
224 cs.entry(col.to_owned())
225 .and_modify(|n| *n += 1)
230 .map(|(col, n)| (n, col))
232 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
235 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
236 let static_columns: HashSet<&str> = config
239 .map(std::string::String::as_str)
243 .filter_map(|(n, col)| {
244 (n >= config.column_threshold && !static_columns.contains(col.as_str())).then_some(col)
249 fn render_one_instance(instance: &Option<String>) -> HTML {
251 None => HTML::from("✓"),
252 Some(instance) => HTML::escape(instance.as_ref()),
256 fn render_instances(instances: &[Option<String>]) -> HTML {
257 let all_empty = instances.iter().all(Option::is_none);
258 if all_empty && instances.len() == 1 {
260 } else if all_empty {
261 HTML(format!("{}", instances.len()))
266 .map(render_one_instance)
267 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
274 fn render_cell(col: &str, row: &mut Row) -> HTML {
275 let row_label = HTML::escape(row.label.as_ref());
276 let col_label = HTML::escape(col);
277 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
278 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
279 let contents = match instances {
280 None => HTML::from(""),
281 Some(is) => render_instances(is),
283 row.entries.remove(col);
285 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
289 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
290 let label = HTML::escape(notcol);
291 let rest = render_instances(instances);
292 if rest == HTML::from("") {
293 HTML(format!("{label}"))
295 HTML(format!("{label}: {rest}"))
299 fn render_all_leftovers(row: &Row) -> HTML {
300 let mut order: Vec<_> = row.entries.keys().collect();
301 order.sort_unstable();
305 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
306 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
312 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
314 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
315 Rowlike::Row(row) => {
316 let row_label = HTML::escape(row.label.as_ref());
317 let static_cells = config
320 .map(|col| render_cell(col, row))
322 let dynamic_cells = columns
324 .map(|col| render_cell(col, row))
326 let leftovers = render_all_leftovers(row);
328 "<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"
334 fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
336 String::from(r#"<tr class="key"><th></th>"#)
337 + &config.static_columns.iter().chain(columns.iter()).fold(
340 let col_header = HTML::escape(col.as_ref());
343 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
355 /// Will return `Err` if
356 /// * there's an i/o error while reading `input`
357 /// * the log has invalid syntax:
358 /// * an indented line with no preceding non-indented line
359 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
360 let (rows, config) = read_input(input)?;
361 let columns = column_order(&config, &rows);
363 "{HEADER}{}{}{FOOTER}",
364 render_column_headers(&config, &columns),
366 .map(|mut r| render_row(&config, &columns, &mut r))
376 fn test_parse_line() {
377 assert_eq!(InputLine::from(""), InputLine::Blank);
378 assert_eq!(InputLine::from(" "), InputLine::Blank);
379 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
380 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
381 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
383 InputLine::from(" foo:bar"),
384 InputLine::Entry("foo", Some("bar"))
387 InputLine::from(" foo: bar"),
388 InputLine::Entry("foo", Some("bar"))
391 InputLine::from(" foo: bar "),
392 InputLine::Entry("foo", Some("bar"))
395 InputLine::from(" foo: bar "),
396 InputLine::Entry("foo", Some("bar"))
399 InputLine::from(" foo : bar "),
400 InputLine::Entry("foo", Some("bar"))
404 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
405 read_input(input).map(|(rows, _)| rows)
407 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
408 read_input(input).map(|(_, config)| config)
411 fn test_read_rows() {
413 read_rows(&b"foo"[..]).unwrap(),
414 vec![Rowlike::Row(Row {
415 label: "foo".to_owned(),
416 entries: HashMap::new(),
420 read_rows(&b"bar"[..]).unwrap(),
421 vec![Rowlike::Row(Row {
422 label: "bar".to_owned(),
423 entries: HashMap::new(),
427 read_rows(&b"foo\nbar\n"[..]).unwrap(),
430 label: "foo".to_owned(),
431 entries: HashMap::new(),
434 label: "bar".to_owned(),
435 entries: HashMap::new(),
440 read_rows(&b"foo\n bar\n"[..]).unwrap(),
441 vec![Rowlike::Row(Row {
442 label: "foo".to_owned(),
443 entries: HashMap::from([("bar".to_owned(), vec![None])]),
447 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
448 vec![Rowlike::Row(Row {
449 label: "foo".to_owned(),
450 entries: HashMap::from([
451 ("bar".to_owned(), vec![None]),
452 ("baz".to_owned(), vec![None])
457 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
460 label: "foo".to_owned(),
461 entries: HashMap::new(),
464 label: "bar".to_owned(),
465 entries: HashMap::new(),
470 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
473 label: "foo".to_owned(),
474 entries: HashMap::new(),
478 label: "bar".to_owned(),
479 entries: HashMap::new(),
484 read_rows(&b"foo\n \nbar\n"[..]).unwrap(),
487 label: "foo".to_owned(),
488 entries: HashMap::new(),
491 label: "bar".to_owned(),
492 entries: HashMap::new(),
497 read_rows(&b"foo \n bar \n"[..]).unwrap(),
498 vec![Rowlike::Row(Row {
499 label: "foo".to_owned(),
500 entries: HashMap::from([("bar".to_owned(), vec![None])]),
504 let bad = read_rows(&b" foo"[..]);
505 assert!(bad.is_err());
506 assert!(format!("{bad:?}").contains("line 1: Entry with no header"));
508 let bad2 = read_rows(&b"foo\n\n bar"[..]);
509 assert!(bad2.is_err());
510 assert!(format!("{bad2:?}").contains("line 3: Entry with no header"));
514 fn test_read_config() {
516 read_config(&b"!col_threshold 10"[..])
522 read_config(&b"!col foo"[..]).unwrap().static_columns,
523 vec!["foo".to_owned()]
526 let bad_command = read_config(&b"!no such command"[..]);
527 assert!(bad_command.is_err());
528 assert!(format!("{bad_command:?}").contains("Unknown command"));
530 let bad_num = read_config(&b"!col_threshold foo"[..]);
531 assert!(bad_num.is_err());
532 assert!(format!("{bad_num:?}").contains("Parse"));
536 fn test_column_counts() {
538 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
539 vec![(1, String::from("bar")), (1, String::from("baz"))]
542 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
543 vec![(2, String::from("baz")), (1, String::from("bar"))]
546 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
547 vec![(2, String::from("baz")), (1, String::from("bar"))]
551 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
553 vec![(2, String::from("baz")), (1, String::from("bar"))]
558 fn test_render_cell() {
563 label: "nope".to_owned(),
564 entries: HashMap::new(),
568 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
575 label: "nope".to_owned(),
576 entries: HashMap::from([("bar".to_owned(), vec![None])]),
580 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
587 label: "nope".to_owned(),
588 entries: HashMap::from([("foo".to_owned(), vec![None])]),
592 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
599 label: "nope".to_owned(),
600 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
604 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
611 label: "nope".to_owned(),
612 entries: HashMap::from([(
614 vec![Some("5".to_owned()), Some("10".to_owned())]
619 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
626 label: "nope".to_owned(),
627 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
631 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
638 label: "nope".to_owned(),
639 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
643 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
650 label: "bob's".to_owned(),
651 entries: HashMap::from([("foo".to_owned(), vec![None])]),
655 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
659 label: "nope".to_owned(),
660 entries: HashMap::from([
661 ("foo".to_owned(), vec![None]),
662 ("baz".to_owned(), vec![None]),
665 assert_eq!(r.entries.len(), 2);
666 render_cell("foo", &mut r);
667 assert_eq!(r.entries.len(), 1);
668 render_cell("bar", &mut r);
669 assert_eq!(r.entries.len(), 1);
670 render_cell("baz", &mut r);
671 assert_eq!(r.entries.len(), 0);
675 fn test_render_leftovers() {
677 render_all_leftovers(&Row {
678 label: "nope".to_owned(),
679 entries: HashMap::from([("foo".to_owned(), vec![None])]),
684 render_all_leftovers(&Row {
685 label: "nope".to_owned(),
686 entries: HashMap::from([
687 ("foo".to_owned(), vec![None]),
688 ("bar".to_owned(), vec![None])
691 HTML::from("bar, foo")
694 render_all_leftovers(&Row {
695 label: "nope".to_owned(),
696 entries: HashMap::from([
697 ("foo".to_owned(), vec![None]),
698 ("bar".to_owned(), vec![None, None])
701 HTML::from("bar: 2, foo")
706 fn test_render_row() {
711 static_columns: vec![],
714 &mut Rowlike::Row(Row {
715 label: "nope".to_owned(),
716 entries: HashMap::from([("bar".to_owned(), vec![None])]),
720 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>
728 static_columns: vec!["foo".to_owned(), "bar".to_owned()],
731 &mut Rowlike::Row(Row {
732 label: "nope".to_owned(),
733 entries: HashMap::from([
734 ("bar".to_owned(), vec![Some("r".to_owned())]),
735 ("baz".to_owned(), vec![Some("z".to_owned())]),
736 ("foo".to_owned(), vec![Some("f".to_owned())]),
741 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>