1 use std::collections::{HashMap, HashSet};
4 use std::iter::Iterator;
6 const HEADER: &str = "<!DOCTYPE html>
9 <meta charset=\"utf-8\">
10 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
12 td { text-align: center; }
13 /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */
14 th, td { white-space: nowrap; }
15 th { text-align: left; font-weight: normal; }
16 table { border-collapse: collapse }
17 tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 }
18 tr.key > th > div { width: 1em; }
19 tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) }
20 td { border: thin solid gray; }
21 td.yes { border: thin solid gray; background-color: #ddd; }
22 /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */
23 .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; }
26 function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } }
27 function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } }
28 function h2(a, b) { highlight(a); highlight(b); }
29 function ch2(a, b) { clear_highlight(a); clear_highlight(b); }
36 const FOOTER: &str = " </tbody>
41 #[derive(Debug, PartialEq, Eq, Hash)]
44 instance: Option<String>,
46 impl From<&str> for Entry {
47 fn from(value: &str) -> Entry {
48 match value.split_once(':') {
50 col: String::from(value),
53 Some((col, instance)) => Entry {
54 col: String::from(col.trim()),
55 instance: Some(String::from(instance.trim())),
61 #[derive(Debug, PartialEq, Eq)]
67 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
68 input: std::iter::Enumerate<Input>,
69 row: Option<RowInput>,
71 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
72 fn new(input: Input) -> Self {
74 input: input.enumerate(),
79 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
80 type Item = Result<RowInput, std::io::Error>;
81 fn next(&mut self) -> Option<Self::Item> {
86 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
88 None => return Ok(std::mem::take(&mut self.row)).transpose(),
89 Some((_, Err(e))) => return Some(Err(e)),
90 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
91 return Ok(std::mem::take(&mut self.row)).transpose()
93 Some((_, Ok(line))) if line.is_empty() => {}
94 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
96 return Some(Err(std::io::Error::other(format!(
97 "{}: Entry with no header",
101 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
103 Some((_, Ok(line))) => {
104 let prev = std::mem::take(&mut self.row);
105 self.row = Some(RowInput {
110 return Ok(prev).transpose();
118 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
119 Reader::new(std::io::BufReader::new(input).lines())
122 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
123 let mut counts: Vec<_> = rows
129 .collect::<HashSet<_>>()
132 .fold(HashMap::new(), |mut cs, col| {
133 cs.entry(String::from(col))
134 .and_modify(|n| *n += 1)
139 .map(|(col, n)| (n, col))
141 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
144 fn column_order(rows: &[RowInput]) -> Vec<String> {
151 fn render_instance(entry: &Entry) -> String {
152 match &entry.instance {
153 None => String::from("✓ "),
154 Some(instance) => String::from(instance) + " ",
158 fn render_cell(col: &str, row: &RowInput) -> String {
159 // TODO: Escape HTML special characters
160 let row_label = &row.label;
161 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
162 let class = if entries.is_empty() { "" } else { "yes" };
163 let all_empty = entries.iter().all(|e| e.instance.is_none());
164 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
166 } else if all_empty {
167 format!("{}", entries.len())
171 .map(|i| render_instance(i))
174 format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col}')\" onmouseout=\"ch2('{row_label}','{col}')\">{}</td>", contents.trim())
177 fn render_row(columns: &[String], row: &RowInput) -> String {
178 // This is O(n^2) & doesn't need to be
179 // TODO: Escape HTML special characters
180 let row_label = &row.label;
182 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
185 .map(|col| render_cell(col, row))
190 fn render_column_headers(columns: &[String]) -> String {
191 // TODO: Escape HTML special characters
192 String::from("<tr class=\"key\"><th></th>")
193 + &columns.iter().fold(String::new(), |mut acc, c| {
194 write!(&mut acc, "<th id=\"{c}\"><div><div>{c}</div></div></th>").unwrap();
202 /// Will return `Err` if
203 /// * there's an i/o error while reading `input`
204 /// * the log has invalid syntax:
205 /// * an indented line with no preceding non-indented line
206 pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> {
207 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
208 let columns = column_order(&rows);
209 Ok(String::from(HEADER)
210 + &render_column_headers(&columns)
213 .map(|r| render_row(&columns, &r))
223 fn test_parse_entry() {
227 col: String::from("foo"),
232 Entry::from("foo:bar"),
234 col: String::from("foo"),
235 instance: Some(String::from("bar"))
239 Entry::from("foo: bar"),
241 col: String::from("foo"),
242 instance: Some(String::from("bar"))
248 fn test_read_rows() {
250 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
252 label: String::from("foo"),
257 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
259 label: String::from("bar"),
264 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
267 label: String::from("foo"),
271 label: String::from("bar"),
277 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
279 label: String::from("foo"),
280 entries: vec![Entry::from("bar")]
284 read_rows(&b"foo\n bar\n baz\n"[..])
286 .collect::<Vec<_>>(),
288 label: String::from("foo"),
289 entries: vec![Entry::from("bar"), Entry::from("baz")]
293 read_rows(&b"foo\n\nbar\n"[..])
295 .collect::<Vec<_>>(),
298 label: String::from("foo"),
302 label: String::from("bar"),
308 read_rows(&b"foo\n \nbar\n"[..])
310 .collect::<Vec<_>>(),
313 label: String::from("foo"),
317 label: String::from("bar"),
323 read_rows(&b"foo \n bar \n"[..])
325 .collect::<Vec<_>>(),
327 label: String::from("foo"),
328 entries: vec![Entry::from("bar")]
332 let bad = read_rows(&b" foo"[..]).next().unwrap();
333 assert!(bad.is_err());
334 assert!(format!("{bad:?}").contains("1: Entry with no header"));
336 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
337 assert!(bad2.is_err());
338 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
342 fn test_column_counts() {
345 &read_rows(&b"foo\n bar\n baz\n"[..])
346 .collect::<Result<Vec<_>, _>>()
349 vec![(1, String::from("bar")), (1, String::from("baz"))]
353 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
354 .collect::<Result<Vec<_>, _>>()
357 vec![(2, String::from("baz")), (1, String::from("bar"))]
361 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
362 .collect::<Result<Vec<_>, _>>()
365 vec![(2, String::from("baz")), (1, String::from("bar"))]
369 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
370 .collect::<Result<Vec<_>, _>>()
373 vec![(2, String::from("baz")), (1, String::from("bar"))]
378 fn test_render_cell() {
383 label: String::from("nope"),
387 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
393 label: String::from("nope"),
394 entries: vec![Entry::from("bar")]
397 String::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
403 label: String::from("nope"),
404 entries: vec![Entry::from("foo")]
407 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
413 label: String::from("nope"),
414 entries: vec![Entry::from("foo"), Entry::from("foo")]
417 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
423 label: String::from("nope"),
424 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
427 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
433 label: String::from("nope"),
434 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
437 String::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")