iceoryx2_cli/
format.rs

1// Copyright (c) 2024 Contributors to the Eclipse Foundation
2//
3// See the NOTICE file(s) distributed with this work for additional
4// information regarding copyright ownership.
5//
6// This program and the accompanying materials are made available under the
7// terms of the Apache Software License 2.0 which is available at
8// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
9// which is available at https://opensource.org/licenses/MIT.
10//
11// SPDX-License-Identifier: Apache-2.0 OR MIT
12
13use anyhow::{anyhow, Context, Error, Result};
14use clap::ValueEnum;
15use core::str::FromStr;
16use serde::Serialize;
17
18#[derive(Clone, Copy, ValueEnum)]
19#[value(rename_all = "UPPERCASE")]
20pub enum Format {
21    Ron,
22    Json,
23    Yaml,
24}
25
26impl Format {
27    pub fn as_string<T: Serialize>(self, data: &T) -> Result<String> {
28        match self {
29            Format::Ron => ron::ser::to_string_pretty(
30                data,
31                ron::ser::PrettyConfig::new().separate_tuple_members(true),
32            )
33            .context("failed to serialize to RON format"),
34            Format::Json => {
35                serde_json::to_string_pretty(data).context("failed to serialize to JSON format")
36            }
37            Format::Yaml => serde_yaml::to_string(data).context("failed to serialize to YAML"),
38        }
39    }
40}
41
42impl FromStr for Format {
43    type Err = Error;
44
45    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
46        match s.to_uppercase().as_str() {
47            "RON" => Ok(Format::Ron),
48            "JSON" => Ok(Format::Json),
49            "YAML" => Ok(Format::Yaml),
50            _ => Err(anyhow!("unsupported output format '{}'", s)),
51        }
52    }
53}