]>
Commit | Line | Data |
---|---|---|
1 | use std::collections::{HashMap, HashSet}; | |
2 | use std::io::BufRead; | |
3 | use std::iter::Iterator; | |
4 | ||
5 | const HEADER: &str = "<!DOCTYPE html> | |
6 | <html> | |
7 | <head> | |
8 | <meta charset=\"utf-8\"> | |
9 | <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> | |
10 | <style> | |
11 | /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */ | |
12 | th, td { white-space: nowrap; } | |
13 | th { text-align: left; font-weight: normal; } | |
14 | table { border-collapse: collapse } | |
15 | tr.key > th { height: 8em; vertical-align: bottom; line-height: 1 } | |
16 | tr.key > th > div { width: 1em; } | |
17 | tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) } | |
18 | td { border: thin solid gray; } | |
19 | td.numeric { text-align: right; } | |
20 | td.yes { border: thin solid gray; background-color: gray; } | |
21 | td.spacer { border: none; } | |
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; } | |
24 | img { height: 1.2em; } | |
25 | </style> | |
26 | <script> | |
27 | function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( \"highlight\"); } } | |
28 | function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove(\"highlight\"); } } | |
29 | function h2(a, b) { highlight(a); highlight(b); } | |
30 | function ch2(a, b) { clear_highlight(a); clear_highlight(b); } | |
31 | </script> | |
32 | </head> | |
33 | <body> | |
34 | <table> | |
35 | <tbody>"; | |
36 | const FOOTER: &str = " </tbody> | |
37 | </table> | |
38 | </body> | |
39 | </html>"; | |
40 | ||
41 | #[derive(Debug, PartialEq, Eq, Hash)] | |
42 | struct Entry { | |
43 | col: String, | |
44 | instance: Option<String>, | |
45 | } | |
46 | impl From<&str> for Entry { | |
47 | fn from(value: &str) -> Entry { | |
48 | match value.split_once(':') { | |
49 | None => Entry { | |
50 | col: String::from(value), | |
51 | instance: None, | |
52 | }, | |
53 | Some((col, instance)) => Entry { | |
54 | col: String::from(col.trim()), | |
55 | instance: Some(String::from(instance.trim())), | |
56 | }, | |
57 | } | |
58 | } | |
59 | } | |
60 | ||
61 | #[derive(Debug, PartialEq, Eq)] | |
62 | struct RowInput { | |
63 | label: String, | |
64 | entries: Vec<Entry>, | |
65 | } | |
66 | ||
67 | struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> { | |
68 | input: std::iter::Enumerate<Input>, | |
69 | row: Option<RowInput>, | |
70 | } | |
71 | impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> { | |
72 | fn new(input: Input) -> Self { | |
73 | Self { | |
74 | input: input.enumerate(), | |
75 | row: None, | |
76 | } | |
77 | } | |
78 | } | |
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> { | |
82 | loop { | |
83 | match self | |
84 | .input | |
85 | .next() | |
86 | .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end())))) | |
87 | { | |
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() | |
92 | } | |
93 | Some((_, Ok(line))) if line.is_empty() => {} | |
94 | Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row { | |
95 | None => { | |
96 | return Some(Err(std::io::Error::other(format!( | |
97 | "{}: Entry with no header", | |
98 | n + 1 | |
99 | )))) | |
100 | } | |
101 | Some(ref mut row) => row.entries.push(Entry::from(line.trim())), | |
102 | }, | |
103 | Some((_, Ok(line))) => { | |
104 | let prev = std::mem::take(&mut self.row); | |
105 | self.row = Some(RowInput { | |
106 | label: line, | |
107 | entries: vec![], | |
108 | }); | |
109 | if prev.is_some() { | |
110 | return Ok(prev).transpose(); | |
111 | } | |
112 | } | |
113 | } | |
114 | } | |
115 | } | |
116 | } | |
117 | ||
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()) | |
120 | } | |
121 | ||
122 | fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> { | |
123 | let mut counts: Vec<_> = rows | |
124 | .iter() | |
125 | .flat_map(|r| { | |
126 | r.entries | |
127 | .iter() | |
128 | .map(|e| &e.col) | |
129 | .collect::<HashSet<_>>() | |
130 | .into_iter() | |
131 | }) | |
132 | .fold(HashMap::new(), |mut cs, col| { | |
133 | cs.entry(String::from(col)) | |
134 | .and_modify(|n| *n += 1) | |
135 | .or_insert(1); | |
136 | cs | |
137 | }) | |
138 | .into_iter() | |
139 | .map(|(col, n)| (n, col)) | |
140 | .collect(); | |
141 | counts.sort(); | |
142 | counts | |
143 | } | |
144 | fn column_order(rows: &[RowInput]) -> Vec<String> { | |
145 | column_counts(rows) | |
146 | .into_iter() | |
147 | .map(|(_, col)| col) | |
148 | .collect() | |
149 | } | |
150 | ||
151 | fn render_instance(entry: &Entry) -> String { | |
152 | match &entry.instance { | |
153 | None => String::from("✓ "), | |
154 | Some(instance) => String::from(instance) + " ", | |
155 | } | |
156 | } | |
157 | ||
158 | fn render_cell(col: &str, row: &RowInput) -> String { | |
159 | // TODO: Escape HTML special characters | |
160 | let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect(); | |
161 | let class = if entries.is_empty() { "" } else { "yes" }; | |
162 | let all_empty = entries.iter().all(|e| e.instance.is_none()); | |
163 | let contents = if entries.is_empty() || (all_empty && entries.len() == 1) { | |
164 | String::new() | |
165 | } else if all_empty { | |
166 | format!("{}", entries.len()) | |
167 | } else { | |
168 | entries | |
169 | .iter() | |
170 | .map(|i| render_instance(i)) | |
171 | .collect::<String>() | |
172 | }; | |
173 | format!("<td class=\"{class}\">{}</td>", contents.trim()) | |
174 | } | |
175 | ||
176 | fn render_row(columns: &[String], row: &RowInput) -> String { | |
177 | // This is O(n^2) & doesn't need to be | |
178 | // TODO: Escape HTML special characters | |
179 | format!( | |
180 | "<tr><th>{}</th>{}</tr>\n", | |
181 | row.label, | |
182 | &columns | |
183 | .iter() | |
184 | .map(|col| render_cell(col, row)) | |
185 | .collect::<String>() | |
186 | ) | |
187 | } | |
188 | ||
189 | /// # Errors | |
190 | /// | |
191 | /// Will return `Err` if | |
192 | /// * there's an i/o error while reading `input` | |
193 | /// * the log has invalid syntax: | |
194 | /// * an indented line with no preceding non-indented line | |
195 | pub fn tablify(input: impl std::io::Read) -> Result<String, std::io::Error> { | |
196 | let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?; | |
197 | let columns = column_order(&rows); | |
198 | Ok(String::from(HEADER) | |
199 | + &rows | |
200 | .into_iter() | |
201 | .map(|r| render_row(&columns, &r)) | |
202 | .collect::<String>() | |
203 | + FOOTER) | |
204 | } | |
205 | ||
206 | #[cfg(test)] | |
207 | mod tests { | |
208 | use super::*; | |
209 | ||
210 | #[test] | |
211 | fn test_parse_entry() { | |
212 | assert_eq!( | |
213 | Entry::from("foo"), | |
214 | Entry { | |
215 | col: String::from("foo"), | |
216 | instance: None | |
217 | } | |
218 | ); | |
219 | assert_eq!( | |
220 | Entry::from("foo:bar"), | |
221 | Entry { | |
222 | col: String::from("foo"), | |
223 | instance: Some(String::from("bar")) | |
224 | } | |
225 | ); | |
226 | assert_eq!( | |
227 | Entry::from("foo: bar"), | |
228 | Entry { | |
229 | col: String::from("foo"), | |
230 | instance: Some(String::from("bar")) | |
231 | } | |
232 | ); | |
233 | } | |
234 | ||
235 | #[test] | |
236 | fn test_read_rows() { | |
237 | assert_eq!( | |
238 | read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(), | |
239 | vec![RowInput { | |
240 | label: String::from("foo"), | |
241 | entries: vec![] | |
242 | }] | |
243 | ); | |
244 | assert_eq!( | |
245 | read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(), | |
246 | vec![RowInput { | |
247 | label: String::from("bar"), | |
248 | entries: vec![] | |
249 | }] | |
250 | ); | |
251 | assert_eq!( | |
252 | read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(), | |
253 | vec![ | |
254 | RowInput { | |
255 | label: String::from("foo"), | |
256 | entries: vec![] | |
257 | }, | |
258 | RowInput { | |
259 | label: String::from("bar"), | |
260 | entries: vec![] | |
261 | } | |
262 | ] | |
263 | ); | |
264 | assert_eq!( | |
265 | read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(), | |
266 | vec![RowInput { | |
267 | label: String::from("foo"), | |
268 | entries: vec![Entry::from("bar")] | |
269 | }] | |
270 | ); | |
271 | assert_eq!( | |
272 | read_rows(&b"foo\n bar\n baz\n"[..]) | |
273 | .flatten() | |
274 | .collect::<Vec<_>>(), | |
275 | vec![RowInput { | |
276 | label: String::from("foo"), | |
277 | entries: vec![Entry::from("bar"), Entry::from("baz")] | |
278 | }] | |
279 | ); | |
280 | assert_eq!( | |
281 | read_rows(&b"foo\n\nbar\n"[..]) | |
282 | .flatten() | |
283 | .collect::<Vec<_>>(), | |
284 | vec![ | |
285 | RowInput { | |
286 | label: String::from("foo"), | |
287 | entries: vec![] | |
288 | }, | |
289 | RowInput { | |
290 | label: String::from("bar"), | |
291 | entries: vec![] | |
292 | } | |
293 | ] | |
294 | ); | |
295 | assert_eq!( | |
296 | read_rows(&b"foo\n \nbar\n"[..]) | |
297 | .flatten() | |
298 | .collect::<Vec<_>>(), | |
299 | vec![ | |
300 | RowInput { | |
301 | label: String::from("foo"), | |
302 | entries: vec![] | |
303 | }, | |
304 | RowInput { | |
305 | label: String::from("bar"), | |
306 | entries: vec![] | |
307 | } | |
308 | ] | |
309 | ); | |
310 | assert_eq!( | |
311 | read_rows(&b"foo \n bar \n"[..]) | |
312 | .flatten() | |
313 | .collect::<Vec<_>>(), | |
314 | vec![RowInput { | |
315 | label: String::from("foo"), | |
316 | entries: vec![Entry::from("bar")] | |
317 | }] | |
318 | ); | |
319 | ||
320 | let bad = read_rows(&b" foo"[..]).next().unwrap(); | |
321 | assert!(bad.is_err()); | |
322 | assert!(format!("{bad:?}").contains("1: Entry with no header")); | |
323 | ||
324 | let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap(); | |
325 | assert!(bad2.is_err()); | |
326 | assert!(format!("{bad2:?}").contains("3: Entry with no header")); | |
327 | } | |
328 | ||
329 | #[test] | |
330 | fn test_column_counts() { | |
331 | assert_eq!( | |
332 | column_counts( | |
333 | &read_rows(&b"foo\n bar\n baz\n"[..]) | |
334 | .collect::<Result<Vec<_>, _>>() | |
335 | .unwrap() | |
336 | ), | |
337 | vec![(1, String::from("bar")), (1, String::from("baz"))] | |
338 | ); | |
339 | assert_eq!( | |
340 | column_counts( | |
341 | &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]) | |
342 | .collect::<Result<Vec<_>, _>>() | |
343 | .unwrap() | |
344 | ), | |
345 | vec![(1, String::from("bar")), (2, String::from("baz"))] | |
346 | ); | |
347 | assert_eq!( | |
348 | column_counts( | |
349 | &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]) | |
350 | .collect::<Result<Vec<_>, _>>() | |
351 | .unwrap() | |
352 | ), | |
353 | vec![(1, String::from("bar")), (2, String::from("baz"))] | |
354 | ); | |
355 | assert_eq!( | |
356 | column_counts( | |
357 | &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]) | |
358 | .collect::<Result<Vec<_>, _>>() | |
359 | .unwrap() | |
360 | ), | |
361 | vec![(1, String::from("bar")), (2, String::from("baz"))] | |
362 | ); | |
363 | } | |
364 | ||
365 | #[test] | |
366 | fn test_render_cell() { | |
367 | assert_eq!( | |
368 | render_cell( | |
369 | "foo", | |
370 | &RowInput { | |
371 | label: String::from("nope"), | |
372 | entries: vec![] | |
373 | } | |
374 | ), | |
375 | String::from("<td class=\"\"></td>") | |
376 | ); | |
377 | assert_eq!( | |
378 | render_cell( | |
379 | "foo", | |
380 | &RowInput { | |
381 | label: String::from("nope"), | |
382 | entries: vec![Entry::from("bar")] | |
383 | } | |
384 | ), | |
385 | String::from("<td class=\"\"></td>") | |
386 | ); | |
387 | assert_eq!( | |
388 | render_cell( | |
389 | "foo", | |
390 | &RowInput { | |
391 | label: String::from("nope"), | |
392 | entries: vec![Entry::from("foo")] | |
393 | } | |
394 | ), | |
395 | String::from("<td class=\"yes\"></td>") | |
396 | ); | |
397 | assert_eq!( | |
398 | render_cell( | |
399 | "foo", | |
400 | &RowInput { | |
401 | label: String::from("nope"), | |
402 | entries: vec![Entry::from("foo"), Entry::from("foo")] | |
403 | } | |
404 | ), | |
405 | String::from("<td class=\"yes\">2</td>") | |
406 | ); | |
407 | assert_eq!( | |
408 | render_cell( | |
409 | "foo", | |
410 | &RowInput { | |
411 | label: String::from("nope"), | |
412 | entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")] | |
413 | } | |
414 | ), | |
415 | String::from("<td class=\"yes\">5 10</td>") | |
416 | ); | |
417 | assert_eq!( | |
418 | render_cell( | |
419 | "foo", | |
420 | &RowInput { | |
421 | label: String::from("nope"), | |
422 | entries: vec![Entry::from("foo: 5"), Entry::from("foo")] | |
423 | } | |
424 | ), | |
425 | String::from("<td class=\"yes\">5 ✓</td>") | |
426 | ); | |
427 | } | |
428 | } |