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