Skip to main content

rocketmq_admin_core/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
15//! CLI output formatters
16//!
17//! Provides multiple output formats: JSON, Table, YAML
18
19mod json_formatter;
20mod table_formatter;
21mod yaml_formatter;
22
23pub use json_formatter::JsonFormatter;
24use serde::Serialize;
25pub use table_formatter::TableFormatter;
26pub use yaml_formatter::YamlFormatter;
27
28/// Output format enum
29#[derive(Debug, Clone, Copy, Default)]
30pub enum OutputFormat {
31    #[default]
32    Table,
33    Json,
34    Yaml,
35}
36
37impl From<&str> for OutputFormat {
38    fn from(s: &str) -> Self {
39        match s.to_lowercase().as_str() {
40            "json" => Self::Json,
41            "yaml" | "yml" => Self::Yaml,
42            _ => Self::Table,
43        }
44    }
45}
46
47/// Formatter trait for output formatting
48pub trait Formatter {
49    /// Format data to string
50    fn format<T: Serialize>(&self, data: &T) -> String;
51}
52
53/// Formatter enum that holds concrete implementations
54pub enum FormatterType {
55    Json(JsonFormatter),
56    Table(TableFormatter),
57    Yaml(YamlFormatter),
58}
59
60impl FormatterType {
61    pub fn format<T: Serialize>(&self, data: &T) -> String {
62        match self {
63            Self::Json(f) => f.format(data),
64            Self::Table(f) => f.format(data),
65            Self::Yaml(f) => f.format(data),
66        }
67    }
68}
69
70impl From<OutputFormat> for FormatterType {
71    fn from(format: OutputFormat) -> Self {
72        match format {
73            OutputFormat::Json => Self::Json(JsonFormatter),
74            OutputFormat::Table => Self::Table(TableFormatter),
75            OutputFormat::Yaml => Self::Yaml(YamlFormatter),
76        }
77    }
78}
79
80/// Get formatter by format type
81pub fn get_formatter(format: OutputFormat) -> FormatterType {
82    FormatterType::from(format)
83}