Skip to main content

rocketmq_admin_cli/
formatters.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod json_formatter;
16mod table_formatter;
17mod yaml_formatter;
18
19pub use json_formatter::JsonFormatter;
20use serde::Serialize;
21pub use table_formatter::TableFormatter;
22pub use yaml_formatter::YamlFormatter;
23
24#[derive(Debug, Clone, Copy, Default)]
25pub enum OutputFormat {
26    #[default]
27    Table,
28    Json,
29    Yaml,
30}
31
32impl From<&str> for OutputFormat {
33    fn from(s: &str) -> Self {
34        match s.to_lowercase().as_str() {
35            "json" => Self::Json,
36            "yaml" | "yml" => Self::Yaml,
37            _ => Self::Table,
38        }
39    }
40}
41
42pub trait Formatter {
43    fn format<T: Serialize>(&self, data: &T) -> String;
44}
45
46pub enum FormatterType {
47    Json(JsonFormatter),
48    Table(TableFormatter),
49    Yaml(YamlFormatter),
50}
51
52impl FormatterType {
53    pub fn format<T: Serialize>(&self, data: &T) -> String {
54        match self {
55            Self::Json(f) => f.format(data),
56            Self::Table(f) => f.format(data),
57            Self::Yaml(f) => f.format(data),
58        }
59    }
60}
61
62impl From<OutputFormat> for FormatterType {
63    fn from(format: OutputFormat) -> Self {
64        match format {
65            OutputFormat::Json => Self::Json(JsonFormatter),
66            OutputFormat::Table => Self::Table(TableFormatter),
67            OutputFormat::Yaml => Self::Yaml(YamlFormatter),
68        }
69    }
70}
71
72pub fn get_formatter(format: OutputFormat) -> FormatterType {
73    FormatterType::from(format)
74}