1use crate::error::Result;
2use colored::Colorize;
3use comfy_table::{presets::UTF8_FULL, Cell, CellAlignment, ContentArrangement, Table};
4use serde::Serialize;
5
6#[derive(Debug, Clone, Copy)]
7pub enum OutputFormat {
8 Table,
9 Json,
10 Yaml,
11}
12
13impl OutputFormat {
14 pub fn from_str(s: &str) -> Self {
15 match s.to_lowercase().as_str() {
16 "json" => Self::Json,
17 "yaml" => Self::Yaml,
18 _ => Self::Table,
19 }
20 }
21}
22
23pub fn print_success(message: &str) {
24 println!("{} {}", "✓".green().bold(), message);
25}
26
27pub fn print_error(message: &str) {
28 eprintln!("{} {}", "✗".red().bold(), message);
29}
30
31pub fn print_warning(message: &str) {
32 println!("{} {}", "⚠".yellow().bold(), message);
33}
34
35pub fn print_info(message: &str) {
36 println!("{} {}", "ℹ".blue().bold(), message);
37}
38
39pub fn format_output<T: Serialize>(data: &T, format: OutputFormat) -> Result<String> {
40 match format {
41 OutputFormat::Json => {
42 let json = serde_json::to_string_pretty(data)?;
43 Ok(json)
44 }
45 OutputFormat::Yaml => {
46 let yaml = serde_yaml::to_string(data)?;
47 Ok(yaml)
48 }
49 OutputFormat::Table => {
50 let json = serde_json::to_string_pretty(data)?;
53 Ok(json)
54 }
55 }
56}
57
58pub fn create_table_with_headers(headers: Vec<&str>) -> Table {
59 let mut table = Table::new();
60 table
61 .load_preset(UTF8_FULL)
62 .set_content_arrangement(ContentArrangement::Dynamic);
63
64 let header_cells: Vec<Cell> = headers
65 .into_iter()
66 .map(|h| Cell::new(h).set_alignment(CellAlignment::Center))
67 .collect();
68 table.set_header(header_cells);
69
70 table
71}
72
73pub fn create_table() -> Table {
74 let mut table = Table::new();
75 table
76 .load_preset(UTF8_FULL)
77 .set_content_arrangement(ContentArrangement::Dynamic);
78 table
79}
80
81pub fn print_table(table: Table) {
82 println!("{}", table);
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88 use serde::Serialize;
89
90 #[derive(Serialize)]
91 struct TestData {
92 name: String,
93 value: i32,
94 }
95
96 #[test]
97 fn test_format_json() {
98 let data = TestData {
99 name: "test".to_string(),
100 value: 42,
101 };
102 let result = format_output(&data, OutputFormat::Json);
103 assert!(result.is_ok());
104 assert!(result.unwrap().contains("test"));
105 }
106
107 #[test]
108 fn test_format_yaml() {
109 let data = TestData {
110 name: "test".to_string(),
111 value: 42,
112 };
113 let result = format_output(&data, OutputFormat::Yaml);
114 assert!(result.is_ok());
115 assert!(result.unwrap().contains("test"));
116 }
117}