Skip to main content

pimalaya_cli/
columns.rs

1//! Text lists printed as aligned columns.
2//!
3//! A command printing a list as text renders it as [`Columns`]: a header
4//! row of labels, then one row per item, the cells aligned in columns
5//! two spaces apart, with no border and no colour. Each line is one item,
6//! greppable and split on blanks, and the list ends with a newline like
7//! every text output. [`Fields`] is its twin for a single record.
8//!
9//! [`Fields`]: crate::fields::Fields
10
11use std::{borrow::Cow, fmt, iter};
12
13use unicode_width::UnicodeWidthStr;
14
15/// A list printed as borderless aligned columns.
16///
17/// Cells are padded to the widest cell of their column, measured in
18/// terminal display columns, and separated by two spaces; the last column
19/// is not padded. An empty or missing cell prints as `-`, and a line break
20/// inside a cell as a space. Nothing is truncated: the terminal folds a
21/// long line. Labels and cells print as given: the caller passes the
22/// labels uppercase, and sanitizes an untrusted cell first with
23/// [`sanitize::text`].
24///
25/// [`sanitize::text`]: crate::sanitize::text
26#[derive(Clone, Debug, Default, Eq, PartialEq)]
27pub struct Columns<'a> {
28    /// The column labels, printed as the header row unless empty.
29    pub header: Vec<&'a str>,
30    /// The rendered cells of each row, in print order.
31    pub rows: Vec<Vec<String>>,
32}
33
34impl<'a> Columns<'a> {
35    /// Builds a list of the given column labels, without rows.
36    pub fn new(header: impl IntoIterator<Item = &'a str>) -> Self {
37        Self {
38            header: header.into_iter().collect(),
39            rows: Vec::new(),
40        }
41    }
42
43    /// Appends a row, rendering its cells.
44    pub fn push(&mut self, row: impl IntoIterator<Item = impl fmt::Display>) {
45        let row = row.into_iter().map(|cell| cell.to_string());
46        self.rows.push(row.collect());
47    }
48}
49
50impl fmt::Display for Columns<'_> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let header = (!self.header.is_empty()).then(|| {
53            let labels = self.header.iter().copied();
54            labels.map(cell).collect::<Vec<_>>()
55        });
56        let rows = self.rows.iter().map(|row| {
57            let cells = row.iter().map(String::as_str);
58            cells.map(cell).collect::<Vec<_>>()
59        });
60        let lines: Vec<_> = iter::once(header).flatten().chain(rows).collect();
61
62        let count = lines.iter().map(Vec::len).max().unwrap_or_default();
63        let mut widths = vec![1; count];
64
65        for line in &lines {
66            for (width, cell) in widths.iter_mut().zip(line) {
67                *width = cell.width().max(*width);
68            }
69        }
70
71        for line in &lines {
72            for (i, width) in widths.iter().enumerate() {
73                let cell = line.get(i).map_or("-", |cell| cell);
74
75                if i > 0 {
76                    f.write_str("  ")?;
77                }
78
79                f.write_str(cell)?;
80
81                if i + 1 < count {
82                    let pad = width - cell.width();
83                    write!(f, "{:pad$}", "")?;
84                }
85            }
86
87            writeln!(f)?;
88        }
89
90        Ok(())
91    }
92}
93
94/// Renders a cell on one line, `-` when empty.
95fn cell(s: &str) -> Cow<'_, str> {
96    if s.is_empty() {
97        Cow::Borrowed("-")
98    } else if s.contains(['\n', '\r']) {
99        Cow::Owned(s.replace(['\n', '\r'], " "))
100    } else {
101        Cow::Borrowed(s)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use crate::columns::*;
108
109    #[test]
110    fn a_wide_last_column_is_not_padded() {
111        let mut columns = Columns::new(["ID", "NAME", "DESCRIPTION"]);
112        columns.push(["1", "Inbox", "Mail received"]);
113        columns.push(["42", "Sent", ""]);
114
115        let expected = "\
116ID  NAME   DESCRIPTION
1171   Inbox  Mail received
11842  Sent   -
119";
120        assert_eq!(columns.to_string(), expected);
121    }
122
123    #[test]
124    fn wide_characters_count_their_display_width() {
125        let mut columns = Columns::new(["NAME", "ID"]);
126        columns.push(["日本語", "1"]);
127        columns.push(["🦀", "2"]);
128        columns.push(["ab", "3"]);
129
130        let expected = "\
131NAME    ID
132日本語  1
133🦀      2
134ab      3
135";
136        assert_eq!(columns.to_string(), expected);
137    }
138
139    #[test]
140    fn empty_and_missing_cells_print_a_dash() {
141        let mut columns = Columns::new(["A", "B", "C"]);
142        columns.push(["", "b"]);
143        columns.push(["a", "", "c"]);
144
145        let expected = "\
146A  B  C
147-  b  -
148a  -  c
149";
150        assert_eq!(columns.to_string(), expected);
151    }
152
153    #[test]
154    fn a_line_break_in_a_cell_prints_as_a_space() {
155        let mut columns = Columns::new(["SUBJECT", "FROM"]);
156        columns.push(["Re:\nhello", "a\r\nb"]);
157
158        let expected = "\
159SUBJECT    FROM
160Re: hello  a  b
161";
162        assert_eq!(columns.to_string(), expected);
163    }
164
165    #[test]
166    fn a_list_without_rows_prints_its_header() {
167        let columns = Columns::new(["ID", "NAME"]);
168        assert_eq!(columns.to_string(), "ID  NAME\n");
169        assert_eq!(Columns::default().to_string(), "");
170    }
171}