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