]> git.scottworley.com Git - tablify/blobdiff - src/lib.rs
Appease clippy::pattern_type_mismatch
[tablify] / src / lib.rs
index 731457e6b07389fdd1cf39ff5e423d71b3c6e27a..23667a1be543bd141b3d179e945ee477a33f26d7 100644 (file)
@@ -5,9 +5,14 @@ use std::io::BufRead;
 use std::iter::Iterator;
 
 fn tally_marks(n: usize, mark: Option<&str>) -> String {
-    let fives = { 0..n / 5 }.map(|_| '𝍸');
-    let ones = { 0..n % 5 }.map(|_| '𝍷');
-    fives.chain(ones).collect()
+    match mark {
+        None => {
+            let fives = { 0..n / 5 }.map(|_| '𝍸');
+            let ones = { 0..n % 5 }.map(|_| '𝍷');
+            fives.chain(ones).collect()
+        }
+        Some(m) => { 0..n }.map(|_| m).collect(),
+    }
 }
 
 #[derive(PartialEq, Eq, Debug)]
@@ -45,6 +50,16 @@ impl Config {
                     .substitute_labels
                     .insert(col.to_owned(), label.to_owned()),
             };
+        } else if let Some(directive) = cmd.strip_prefix("mark ") {
+            match directive.split_once(':') {
+                None => {
+                    return Err(std::io::Error::new(
+                        std::io::ErrorKind::InvalidInput,
+                        format!("line {line_num}: Mark missing ':'"),
+                    ))
+                }
+                Some((col, label)) => self.mark.insert(col.to_owned(), label.to_owned()),
+            };
         } else {
             return Err(std::io::Error::new(
                 std::io::ErrorKind::InvalidInput,
@@ -192,9 +207,7 @@ impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg,
         }
     }
 }
-impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
-    for Reader<'cfg, Input>
-{
+impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<'_, Input> {
     type Item = Result<Rowlike, std::io::Error>;
     fn next(&mut self) -> Option<Self::Item> {
         loop {
@@ -211,7 +224,7 @@ impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Iterator
                         return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
                     }
                     InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
-                    InputLine::Entry(col, instance) => match &mut self.row {
+                    InputLine::Entry(col, instance) => match self.row {
                         None => {
                             return Some(Err(std::io::Error::other(format!(
                                 "line {}: Entry with no header",
@@ -253,8 +266,8 @@ fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
     let empty = HashMap::new();
     let mut counts: Vec<_> = rows
         .iter()
-        .flat_map(|rl| match rl {
-            Rowlike::Row(r) => r.entries.keys(),
+        .flat_map(|rl| match *rl {
+            Rowlike::Row(ref r) => r.entries.keys(),
             Rowlike::Spacer => empty.keys(),
         })
         .fold(HashMap::new(), |mut cs, col| {
@@ -266,7 +279,7 @@ fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
         .into_iter()
         .map(|(col, n)| (n, col))
         .collect();
-    counts.sort_unstable_by(|(an, acol), (bn, bcol)| bn.cmp(an).then(acol.cmp(bcol)));
+    counts.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
     counts
 }
 fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
@@ -291,9 +304,9 @@ fn render_instances(instances: &[Option<String>], mark: Option<&str>) -> HTML {
     let mut tally = 0;
     let mut out = vec![];
     for ins in instances {
-        match ins {
+        match *ins {
             None => tally += 1,
-            Some(content) => {
+            Some(ref content) => {
                 if tally > 0 {
                     out.push(HTML(tally_marks(tally, mark)));
                     tally = 0;
@@ -324,9 +337,9 @@ fn render_cell(config: &Config, col: &str, row: &mut Row) -> HTML {
     let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
     let is_empty = match instances {
         None => true,
-        Some(is) => is.iter().all(|ins| match ins {
+        Some(is) => is.iter().all(|ins| match *ins {
             None => false,
-            Some(content) => content == "Γ—",
+            Some(ref content) => content == "Γ—",
         }),
     };
     let class = HTML::from(if is_empty { "" } else { r#" class="yes""# });
@@ -374,16 +387,16 @@ fn render_all_leftovers(config: &Config, row: &Row) -> HTML {
 }
 
 fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
-    match rowlike {
+    match *rowlike {
         Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
-        Rowlike::Row(row) => {
+        Rowlike::Row(ref mut row) => {
             let row_label = HTML::escape(row.label.as_ref());
             let static_cells = config
                 .static_columns
                 .iter()
-                .map(|ocol| match ocol {
-                    Some(col) if config.hidden_columns.contains(col) => HTML::from(""),
-                    Some(col) => render_cell(config, col, row),
+                .map(|ocol| match *ocol {
+                    Some(ref col) if config.hidden_columns.contains(col) => HTML::from(""),
+                    Some(ref col) => render_cell(config, col, row),
                     None => HTML::from(r#"<td class="spacer_col"></td>"#),
                 })
                 .collect::<HTML>();
@@ -408,7 +421,7 @@ fn column_header_labels<'a>(
     let dynamic_columns = columns.iter().map(Some);
     static_columns
         .chain(dynamic_columns)
-        .filter(|ocol| ocol.map_or(true, |col| !config.hidden_columns.contains(col)))
+        .filter(|ocol| ocol.is_none_or(|col| !config.hidden_columns.contains(col)))
         .map(|ocol| {
             ocol.map(|col| match config.substitute_labels.get(col) {
                 None => col,
@@ -444,7 +457,7 @@ fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
 ///   * there's an i/o error while reading `input`
 ///   * the log has invalid syntax:
 ///     * an indented line with no preceding non-indented line
-pub fn tablify(input: impl std::io::Read) -> Result<HTML, std::io::Error> {
+pub fn tablify<R: std::io::Read>(input: R) -> Result<HTML, std::io::Error> {
     let (rows, config) = read_input(input)?;
     let columns = column_order(&config, &rows);
     Ok(HTML(format!(
@@ -502,6 +515,11 @@ mod tests {
         assert_eq!(tally_marks(9, None), "𝍸𝍷𝍷𝍷𝍷");
         assert_eq!(tally_marks(10, None), "𝍸𝍸");
         assert_eq!(tally_marks(11, None), "𝍸𝍸𝍷");
+        assert_eq!(tally_marks(1, Some("x")), "x");
+        assert_eq!(tally_marks(4, Some("x")), "xxxx");
+        assert_eq!(tally_marks(5, Some("x")), "xxxxx");
+        assert_eq!(tally_marks(6, Some("x")), "xxxxxx");
+        assert_eq!(tally_marks(2, Some("πŸ”")), "πŸ”πŸ”");
     }
 
     fn read_rows(input: impl std::io::Read) -> Result<Vec<Rowlike>, std::io::Error> {
@@ -631,6 +649,7 @@ mod tests {
                 .substitute_labels["foo"],
             "bar"
         );
+        assert_eq!(read_config(&b"!mark foo:*"[..]).unwrap().mark["foo"], "*");
 
         let bad_command = read_config(&b"!no such command"[..]);
         assert!(bad_command.is_err());
@@ -643,6 +662,10 @@ mod tests {
         let bad_sub = read_config(&b"!label foo"[..]);
         assert!(bad_sub.is_err());
         assert!(format!("{bad_sub:?}").contains("line 1: Annotation missing ':'"));
+
+        let bad_mark = read_config(&b"!mark foo"[..]);
+        assert!(bad_mark.is_err());
+        assert!(format!("{bad_mark:?}").contains("line 1: Mark missing ':'"));
     }
 
     #[test]
@@ -821,6 +844,26 @@ mod tests {
                 r#"<td class="yes" onmouseover="h2('bob&#39;s','foo')" onmouseout="ch2('bob&#39;s','foo')">𝍷</td>"#
             )
         );
+        assert_eq!(
+            render_cell(
+                &Config {
+                    column_threshold: 2,
+                    static_columns: vec![],
+                    hidden_columns: HashSet::new(),
+                    substitute_labels: HashMap::new(),
+                    mark: HashMap::from([("foo".to_owned(), "πŸ¦„".to_owned())]),
+                },
+                "foo",
+                &mut Row {
+                    label: "nope".to_owned(),
+                    entries: HashMap::from([("foo".to_owned(), vec![None])]),
+                }
+            ),
+            HTML::from(
+                r#"<td class="yes" onmouseover="h2('nope','foo')" onmouseout="ch2('nope','foo')">πŸ¦„</td>"#
+            )
+        );
+
         let mut r = Row {
             label: "nope".to_owned(),
             entries: HashMap::from([
@@ -891,6 +934,22 @@ mod tests {
             ),
             HTML::from("")
         );
+        assert_eq!(
+            render_all_leftovers(
+                &Config {
+                    column_threshold: 2,
+                    static_columns: vec![],
+                    hidden_columns: HashSet::new(),
+                    substitute_labels: HashMap::new(),
+                    mark: HashMap::from([("foo".to_owned(), "🌈".to_owned())]),
+                },
+                &Row {
+                    label: "nope".to_owned(),
+                    entries: HashMap::from([("foo".to_owned(), vec![None, None])]),
+                }
+            ),
+            HTML::from("foo: πŸŒˆπŸŒˆ")
+        );
     }
 
     #[test]