use std::fmt;
use serde::Serialize;
use tabled::{Table, Tabled, settings::Style};
use crate::error::TwcError;
pub fn render_table<T: Tabled>(rows: &[T]) -> String {
Table::new(rows).with(Style::rounded()).to_string()
}
pub fn serialized<T: Serialize>(
format: OutputFormat,
value: &T
) -> Option<Result<String, TwcError>> {
match format {
OutputFormat::Json => {
Some(serde_json::to_string_pretty(value).map_err(|e| TwcError::Api(e.to_string())))
}
OutputFormat::Yaml => {
Some(serde_yaml_ng::to_string(value).map_err(|e| TwcError::Api(e.to_string())))
}
OutputFormat::Table | OutputFormat::Quiet => None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
#[default]
Table,
Json,
Yaml,
Quiet
}
impl OutputFormat {
pub fn parse(s: &str) -> Result<Self, String> {
match s.to_lowercase().as_str() {
"table" | "tbl" => Ok(Self::Table),
"json" | "js" => Ok(Self::Json),
"yaml" | "yml" => Ok(Self::Yaml),
"quiet" | "q" => Ok(Self::Quiet),
_ => Err(format!(
"unknown output format: {s} \
(expected table, json, yaml, or quiet)"
))
}
}
}
impl fmt::Display for OutputFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Table => write!(f, "table"),
Self::Json => write!(f, "json"),
Self::Yaml => write!(f, "yaml"),
Self::Quiet => write!(f, "quiet")
}
}
}
#[cfg(test)]
mod tests;