]>
Commit | Line | Data |
---|---|---|
397ef957 | 1 | use std::collections::{HashMap, HashSet}; |
7067975b | 2 | use std::fmt::Write; |
9dfa98b7 | 3 | use std::io::BufRead; |
75bb888a SW |
4 | use std::iter::Iterator; |
5 | ||
cc2378d5 SW |
6 | const HEADER: &str = "<!DOCTYPE html> |
7 | <html> | |
8 | <head> | |
9 | <meta charset=\"utf-8\"> | |
10 | <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> | |
11 | <style> | |
b8b365ce | 12 | td { text-align: center; } |
cc2378d5 SW |
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 } | |
3bc643e9 | 17 | tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 } |
cc2378d5 SW |
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; } | |
1dda21e6 | 21 | td.yes { border: thin solid gray; background-color: #ddd; } |
cc2378d5 SW |
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; } | |
cc2378d5 SW |
24 | </style> |
25 | <script> | |
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); } | |
30 | </script> | |
31 | </head> | |
32 | <body> | |
33 | <table> | |
76638ea1 SW |
34 | <tbody> |
35 | "; | |
cc2378d5 SW |
36 | const FOOTER: &str = " </tbody> |
37 | </table> | |
38 | </body> | |
39 | </html>"; | |
40 | ||
70436f23 SW |
41 | #[derive(PartialEq, Eq, Debug)] |
42 | pub struct HTML(String); | |
43 | impl HTML { | |
44 | fn escape(value: &str) -> HTML { | |
45 | let mut escaped: String = String::new(); | |
46 | for c in value.chars() { | |
47 | match c { | |
48 | '>' => escaped.push_str(">"), | |
49 | '<' => escaped.push_str("<"), | |
50 | '\'' => escaped.push_str("'"), | |
51 | '"' => escaped.push_str("""), | |
52 | '&' => escaped.push_str("&"), | |
53 | ok_c => escaped.push(ok_c), | |
54 | } | |
55 | } | |
56 | HTML(escaped) | |
57 | } | |
58 | } | |
59 | impl From<&str> for HTML { | |
60 | fn from(value: &str) -> HTML { | |
61 | HTML(String::from(value)) | |
62 | } | |
63 | } | |
64 | impl FromIterator<HTML> for HTML { | |
65 | fn from_iter<T>(iter: T) -> HTML | |
66 | where | |
67 | T: IntoIterator<Item = HTML>, | |
68 | { | |
69 | HTML(iter.into_iter().map(|html| html.0).collect::<String>()) | |
70 | } | |
71 | } | |
72 | impl std::fmt::Display for HTML { | |
73 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
74 | write!(f, "{}", self.0) | |
75 | } | |
76 | } | |
77 | ||
14e9852b | 78 | #[derive(Debug, PartialEq, Eq, Hash)] |
116fc215 SW |
79 | struct Entry<'a> { |
80 | col: &'a str, | |
81 | instance: Option<&'a str>, | |
e8657dff | 82 | } |
116fc215 SW |
83 | impl<'a> From<&'a str> for Entry<'a> { |
84 | fn from(value: &'a str) -> Entry<'a> { | |
b8907770 SW |
85 | match value.split_once(':') { |
86 | None => Entry { | |
116fc215 | 87 | col: value, |
b8907770 SW |
88 | instance: None, |
89 | }, | |
90 | Some((col, instance)) => Entry { | |
116fc215 SW |
91 | col: col.trim(), |
92 | instance: Some(instance.trim()), | |
b8907770 | 93 | }, |
e8657dff SW |
94 | } |
95 | } | |
96 | } | |
14e9852b | 97 | |
75bb888a | 98 | #[derive(Debug, PartialEq, Eq)] |
116fc215 SW |
99 | struct RowInput<'a> { |
100 | label: &'a str, | |
101 | entries: Vec<Entry<'a>>, | |
75bb888a SW |
102 | } |
103 | ||
116fc215 | 104 | struct Reader<'a, Input: Iterator<Item = Result<String, std::io::Error>>> { |
8110b492 | 105 | input: std::iter::Enumerate<Input>, |
116fc215 | 106 | row: Option<RowInput<'a>>, |
201b9ef3 | 107 | } |
116fc215 | 108 | impl<'a, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'a, Input> { |
201b9ef3 | 109 | fn new(input: Input) -> Self { |
8110b492 SW |
110 | Self { |
111 | input: input.enumerate(), | |
112 | row: None, | |
113 | } | |
201b9ef3 SW |
114 | } |
115 | } | |
116fc215 SW |
116 | impl<'a, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<'a, Input> { |
117 | type Item = Result<RowInput<'a>, std::io::Error>; | |
201b9ef3 SW |
118 | fn next(&mut self) -> Option<Self::Item> { |
119 | loop { | |
1f6bd845 SW |
120 | match self |
121 | .input | |
122 | .next() | |
116fc215 SW |
123 | // TODO: Don't leak |
124 | .map(|(n, r)| (n, r.map(|line| String::from(line).leak().trim_end()))) | |
1f6bd845 | 125 | { |
201b9ef3 | 126 | None => return Ok(std::mem::take(&mut self.row)).transpose(), |
8110b492 SW |
127 | Some((_, Err(e))) => return Some(Err(e)), |
128 | Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => { | |
201b9ef3 SW |
129 | return Ok(std::mem::take(&mut self.row)).transpose() |
130 | } | |
8110b492 SW |
131 | Some((_, Ok(line))) if line.is_empty() => {} |
132 | Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row { | |
133 | None => { | |
134 | return Some(Err(std::io::Error::other(format!( | |
135 | "{}: Entry with no header", | |
136 | n + 1 | |
137 | )))) | |
138 | } | |
e8657dff | 139 | Some(ref mut row) => row.entries.push(Entry::from(line.trim())), |
201b9ef3 | 140 | }, |
8110b492 | 141 | Some((_, Ok(line))) => { |
201b9ef3 SW |
142 | let prev = std::mem::take(&mut self.row); |
143 | self.row = Some(RowInput { | |
144 | label: line, | |
145 | entries: vec![], | |
146 | }); | |
147 | if prev.is_some() { | |
148 | return Ok(prev).transpose(); | |
149 | } | |
150 | } | |
151 | } | |
152 | } | |
153 | } | |
154 | } | |
155 | ||
116fc215 SW |
156 | fn read_rows( |
157 | input: impl std::io::Read, | |
158 | ) -> impl Iterator<Item = Result<RowInput<'static>, std::io::Error>> { | |
201b9ef3 | 159 | Reader::new(std::io::BufReader::new(input).lines()) |
75bb888a SW |
160 | } |
161 | ||
58b5f36d SW |
162 | fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> { |
163 | let mut counts: Vec<_> = rows | |
164 | .iter() | |
b8907770 SW |
165 | .flat_map(|r| { |
166 | r.entries | |
167 | .iter() | |
168 | .map(|e| &e.col) | |
169 | .collect::<HashSet<_>>() | |
170 | .into_iter() | |
171 | }) | |
172 | .fold(HashMap::new(), |mut cs, col| { | |
116fc215 | 173 | cs.entry(String::from(*col)) |
58b5f36d | 174 | .and_modify(|n| *n += 1) |
f272e502 | 175 | .or_insert(1); |
58b5f36d | 176 | cs |
f272e502 | 177 | }) |
58b5f36d SW |
178 | .into_iter() |
179 | .map(|(col, n)| (n, col)) | |
180 | .collect(); | |
38d1167a | 181 | counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol))); |
58b5f36d | 182 | counts |
f272e502 | 183 | } |
d22b2e05 SW |
184 | fn column_order(rows: &[RowInput]) -> Vec<String> { |
185 | column_counts(rows) | |
186 | .into_iter() | |
187 | .map(|(_, col)| col) | |
188 | .collect() | |
189 | } | |
f272e502 | 190 | |
70436f23 | 191 | fn render_instance(entry: &Entry) -> HTML { |
de408c29 | 192 | match &entry.instance { |
70436f23 SW |
193 | None => HTML::from("✓"), |
194 | Some(instance) => HTML::escape(instance.as_ref()), | |
de408c29 SW |
195 | } |
196 | } | |
197 | ||
70436f23 SW |
198 | fn render_cell(col: &str, row: &RowInput) -> HTML { |
199 | let row_label = HTML::escape(row.label.as_ref()); | |
200 | let col_label = HTML::escape(col); | |
de408c29 | 201 | let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect(); |
70436f23 | 202 | let class = HTML::from(if entries.is_empty() { "" } else { "yes" }); |
de408c29 SW |
203 | let all_empty = entries.iter().all(|e| e.instance.is_none()); |
204 | let contents = if entries.is_empty() || (all_empty && entries.len() == 1) { | |
70436f23 | 205 | HTML::from("") |
de408c29 | 206 | } else if all_empty { |
70436f23 | 207 | HTML(format!("{}", entries.len())) |
de408c29 | 208 | } else { |
70436f23 SW |
209 | HTML( |
210 | entries | |
211 | .iter() | |
212 | .map(|i| render_instance(i)) | |
213 | .map(|html| html.0) // Waiting for slice_concat_trait to stabilize | |
214 | .collect::<Vec<_>>() | |
215 | .join(" "), | |
216 | ) | |
de408c29 | 217 | }; |
70436f23 | 218 | HTML(format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col_label}')\" onmouseout=\"ch2('{row_label}','{col_label}')\">{contents}</td>")) |
de408c29 SW |
219 | } |
220 | ||
70436f23 | 221 | fn render_row(columns: &[String], row: &RowInput) -> HTML { |
de408c29 | 222 | // This is O(n^2) & doesn't need to be |
70436f23 SW |
223 | let row_label = HTML::escape(row.label.as_ref()); |
224 | HTML(format!( | |
92476edc | 225 | "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n", |
de408c29 SW |
226 | &columns |
227 | .iter() | |
228 | .map(|col| render_cell(col, row)) | |
70436f23 SW |
229 | .collect::<HTML>() |
230 | )) | |
de408c29 SW |
231 | } |
232 | ||
70436f23 SW |
233 | fn render_column_headers(columns: &[String]) -> HTML { |
234 | HTML( | |
235 | String::from("<tr class=\"key\"><th></th>") | |
236 | + &columns.iter().fold(String::new(), |mut acc, col| { | |
237 | let col_header = HTML::escape(col.as_ref()); | |
238 | write!( | |
239 | &mut acc, | |
240 | "<th id=\"{col_header}\"><div><div>{col_header}</div></div></th>" | |
241 | ) | |
242 | .unwrap(); | |
243 | acc | |
244 | }) | |
245 | + "</tr>\n", | |
246 | ) | |
76638ea1 SW |
247 | } |
248 | ||
4b99fb70 SW |
249 | /// # Errors |
250 | /// | |
251 | /// Will return `Err` if | |
252 | /// * there's an i/o error while reading `input` | |
253 | /// * the log has invalid syntax: | |
254 | /// * an indented line with no preceding non-indented line | |
70436f23 | 255 | pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> { |
4b99fb70 | 256 | let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?; |
de408c29 | 257 | let columns = column_order(&rows); |
70436f23 SW |
258 | Ok(HTML(format!( |
259 | "{HEADER}{}{}{FOOTER}", | |
260 | render_column_headers(&columns), | |
261 | rows.into_iter() | |
de408c29 | 262 | .map(|r| render_row(&columns, &r)) |
70436f23 SW |
263 | .collect::<HTML>() |
264 | ))) | |
ece97615 | 265 | } |
75bb888a SW |
266 | |
267 | #[cfg(test)] | |
268 | mod tests { | |
269 | use super::*; | |
270 | ||
b8907770 SW |
271 | #[test] |
272 | fn test_parse_entry() { | |
273 | assert_eq!( | |
274 | Entry::from("foo"), | |
275 | Entry { | |
116fc215 | 276 | col: "foo", |
b8907770 SW |
277 | instance: None |
278 | } | |
279 | ); | |
280 | assert_eq!( | |
281 | Entry::from("foo:bar"), | |
282 | Entry { | |
116fc215 SW |
283 | col: "foo", |
284 | instance: Some("bar") | |
b8907770 SW |
285 | } |
286 | ); | |
0d999bc3 SW |
287 | assert_eq!( |
288 | Entry::from("foo: bar"), | |
289 | Entry { | |
116fc215 SW |
290 | col: "foo", |
291 | instance: Some("bar") | |
0d999bc3 SW |
292 | } |
293 | ); | |
b8907770 SW |
294 | } |
295 | ||
75bb888a SW |
296 | #[test] |
297 | fn test_read_rows() { | |
298 | assert_eq!( | |
201b9ef3 | 299 | read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(), |
75bb888a | 300 | vec![RowInput { |
116fc215 | 301 | label: "foo", |
75bb888a SW |
302 | entries: vec![] |
303 | }] | |
304 | ); | |
9dfa98b7 | 305 | assert_eq!( |
201b9ef3 | 306 | read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(), |
9dfa98b7 | 307 | vec![RowInput { |
116fc215 | 308 | label: "bar", |
9dfa98b7 SW |
309 | entries: vec![] |
310 | }] | |
311 | ); | |
2aa9ef94 | 312 | assert_eq!( |
201b9ef3 | 313 | read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(), |
2aa9ef94 SW |
314 | vec![ |
315 | RowInput { | |
116fc215 | 316 | label: "foo", |
2aa9ef94 SW |
317 | entries: vec![] |
318 | }, | |
319 | RowInput { | |
116fc215 | 320 | label: "bar", |
2aa9ef94 SW |
321 | entries: vec![] |
322 | } | |
323 | ] | |
324 | ); | |
201b9ef3 SW |
325 | assert_eq!( |
326 | read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(), | |
327 | vec![RowInput { | |
116fc215 | 328 | label: "foo", |
e8657dff | 329 | entries: vec![Entry::from("bar")] |
201b9ef3 SW |
330 | }] |
331 | ); | |
332 | assert_eq!( | |
333 | read_rows(&b"foo\n bar\n baz\n"[..]) | |
334 | .flatten() | |
335 | .collect::<Vec<_>>(), | |
336 | vec![RowInput { | |
116fc215 | 337 | label: "foo", |
e8657dff | 338 | entries: vec![Entry::from("bar"), Entry::from("baz")] |
201b9ef3 SW |
339 | }] |
340 | ); | |
341 | assert_eq!( | |
342 | read_rows(&b"foo\n\nbar\n"[..]) | |
343 | .flatten() | |
344 | .collect::<Vec<_>>(), | |
345 | vec![ | |
346 | RowInput { | |
116fc215 | 347 | label: "foo", |
201b9ef3 SW |
348 | entries: vec![] |
349 | }, | |
350 | RowInput { | |
116fc215 | 351 | label: "bar", |
201b9ef3 SW |
352 | entries: vec![] |
353 | } | |
354 | ] | |
355 | ); | |
1f6bd845 SW |
356 | assert_eq!( |
357 | read_rows(&b"foo\n \nbar\n"[..]) | |
358 | .flatten() | |
359 | .collect::<Vec<_>>(), | |
360 | vec![ | |
361 | RowInput { | |
116fc215 | 362 | label: "foo", |
1f6bd845 SW |
363 | entries: vec![] |
364 | }, | |
365 | RowInput { | |
116fc215 | 366 | label: "bar", |
1f6bd845 SW |
367 | entries: vec![] |
368 | } | |
369 | ] | |
370 | ); | |
371 | assert_eq!( | |
372 | read_rows(&b"foo \n bar \n"[..]) | |
373 | .flatten() | |
374 | .collect::<Vec<_>>(), | |
375 | vec![RowInput { | |
116fc215 | 376 | label: "foo", |
e8657dff | 377 | entries: vec![Entry::from("bar")] |
1f6bd845 SW |
378 | }] |
379 | ); | |
201b9ef3 SW |
380 | |
381 | let bad = read_rows(&b" foo"[..]).next().unwrap(); | |
382 | assert!(bad.is_err()); | |
8110b492 | 383 | assert!(format!("{bad:?}").contains("1: Entry with no header")); |
201b9ef3 SW |
384 | |
385 | let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap(); | |
386 | assert!(bad2.is_err()); | |
8110b492 | 387 | assert!(format!("{bad2:?}").contains("3: Entry with no header")); |
75bb888a | 388 | } |
f272e502 SW |
389 | |
390 | #[test] | |
391 | fn test_column_counts() { | |
392 | assert_eq!( | |
393 | column_counts( | |
394 | &read_rows(&b"foo\n bar\n baz\n"[..]) | |
395 | .collect::<Result<Vec<_>, _>>() | |
396 | .unwrap() | |
397 | ), | |
58b5f36d | 398 | vec![(1, String::from("bar")), (1, String::from("baz"))] |
f272e502 SW |
399 | ); |
400 | assert_eq!( | |
401 | column_counts( | |
402 | &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]) | |
403 | .collect::<Result<Vec<_>, _>>() | |
404 | .unwrap() | |
405 | ), | |
38d1167a | 406 | vec![(2, String::from("baz")), (1, String::from("bar"))] |
f272e502 | 407 | ); |
397ef957 SW |
408 | assert_eq!( |
409 | column_counts( | |
410 | &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]) | |
411 | .collect::<Result<Vec<_>, _>>() | |
412 | .unwrap() | |
413 | ), | |
38d1167a | 414 | vec![(2, String::from("baz")), (1, String::from("bar"))] |
397ef957 | 415 | ); |
b8907770 SW |
416 | assert_eq!( |
417 | column_counts( | |
418 | &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]) | |
419 | .collect::<Result<Vec<_>, _>>() | |
420 | .unwrap() | |
421 | ), | |
38d1167a | 422 | vec![(2, String::from("baz")), (1, String::from("bar"))] |
b8907770 | 423 | ); |
f272e502 | 424 | } |
de408c29 SW |
425 | |
426 | #[test] | |
427 | fn test_render_cell() { | |
428 | assert_eq!( | |
429 | render_cell( | |
430 | "foo", | |
431 | &RowInput { | |
116fc215 | 432 | label: "nope", |
de408c29 SW |
433 | entries: vec![] |
434 | } | |
435 | ), | |
70436f23 | 436 | HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>") |
de408c29 SW |
437 | ); |
438 | assert_eq!( | |
439 | render_cell( | |
440 | "foo", | |
441 | &RowInput { | |
116fc215 | 442 | label: "nope", |
de408c29 SW |
443 | entries: vec![Entry::from("bar")] |
444 | } | |
445 | ), | |
70436f23 | 446 | HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>") |
de408c29 SW |
447 | ); |
448 | assert_eq!( | |
449 | render_cell( | |
450 | "foo", | |
451 | &RowInput { | |
116fc215 | 452 | label: "nope", |
de408c29 SW |
453 | entries: vec![Entry::from("foo")] |
454 | } | |
455 | ), | |
70436f23 | 456 | HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>") |
de408c29 SW |
457 | ); |
458 | assert_eq!( | |
459 | render_cell( | |
460 | "foo", | |
461 | &RowInput { | |
116fc215 | 462 | label: "nope", |
de408c29 SW |
463 | entries: vec![Entry::from("foo"), Entry::from("foo")] |
464 | } | |
465 | ), | |
70436f23 | 466 | HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>") |
de408c29 SW |
467 | ); |
468 | assert_eq!( | |
469 | render_cell( | |
470 | "foo", | |
471 | &RowInput { | |
116fc215 | 472 | label: "nope", |
de408c29 SW |
473 | entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")] |
474 | } | |
475 | ), | |
70436f23 | 476 | HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>") |
de408c29 SW |
477 | ); |
478 | assert_eq!( | |
479 | render_cell( | |
480 | "foo", | |
481 | &RowInput { | |
116fc215 | 482 | label: "nope", |
de408c29 SW |
483 | entries: vec![Entry::from("foo: 5"), Entry::from("foo")] |
484 | } | |
485 | ), | |
70436f23 SW |
486 | HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>") |
487 | ); | |
488 | assert_eq!( | |
489 | render_cell( | |
490 | "heart", | |
491 | &RowInput { | |
116fc215 | 492 | label: "nope", |
70436f23 SW |
493 | entries: vec![Entry::from("heart: <3")] |
494 | } | |
495 | ), | |
496 | HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','heart')\" onmouseout=\"ch2('nope','heart')\"><3</td>") | |
497 | ); | |
498 | assert_eq!( | |
499 | render_cell( | |
500 | "foo", | |
501 | &RowInput { | |
116fc215 | 502 | label: "bob's", |
70436f23 SW |
503 | entries: vec![Entry::from("foo")] |
504 | } | |
505 | ), | |
506 | HTML::from("<td class=\"yes\" onmouseover=\"h2('bob's','foo')\" onmouseout=\"ch2('bob's','foo')\"></td>") | |
de408c29 SW |
507 | ); |
508 | } | |
75bb888a | 509 | } |