1 use std::borrow::ToOwned;
2 use std::collections::HashMap;
5 use std::iter::Iterator;
7 #[derive(PartialEq, Eq, Debug)]
9 column_threshold: usize,
12 fn apply_command(&mut self, cmd: &str) -> Result<(), std::io::Error> {
13 if let Some(threshold) = cmd.strip_prefix("col_threshold ") {
14 self.column_threshold = threshold
16 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
22 const HEADER: &str = r#"<!DOCTYPE html>
25 <meta charset="utf-8">
26 <meta name="viewport" content="width=device-width, initial-scale=1">
28 td { text-align: center; }
29 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
30 th, td { white-space: nowrap; }
31 th { text-align: left; font-weight: normal; }
32 th.spacer_row { height: .3em; }
33 table { border-collapse: collapse }
34 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
35 tr.key > th > div { width: 1em; }
36 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
37 td { border: thin solid gray; }
38 td.leftover { text-align: left; border: none; padding-left: .4em; }
39 td.yes { border: thin solid gray; background-color: #ddd; }
40 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
41 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
44 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } }
45 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } }
46 function h2(a, b) { highlight(a); highlight(b); }
47 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
54 const FOOTER: &str = " </tbody>
59 #[derive(PartialEq, Eq, Debug)]
60 pub struct HTML(String);
62 fn escape(value: &str) -> HTML {
63 let mut escaped: String = String::new();
64 for c in value.chars() {
66 '>' => escaped.push_str(">"),
67 '<' => escaped.push_str("<"),
68 '\'' => escaped.push_str("'"),
69 '"' => escaped.push_str("""),
70 '&' => escaped.push_str("&"),
71 ok_c => escaped.push(ok_c),
77 impl From<&str> for HTML {
78 fn from(value: &str) -> HTML {
79 HTML(String::from(value))
82 impl FromIterator<HTML> for HTML {
83 fn from_iter<T>(iter: T) -> HTML
85 T: IntoIterator<Item = HTML>,
87 HTML(iter.into_iter().map(|html| html.0).collect::<String>())
90 impl std::fmt::Display for HTML {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 write!(f, "{}", self.0)
96 #[derive(Debug, PartialEq, Eq)]
100 Entry(&'a str, Option<&'a str>),
103 impl<'a> From<&'a str> for InputLine<'a> {
104 fn from(value: &'a str) -> InputLine<'a> {
105 let trimmed = value.trim_end();
106 if trimmed.is_empty() {
108 } else if let Some(cmd) = trimmed.strip_prefix('!') {
109 InputLine::Command(cmd)
110 } else if !trimmed.starts_with(' ') {
111 InputLine::RowHeader(value.trim())
113 match value.split_once(':') {
114 None => InputLine::Entry(value.trim(), None),
115 Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())),
121 #[derive(Debug, PartialEq, Eq)]
124 entries: HashMap<String, Vec<Option<String>>>,
127 #[derive(Debug, PartialEq, Eq)]
133 struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
134 input: std::iter::Enumerate<Input>,
136 config: &'cfg mut Config,
138 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
139 fn new(config: &'cfg mut Config, input: Input) -> Self {
141 input: input.enumerate(),
147 impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
148 for Reader<'cfg, Input>
150 type Item = Result<Rowlike, std::io::Error>;
151 fn next(&mut self) -> Option<Self::Item> {
153 match self.input.next() {
154 None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
155 Some((_, Err(e))) => return Some(Err(e)),
156 Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
157 InputLine::Command(cmd) => {
158 if let Err(e) = self.config.apply_command(cmd) {
162 InputLine::Blank if self.row.is_some() => {
163 return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
165 InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
166 InputLine::Entry(col, instance) => match &mut self.row {
168 return Some(Err(std::io::Error::other(format!(
169 "{}: Entry with no header",
173 Some(ref mut row) => {
175 .entry(col.to_owned())
176 .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
177 .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
180 InputLine::RowHeader(row) => {
181 let prev = std::mem::take(&mut self.row);
182 self.row = Some(Row {
183 label: row.to_owned(),
184 entries: HashMap::new(),
187 return Ok(prev.map(Rowlike::Row)).transpose();
196 fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
197 let mut config = Config {
200 let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
202 .collect::<Result<Vec<_>, _>>()
203 .map(|rows| (rows, config))
206 fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
207 let empty = HashMap::new();
208 let mut counts: Vec<_> = rows
210 .flat_map(|rl| match rl {
211 Rowlike::Row(r) => r.entries.keys(),
212 Rowlike::Spacer => empty.keys(),
214 .fold(HashMap::new(), |mut cs, col| {
215 cs.entry(col.to_owned())
216 .and_modify(|n| *n += 1)
221 .map(|(col, n)| (n, col))
223 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
226 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
229 .filter_map(|(n, col)| (n >= config.column_threshold).then_some(col))
233 fn render_one_instance(instance: &Option<String>) -> HTML {
235 None => HTML::from("✓"),
236 Some(instance) => HTML::escape(instance.as_ref()),
240 fn render_instances(instances: &[Option<String>]) -> HTML {
241 let all_empty = instances.iter().all(Option::is_none);
242 if all_empty && instances.len() == 1 {
244 } else if all_empty {
245 HTML(format!("{}", instances.len()))
250 .map(render_one_instance)
251 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
258 fn render_cell(col: &str, row: &mut Row) -> HTML {
259 let row_label = HTML::escape(row.label.as_ref());
260 let col_label = HTML::escape(col);
261 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
262 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
263 let contents = match instances {
264 None => HTML::from(""),
265 Some(is) => render_instances(is),
267 row.entries.remove(col);
269 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
273 fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML {
274 let label = HTML::escape(notcol);
275 let rest = render_instances(instances);
276 if rest == HTML::from("") {
277 HTML(format!("{label}"))
279 HTML(format!("{label}: {rest}"))
283 fn render_all_leftovers(row: &Row) -> HTML {
284 let mut order: Vec<_> = row.entries.keys().collect();
285 order.sort_unstable();
289 .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!")))
290 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
296 fn render_row(columns: &[String], rowlike: &mut Rowlike) -> HTML {
298 Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
299 Rowlike::Row(row) => {
300 let row_label = HTML::escape(row.label.as_ref());
303 .map(|col| render_cell(col, row))
305 let leftovers = render_all_leftovers(row);
307 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
313 fn render_column_headers(columns: &[String]) -> HTML {
315 String::from(r#"<tr class="key"><th></th>"#)
316 + &columns.iter().fold(String::new(), |mut acc, col| {
317 let col_header = HTML::escape(col.as_ref());
320 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
331 /// Will return `Err` if
332 /// * there's an i/o error while reading `input`
333 /// * the log has invalid syntax:
334 /// * an indented line with no preceding non-indented line
335 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
336 let (rows, config) = read_input(input)?;
337 let columns = column_order(&config, &rows);
339 "{HEADER}{}{}{FOOTER}",
340 render_column_headers(&columns),
342 .map(|mut r| render_row(&columns, &mut r))
352 fn test_parse_line() {
353 assert_eq!(InputLine::from(""), InputLine::Blank);
354 assert_eq!(InputLine::from(" "), InputLine::Blank);
355 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
356 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
357 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
359 InputLine::from(" foo:bar"),
360 InputLine::Entry("foo", Some("bar"))
363 InputLine::from(" foo: bar"),
364 InputLine::Entry("foo", Some("bar"))
367 InputLine::from(" foo: bar "),
368 InputLine::Entry("foo", Some("bar"))
371 InputLine::from(" foo: bar "),
372 InputLine::Entry("foo", Some("bar"))
375 InputLine::from(" foo : bar "),
376 InputLine::Entry("foo", Some("bar"))
380 fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
381 read_input(input).map(|(rows, _)| rows)
383 fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> {
384 read_input(input).map(|(_, config)| config)
387 fn test_read_rows() {
389 read_rows(&b"foo"[..]).unwrap(),
390 vec![Rowlike::Row(Row {
391 label: "foo".to_owned(),
392 entries: HashMap::new(),
396 read_rows(&b"bar"[..]).unwrap(),
397 vec![Rowlike::Row(Row {
398 label: "bar".to_owned(),
399 entries: HashMap::new(),
403 read_rows(&b"foo\nbar\n"[..]).unwrap(),
406 label: "foo".to_owned(),
407 entries: HashMap::new(),
410 label: "bar".to_owned(),
411 entries: HashMap::new(),
416 read_rows(&b"foo\n bar\n"[..]).unwrap(),
417 vec![Rowlike::Row(Row {
418 label: "foo".to_owned(),
419 entries: HashMap::from([("bar".to_owned(), vec![None])]),
423 read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(),
424 vec![Rowlike::Row(Row {
425 label: "foo".to_owned(),
426 entries: HashMap::from([
427 ("bar".to_owned(), vec![None]),
428 ("baz".to_owned(), vec![None])
433 read_rows(&b"foo\n\nbar\n"[..]).unwrap(),
436 label: "foo".to_owned(),
437 entries: HashMap::new(),
440 label: "bar".to_owned(),
441 entries: HashMap::new(),
446 read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(),
449 label: "foo".to_owned(),
450 entries: HashMap::new(),
454 label: "bar".to_owned(),
455 entries: HashMap::new(),
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 bar \n"[..]).unwrap(),
474 vec![Rowlike::Row(Row {
475 label: "foo".to_owned(),
476 entries: HashMap::from([("bar".to_owned(), vec![None])]),
480 let bad = read_rows(&b" foo"[..]);
481 assert!(bad.is_err());
482 assert!(format!("{bad:?}").contains("1: Entry with no header"));
484 let bad2 = read_rows(&b"foo\n\n bar"[..]);
485 assert!(bad2.is_err());
486 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
490 fn test_read_config() {
492 read_config(&b"!col_threshold 10"[..])
498 let bad_num = read_config(&b"!col_threshold foo"[..]);
499 assert!(bad_num.is_err());
500 assert!(format!("{bad_num:?}").contains("Parse"));
504 fn test_column_counts() {
506 column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()),
507 vec![(1, String::from("bar")), (1, String::from("baz"))]
510 column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()),
511 vec![(2, String::from("baz")), (1, String::from("bar"))]
514 column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()),
515 vec![(2, String::from("baz")), (1, String::from("bar"))]
519 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap()
521 vec![(2, String::from("baz")), (1, String::from("bar"))]
526 fn test_render_cell() {
531 label: "nope".to_owned(),
532 entries: HashMap::new(),
536 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
543 label: "nope".to_owned(),
544 entries: HashMap::from([("bar".to_owned(), vec![None])]),
548 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
555 label: "nope".to_owned(),
556 entries: HashMap::from([("foo".to_owned(), vec![None])]),
560 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
567 label: "nope".to_owned(),
568 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
572 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
579 label: "nope".to_owned(),
580 entries: HashMap::from([(
582 vec![Some("5".to_owned()), Some("10".to_owned())]
587 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
594 label: "nope".to_owned(),
595 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
599 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
606 label: "nope".to_owned(),
607 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
611 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"#
618 label: "bob's".to_owned(),
619 entries: HashMap::from([("foo".to_owned(), vec![None])]),
623 r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"#
627 label: "nope".to_owned(),
628 entries: HashMap::from([
629 ("foo".to_owned(), vec![None]),
630 ("baz".to_owned(), vec![None]),
633 assert_eq!(r.entries.len(), 2);
634 render_cell("foo", &mut r);
635 assert_eq!(r.entries.len(), 1);
636 render_cell("bar", &mut r);
637 assert_eq!(r.entries.len(), 1);
638 render_cell("baz", &mut r);
639 assert_eq!(r.entries.len(), 0);
643 fn test_render_leftovers() {
645 render_all_leftovers(&Row {
646 label: "nope".to_owned(),
647 entries: HashMap::from([("foo".to_owned(), vec![None])]),
652 render_all_leftovers(&Row {
653 label: "nope".to_owned(),
654 entries: HashMap::from([
655 ("foo".to_owned(), vec![None]),
656 ("bar".to_owned(), vec![None])
659 HTML::from("bar, foo")
662 render_all_leftovers(&Row {
663 label: "nope".to_owned(),
664 entries: HashMap::from([
665 ("foo".to_owned(), vec![None]),
666 ("bar".to_owned(), vec![None, None])
669 HTML::from("bar: 2, foo")
674 fn test_render_row() {
678 &mut Rowlike::Row(Row {
679 label: "nope".to_owned(),
680 entries: HashMap::from([("bar".to_owned(), vec![None])]),
684 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>