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