Skip to main content

systemprompt_logging/services/cli/
table.rs

1//! Box-drawing table renderers for CLI output.
2//!
3//! [`render_table`] draws an arbitrary header/row grid;
4//! [`render_service_table`] renders the service-status table from
5//! [`ServiceTableEntry`] values; and [`render_startup_complete`] prints the
6//! post-boot summary. Output goes to stdout via this sanctioned display sink.
7//!
8//! Copyright (c) systemprompt.io — Business Source License 1.1.
9//! See <https://systemprompt.io> for licensing details.
10
11use std::io::Write;
12use std::time::Duration;
13
14use crate::services::cli::theme::{BrandColors, ServiceStatus};
15
16fn stdout_write(args: std::fmt::Arguments<'_>) {
17    let mut out = std::io::stdout();
18    write!(out, "{args}").ok();
19}
20
21fn stdout_writeln(args: std::fmt::Arguments<'_>) {
22    let mut out = std::io::stdout();
23    writeln!(out, "{args}").ok();
24}
25
26#[derive(Debug, Clone)]
27pub struct ServiceTableEntry {
28    pub name: String,
29    pub service_type: String,
30    pub port: Option<u16>,
31    pub status: ServiceStatus,
32}
33
34impl ServiceTableEntry {
35    pub fn new(
36        name: impl Into<String>,
37        service_type: impl Into<String>,
38        port: Option<u16>,
39        status: ServiceStatus,
40    ) -> Self {
41        Self {
42            name: name.into(),
43            service_type: service_type.into(),
44            port,
45            status,
46        }
47    }
48}
49
50pub fn truncate_to_width(s: &str, width: usize) -> String {
51    if s.chars().count() <= width {
52        return s.to_owned();
53    }
54    let truncate_to = width.saturating_sub(3);
55    let truncated: String = s.chars().take(truncate_to).collect();
56    format!("{truncated}...")
57}
58
59fn calculate_column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
60    let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
61
62    for row in rows {
63        for (i, cell) in row.iter().enumerate() {
64            if i < widths.len() {
65                widths[i] = widths[i].max(cell.len());
66            }
67        }
68    }
69
70    widths
71}
72
73fn render_table_border(widths: &[usize], left: &str, middle: &str, right: &str) {
74    stdout_write(format_args!("{left}"));
75    for (i, &width) in widths.iter().enumerate() {
76        stdout_write(format_args!("{}", "\u{2500}".repeat(width + 2)));
77        if i < widths.len() - 1 {
78            stdout_write(format_args!("{middle}"));
79        }
80    }
81    stdout_writeln(format_args!("{right}"));
82}
83
84fn render_table_row(cells: &[&str], widths: &[usize]) {
85    stdout_write(format_args!("\u{2502}"));
86    for (i, (&cell, &width)) in cells.iter().zip(widths.iter()).enumerate() {
87        let truncated = truncate_to_width(cell, width);
88        stdout_write(format_args!(" {truncated:<width$} "));
89        if i < widths.len() - 1 {
90            stdout_write(format_args!("\u{2502}"));
91        }
92    }
93    stdout_writeln(format_args!("\u{2502}"));
94}
95
96pub fn render_table(headers: &[&str], rows: &[Vec<String>]) {
97    if rows.is_empty() {
98        return;
99    }
100
101    let widths = calculate_column_widths(headers, rows);
102
103    render_table_border(&widths, "\u{250c}", "\u{252c}", "\u{2510}");
104    render_table_row(headers, &widths);
105    render_table_border(&widths, "\u{251c}", "\u{253c}", "\u{2524}");
106
107    for row in rows {
108        let cells: Vec<&str> = row.iter().map(String::as_str).collect();
109        render_table_row(&cells, &widths);
110    }
111
112    render_table_border(&widths, "\u{2514}", "\u{2534}", "\u{2518}");
113}
114
115struct ServiceColumns {
116    name: usize,
117    service_type: usize,
118    port: usize,
119    status: usize,
120}
121
122impl ServiceColumns {
123    fn measure(services: &[ServiceTableEntry]) -> Self {
124        let name = services
125            .iter()
126            .map(|s| s.name.len())
127            .max()
128            .unwrap_or(4)
129            .max(4);
130        let service_type = services
131            .iter()
132            .map(|s| s.service_type.len())
133            .max()
134            .unwrap_or(4)
135            .max(4);
136        Self {
137            name,
138            service_type,
139            port: 5,
140            status: 10,
141        }
142    }
143
144    fn rule(&self, left: &str, middle: &str, right: &str) {
145        stdout_writeln(format_args!(
146            "{left}{}{middle}{}{middle}{}{middle}{}{right}",
147            "\u{2500}".repeat(self.name + 2),
148            "\u{2500}".repeat(self.service_type + 2),
149            "\u{2500}".repeat(self.port + 2),
150            "\u{2500}".repeat(self.status + 2)
151        ));
152    }
153}
154
155pub fn render_service_table(title: &str, services: &[ServiceTableEntry]) {
156    if services.is_empty() {
157        return;
158    }
159
160    let cols = ServiceColumns::measure(services);
161    let total_width = cols.name + cols.service_type + cols.port + cols.status + 13;
162
163    stdout_writeln(format_args!(""));
164    stdout_writeln(format_args!(
165        "\u{250c}{}\u{2510}",
166        "\u{2500}".repeat(total_width)
167    ));
168    stdout_writeln(format_args!(
169        "\u{2502} {:<width$} \u{2502}",
170        BrandColors::white_bold(title),
171        width = total_width - 3
172    ));
173
174    cols.rule("\u{251c}", "\u{252c}", "\u{2524}");
175    render_service_header(&cols);
176    cols.rule("\u{251c}", "\u{253c}", "\u{2524}");
177
178    for service in services {
179        render_service_row(service, &cols);
180    }
181
182    cols.rule("\u{2514}", "\u{2534}", "\u{2518}");
183}
184
185fn render_service_header(cols: &ServiceColumns) {
186    let name_width = cols.name;
187    let type_width = cols.service_type;
188    let port_width = cols.port;
189    let status_width = cols.status;
190    stdout_writeln(format_args!(
191        "\u{2502} {:<name_width$} \u{2502} {:<type_width$} \u{2502} {:<port_width$} \u{2502} \
192         {:<status_width$} \u{2502}",
193        BrandColors::dim("Name"),
194        BrandColors::dim("Type"),
195        BrandColors::dim("Port"),
196        BrandColors::dim("Status"),
197    ));
198}
199
200fn render_service_row(service: &ServiceTableEntry, cols: &ServiceColumns) {
201    let name_width = cols.name;
202    let type_width = cols.service_type;
203    let port_width = cols.port;
204    let status_width = cols.status;
205
206    let port_str = service
207        .port
208        .map_or_else(|| "-".to_owned(), |p| p.to_string());
209
210    let status_display = format!("{} {}", service.status.symbol(), service.status.text());
211    let colored_status = match service.status {
212        ServiceStatus::Running => format!("{}", BrandColors::running(&status_display)),
213        ServiceStatus::Starting => format!("{}", BrandColors::starting(&status_display)),
214        ServiceStatus::Stopped | ServiceStatus::Failed => {
215            format!("{}", BrandColors::stopped(&status_display))
216        },
217        ServiceStatus::Unknown => format!("{}", BrandColors::dim(&status_display)),
218    };
219
220    stdout_writeln(format_args!(
221        "\u{2502} {:<name_width$} \u{2502} {:<type_width$} \u{2502} {:>port_width$} \u{2502} \
222         {:<status_width$} \u{2502}",
223        service.name, service.service_type, port_str, colored_status,
224    ));
225}
226
227pub fn render_startup_complete(duration: Duration, api_url: &str) {
228    let secs = duration.as_secs_f64();
229    stdout_writeln(format_args!(""));
230    stdout_writeln(format_args!(
231        "{} {} {}",
232        BrandColors::running("\u{2713}"),
233        BrandColors::white_bold("All services started successfully"),
234        BrandColors::dim(format!("({:.1}s)", secs))
235    ));
236    stdout_writeln(format_args!(
237        "  {} {}",
238        BrandColors::dim("API:"),
239        BrandColors::highlight(api_url)
240    ));
241    stdout_writeln(format_args!(""));
242}