]>
Commit | Line | Data |
---|---|---|
1 | use std::borrow::ToOwned; | |
2 | use std::collections::{HashMap, HashSet}; | |
3 | use std::fmt::Write; | |
4 | use std::io::BufRead; | |
5 | use std::iter::Iterator; | |
6 | ||
7 | #[derive(PartialEq, Eq, Debug)] | |
8 | struct Config { | |
9 | column_threshold: usize, | |
10 | static_columns: Vec<Option<String>>, | |
11 | hidden_columns: HashSet<String>, | |
12 | substitute_labels: HashMap<String, String>, | |
13 | } | |
14 | impl Config { | |
15 | fn apply_command(&mut self, line_num: usize, cmd: &str) -> Result<(), std::io::Error> { | |
16 | if let Some(threshold) = cmd.strip_prefix("col_threshold ") { | |
17 | self.column_threshold = threshold.parse().map_err(|e| { | |
18 | std::io::Error::new( | |
19 | std::io::ErrorKind::InvalidInput, | |
20 | format!("line {line_num}: col_threshold must be numeric: {e}"), | |
21 | ) | |
22 | })?; | |
23 | } else if let Some(col) = cmd.strip_prefix("hide ") { | |
24 | self.hidden_columns.insert(col.to_owned()); | |
25 | } else if let Some(col) = cmd.strip_prefix("col ") { | |
26 | self.static_columns.push(Some(col.to_owned())); | |
27 | } else if cmd == "colsep" { | |
28 | self.static_columns.push(None); | |
29 | } else if let Some(directive) = cmd.strip_prefix("label ") { | |
30 | match directive.split_once(':') { | |
31 | None => { | |
32 | return Err(std::io::Error::new( | |
33 | std::io::ErrorKind::InvalidInput, | |
34 | format!("line {line_num}: Annotation missing ':'"), | |
35 | )) | |
36 | } | |
37 | Some((col, label)) => self | |
38 | .substitute_labels | |
39 | .insert(col.to_owned(), label.to_owned()), | |
40 | }; | |
41 | } else { | |
42 | return Err(std::io::Error::new( | |
43 | std::io::ErrorKind::InvalidInput, | |
44 | format!("line {line_num}: Unknown command: {cmd}"), | |
45 | )); | |
46 | } | |
47 | Ok(()) | |
48 | } | |
49 | } | |
50 | impl Default for Config { | |
51 | fn default() -> Self { | |
52 | Self { | |
53 | column_threshold: 2, | |
54 | static_columns: vec![], | |
55 | hidden_columns: HashSet::new(), | |
56 | substitute_labels: HashMap::new(), | |
57 | } | |
58 | } | |
59 | } | |
60 | ||
61 | const HEADER: &str = r#"<!DOCTYPE html> | |
62 | <html> | |
63 | <head> | |
64 | <meta charset="utf-8"> | |
65 | <meta name="viewport" content="width=device-width, initial-scale=1"> | |
66 | <style> | |
67 | td { text-align: center; } | |
68 | /* h/t https://wabain.github.io/2019/10/13/css-rotated-table-header.html */ | |
69 | th, td { white-space: nowrap; } | |
70 | th { text-align: left; font-weight: normal; } | |
71 | th.spacer_row { height: .3em; } | |
72 | .spacer_col { border: none; width: .2em; } | |
73 | table { border-collapse: collapse } | |
74 | tr.key > th { height: 10em; vertical-align: bottom; line-height: 1 } | |
75 | tr.key > th > div { width: 1em; } | |
76 | tr.key > th > div > div { width: 5em; transform-origin: bottom left; transform: translateX(1em) rotate(-65deg) } | |
77 | td { border: thin solid gray; } | |
78 | td.leftover { text-align: left; border: none; padding-left: .4em; } | |
79 | td.yes { border: thin solid gray; background-color: #ddd; } | |
80 | /* h/t https://stackoverflow.com/questions/5687035/css-bolding-some-text-without-changing-its-containers-size/46452396#46452396 */ | |
81 | .highlight { text-shadow: -0.06ex 0 black, 0.06ex 0 black; } | |
82 | </style> | |
83 | <script> | |
84 | function highlight(id) { const e = document.getElementById(id); if (e) { e.classList.add( "highlight"); } } | |
85 | function clear_highlight(id) { const e = document.getElementById(id); if (e) { e.classList.remove("highlight"); } } | |
86 | function h2(a, b) { highlight(a); highlight(b); } | |
87 | function ch2(a, b) { clear_highlight(a); clear_highlight(b); } | |
88 | </script> | |
89 | </head> | |
90 | <body> | |
91 | <table> | |
92 | <tbody> | |
93 | "#; | |
94 | const FOOTER: &str = " </tbody> | |
95 | </table> | |
96 | </body> | |
97 | </html>"; | |
98 | ||
99 | #[derive(PartialEq, Eq, Debug)] | |
100 | pub struct HTML(String); | |
101 | impl HTML { | |
102 | fn escape(value: &str) -> HTML { | |
103 | let mut escaped: String = String::new(); | |
104 | for c in value.chars() { | |
105 | match c { | |
106 | '>' => escaped.push_str(">"), | |
107 | '<' => escaped.push_str("<"), | |
108 | '\'' => escaped.push_str("'"), | |
109 | '"' => escaped.push_str("""), | |
110 | '&' => escaped.push_str("&"), | |
111 | ok_c => escaped.push(ok_c), | |
112 | } | |
113 | } | |
114 | HTML(escaped) | |
115 | } | |
116 | } | |
117 | impl From<&str> for HTML { | |
118 | fn from(value: &str) -> HTML { | |
119 | HTML(String::from(value)) | |
120 | } | |
121 | } | |
122 | impl FromIterator<HTML> for HTML { | |
123 | fn from_iter<T>(iter: T) -> HTML | |
124 | where | |
125 | T: IntoIterator<Item = HTML>, | |
126 | { | |
127 | HTML(iter.into_iter().map(|html| html.0).collect::<String>()) | |
128 | } | |
129 | } | |
130 | impl std::fmt::Display for HTML { | |
131 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
132 | write!(f, "{}", self.0) | |
133 | } | |
134 | } | |
135 | ||
136 | #[derive(Debug, PartialEq, Eq)] | |
137 | enum InputLine<'a> { | |
138 | Blank, | |
139 | RowHeader(&'a str), | |
140 | Entry(&'a str, Option<&'a str>), | |
141 | Command(&'a str), | |
142 | } | |
143 | impl<'a> From<&'a str> for InputLine<'a> { | |
144 | fn from(value: &'a str) -> InputLine<'a> { | |
145 | let trimmed = value.trim_end(); | |
146 | if trimmed.is_empty() { | |
147 | InputLine::Blank | |
148 | } else if let Some(cmd) = trimmed.strip_prefix('!') { | |
149 | InputLine::Command(cmd) | |
150 | } else if !trimmed.starts_with(' ') { | |
151 | InputLine::RowHeader(value.trim()) | |
152 | } else { | |
153 | match value.split_once(':') { | |
154 | None => InputLine::Entry(value.trim(), None), | |
155 | Some((col, instance)) => InputLine::Entry(col.trim(), Some(instance.trim())), | |
156 | } | |
157 | } | |
158 | } | |
159 | } | |
160 | ||
161 | #[derive(Debug, PartialEq, Eq)] | |
162 | struct Row { | |
163 | label: String, | |
164 | entries: HashMap<String, Vec<Option<String>>>, | |
165 | } | |
166 | ||
167 | #[derive(Debug, PartialEq, Eq)] | |
168 | enum Rowlike { | |
169 | Row(Row), | |
170 | Spacer, | |
171 | } | |
172 | ||
173 | struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> { | |
174 | input: std::iter::Enumerate<Input>, | |
175 | row: Option<Row>, | |
176 | config: &'cfg mut Config, | |
177 | } | |
178 | impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> { | |
179 | fn new(config: &'cfg mut Config, input: Input) -> Self { | |
180 | Self { | |
181 | input: input.enumerate(), | |
182 | row: None, | |
183 | config, | |
184 | } | |
185 | } | |
186 | } | |
187 | impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator | |
188 | for Reader<'cfg, Input> | |
189 | { | |
190 | type Item = Result<Rowlike, std::io::Error>; | |
191 | fn next(&mut self) -> Option<Self::Item> { | |
192 | loop { | |
193 | match self.input.next() { | |
194 | None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(), | |
195 | Some((_, Err(e))) => return Some(Err(e)), | |
196 | Some((n, Ok(line))) => match InputLine::from(line.as_ref()) { | |
197 | InputLine::Command(cmd) => { | |
198 | if let Err(e) = self.config.apply_command(n + 1, cmd) { | |
199 | return Some(Err(e)); | |
200 | } | |
201 | } | |
202 | InputLine::Blank if self.row.is_some() => { | |
203 | return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose() | |
204 | } | |
205 | InputLine::Blank => return Some(Ok(Rowlike::Spacer)), | |
206 | InputLine::Entry(col, instance) => match &mut self.row { | |
207 | None => { | |
208 | return Some(Err(std::io::Error::other(format!( | |
209 | "line {}: Entry with no header", | |
210 | n + 1 | |
211 | )))) | |
212 | } | |
213 | Some(ref mut row) => { | |
214 | row.entries | |
215 | .entry(col.to_owned()) | |
216 | .and_modify(|is| is.push(instance.map(ToOwned::to_owned))) | |
217 | .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]); | |
218 | } | |
219 | }, | |
220 | InputLine::RowHeader(row) => { | |
221 | let prev = std::mem::take(&mut self.row); | |
222 | self.row = Some(Row { | |
223 | label: row.to_owned(), | |
224 | entries: HashMap::new(), | |
225 | }); | |
226 | if prev.is_some() { | |
227 | return Ok(prev.map(Rowlike::Row)).transpose(); | |
228 | } | |
229 | } | |
230 | }, | |
231 | } | |
232 | } | |
233 | } | |
234 | } | |
235 | ||
236 | fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> { | |
237 | let mut config = Config::default(); | |
238 | let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines()); | |
239 | reader | |
240 | .collect::<Result<Vec<_>, _>>() | |
241 | .map(|rows| (rows, config)) | |
242 | } | |
243 | ||
244 | fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> { | |
245 | let empty = HashMap::new(); | |
246 | let mut counts: Vec<_> = rows | |
247 | .iter() | |
248 | .flat_map(|rl| match rl { | |
249 | Rowlike::Row(r) => r.entries.keys(), | |
250 | Rowlike::Spacer => empty.keys(), | |
251 | }) | |
252 | .fold(HashMap::new(), |mut cs, col| { | |
253 | cs.entry(col.to_owned()) | |
254 | .and_modify(|n| *n += 1) | |
255 | .or_insert(1); | |
256 | cs | |
257 | }) | |
258 | .into_iter() | |
259 | .map(|(col, n)| (n, col)) | |
260 | .collect(); | |
261 | counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol))); | |
262 | counts | |
263 | } | |
264 | fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> { | |
265 | let static_columns: HashSet<&str> = config | |
266 | .static_columns | |
267 | .iter() | |
268 | .flatten() | |
269 | .map(std::string::String::as_str) | |
270 | .collect(); | |
271 | column_counts(rows) | |
272 | .into_iter() | |
273 | .filter_map(|(n, col)| { | |
274 | (n >= config.column_threshold | |
275 | && !static_columns.contains(col.as_str()) | |
276 | && !config.hidden_columns.contains(&col)) | |
277 | .then_some(col) | |
278 | }) | |
279 | .collect() | |
280 | } | |
281 | ||
282 | fn render_one_instance(instance: &Option<String>) -> HTML { | |
283 | match instance { | |
284 | None => HTML::from("✓"), | |
285 | Some(instance) => HTML::escape(instance.as_ref()), | |
286 | } | |
287 | } | |
288 | ||
289 | fn render_instances(instances: &[Option<String>]) -> HTML { | |
290 | let all_empty = instances.iter().all(Option::is_none); | |
291 | if all_empty && instances.len() == 1 { | |
292 | HTML::from("") | |
293 | } else if all_empty { | |
294 | HTML(format!("{}", instances.len())) | |
295 | } else { | |
296 | HTML( | |
297 | instances | |
298 | .iter() | |
299 | .map(render_one_instance) | |
300 | .map(|html| html.0) // Waiting for slice_concat_trait to stabilize | |
301 | .collect::<Vec<_>>() | |
302 | .join(" "), | |
303 | ) | |
304 | } | |
305 | } | |
306 | ||
307 | fn render_cell(col: &str, row: &mut Row) -> HTML { | |
308 | let row_label = HTML::escape(row.label.as_ref()); | |
309 | let col_label = HTML::escape(col); | |
310 | let instances: Option<&Vec<Option<String>>> = row.entries.get(col); | |
311 | let class = HTML::from(if instances.is_none() { "" } else { "yes" }); | |
312 | let contents = match instances { | |
313 | None => HTML::from(""), | |
314 | Some(is) => render_instances(is), | |
315 | }; | |
316 | row.entries.remove(col); | |
317 | HTML(format!( | |
318 | r#"<td class="{class}" onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"# | |
319 | )) | |
320 | } | |
321 | ||
322 | fn render_leftover(notcol: &str, instances: &[Option<String>]) -> HTML { | |
323 | let label = HTML::escape(notcol); | |
324 | let rest = render_instances(instances); | |
325 | if rest == HTML::from("") { | |
326 | HTML(format!("{label}")) | |
327 | } else { | |
328 | HTML(format!("{label}: {rest}")) | |
329 | } | |
330 | } | |
331 | ||
332 | fn render_all_leftovers(config: &Config, row: &Row) -> HTML { | |
333 | let mut order: Vec<_> = row | |
334 | .entries | |
335 | .keys() | |
336 | .filter(|&col| !config.hidden_columns.contains(col)) | |
337 | .collect(); | |
338 | order.sort_unstable(); | |
339 | HTML( | |
340 | order | |
341 | .into_iter() | |
342 | .map(|notcol| render_leftover(notcol, row.entries.get(notcol).expect("Key vanished?!"))) | |
343 | .map(|html| html.0) // Waiting for slice_concat_trait to stabilize | |
344 | .collect::<Vec<_>>() | |
345 | .join(", "), | |
346 | ) | |
347 | } | |
348 | ||
349 | fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML { | |
350 | match rowlike { | |
351 | Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"), | |
352 | Rowlike::Row(row) => { | |
353 | let row_label = HTML::escape(row.label.as_ref()); | |
354 | let static_cells = config | |
355 | .static_columns | |
356 | .iter() | |
357 | .map(|ocol| match ocol { | |
358 | Some(col) if config.hidden_columns.contains(col) => HTML::from(""), | |
359 | Some(col) => render_cell(col, row), | |
360 | None => HTML::from(r#"<td class="spacer_col"></td>"#), | |
361 | }) | |
362 | .collect::<HTML>(); | |
363 | let dynamic_cells = columns | |
364 | .iter() | |
365 | .filter(|&col| !config.hidden_columns.contains(col)) | |
366 | .map(|col| render_cell(col, row)) | |
367 | .collect::<HTML>(); | |
368 | let leftovers = render_all_leftovers(config, row); | |
369 | HTML(format!( | |
370 | "<tr><th id=\"{row_label}\">{row_label}</th>{static_cells}{dynamic_cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n" | |
371 | )) | |
372 | } | |
373 | } | |
374 | } | |
375 | ||
376 | fn column_header_labels<'a>( | |
377 | config: &'a Config, | |
378 | columns: &'a [String], | |
379 | ) -> impl Iterator<Item = Option<&'a String>> { | |
380 | let static_columns = config.static_columns.iter().map(|oc| oc.as_ref()); | |
381 | let dynamic_columns = columns.iter().map(Some); | |
382 | static_columns | |
383 | .chain(dynamic_columns) | |
384 | .filter(|ocol| ocol.map_or(true, |col| !config.hidden_columns.contains(col))) | |
385 | .map(|ocol| { | |
386 | ocol.map(|col| match config.substitute_labels.get(col) { | |
387 | None => col, | |
388 | Some(substitute) => substitute, | |
389 | }) | |
390 | }) | |
391 | } | |
392 | ||
393 | fn render_column_headers(config: &Config, columns: &[String]) -> HTML { | |
394 | HTML( | |
395 | String::from(r#"<tr class="key"><th></th>"#) | |
396 | + &column_header_labels(config, columns).fold(String::new(), |mut acc, ocol| { | |
397 | match ocol { | |
398 | Some(col) => { | |
399 | let col_header = HTML::escape(col); | |
400 | write!( | |
401 | &mut acc, | |
402 | r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"# | |
403 | ) | |
404 | } | |
405 | None => write!(&mut acc, r#"<th class="col_spacer"></th>"#), | |
406 | } | |
407 | .unwrap(); | |
408 | acc | |
409 | }) | |
410 | + "</tr>\n", | |
411 | ) | |
412 | } | |
413 | ||
414 | /// # Errors | |
415 | /// | |
416 | /// Will return `Err` if | |
417 | /// * there's an i/o error while reading `input` | |
418 | /// * the log has invalid syntax: | |
419 | /// * an indented line with no preceding non-indented line | |
420 | pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> { | |
421 | let (rows, config) = read_input(input)?; | |
422 | let columns = column_order(&config, &rows); | |
423 | Ok(HTML(format!( | |
424 | "{HEADER}{}{}{FOOTER}", | |
425 | render_column_headers(&config, &columns), | |
426 | rows.into_iter() | |
427 | .map(|mut r| render_row(&config, &columns, &mut r)) | |
428 | .collect::<HTML>() | |
429 | ))) | |
430 | } | |
431 | ||
432 | #[cfg(test)] | |
433 | mod tests { | |
434 | use super::*; | |
435 | ||
436 | #[test] | |
437 | fn test_parse_line() { | |
438 | assert_eq!(InputLine::from(""), InputLine::Blank); | |
439 | assert_eq!(InputLine::from(" "), InputLine::Blank); | |
440 | assert_eq!(InputLine::from("foo"), InputLine::RowHeader("foo")); | |
441 | assert_eq!(InputLine::from("foo "), InputLine::RowHeader("foo")); | |
442 | assert_eq!(InputLine::from(" foo"), InputLine::Entry("foo", None)); | |
443 | assert_eq!( | |
444 | InputLine::from(" foo:bar"), | |
445 | InputLine::Entry("foo", Some("bar")) | |
446 | ); | |
447 | assert_eq!( | |
448 | InputLine::from(" foo: bar"), | |
449 | InputLine::Entry("foo", Some("bar")) | |
450 | ); | |
451 | assert_eq!( | |
452 | InputLine::from(" foo: bar "), | |
453 | InputLine::Entry("foo", Some("bar")) | |
454 | ); | |
455 | assert_eq!( | |
456 | InputLine::from(" foo: bar "), | |
457 | InputLine::Entry("foo", Some("bar")) | |
458 | ); | |
459 | assert_eq!( | |
460 | InputLine::from(" foo : bar "), | |
461 | InputLine::Entry("foo", Some("bar")) | |
462 | ); | |
463 | } | |
464 | ||
465 | fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> { | |
466 | read_input(input).map(|(rows, _)| rows) | |
467 | } | |
468 | fn read_config(input: impl std::io::Read) -> Result<Config, std::io::Error> { | |
469 | read_input(input).map(|(_, config)| config) | |
470 | } | |
471 | #[test] | |
472 | fn test_read_rows() { | |
473 | assert_eq!( | |
474 | read_rows(&b"foo"[..]).unwrap(), | |
475 | vec![Rowlike::Row(Row { | |
476 | label: "foo".to_owned(), | |
477 | entries: HashMap::new(), | |
478 | })] | |
479 | ); | |
480 | assert_eq!( | |
481 | read_rows(&b"bar"[..]).unwrap(), | |
482 | vec![Rowlike::Row(Row { | |
483 | label: "bar".to_owned(), | |
484 | entries: HashMap::new(), | |
485 | })] | |
486 | ); | |
487 | assert_eq!( | |
488 | read_rows(&b"foo\nbar\n"[..]).unwrap(), | |
489 | vec![ | |
490 | Rowlike::Row(Row { | |
491 | label: "foo".to_owned(), | |
492 | entries: HashMap::new(), | |
493 | }), | |
494 | Rowlike::Row(Row { | |
495 | label: "bar".to_owned(), | |
496 | entries: HashMap::new(), | |
497 | }) | |
498 | ] | |
499 | ); | |
500 | assert_eq!( | |
501 | read_rows(&b"foo\n bar\n"[..]).unwrap(), | |
502 | vec![Rowlike::Row(Row { | |
503 | label: "foo".to_owned(), | |
504 | entries: HashMap::from([("bar".to_owned(), vec![None])]), | |
505 | })] | |
506 | ); | |
507 | assert_eq!( | |
508 | read_rows(&b"foo\n bar\n baz\n"[..]).unwrap(), | |
509 | vec![Rowlike::Row(Row { | |
510 | label: "foo".to_owned(), | |
511 | entries: HashMap::from([ | |
512 | ("bar".to_owned(), vec![None]), | |
513 | ("baz".to_owned(), vec![None]) | |
514 | ]), | |
515 | })] | |
516 | ); | |
517 | assert_eq!( | |
518 | read_rows(&b"foo\n\nbar\n"[..]).unwrap(), | |
519 | vec![ | |
520 | Rowlike::Row(Row { | |
521 | label: "foo".to_owned(), | |
522 | entries: HashMap::new(), | |
523 | }), | |
524 | Rowlike::Row(Row { | |
525 | label: "bar".to_owned(), | |
526 | entries: HashMap::new(), | |
527 | }) | |
528 | ] | |
529 | ); | |
530 | assert_eq!( | |
531 | read_rows(&b"foo\n\n\nbar\n"[..]).unwrap(), | |
532 | vec![ | |
533 | Rowlike::Row(Row { | |
534 | label: "foo".to_owned(), | |
535 | entries: HashMap::new(), | |
536 | }), | |
537 | Rowlike::Spacer, | |
538 | Rowlike::Row(Row { | |
539 | label: "bar".to_owned(), | |
540 | entries: HashMap::new(), | |
541 | }) | |
542 | ] | |
543 | ); | |
544 | assert_eq!( | |
545 | read_rows(&b"foo\n \nbar\n"[..]).unwrap(), | |
546 | vec![ | |
547 | Rowlike::Row(Row { | |
548 | label: "foo".to_owned(), | |
549 | entries: HashMap::new(), | |
550 | }), | |
551 | Rowlike::Row(Row { | |
552 | label: "bar".to_owned(), | |
553 | entries: HashMap::new(), | |
554 | }) | |
555 | ] | |
556 | ); | |
557 | assert_eq!( | |
558 | read_rows(&b"foo \n bar \n"[..]).unwrap(), | |
559 | vec![Rowlike::Row(Row { | |
560 | label: "foo".to_owned(), | |
561 | entries: HashMap::from([("bar".to_owned(), vec![None])]), | |
562 | })] | |
563 | ); | |
564 | ||
565 | let bad = read_rows(&b" foo"[..]); | |
566 | assert!(bad.is_err()); | |
567 | assert!(format!("{bad:?}").contains("line 1: Entry with no header")); | |
568 | ||
569 | let bad2 = read_rows(&b"foo\n\n bar"[..]); | |
570 | assert!(bad2.is_err()); | |
571 | assert!(format!("{bad2:?}").contains("line 3: Entry with no header")); | |
572 | } | |
573 | ||
574 | #[test] | |
575 | fn test_read_config() { | |
576 | assert_eq!( | |
577 | read_config(&b"!col_threshold 10"[..]) | |
578 | .unwrap() | |
579 | .column_threshold, | |
580 | 10 | |
581 | ); | |
582 | assert_eq!( | |
583 | read_config(&b"!col foo"[..]).unwrap().static_columns, | |
584 | vec![Some("foo".to_owned())] | |
585 | ); | |
586 | assert_eq!( | |
587 | read_config(&b"!label foo:bar"[..]) | |
588 | .unwrap() | |
589 | .substitute_labels["foo"], | |
590 | "bar" | |
591 | ); | |
592 | ||
593 | let bad_command = read_config(&b"!no such command"[..]); | |
594 | assert!(bad_command.is_err()); | |
595 | assert!(format!("{bad_command:?}").contains("line 1: Unknown command")); | |
596 | ||
597 | let bad_num = read_config(&b"!col_threshold foo"[..]); | |
598 | assert!(bad_num.is_err()); | |
599 | assert!(format!("{bad_num:?}").contains("line 1: col_threshold must be numeric")); | |
600 | ||
601 | let bad_sub = read_config(&b"!label foo"[..]); | |
602 | assert!(bad_sub.is_err()); | |
603 | assert!(format!("{bad_sub:?}").contains("line 1: Annotation missing ':'")); | |
604 | } | |
605 | ||
606 | #[test] | |
607 | fn test_column_counts() { | |
608 | assert_eq!( | |
609 | column_counts(&read_rows(&b"foo\n bar\n baz\n"[..]).unwrap()), | |
610 | vec![(1, String::from("bar")), (1, String::from("baz"))] | |
611 | ); | |
612 | assert_eq!( | |
613 | column_counts(&read_rows(&b"foo\n bar\n baz\nquux\n baz"[..]).unwrap()), | |
614 | vec![(2, String::from("baz")), (1, String::from("bar"))] | |
615 | ); | |
616 | assert_eq!( | |
617 | column_counts(&read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..]).unwrap()), | |
618 | vec![(2, String::from("baz")), (1, String::from("bar"))] | |
619 | ); | |
620 | assert_eq!( | |
621 | column_counts( | |
622 | &read_rows(&b"foo\n bar: 1\n bar: 2\n baz\n bar\nquux\n baz"[..]).unwrap() | |
623 | ), | |
624 | vec![(2, String::from("baz")), (1, String::from("bar"))] | |
625 | ); | |
626 | } | |
627 | ||
628 | #[test] | |
629 | fn test_column_header_labels() { | |
630 | let mut cfg = Config::default(); | |
631 | ||
632 | assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"foo".to_owned())])); | |
633 | ||
634 | cfg.static_columns.push(Some("bar".to_owned())); | |
635 | assert!(column_header_labels(&cfg, &["foo".to_owned()]) | |
636 | .eq([Some(&"bar".to_owned()), Some(&"foo".to_owned())])); | |
637 | ||
638 | cfg.static_columns.push(None); | |
639 | assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([ | |
640 | Some(&"bar".to_owned()), | |
641 | None, | |
642 | Some(&"foo".to_owned()) | |
643 | ])); | |
644 | ||
645 | cfg.substitute_labels | |
646 | .insert("foo".to_owned(), "foo (bits)".to_owned()); | |
647 | assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([ | |
648 | Some(&"bar".to_owned()), | |
649 | None, | |
650 | Some(&"foo (bits)".to_owned()) | |
651 | ])); | |
652 | ||
653 | cfg.hidden_columns.insert("foo".to_owned()); | |
654 | assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([Some(&"bar".to_owned()), None])); | |
655 | ||
656 | cfg.hidden_columns.insert("bar".to_owned()); | |
657 | assert!(column_header_labels(&cfg, &["foo".to_owned()]).eq([None])); | |
658 | } | |
659 | ||
660 | #[test] | |
661 | fn test_render_cell() { | |
662 | assert_eq!( | |
663 | render_cell( | |
664 | "foo", | |
665 | &mut Row { | |
666 | label: "nope".to_owned(), | |
667 | entries: HashMap::new(), | |
668 | } | |
669 | ), | |
670 | HTML::from( | |
671 | r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"# | |
672 | ) | |
673 | ); | |
674 | assert_eq!( | |
675 | render_cell( | |
676 | "foo", | |
677 | &mut Row { | |
678 | label: "nope".to_owned(), | |
679 | entries: HashMap::from([("bar".to_owned(), vec![None])]), | |
680 | } | |
681 | ), | |
682 | HTML::from( | |
683 | r#"<td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"# | |
684 | ) | |
685 | ); | |
686 | assert_eq!( | |
687 | render_cell( | |
688 | "foo", | |
689 | &mut Row { | |
690 | label: "nope".to_owned(), | |
691 | entries: HashMap::from([("foo".to_owned(), vec![None])]), | |
692 | } | |
693 | ), | |
694 | HTML::from( | |
695 | r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td>"# | |
696 | ) | |
697 | ); | |
698 | assert_eq!( | |
699 | render_cell( | |
700 | "foo", | |
701 | &mut Row { | |
702 | label: "nope".to_owned(), | |
703 | entries: HashMap::from([("foo".to_owned(), vec![None, None])]), | |
704 | } | |
705 | ), | |
706 | HTML::from( | |
707 | r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">2</td>"# | |
708 | ) | |
709 | ); | |
710 | assert_eq!( | |
711 | render_cell( | |
712 | "foo", | |
713 | &mut Row { | |
714 | label: "nope".to_owned(), | |
715 | entries: HashMap::from([( | |
716 | "foo".to_owned(), | |
717 | vec![Some("5".to_owned()), Some("10".to_owned())] | |
718 | )]), | |
719 | } | |
720 | ), | |
721 | HTML::from( | |
722 | r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 10</td>"# | |
723 | ) | |
724 | ); | |
725 | assert_eq!( | |
726 | render_cell( | |
727 | "foo", | |
728 | &mut Row { | |
729 | label: "nope".to_owned(), | |
730 | entries: HashMap::from([("foo".to_owned(), vec![Some("5".to_owned()), None])]), | |
731 | } | |
732 | ), | |
733 | HTML::from( | |
734 | r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">5 ✓</td>"# | |
735 | ) | |
736 | ); | |
737 | assert_eq!( | |
738 | render_cell( | |
739 | "heart", | |
740 | &mut Row { | |
741 | label: "nope".to_owned(), | |
742 | entries: HashMap::from([("heart".to_owned(), vec![Some("<3".to_owned())])]), | |
743 | } | |
744 | ), | |
745 | HTML::from( | |
746 | r#"<td class="yes" onmouseover="h2('nope','heart')" onmouseout="ch2('nope','heart')"><3</td>"# | |
747 | ) | |
748 | ); | |
749 | assert_eq!( | |
750 | render_cell( | |
751 | "foo", | |
752 | &mut Row { | |
753 | label: "bob's".to_owned(), | |
754 | entries: HashMap::from([("foo".to_owned(), vec![None])]), | |
755 | } | |
756 | ), | |
757 | HTML::from( | |
758 | r#"<td class="yes" onmouseover="h2('bob's','foo')" onmouseout="ch2('bob's','foo')"></td>"# | |
759 | ) | |
760 | ); | |
761 | let mut r = Row { | |
762 | label: "nope".to_owned(), | |
763 | entries: HashMap::from([ | |
764 | ("foo".to_owned(), vec![None]), | |
765 | ("baz".to_owned(), vec![None]), | |
766 | ]), | |
767 | }; | |
768 | assert_eq!(r.entries.len(), 2); | |
769 | render_cell("foo", &mut r); | |
770 | assert_eq!(r.entries.len(), 1); | |
771 | render_cell("bar", &mut r); | |
772 | assert_eq!(r.entries.len(), 1); | |
773 | render_cell("baz", &mut r); | |
774 | assert_eq!(r.entries.len(), 0); | |
775 | } | |
776 | ||
777 | #[test] | |
778 | fn test_render_leftovers() { | |
779 | assert_eq!( | |
780 | render_all_leftovers( | |
781 | &Config::default(), | |
782 | &Row { | |
783 | label: "nope".to_owned(), | |
784 | entries: HashMap::from([("foo".to_owned(), vec![None])]), | |
785 | } | |
786 | ), | |
787 | HTML::from("foo") | |
788 | ); | |
789 | assert_eq!( | |
790 | render_all_leftovers( | |
791 | &Config::default(), | |
792 | &Row { | |
793 | label: "nope".to_owned(), | |
794 | entries: HashMap::from([ | |
795 | ("foo".to_owned(), vec![None]), | |
796 | ("bar".to_owned(), vec![None]) | |
797 | ]), | |
798 | } | |
799 | ), | |
800 | HTML::from("bar, foo") | |
801 | ); | |
802 | assert_eq!( | |
803 | render_all_leftovers( | |
804 | &Config::default(), | |
805 | &Row { | |
806 | label: "nope".to_owned(), | |
807 | entries: HashMap::from([ | |
808 | ("foo".to_owned(), vec![None]), | |
809 | ("bar".to_owned(), vec![None, None]) | |
810 | ]), | |
811 | } | |
812 | ), | |
813 | HTML::from("bar: 2, foo") | |
814 | ); | |
815 | assert_eq!( | |
816 | render_all_leftovers( | |
817 | &Config { | |
818 | column_threshold: 2, | |
819 | static_columns: vec![], | |
820 | hidden_columns: HashSet::from(["private".to_owned()]), | |
821 | substitute_labels: HashMap::new(), | |
822 | }, | |
823 | &Row { | |
824 | label: "nope".to_owned(), | |
825 | entries: HashMap::from([("private".to_owned(), vec![None]),]), | |
826 | } | |
827 | ), | |
828 | HTML::from("") | |
829 | ); | |
830 | } | |
831 | ||
832 | #[test] | |
833 | fn test_render_row() { | |
834 | assert_eq!( | |
835 | render_row( | |
836 | &Config::default(), | |
837 | &["foo".to_owned()], | |
838 | &mut Rowlike::Row(Row { | |
839 | label: "nope".to_owned(), | |
840 | entries: HashMap::from([("bar".to_owned(), vec![None])]), | |
841 | }) | |
842 | ), | |
843 | HTML::from( | |
844 | r#"<tr><th id="nope">nope</th><td class="" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')"></td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')">bar</td></tr> | |
845 | "# | |
846 | ) | |
847 | ); | |
848 | assert_eq!( | |
849 | render_row( | |
850 | &Config { | |
851 | column_threshold: 0, | |
852 | static_columns: vec![Some("foo".to_owned()), Some("bar".to_owned())], | |
853 | hidden_columns: HashSet::new(), | |
854 | substitute_labels: HashMap::new(), | |
855 | }, | |
856 | &["baz".to_owned()], | |
857 | &mut Rowlike::Row(Row { | |
858 | label: "nope".to_owned(), | |
859 | entries: HashMap::from([ | |
860 | ("bar".to_owned(), vec![Some("r".to_owned())]), | |
861 | ("baz".to_owned(), vec![Some("z".to_owned())]), | |
862 | ("foo".to_owned(), vec![Some("f".to_owned())]), | |
863 | ]), | |
864 | }) | |
865 | ), | |
866 | HTML::from( | |
867 | r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="yes" onmouseover="h2('nope','baz')" onmouseout="ch2('nope','baz')">z</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr> | |
868 | "# | |
869 | ) | |
870 | ); | |
871 | assert_eq!( | |
872 | render_row( | |
873 | &Config { | |
874 | column_threshold: 0, | |
875 | static_columns: vec![Some("foo".to_owned()), None, Some("bar".to_owned())], | |
876 | hidden_columns: HashSet::new(), | |
877 | substitute_labels: HashMap::new(), | |
878 | }, | |
879 | &[], | |
880 | &mut Rowlike::Row(Row { | |
881 | label: "nope".to_owned(), | |
882 | entries: HashMap::from([ | |
883 | ("bar".to_owned(), vec![Some("r".to_owned())]), | |
884 | ("foo".to_owned(), vec![Some("f".to_owned())]), | |
885 | ]), | |
886 | }) | |
887 | ), | |
888 | HTML::from( | |
889 | r#"<tr><th id="nope">nope</th><td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">f</td><td class="spacer_col"></td><td class="yes" onmouseover="h2('nope','bar')" onmouseout="ch2('nope','bar')">r</td><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr> | |
890 | "# | |
891 | ) | |
892 | ); | |
893 | assert_eq!( | |
894 | render_row( | |
895 | &Config { | |
896 | column_threshold: 0, | |
897 | static_columns: vec![], | |
898 | hidden_columns: HashSet::from(["foo".to_owned()]), | |
899 | substitute_labels: HashMap::new(), | |
900 | }, | |
901 | &[], | |
902 | &mut Rowlike::Row(Row { | |
903 | label: "nope".to_owned(), | |
904 | entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]), | |
905 | }) | |
906 | ), | |
907 | HTML::from( | |
908 | r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr> | |
909 | "# | |
910 | ) | |
911 | ); | |
912 | assert_eq!( | |
913 | render_row( | |
914 | &Config { | |
915 | column_threshold: 0, | |
916 | static_columns: vec![Some("foo".to_owned())], | |
917 | hidden_columns: HashSet::from(["foo".to_owned()]), | |
918 | substitute_labels: HashMap::new(), | |
919 | }, | |
920 | &[], | |
921 | &mut Rowlike::Row(Row { | |
922 | label: "nope".to_owned(), | |
923 | entries: HashMap::from([("foo".to_owned(), vec![Some("f".to_owned())]),]), | |
924 | }) | |
925 | ), | |
926 | HTML::from( | |
927 | r#"<tr><th id="nope">nope</th><td class="leftover" onmouseover="highlight('nope')" onmouseout="clear_highlight('nope')"></td></tr> | |
928 | "# | |
929 | ) | |
930 | ); | |
931 | } | |
932 | } |