Skip to main content

ocpi_tariffs_cli/
print.rs

1//! Helper items for printing text to a terminal.
2
3use std::fmt::{self, Write as _};
4
5use console::{measure_text_width, style};
6use ocpi_tariffs::{
7    Warning,
8    json::{Component, Path},
9    price::TariffReport,
10    timezone, warning,
11};
12use tracing::error;
13
14/// A general purpose horizontal break.
15const LINE: &str = "----------------------------------------------------------------";
16/// The initial amount of memory allocated for writing out the table.
17const TABLE_BUF_LEN: usize = 4096;
18
19/// A helper for printing `Option<T>` without creating a `String`.
20pub struct Optional<T>(pub Option<T>)
21where
22    T: fmt::Display;
23
24impl<T> fmt::Display for Optional<T>
25where
26    T: fmt::Display,
27{
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match &self.0 {
30            Some(v) => fmt::Display::fmt(v, f),
31            None => f.write_str("-"),
32        }
33    }
34}
35
36/// Renders a [`Path`] with each component styled independently: dim delimiters,
37/// cyan object members and yellow array indices.
38///
39/// `console` disables the ANSI codes automatically when the stream is not a
40/// terminal, so the output stays plain when redirected.
41pub struct DisplayPath<'a>(pub &'a Path);
42
43impl fmt::Display for DisplayPath<'_> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(f, "{}", style('$').dim())?;
46
47        for component in self.0.components() {
48            match component {
49                Component::Member(name) => {
50                    write!(f, "{}{}", style('.').dim(), style(name).cyan())?;
51                }
52                Component::Index(index) => {
53                    write!(
54                        f,
55                        "{}{}{}",
56                        style('[').dim(),
57                        style(index).yellow(),
58                        style(']').dim(),
59                    )?;
60                }
61            }
62        }
63
64        Ok(())
65    }
66}
67
68/// Print the error produced by a call to `ocpi-tariffs::timezone::find_or_infer`.
69pub fn timezone_error(error: &warning::Error<timezone::Warning>) {
70    eprintln!(
71        "{}: Unable to find timezone due to error at path `{}`: {}",
72        style("ERR").red(),
73        DisplayPath(&error.element().path),
74        error.warning()
75    );
76}
77
78/// Print a set of warnings to `stderr`, one per line with its source path.
79///
80/// `feature` names the operation the warnings came from (for example `"pricing the CDR"` or
81/// `"the timezone search"`); it appears in the header `N warnings from {feature}`. Nothing is
82/// printed when the set is empty.
83pub fn warning_set<W: Warning>(feature: &'static str, warnings: &warning::Set<W>) {
84    if warnings.is_empty() {
85        return;
86    }
87
88    eprintln!(
89        "{}: {} warnings from {}",
90        style("WARN").yellow(),
91        warnings.len_warnings(),
92        feature
93    );
94
95    for group in warnings {
96        let (element, warnings) = group.to_parts();
97        for warning in warnings {
98            eprintln!(
99                "  - path: {}: {}",
100                DisplayPath(&element.path),
101                style(warning).yellow()
102            );
103        }
104    }
105
106    let line = style(LINE).yellow();
107    eprintln!("{line}");
108}
109
110/// Print the unexpected fields of a list of tariffs to `stderr`.
111pub fn tariff_reports(reports: &[TariffReport]) {
112    if reports.iter().all(|report| report.warnings.is_empty()) {
113        return;
114    }
115
116    let line = style(LINE).yellow();
117
118    eprintln!("{}: warnings found in tariffs", style("WARN").yellow());
119
120    for report in reports {
121        let TariffReport { origin, warnings } = report;
122
123        if warnings.is_empty() {
124            continue;
125        }
126
127        eprintln!(
128            "{}: {} warnings from tariff with id: {}",
129            style("WARN").yellow(),
130            warnings.len(),
131            style(&origin.id).yellow(),
132        );
133
134        for (elem_path, warnings) in warnings {
135            eprintln!("  {}", DisplayPath(elem_path));
136
137            for warning in warnings {
138                eprintln!("  - {}", style(warning).yellow());
139            }
140        }
141
142        eprintln!("{line}");
143    }
144
145    eprintln!("{line}");
146}
147
148/// A helper for printing tables with fixed width cols.
149pub struct Table {
150    /// The widths given in the `header` fn.
151    widths: Vec<usize>,
152
153    /// The table is written into this buffer.
154    buf: String,
155}
156
157/// The column of a table.
158pub struct Col<'caller> {
159    /// The label to display for this column.
160    pub label: &'caller dyn fmt::Display,
161
162    /// The width this column should occupy.
163    pub width: usize,
164}
165
166impl Col<'_> {
167    /// Create a `Col` without a name.
168    pub fn empty(width: usize) -> Self {
169        Self { label: &"", width }
170    }
171}
172
173impl Table {
174    /// Print the table header and use the column widths for all the following rows.
175    pub fn header(header: &[Col<'_>]) -> Self {
176        let widths = header
177            .iter()
178            .map(|Col { label: _, width }| *width)
179            .collect::<Vec<_>>();
180        let mut buf = String::with_capacity(TABLE_BUF_LEN);
181        let labels = header
182            .iter()
183            .map(|Col { label, width: _ }| *label)
184            .collect::<Vec<_>>();
185
186        print_table_line(&mut buf, &widths);
187        print_table_row(&mut buf, &widths, &labels);
188        print_table_line(&mut buf, &widths);
189
190        Self { widths, buf }
191    }
192
193    /// Print a separating line.
194    pub fn print_line(&mut self) {
195        print_table_line(&mut self.buf, &self.widths);
196    }
197
198    /// Print a single row of values.
199    pub fn print_row(&mut self, values: &[&dyn fmt::Display]) {
200        print_table_row(&mut self.buf, &self.widths, values);
201    }
202
203    /// Print a single row with a label stylized based of the validity.
204    ///
205    /// If the row represents a valid value, the label is colored green.
206    /// Otherwise, the label is colored red.
207    pub fn print_valid_row(
208        &mut self,
209        is_valid: bool,
210        label: &'static str,
211        values: &[&dyn fmt::Display],
212    ) {
213        let label = if is_valid {
214            style(label).green()
215        } else {
216            style(label).red()
217        };
218        print_table_row_with_label(&mut self.buf, &self.widths, &label, values);
219    }
220
221    /// Print the bottom line of the table and return the buffer for printing.
222    pub fn finish(self) -> String {
223        let Self { widths, mut buf } = self;
224        print_table_line(&mut buf, &widths);
225        buf
226    }
227}
228
229/// Just like the std lib `write!` macro except that it suppresses in `fmt::Result`.
230///
231/// This should only be used if you are in control of the buffer you're writing to
232/// and the only way it can fail is if the OS allocator fails.
233///
234/// * See: <https://doc.rust-lang.org/std/io/trait.Write.html#method.write_fmt>.
235#[macro_export]
236macro_rules! write_or {
237    ($dst:expr, $($arg:tt)*) => {{
238        let _ignore_result = $dst.write_fmt(std::format_args!($($arg)*));
239    }};
240}
241
242/// Print a separation line for a table.
243fn print_table_line(buf: &mut String, widths: &[usize]) {
244    write_or!(buf, "+");
245
246    for width in widths {
247        write_or!(
248            buf,
249            "{0:->1$}+",
250            "",
251            width.checked_add(2).unwrap_or_default()
252        );
253    }
254
255    write_or!(buf, "\n");
256}
257
258/// Print a single row to the buffer with a label.
259fn print_table_row(buf: &mut String, widths: &[usize], values: &[&dyn fmt::Display]) {
260    assert_eq!(
261        widths.len(),
262        values.len(),
263        "The widths and values amounts should be the same"
264    );
265    print_table_row_(buf, widths, values, None);
266}
267
268/// Print a single row to the buffer with a distinct label.
269///
270/// This fn is used to create a row with a stylized label.
271fn print_table_row_with_label(
272    buf: &mut String,
273    widths: &[usize],
274    label: &dyn fmt::Display,
275    values: &[&dyn fmt::Display],
276) {
277    print_table_row_(buf, widths, values, Some(label));
278}
279
280/// Print a single row to the buffer.
281fn print_table_row_(
282    buf: &mut String,
283    widths: &[usize],
284    values: &[&dyn fmt::Display],
285    label: Option<&dyn fmt::Display>,
286) {
287    write_or!(buf, "|");
288
289    if let Some(label) = label {
290        let mut widths = widths.iter();
291        let Some(width) = widths.next() else {
292            return;
293        };
294        print_col(buf, label, *width);
295
296        for (value, width) in values.iter().zip(widths) {
297            print_col(buf, *value, *width);
298        }
299    } else {
300        for (value, width) in values.iter().zip(widths) {
301            print_col(buf, *value, *width);
302        }
303    }
304
305    write_or!(buf, "\n");
306}
307
308/// Print a single column to the buffer.
309fn print_col(buf: &mut String, value: &dyn fmt::Display, width: usize) {
310    write_or!(buf, " ");
311
312    // The value could contain ANSI escape codes and the `Display` impl of the type
313    // may not implement fill and alignment logic. So we need to implement left-aligned text ourselves.
314    let len_before = buf.len();
315    write_or!(buf, "{value}");
316    let len_after = buf.len();
317
318    // Use the length before and after to capture the str just written.
319    // And compute it's visible length in the terminal.
320    let Some(s) = &buf.get(len_before..len_after) else {
321        error!("Non UTF8 values were written as a column value");
322        return;
323    };
324
325    let len = measure_text_width(s);
326    // Calculate the padding we need to apply at the end of the str.
327    let padding = width.saturating_sub(len);
328
329    // and apply the padding
330    for _ in 0..padding {
331        write_or!(buf, " ");
332    }
333
334    write_or!(buf, " |");
335}