Skip to main content

pimalaya_cli/
listing.rs

1//! # Listing
2//!
3//! The text frame of every list: the fields placing it (the account, what
4//! is listed, the page it holds) as [`Fields`], one blank line, the items
5//! as [`Columns`] with no header row, then the `Next page:` line reaching
6//! the next page and the item errors as [`ItemErrors`] prints them, each
7//! one blank line apart.
8//!
9//! [`Fields`]: crate::fields::Fields
10//! [`ItemErrors`]: crate::error::ItemErrors
11
12use std::fmt;
13
14use crate::{columns::Columns, error::ItemErrors, fields::Fields, sanitize};
15
16/// A list printed one item per line under the fields placing it.
17#[derive(Clone, Debug, Default)]
18pub struct Listing<'a> {
19    /// The fields above the items, their values sanitized.
20    pub header: Vec<(&'static str, String)>,
21    /// The items, one per line, with no header row.
22    pub items: Columns<'a>,
23    /// The line printed in place of the items when there are none.
24    pub empty: Option<&'static str>,
25    /// The flag reaching the next page, sanitized, printed after the
26    /// items as `Next page: <flag> <value>`.
27    pub next_page: Option<String>,
28    /// The items the command could not list, printed last.
29    pub errors: ItemErrors,
30}
31
32/// The page a listing holds.
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum ListingPage {
35    /// The whole listing, unpaged.
36    All,
37    /// A page of a listing paged by number, reached by `--page`.
38    Numbered {
39        /// The page held, from 1.
40        page: u64,
41        /// The number of items a full page holds.
42        size: u64,
43    },
44    /// A page reached by an opaque token, reached by `--page-token`.
45    Token,
46}
47
48impl<'a> Listing<'a> {
49    /// A listing headed by the account, its backend in parentheses.
50    pub fn new(account: &str, backend: Option<&str>) -> Self {
51        let mut value = sanitize::text(account).into_owned();
52
53        if let Some(backend) = backend {
54            value.push_str(&format!(" ({backend})"));
55        }
56
57        Self {
58            header: vec![("Account", value)],
59            ..Default::default()
60        }
61    }
62
63    /// Adds a field above the items, its value sanitized.
64    pub fn head(&mut self, label: &'static str, value: &str) {
65        let value = sanitize::text(value).into_owned();
66        self.header.push((label, value));
67    }
68
69    /// Adds the page the `count` items fill, named by their singular and
70    /// plural `nouns`, and sets the flag reaching the `next` page.
71    pub fn page(&mut self, page: ListingPage, count: usize, nouns: [&str; 2], next: Option<&str>) {
72        let count = count as u64;
73        let [one, many] = nouns;
74
75        let (number, first) = match page {
76            ListingPage::All => (Some(String::from("all")), Some(1)),
77            ListingPage::Numbered { page, size } => {
78                let first = page.saturating_sub(1) * size + 1;
79                (Some(page.to_string()), Some(first))
80            }
81            ListingPage::Token => (None, None),
82        };
83
84        let held = match (count, first) {
85            (0, _) => String::from("empty"),
86            (1, Some(first)) => format!("{one} {first}"),
87            (n, Some(first)) => format!("{many} {first} to {}", first + n - 1),
88            (1, None) => format!("1 {one}"),
89            (n, None) => format!("{n} {many}"),
90        };
91
92        let last = match (page, next) {
93            (ListingPage::All, _) | (_, Some(_)) => "",
94            _ if count == 0 => "",
95            _ => ", the last",
96        };
97
98        let value = match number {
99            Some(number) => format!("{number}, {held}{last}"),
100            None => format!("{held}{last}"),
101        };
102
103        self.header.push(("Page", value));
104
105        if let Some(token) = next {
106            let flag = match page {
107                ListingPage::All | ListingPage::Numbered { .. } => "--page",
108                ListingPage::Token => "--page-token",
109            };
110
111            let token = sanitize::text(token);
112            self.next_page = Some(format!("{flag} {token}"));
113        }
114    }
115}
116
117impl fmt::Display for Listing<'_> {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        let mut header = Fields::default();
120
121        for (label, value) in &self.header {
122            header.push(label, value);
123        }
124
125        let mut printed = header.to_string();
126
127        let body = match (self.items.rows.is_empty(), self.empty) {
128            (false, _) => Some(self.items.to_string()),
129            (true, Some(empty)) => Some(format!("{empty}\n")),
130            (true, None) => None,
131        };
132
133        let next = self.next_page.as_ref().map(|n| format!("Next page: {n}\n"));
134
135        for block in [body, next].into_iter().flatten() {
136            if !printed.is_empty() {
137                printed.push('\n');
138            }
139
140            printed.push_str(&block);
141        }
142
143        f.write_str(&printed)?;
144
145        if printed.is_empty() {
146            return write!(f, "{}", self.errors);
147        }
148
149        self.errors.write_after(f)
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use anyhow::anyhow;
156    use schemars::JsonSchema;
157    use serde::Serialize;
158
159    use crate::{
160        error::{CodedError, ItemError},
161        listing::*,
162    };
163
164    #[derive(Clone, Debug, Serialize, JsonSchema)]
165    #[serde(rename_all = "kebab-case")]
166    enum TestCode {
167        MessageUnreadable,
168    }
169
170    fn listing(rows: usize) -> Listing<'static> {
171        let mut listing = Listing::new("work", Some("imap"));
172
173        for i in 0..rows {
174            listing.items.push([i.to_string(), String::from("x")]);
175        }
176
177        listing
178    }
179
180    #[test]
181    fn a_numbered_page_counts_its_items_and_names_the_next_after_them() {
182        let mut first = listing(2);
183        first.head("Mailbox", "INBOX");
184        first.page(
185            ListingPage::Numbered { page: 2, size: 2 },
186            2,
187            ["envelope", "envelopes"],
188            Some("3"),
189        );
190
191        let expected = "\
192Account:  work (imap)
193Mailbox:  INBOX
194Page:     2, envelopes 3 to 4
195
1960  x
1971  x
198
199Next page: --page 3
200";
201        assert_eq!(first.to_string(), expected);
202
203        let mut last = listing(1);
204        last.page(
205            ListingPage::Numbered { page: 3, size: 2 },
206            1,
207            ["envelope", "envelopes"],
208            None,
209        );
210
211        let expected = "\
212Account:  work (imap)
213Page:     3, envelope 5, the last
214
2150  x
216";
217        assert_eq!(last.to_string(), expected);
218    }
219
220    #[test]
221    fn a_token_page_counts_what_it_holds() {
222        let mut first = listing(2);
223        first.page(ListingPage::Token, 2, ["draft", "drafts"], Some("abc"));
224
225        let expected = "\
226Account:  work (imap)
227Page:     2 drafts
228
2290  x
2301  x
231
232Next page: --page-token abc
233";
234        assert_eq!(first.to_string(), expected);
235
236        let mut empty = listing(0);
237        empty.page(ListingPage::Token, 0, ["draft", "drafts"], None);
238        assert_eq!(
239            empty.to_string(),
240            "Account:  work (imap)\nPage:     empty\n"
241        );
242    }
243
244    #[test]
245    fn an_empty_page_still_names_the_next() {
246        let mut empty = listing(0);
247        empty.empty = Some("No draft");
248        empty.page(ListingPage::Token, 0, ["draft", "drafts"], Some("abc"));
249
250        let expected = "\
251Account:  work (imap)
252Page:     empty
253
254No draft
255
256Next page: --page-token abc
257";
258        assert_eq!(empty.to_string(), expected);
259    }
260
261    #[test]
262    fn header_values_align_past_the_longest_label() {
263        let mut listing = listing(0);
264        listing.head("Addressbook", "contacts");
265        listing.empty = Some("No card");
266
267        let expected = "\
268Account:      work (imap)
269Addressbook:  contacts
270
271No card
272";
273        assert_eq!(listing.to_string(), expected);
274    }
275
276    #[test]
277    fn item_errors_print_last_after_the_next_page() {
278        let mut listing = listing(1);
279        listing.page(
280            ListingPage::Numbered { page: 1, size: 1 },
281            1,
282            ["envelope", "envelopes"],
283            Some("2"),
284        );
285
286        let unreadable = CodedError::new(TestCode::MessageUnreadable, "Cannot decode it");
287        listing
288            .errors
289            .push(&ItemError::<TestCode>::new(None, &unreadable.into()));
290        listing
291            .errors
292            .push(&ItemError::<TestCode>::new(Some("42"), &anyhow!("Gone")));
293
294        let expected = "\
295Account:  work (imap)
296Page:     1, envelope 1
297
2980  x
299
300Next page: --page 2
301
302Error:  -   message-unreadable  Cannot decode it
303Error:  42  -                   Gone
304";
305        assert_eq!(listing.to_string(), expected);
306    }
307
308    #[test]
309    fn a_bare_listing_prints_its_items_alone() {
310        let mut bare = Listing::default();
311        bare.items.push(["a", "b"]);
312        assert_eq!(bare.to_string(), "a  b\n");
313
314        let mut errors_only = Listing::default();
315        errors_only
316            .errors
317            .push(&ItemError::<TestCode>::new(None, &anyhow!("Gone")));
318        assert_eq!(errors_only.to_string(), "Error:  -  -  Gone\n");
319    }
320}