Skip to main content

opcda_bridge_client/
output.rs

1//! Output format selection and rendering for client command results.
2//!
3//! Every command builds a `Vec` of row structs that derive both `Tabled`
4//! (for the default human-readable table) and `Serialize` (for `--output
5//! json`), then routes them through [`render`] — the single place that
6//! decides how a result becomes text. This mirrors `commands::render_tree`,
7//! which the codebase deliberately made return a `String` rather than print
8//! directly, so both paths are unit-testable without capturing stdout.
9
10use clap::ValueEnum;
11use serde::{Deserialize, Serialize};
12use tabled::{Table, Tabled};
13
14/// How a command's result is printed.
15#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum OutputFormat {
18    /// Human-readable table (default).
19    Table,
20    /// Pretty-printed JSON: a bare array of objects, one per row, using the
21    /// Rust field names as keys. This is the external contract for
22    /// programmatic consumers, so it must not change silently.
23    Json,
24}
25
26/// Render a command's rows in the requested format.
27pub fn render<T: Tabled + Serialize>(rows: Vec<T>, format: OutputFormat) -> anyhow::Result<String> {
28    match format {
29        OutputFormat::Table => Ok(Table::new(rows).to_string()),
30        OutputFormat::Json => Ok(serde_json::to_string_pretty(&rows)?),
31    }
32}
33
34/// Format an error for display, matching the requested output format.
35///
36/// The `Table` branch reproduces Rust's default `Termination` behavior for
37/// `Err` (`"Error: {:?}"`, the `Debug` chain anyhow builds), so plain-table
38/// users see the same error text as before this flag existed. The `Json`
39/// branch emits `{"error": "<message>"}` so scripted consumers never have
40/// to parse free-text stderr.
41pub fn format_error(err: &anyhow::Error, format: OutputFormat) -> String {
42    match format {
43        OutputFormat::Table => format!("Error: {err:?}"),
44        OutputFormat::Json => {
45            let payload = serde_json::json!({ "error": err.to_string() });
46            serde_json::to_string_pretty(&payload)
47                .unwrap_or_else(|_| format!("{{\"error\": \"{err}\"}}"))
48        }
49    }
50}
51
52/// Extract the output format from CLI-only sources: `--json` (which wins if
53/// both are set) or `--output` (which already folds in `OPC_BRIDGE_OUTPUT`
54/// via clap's `env` attribute). Returns `None` if neither was given, so the
55/// caller can still fall back to a config file.
56///
57/// Kept CLI-only (no config file access) because config loading can itself
58/// fail, and an error at that stage must still be reportable in *some*
59/// format before the config file's `output` key could ever be known.
60pub fn resolve_from_cli(cli: &crate::cli::Cli) -> Option<OutputFormat> {
61    if cli.json {
62        Some(OutputFormat::Json)
63    } else {
64        cli.output
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[derive(Tabled, Serialize)]
73    struct Row {
74        name: String,
75        count: u32,
76    }
77
78    #[test]
79    fn test_render_table() {
80        let rows = vec![Row {
81            name: "a".into(),
82            count: 1,
83        }];
84        let out = render(rows, OutputFormat::Table).unwrap();
85        assert!(out.contains("name"));
86        assert!(out.contains("a"));
87    }
88
89    #[test]
90    fn test_render_json_shape_and_keys() {
91        let rows = vec![Row {
92            name: "a".into(),
93            count: 1,
94        }];
95        let out = render(rows, OutputFormat::Json).unwrap();
96        let value: serde_json::Value = serde_json::from_str(&out).unwrap();
97        let arr = value.as_array().unwrap();
98        assert_eq!(arr.len(), 1);
99        assert_eq!(arr[0]["name"], "a");
100        assert_eq!(arr[0]["count"], 1);
101    }
102
103    #[test]
104    fn test_render_json_empty_is_bare_array_not_null() {
105        let rows: Vec<Row> = vec![];
106        let out = render(rows, OutputFormat::Json).unwrap();
107        assert_eq!(out, "[]");
108    }
109
110    #[test]
111    fn test_render_json_is_pretty_printed() {
112        let rows = vec![Row {
113            name: "a".into(),
114            count: 1,
115        }];
116        let out = render(rows, OutputFormat::Json).unwrap();
117        assert!(out.contains('\n'), "expected multi-line pretty JSON");
118    }
119
120    #[test]
121    fn test_format_error_table_matches_debug_chain() {
122        let err = anyhow::anyhow!("boom");
123        let out = format_error(&err, OutputFormat::Table);
124        assert_eq!(out, format!("Error: {err:?}"));
125    }
126
127    #[test]
128    fn test_format_error_json_is_valid_json_with_message() {
129        let err = anyhow::anyhow!("boom");
130        let out = format_error(&err, OutputFormat::Json);
131        let value: serde_json::Value = serde_json::from_str(&out).unwrap();
132        assert_eq!(value["error"], "boom");
133    }
134
135    #[test]
136    fn test_output_format_deserialize_lowercase() {
137        #[derive(Deserialize)]
138        struct Wrapper {
139            output: OutputFormat,
140        }
141        let w: Wrapper = toml::from_str("output = \"json\"").unwrap();
142        assert_eq!(w.output, OutputFormat::Json);
143        let w: Wrapper = toml::from_str("output = \"table\"").unwrap();
144        assert_eq!(w.output, OutputFormat::Table);
145    }
146}