Skip to main content

euv_cli/dx/output/
impl.rs

1use super::*;
2
3/// Label helpers on `StatusBadge`.
4impl StatusBadge {
5    /// Returns the short uppercase badge label (`PASS`, `SKIP`, `FAIL`, `WARN`, `INFO`).
6    ///
7    /// # Returns
8    ///
9    /// - `&'static str` - Fixed-width status token.
10    #[must_use]
11    pub const fn as_str(self) -> &'static str {
12        match self {
13            Self::Pass => BADGE_PASS,
14            Self::Skip => BADGE_SKIP,
15            Self::Fail => BADGE_FAIL,
16            Self::Warn => BADGE_WARN,
17            Self::Info => BADGE_INFO,
18        }
19    }
20}
21
22/// Builder and rendering methods on `TerminalTable`.
23impl TerminalTable {
24    /// Creates a new `TerminalTable` initialized with `headers`.
25    ///
26    /// # Arguments
27    ///
28    /// - `Vec<String>` - Ordered column header labels.
29    ///
30    /// # Returns
31    ///
32    /// - `Self` - Empty table ready for row insertion.
33    #[must_use]
34    pub fn with_headers(headers: Vec<String>) -> Self {
35        Self {
36            headers,
37            rows: Vec::new(),
38        }
39    }
40
41    /// Appends a single row of cell values to this table.
42    ///
43    /// # Arguments
44    ///
45    /// - `Vec<String>` - Cell texts matching column order.
46    pub fn push_row(&mut self, row: Vec<String>) {
47        let Self { rows, .. } = self;
48        rows.push(row);
49    }
50
51    /// Renders this table into aligned plain-text lines separated by two spaces.
52    ///
53    /// # Returns
54    ///
55    /// - `String` - Rendered multi-line terminal table.
56    #[must_use]
57    pub fn render(&self) -> String {
58        let headers: &[String] = self.get_headers();
59        let rows: &[Vec<String>] = self.get_rows();
60        let col_count: usize = headers.len().max(
61            rows.iter()
62                .map(|row: &Vec<String>| row.len())
63                .max()
64                .unwrap_or(0),
65        );
66        if col_count == 0 {
67            return String::new();
68        }
69        let mut widths: Vec<usize> = vec![0; col_count];
70        for (idx, cell) in headers.iter().enumerate() {
71            widths[idx] = widths[idx].max(cell.chars().count());
72        }
73        for row in rows.iter() {
74            for (idx, cell) in row.iter().enumerate() {
75                widths[idx] = widths[idx].max(cell.chars().count());
76            }
77        }
78        let mut out: String = String::new();
79        if !headers.is_empty() {
80            write_table_row(&mut out, headers, &widths);
81            let divider: Vec<String> = widths
82                .iter()
83                .map(|width: &usize| "-".repeat((*width).max(3)))
84                .collect();
85            write_table_row(&mut out, &divider, &widths);
86        }
87        for row in rows.iter() {
88            write_table_row(&mut out, row, &widths);
89        }
90        out
91    }
92}