Skip to main content

rocketmq_admin_cli/formatters/
table_formatter.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
15use serde::Serialize;
16use tabled::Table;
17use tabled::Tabled;
18
19use tabled::settings::Style;
20
21use super::Formatter;
22
23pub struct TableFormatter;
24
25impl Formatter for TableFormatter {
26    fn format<T: Serialize>(&self, data: &T) -> String {
27        serde_json::to_string_pretty(data).unwrap_or_else(|e| format!("Error: {}", e))
28    }
29}
30
31impl TableFormatter {
32    pub fn format_tabled<T: Tabled>(data: &[T]) -> String {
33        let mut table = Table::new(data);
34        table.with(Style::extended());
35        table.to_string()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[derive(Tabled)]
44    struct TestData {
45        name: String,
46        value: i32,
47    }
48
49    #[test]
50    fn formats_tabled_rows() {
51        let data = vec![
52            TestData {
53                name: "test1".to_string(),
54                value: 1,
55            },
56            TestData {
57                name: "test2".to_string(),
58                value: 2,
59            },
60        ];
61
62        let output = TableFormatter::format_tabled(&data);
63        assert!(output.contains("name"));
64        assert!(output.contains("test1"));
65    }
66}