Skip to main content

bunsen_tool/support/
output_format.rs

1//! `--format`: YAML or JSON.
2
3use bunsen::errors::{
4    BunsenError,
5    BunsenResult,
6};
7use serde::Serialize;
8
9/// `--format`.
10#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
11pub enum Format {
12    /// YAML.
13    #[value(alias = "yaml")]
14    Yml,
15
16    /// JSON, unindented.
17    Json,
18}
19
20impl Format {
21    /// `value` in this format: YAML, or JSON on one line, each ending in a
22    /// newline. `what` names the value for the error.
23    ///
24    /// # Errors
25    /// [`Internal`](bunsen::errors::BunsenErrorKind::Internal) if it does not
26    /// serialize.
27    pub fn render<T: Serialize>(
28        self,
29        value: &T,
30        what: &str,
31    ) -> BunsenResult<String> {
32        match self {
33            Format::Yml => serde_saphyr::to_string(value)
34                .map_err(|e| BunsenError::internal(format!("render {what} as YAML: {e}"))),
35            Format::Json => serde_json::to_string(value)
36                .map(|json| json + "\n")
37                .map_err(|e| BunsenError::internal(format!("render {what} as JSON: {e}"))),
38        }
39    }
40}