]> git.scottworley.com Git - tablify/blob - src/lib.rs
Move the trim_end() down
[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.input.next() {
121 None => return Ok(std::mem::take(&mut self.row)).transpose(),
122 Some((_, Err(e))) => return Some(Err(e)),
123 Some((_, Ok(line))) if line.trim_end().is_empty() && self.row.is_some() => {
124 return Ok(std::mem::take(&mut self.row)).transpose()
125 }
126 Some((_, Ok(line))) if line.trim_end().is_empty() => {}
127 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
128 None => {
129 return Some(Err(std::io::Error::other(format!(
130 "{}: Entry with no header",
131 n + 1
132 ))))
133 }
134 // TODO: Don't leak
135 Some(ref mut row) => row.entries.push(Entry::from(line.leak().trim())),
136 },
137 Some((_, Ok(line))) => {
138 let prev = std::mem::take(&mut self.row);
139 self.row = Some(RowInput {
140 // TODO: Don't leak
141 label: line.leak().trim_end(),
142 entries: vec![],
143 });
144 if prev.is_some() {
145 return Ok(prev).transpose();
146 }
147 }
148 }
149 }
150 }
151 }
152
153 fn read_rows(
154 input: impl std::io::Read,
155 ) -> impl Iterator<Item = Result<RowInput<'static>, std::io::Error>> {
156 Reader::new(std::io::BufReader::new(input).lines())
157 }
158
159 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
160 let mut counts: Vec<_> = rows
161 .iter()
162 .flat_map(|r| {
163 r.entries
164 .iter()
165 .map(|e| &e.col)
166 .collect::<HashSet<_>>()
167 .into_iter()
168 })
169 .fold(HashMap::new(), |mut cs, col| {
170 cs.entry(String::from(*col))
171 .and_modify(|n| *n += 1)
172 .or_insert(1);
173 cs
174 })
175 .into_iter()
176 .map(|(col, n)| (n, col))
177 .collect();
178 counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
179 counts
180 }
181 fn column_order(rows: &[RowInput]) -> Vec<String> {
182 column_counts(rows)
183 .into_iter()
184 .map(|(_, col)| col)
185 .collect()
186 }
187
188 fn render_instance(entry: &Entry) -> HTML {
189 match &entry.instance {
190 None => HTML::from("✓"),
191 Some(instance) => HTML::escape(instance.as_ref()),
192 }
193 }
194
195 fn render_cell(col: &str, row: &RowInput) -> HTML {
196 let row_label = HTML::escape(row.label.as_ref());
197 let col_label = HTML::escape(col);
198 let entries: Vec<&Entry> = row.entries.iter().filter(|e| e.col == col).collect();
199 let class = HTML::from(if entries.is_empty() { "" } else { "yes" });
200 let all_empty = entries.iter().all(|e| e.instance.is_none());
201 let contents = if entries.is_empty() || (all_empty && entries.len() == 1) {
202 HTML::from("")
203 } else if all_empty {
204 HTML(format!("{}", entries.len()))
205 } else {
206 HTML(
207 entries
208 .iter()
209 .map(|i| render_instance(i))
210 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
211 .collect::<Vec<_>>()
212 .join(" "),
213 )
214 };
215 HTML(format!("<td class=\"{class}\" onmouseover=\"h2('{row_label}','{col_label}')\" onmouseout=\"ch2('{row_label}','{col_label}')\">{contents}</td>"))
216 }
217
218 fn render_row(columns: &[String], row: &RowInput) -> HTML {
219 // This is O(n^2) & doesn't need to be
220 let row_label = HTML::escape(row.label.as_ref());
221 HTML(format!(
222 "<tr><th id=\"{row_label}\">{row_label}</th>{}</tr>\n",
223 &columns
224 .iter()
225 .map(|col| render_cell(col, row))
226 .collect::<HTML>()
227 ))
228 }
229
230 fn render_column_headers(columns: &[String]) -> HTML {
231 HTML(
232 String::from("<tr class=\"key\"><th></th>")
233 + &columns.iter().fold(String::new(), |mut acc, col| {
234 let col_header = HTML::escape(col.as_ref());
235 write!(
236 &mut acc,
237 "<th id=\"{col_header}\"><div><div>{col_header}</div></div></th>"
238 )
239 .unwrap();
240 acc
241 })
242 + "</tr>\n",
243 )
244 }
245
246 /// # Errors
247 ///
248 /// Will return `Err` if
249 /// * there's an i/o error while reading `input`
250 /// * the log has invalid syntax:
251 /// * an indented line with no preceding non-indented line
252 pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
253 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
254 let columns = column_order(&rows);
255 Ok(HTML(format!(
256 "{HEADER}{}{}{FOOTER}",
257 render_column_headers(&columns),
258 rows.into_iter()
259 .map(|r| render_row(&columns, &r))
260 .collect::<HTML>()
261 )))
262 }
263
264 #[cfg(test)]
265 mod tests {
266 use super::*;
267
268 #[test]
269 fn test_parse_entry() {
270 assert_eq!(
271 Entry::from("foo"),
272 Entry {
273 col: "foo",
274 instance: None
275 }
276 );
277 assert_eq!(
278 Entry::from("foo:bar"),
279 Entry {
280 col: "foo",
281 instance: Some("bar")
282 }
283 );
284 assert_eq!(
285 Entry::from("foo: bar"),
286 Entry {
287 col: "foo",
288 instance: Some("bar")
289 }
290 );
291 }
292
293 #[test]
294 fn test_read_rows() {
295 assert_eq!(
296 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
297 vec![RowInput {
298 label: "foo",
299 entries: vec![]
300 }]
301 );
302 assert_eq!(
303 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
304 vec![RowInput {
305 label: "bar",
306 entries: vec![]
307 }]
308 );
309 assert_eq!(
310 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
311 vec![
312 RowInput {
313 label: "foo",
314 entries: vec![]
315 },
316 RowInput {
317 label: "bar",
318 entries: vec![]
319 }
320 ]
321 );
322 assert_eq!(
323 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
324 vec![RowInput {
325 label: "foo",
326 entries: vec![Entry::from("bar")]
327 }]
328 );
329 assert_eq!(
330 read_rows(&b"foo\n bar\n baz\n"[..])
331 .flatten()
332 .collect::<Vec<_>>(),
333 vec![RowInput {
334 label: "foo",
335 entries: vec![Entry::from("bar"), Entry::from("baz")]
336 }]
337 );
338 assert_eq!(
339 read_rows(&b"foo\n\nbar\n"[..])
340 .flatten()
341 .collect::<Vec<_>>(),
342 vec![
343 RowInput {
344 label: "foo",
345 entries: vec![]
346 },
347 RowInput {
348 label: "bar",
349 entries: vec![]
350 }
351 ]
352 );
353 assert_eq!(
354 read_rows(&b"foo\n \nbar\n"[..])
355 .flatten()
356 .collect::<Vec<_>>(),
357 vec![
358 RowInput {
359 label: "foo",
360 entries: vec![]
361 },
362 RowInput {
363 label: "bar",
364 entries: vec![]
365 }
366 ]
367 );
368 assert_eq!(
369 read_rows(&b"foo \n bar \n"[..])
370 .flatten()
371 .collect::<Vec<_>>(),
372 vec![RowInput {
373 label: "foo",
374 entries: vec![Entry::from("bar")]
375 }]
376 );
377
378 let bad = read_rows(&b" foo"[..]).next().unwrap();
379 assert!(bad.is_err());
380 assert!(format!("{bad:?}").contains("1: Entry with no header"));
381
382 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
383 assert!(bad2.is_err());
384 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
385 }
386
387 #[test]
388 fn test_column_counts() {
389 assert_eq!(
390 column_counts(
391 &read_rows(&b"foo\n bar\n baz\n"[..])
392 .collect::<Result<Vec<_>, _>>()
393 .unwrap()
394 ),
395 vec![(1, String::from("bar")), (1, String::from("baz"))]
396 );
397 assert_eq!(
398 column_counts(
399 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
400 .collect::<Result<Vec<_>, _>>()
401 .unwrap()
402 ),
403 vec![(2, String::from("baz")), (1, String::from("bar"))]
404 );
405 assert_eq!(
406 column_counts(
407 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
408 .collect::<Result<Vec<_>, _>>()
409 .unwrap()
410 ),
411 vec![(2, String::from("baz")), (1, String::from("bar"))]
412 );
413 assert_eq!(
414 column_counts(
415 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
416 .collect::<Result<Vec<_>, _>>()
417 .unwrap()
418 ),
419 vec![(2, String::from("baz")), (1, String::from("bar"))]
420 );
421 }
422
423 #[test]
424 fn test_render_cell() {
425 assert_eq!(
426 render_cell(
427 "foo",
428 &RowInput {
429 label: "nope",
430 entries: vec![]
431 }
432 ),
433 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
434 );
435 assert_eq!(
436 render_cell(
437 "foo",
438 &RowInput {
439 label: "nope",
440 entries: vec![Entry::from("bar")]
441 }
442 ),
443 HTML::from("<td class=\"\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
444 );
445 assert_eq!(
446 render_cell(
447 "foo",
448 &RowInput {
449 label: "nope",
450 entries: vec![Entry::from("foo")]
451 }
452 ),
453 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\"></td>")
454 );
455 assert_eq!(
456 render_cell(
457 "foo",
458 &RowInput {
459 label: "nope",
460 entries: vec![Entry::from("foo"), Entry::from("foo")]
461 }
462 ),
463 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">2</td>")
464 );
465 assert_eq!(
466 render_cell(
467 "foo",
468 &RowInput {
469 label: "nope",
470 entries: vec![Entry::from("foo: 5"), Entry::from("foo: 10")]
471 }
472 ),
473 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 10</td>")
474 );
475 assert_eq!(
476 render_cell(
477 "foo",
478 &RowInput {
479 label: "nope",
480 entries: vec![Entry::from("foo: 5"), Entry::from("foo")]
481 }
482 ),
483 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','foo')\" onmouseout=\"ch2('nope','foo')\">5 ✓</td>")
484 );
485 assert_eq!(
486 render_cell(
487 "heart",
488 &RowInput {
489 label: "nope",
490 entries: vec![Entry::from("heart: <3")]
491 }
492 ),
493 HTML::from("<td class=\"yes\" onmouseover=\"h2('nope','heart')\" onmouseout=\"ch2('nope','heart')\">&lt;3</td>")
494 );
495 assert_eq!(
496 render_cell(
497 "foo",
498 &RowInput {
499 label: "bob's",
500 entries: vec![Entry::from("foo")]
501 }
502 ),
503 HTML::from("<td class=\"yes\" onmouseover=\"h2('bob&#39;s','foo')\" onmouseout=\"ch2('bob&#39;s','foo')\"></td>")
504 );
505 }
506 }