]> git.scottworley.com Git - tablify/blob - src/lib.rs
Prefer &str over String
[tablify] / src / lib.rs
1 use std::collections::{HashMap, HashSet};
2 use std::fmt::Write;
3 use std::io::BufRead;
4 use std::iter::Iterator;
5
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>
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; }
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>
34 <tbody>
35 ";
36 const FOOTER: &str = " </tbody>
37 </table>
38 </body>
39 </html>";
40
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("&gt;"),
49 '<' => escaped.push_str("&lt;"),
50 '\'' => escaped.push_str("&#39;"),
51 '"' => escaped.push_str("&quot;"),
52 '&' => escaped.push_str("&amp;"),
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
78 #[derive(Debug, PartialEq, Eq, Hash)]
79 struct Entry<'a> {
80 col: &'a str,
81 instance: Option<&'a str>,
82 }
83 impl<'a> From<&'a str> for Entry<'a> {
84 fn from(value: &'a str) -> Entry<'a> {
85 match value.split_once(':') {
86 None => Entry {
87 col: value,
88 instance: None,
89 },
90 Some((col, instance)) => Entry {
91 col: col.trim(),
92 instance: Some(instance.trim()),
93 },
94 }
95 }
96 }
97
98 #[derive(Debug, PartialEq, Eq)]
99 struct RowInput<'a> {
100 label: &'a str,
101 entries: Vec<Entry<'a>>,
102 }
103
104 struct Reader<'a, Input: Iterator<Item = Result<String, std::io::Error>>> {
105 input: std::iter::Enumerate<Input>,
106 row: Option<RowInput<'a>>,
107 }
108 impl<'a, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'a, Input> {
109 fn new(input: Input) -> Self {
110 Self {
111 input: input.enumerate(),
112 row: None,
113 }
114 }
115 }
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>;
118 fn next(&mut self) -> Option<Self::Item> {
119 loop {
120 match self
121 .input
122 .next()
123 // TODO: Don't leak
124 .map(|(n, r)| (n, r.map(|line| String::from(line).leak().trim_end())))
125 {
126 None => return Ok(std::mem::take(&mut self.row)).transpose(),
127 Some((_, Err(e))) => return Some(Err(e)),
128 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
129 return Ok(std::mem::take(&mut self.row)).transpose()
130 }
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 }
139 Some(ref mut row) => row.entries.push(Entry::from(line.trim())),
140 },
141 Some((_, Ok(line))) => {
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
156 fn read_rows(
157 input: impl std::io::Read,
158 ) -> impl Iterator<Item = Result<RowInput<'static>, std::io::Error>> {
159 Reader::new(std::io::BufReader::new(input).lines())
160 }
161
162 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
163 let mut counts: Vec<_> = rows
164 .iter()
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| {
173 cs.entry(String::from(*col))
174 .and_modify(|n| *n += 1)
175 .or_insert(1);
176 cs
177 })
178 .into_iter()
179 .map(|(col, n)| (n, col))
180 .collect();
181 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
182 counts
183 }
184 fn column_order(rows: &[RowInput]) -> Vec<String> {
185 column_counts(rows)
186 .into_iter()
187 .map(|(_, col)| col)
188 .collect()
189 }
190
191 fn render_instance(entry: &Entry) -> HTML {
192 match &entry.instance {
193 None => HTML::from("✓"),
194 Some(instance) => HTML::escape(instance.as_ref()),
195 }
196 }
197
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);
201 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
202 let class = HTML::from(if entries.is_empty() { "" } else { "yes" });
203 let all_empty = entries.iter().all(|e| e.instance.is_none());
204 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
205 HTML::from("")
206 } else if all_empty {
207 HTML(format!("{}", entries.len()))
208 } else {
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 )
217 };
218 HTML(format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col_label}')\" onmouseout=\"ch2('{row_label}','{col_label}')\">{contents}</td>"))
219 }
220
221 fn render_row(columns: &[String], row: &RowInput) -> HTML {
222 // This is O(n^2) & doesn't need to be
223 let row_label = HTML::escape(row.label.as_ref());
224 HTML(format!(
225 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
226 &columns
227 .iter()
228 .map(|col| render_cell(col, row))
229 .collect::<HTML>()
230 ))
231 }
232
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 )
247 }
248
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
255 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
256 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
257 let columns = column_order(&rows);
258 Ok(HTML(format!(
259 "{HEADER}{}{}{FOOTER}",
260 render_column_headers(&columns),
261 rows.into_iter()
262 .map(|r| render_row(&columns, &r))
263 .collect::<HTML>()
264 )))
265 }
266
267 #[cfg(test)]
268 mod tests {
269 use super::*;
270
271 #[test]
272 fn test_parse_entry() {
273 assert_eq!(
274 Entry::from("foo"),
275 Entry {
276 col: "foo",
277 instance: None
278 }
279 );
280 assert_eq!(
281 Entry::from("foo:bar"),
282 Entry {
283 col: "foo",
284 instance: Some("bar")
285 }
286 );
287 assert_eq!(
288 Entry::from("foo: bar"),
289 Entry {
290 col: "foo",
291 instance: Some("bar")
292 }
293 );
294 }
295
296 #[test]
297 fn test_read_rows() {
298 assert_eq!(
299 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
300 vec![RowInput {
301 label: "foo",
302 entries: vec![]
303 }]
304 );
305 assert_eq!(
306 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
307 vec![RowInput {
308 label: "bar",
309 entries: vec![]
310 }]
311 );
312 assert_eq!(
313 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
314 vec![
315 RowInput {
316 label: "foo",
317 entries: vec![]
318 },
319 RowInput {
320 label: "bar",
321 entries: vec![]
322 }
323 ]
324 );
325 assert_eq!(
326 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
327 vec![RowInput {
328 label: "foo",
329 entries: vec![Entry::from("bar")]
330 }]
331 );
332 assert_eq!(
333 read_rows(&b"foo\n bar\n baz\n"[..])
334 .flatten()
335 .collect::<Vec<_>>(),
336 vec![RowInput {
337 label: "foo",
338 entries: vec![Entry::from("bar"), Entry::from("baz")]
339 }]
340 );
341 assert_eq!(
342 read_rows(&b"foo\n\nbar\n"[..])
343 .flatten()
344 .collect::<Vec<_>>(),
345 vec![
346 RowInput {
347 label: "foo",
348 entries: vec![]
349 },
350 RowInput {
351 label: "bar",
352 entries: vec![]
353 }
354 ]
355 );
356 assert_eq!(
357 read_rows(&b"foo\n \nbar\n"[..])
358 .flatten()
359 .collect::<Vec<_>>(),
360 vec![
361 RowInput {
362 label: "foo",
363 entries: vec![]
364 },
365 RowInput {
366 label: "bar",
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 {
376 label: "foo",
377 entries: vec![Entry::from("bar")]
378 }]
379 );
380
381 let bad = read_rows(&b" foo"[..]).next().unwrap();
382 assert!(bad.is_err());
383 assert!(format!("{bad:?}").contains("1: Entry with no header"));
384
385 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
386 assert!(bad2.is_err());
387 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
388 }
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 ),
398 vec![(1, String::from("bar")), (1, String::from("baz"))]
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 ),
406 vec![(2, String::from("baz")), (1, String::from("bar"))]
407 );
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 ),
414 vec![(2, String::from("baz")), (1, String::from("bar"))]
415 );
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 ),
422 vec![(2, String::from("baz")), (1, String::from("bar"))]
423 );
424 }
425
426 #[test]
427 fn test_render_cell() {
428 assert_eq!(
429 render_cell(
430 "foo",
431 &RowInput {
432 label: "nope",
433 entries: vec![]
434 }
435 ),
436 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
437 );
438 assert_eq!(
439 render_cell(
440 "foo",
441 &RowInput {
442 label: "nope",
443 entries: vec![Entry::from("bar")]
444 }
445 ),
446 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
447 );
448 assert_eq!(
449 render_cell(
450 "foo",
451 &RowInput {
452 label: "nope",
453 entries: vec![Entry::from("foo")]
454 }
455 ),
456 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
457 );
458 assert_eq!(
459 render_cell(
460 "foo",
461 &RowInput {
462 label: "nope",
463 entries: vec![Entry::from("foo"), Entry::from("foo")]
464 }
465 ),
466 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
467 );
468 assert_eq!(
469 render_cell(
470 "foo",
471 &RowInput {
472 label: "nope",
473 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
474 }
475 ),
476 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
477 );
478 assert_eq!(
479 render_cell(
480 "foo",
481 &RowInput {
482 label: "nope",
483 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
484 }
485 ),
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 {
492 label: "nope",
493 entries: vec![Entry::from("heart: <3")]
494 }
495 ),
496 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','heart')\" onmouseout=\"ch2('nope','heart')\">&lt;3</td>")
497 );
498 assert_eq!(
499 render_cell(
500 "foo",
501 &RowInput {
502 label: "bob's",
503 entries: vec![Entry::from("foo")]
504 }
505 ),
506 HTML::from("<td class=\"yes\" onmouseover=\"h2('bob&#39;s','foo')\" onmouseout=\"ch2('bob&#39;s','foo')\"></td>")
507 );
508 }
509 }