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