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