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