]> git.scottworley.com Git - tablify/blame_incremental - src/lib.rs
extract render_instances()
[tablify] / src / lib.rs
... / ...
CommitLineData
1use std::borrow::ToOwned;
2use std::collections::HashMap;
3use std::fmt::Write;
4use std::io::BufRead;
5use std::iter::Iterator;
6
7pub struct Config {}
8
9const 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"#;
39const FOOTER: &str = " </tbody>
40 </table>
41</body>
42</html>";
43
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
81#[derive(Debug, PartialEq, Eq)]
82enum InputLine<'a> {
83 Blank,
84 RowHeader(&'a str),
85 Entry(&'a str, Option<&'a str>),
86}
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 }
99 }
100 }
101}
102
103#[derive(Debug, PartialEq, Eq)]
104struct Row {
105 label: String,
106 entries: HashMap<String, Vec<Option<String>>>,
107}
108
109struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
110 input: std::iter::Enumerate<Input>,
111 row: Option<Row>,
112}
113impl<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}
121impl<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
163fn 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
167fn 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}
183fn column_order(rows: &[Row]) -> Vec<String> {
184 column_counts(rows)
185 .into_iter()
186 .map(|(_, col)| col)
187 .collect()
188}
189
190fn render_one_instance(instance: &Option<String>) -> HTML {
191 match instance {
192 None => HTML::from("✓"),
193 Some(instance) => HTML::escape(instance.as_ref()),
194 }
195}
196
197fn render_instances(instances: &[Option<String>]) -> HTML {
198 let all_empty = instances.iter().all(Option::is_none);
199 if all_empty && instances.len() == 1 {
200 HTML::from("")
201 } else if all_empty {
202 HTML(format!("{}", instances.len()))
203 } else {
204 HTML(
205 instances
206 .iter()
207 .map(render_one_instance)
208 .map(|html| html.0) // Waiting for slice_concat_trait to stabilize
209 .collect::<Vec<_>>()
210 .join(" "),
211 )
212 }
213}
214
215fn render_cell(col: &str, row: &mut Row) -> HTML {
216 let row_label = HTML::escape(row.label.as_ref());
217 let col_label = HTML::escape(col);
218 let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
219 let class = HTML::from(if instances.is_none() { "" } else { "yes" });
220 let contents = match instances {
221 None => HTML::from(""),
222 Some(is) => render_instances(is),
223 };
224 row.entries.remove(col);
225 HTML(format!(
226 r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
227 ))
228}
229
230fn render_row(columns: &[String], row: &mut Row) -> HTML {
231 let row_label = HTML::escape(row.label.as_ref());
232 let cells = columns
233 .iter()
234 .map(|col| render_cell(col, row))
235 .collect::<HTML>();
236 HTML(format!(
237 "<tr><th id=\"{row_label}\">{row_label}</th>{cells}</tr>\n"
238 ))
239}
240
241fn render_column_headers(columns: &[String]) -> HTML {
242 HTML(
243 String::from(r#"<tr class="key"><th></th>"#)
244 + &columns.iter().fold(String::new(), |mut acc, col| {
245 let col_header = HTML::escape(col.as_ref());
246 write!(
247 &mut acc,
248 r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
249 )
250 .unwrap();
251 acc
252 })
253 + "</tr>\n",
254 )
255}
256
257/// # Errors
258///
259/// Will return `Err` if
260/// * there's an i/o error while reading `input`
261/// * the log has invalid syntax:
262/// * an indented line with no preceding non-indented line
263pub fn tablify(config: &Config, input: impl std::io::Read) -> Result<HTML, std::io::Error> {
264 let rows = read_rows(input).collect::<Result<Vec<_>, _>>()?;
265 let columns = column_order(&rows);
266 Ok(HTML(format!(
267 "{HEADER}{}{}{FOOTER}",
268 render_column_headers(&columns),
269 rows.into_iter()
270 .map(|mut r| render_row(&columns, &mut r))
271 .collect::<HTML>()
272 )))
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 #[test]
280 fn test_parse_line() {
281 assert_eq!(InputLine::from(""), InputLine::Blank);
282 assert_eq!(InputLine::from(" "), InputLine::Blank);
283 assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo"));
284 assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo"));
285 assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None));
286 assert_eq!(
287 InputLine::from(" foo:bar"),
288 InputLine::Entry("foo", Some("bar"))
289 );
290 assert_eq!(
291 InputLine::from(" foo: bar"),
292 InputLine::Entry("foo", Some("bar"))
293 );
294 assert_eq!(
295 InputLine::from(" foo: bar "),
296 InputLine::Entry("foo", Some("bar"))
297 );
298 assert_eq!(
299 InputLine::from(" foo: bar "),
300 InputLine::Entry("foo", Some("bar"))
301 );
302 assert_eq!(
303 InputLine::from(" foo : bar "),
304 InputLine::Entry("foo", Some("bar"))
305 );
306 }
307
308 #[test]
309 fn test_read_rows() {
310 assert_eq!(
311 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
312 vec![Row {
313 label: "foo".to_owned(),
314 entries: HashMap::new(),
315 }]
316 );
317 assert_eq!(
318 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
319 vec![Row {
320 label: "bar".to_owned(),
321 entries: HashMap::new(),
322 }]
323 );
324 assert_eq!(
325 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
326 vec![
327 Row {
328 label: "foo".to_owned(),
329 entries: HashMap::new(),
330 },
331 Row {
332 label: "bar".to_owned(),
333 entries: HashMap::new(),
334 }
335 ]
336 );
337 assert_eq!(
338 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
339 vec![Row {
340 label: "foo".to_owned(),
341 entries: HashMap::from([("bar".to_owned(), vec![None])]),
342 }]
343 );
344 assert_eq!(
345 read_rows(&b"foo\n bar\n baz\n"[..])
346 .flatten()
347 .collect::<Vec<_>>(),
348 vec![Row {
349 label: "foo".to_owned(),
350 entries: HashMap::from([
351 ("bar".to_owned(), vec![None]),
352 ("baz".to_owned(), vec![None])
353 ]),
354 }]
355 );
356 assert_eq!(
357 read_rows(&b"foo\n\nbar\n"[..])
358 .flatten()
359 .collect::<Vec<_>>(),
360 vec![
361 Row {
362 label: "foo".to_owned(),
363 entries: HashMap::new(),
364 },
365 Row {
366 label: "bar".to_owned(),
367 entries: HashMap::new(),
368 }
369 ]
370 );
371 assert_eq!(
372 read_rows(&b"foo\n \nbar\n"[..])
373 .flatten()
374 .collect::<Vec<_>>(),
375 vec![
376 Row {
377 label: "foo".to_owned(),
378 entries: HashMap::new(),
379 },
380 Row {
381 label: "bar".to_owned(),
382 entries: HashMap::new(),
383 }
384 ]
385 );
386 assert_eq!(
387 read_rows(&b"foo \n bar \n"[..])
388 .flatten()
389 .collect::<Vec<_>>(),
390 vec![Row {
391 label: "foo".to_owned(),
392 entries: HashMap::from([("bar".to_owned(), vec![None])]),
393 }]
394 );
395
396 let bad = read_rows(&b" foo"[..]).next().unwrap();
397 assert!(bad.is_err());
398 assert!(format!("{bad:?}").contains("1: Entry with no header"));
399
400 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
401 assert!(bad2.is_err());
402 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
403 }
404
405 #[test]
406 fn test_column_counts() {
407 assert_eq!(
408 column_counts(
409 &read_rows(&b"foo\n bar\n baz\n"[..])
410 .collect::<Result<Vec<_>, _>>()
411 .unwrap()
412 ),
413 vec![(1, String::from("bar")), (1, String::from("baz"))]
414 );
415 assert_eq!(
416 column_counts(
417 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
418 .collect::<Result<Vec<_>, _>>()
419 .unwrap()
420 ),
421 vec![(2, String::from("baz")), (1, String::from("bar"))]
422 );
423 assert_eq!(
424 column_counts(
425 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
426 .collect::<Result<Vec<_>, _>>()
427 .unwrap()
428 ),
429 vec![(2, String::from("baz")), (1, String::from("bar"))]
430 );
431 assert_eq!(
432 column_counts(
433 &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..])
434 .collect::<Result<Vec<_>, _>>()
435 .unwrap()
436 ),
437 vec![(2, String::from("baz")), (1, String::from("bar"))]
438 );
439 }
440
441 #[test]
442 fn test_render_cell() {
443 assert_eq!(
444 render_cell(
445 "foo",
446 &mut Row {
447 label: "nope".to_owned(),
448 entries: HashMap::new(),
449 }
450 ),
451 HTML::from(
452 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
453 )
454 );
455 assert_eq!(
456 render_cell(
457 "foo",
458 &mut Row {
459 label: "nope".to_owned(),
460 entries: HashMap::from([("bar".to_owned(), vec![None])]),
461 }
462 ),
463 HTML::from(
464 r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
465 )
466 );
467 assert_eq!(
468 render_cell(
469 "foo",
470 &mut Row {
471 label: "nope".to_owned(),
472 entries: HashMap::from([("foo".to_owned(), vec![None])]),
473 }
474 ),
475 HTML::from(
476 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"#
477 )
478 );
479 assert_eq!(
480 render_cell(
481 "foo",
482 &mut Row {
483 label: "nope".to_owned(),
484 entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
485 }
486 ),
487 HTML::from(
488 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"#
489 )
490 );
491 assert_eq!(
492 render_cell(
493 "foo",
494 &mut Row {
495 label: "nope".to_owned(),
496 entries: HashMap::from([(
497 "foo".to_owned(),
498 vec![Some("5".to_owned()), Some("10".to_owned())]
499 )]),
500 }
501 ),
502 HTML::from(
503 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"#
504 )
505 );
506 assert_eq!(
507 render_cell(
508 "foo",
509 &mut Row {
510 label: "nope".to_owned(),
511 entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]),
512 }
513 ),
514 HTML::from(
515 r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"#
516 )
517 );
518 assert_eq!(
519 render_cell(
520 "heart",
521 &mut Row {
522 label: "nope".to_owned(),
523 entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]),
524 }
525 ),
526 HTML::from(
527 r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')">&lt;3</td>"#
528 )
529 );
530 assert_eq!(
531 render_cell(
532 "foo",
533 &mut Row {
534 label: "bob's".to_owned(),
535 entries: HashMap::from([("foo".to_owned(), vec![None])]),
536 }
537 ),
538 HTML::from(
539 r#"<td class="yes" onmouseover="h2('bob&#39;s','foo')" onmouseout="ch2('bob&#39;s','foo')"></td>"#
540 )
541 );
542 let mut r = Row {
543 label: "nope".to_owned(),
544 entries: HashMap::from([
545 ("foo".to_owned(), vec![None]),
546 ("baz".to_owned(), vec![None]),
547 ]),
548 };
549 assert_eq!(r.entries.len(), 2);
550 render_cell("foo", &mut r);
551 assert_eq!(r.entries.len(), 1);
552 render_cell("bar", &mut r);
553 assert_eq!(r.entries.len(), 1);
554 render_cell("baz", &mut r);
555 assert_eq!(r.entries.len(), 0);
556 }
557
558 #[test]
559 fn test_render_row() {
560 assert_eq!(
561 render_row(
562 &["foo".to_owned()],
563 &mut Row {
564 label: "nope".to_owned(),
565 entries: HashMap::from([("bar".to_owned(), vec![None])]),
566 }
567 ),
568 HTML::from(
569 r#"<tr><th id="nope">nope</th><td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td></tr>
570"#
571 )
572 );
573 }
574}