Skip to main content

multicast_extras/
lib.rs

1//! Opt-in output formats that the default multicast CLI surface does not expose.
2
3use serde_json::Value;
4
5/// Output formats excluded from the default CLI surface.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ExtraFormat {
8    /// Aligned ASCII table output.
9    Table,
10    /// Comma-separated value output.
11    Csv,
12}
13
14impl ExtraFormat {
15    /// Formats a JSON value using this extension format.
16    pub fn format(self, value: &Value) -> String {
17        match self {
18            Self::Table => multicast::formatter::format_table(value),
19            Self::Csv => multicast::formatter::format_csv(value),
20        }
21    }
22
23    /// Returns the corresponding core format for explicitly configured CLI defaults.
24    pub fn core(self) -> multicast::output::Format {
25        match self {
26            Self::Table => multicast::output::Format::Table,
27            Self::Csv => multicast::output::Format::Csv,
28        }
29    }
30}
31
32/// Extension methods for explicitly opting a CLI into these formats.
33pub trait CliExtras {
34    /// Sets a default output format without changing the built-in format flags.
35    fn default_extra_format(self, format: ExtraFormat) -> Self;
36}
37
38impl CliExtras for multicast::cli::Cli {
39    fn default_extra_format(self, format: ExtraFormat) -> Self {
40        self.enable_extra_formats([ExtraFormat::Table.core(), ExtraFormat::Csv.core()])
41            .format(format.core())
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn formats_are_available_only_through_explicit_extension_api() {
51        let value = serde_json::json!([{ "name": "Ada", "active": true }]);
52        assert!(ExtraFormat::Table.format(&value).contains("Ada"));
53        assert_eq!(ExtraFormat::Csv.format(&value), "name,active\nAda,true");
54    }
55
56    #[tokio::test]
57    async fn extension_enables_table_and_csv_cli_values() {
58        let cli = multicast::cli::Cli::create("demo").default_extra_format(ExtraFormat::Table);
59        let mut table_output = Vec::new();
60        let table = cli
61            .serve_to(
62                vec!["--format".into(), "table".into()],
63                &mut table_output,
64                false,
65            )
66            .await
67            .expect("table invocation");
68        let mut csv_output = Vec::new();
69        let csv = cli
70            .serve_to(
71                vec!["--format".into(), "csv".into()],
72                &mut csv_output,
73                false,
74            )
75            .await
76            .expect("csv invocation");
77        assert_ne!(table, Some(1), "{}", String::from_utf8_lossy(&table_output));
78        assert_ne!(csv, Some(1), "{}", String::from_utf8_lossy(&csv_output));
79    }
80}