wasmer_cli/utils/
render.rs1#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
2pub enum ItemFormat {
3 Json,
4 Yaml,
5 #[default]
6 Table,
7}
8
9impl ItemFormat {
10 pub fn render<T: CliRender>(self, item: &T) -> String {
11 CliRender::render_item(item, self)
12 }
13}
14
15impl std::str::FromStr for ItemFormat {
16 type Err = String;
17
18 fn from_str(s: &str) -> Result<Self, Self::Err> {
19 match s {
20 "json" => Ok(ItemFormat::Json),
21 "yaml" => Ok(ItemFormat::Yaml),
22 "table" => Ok(ItemFormat::Table),
23 other => Err(format!("Unknown output format: '{other}'")),
24 }
25 }
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
29pub enum ListFormat {
30 Json,
31 Yaml,
32 #[default]
33 Table,
34 ItemTable,
35}
36
37impl ListFormat {
38 pub fn render<T: CliRender>(self, items: &[T]) -> String {
39 CliRender::render_list(items, self)
40 }
41}
42
43impl std::str::FromStr for ListFormat {
44 type Err = String;
45
46 fn from_str(s: &str) -> Result<Self, Self::Err> {
47 match s {
48 "json" => Ok(ListFormat::Json),
49 "yaml" => Ok(ListFormat::Yaml),
50 "table" => Ok(ListFormat::Table),
51 "item-table" => Ok(ListFormat::ItemTable),
52 other => Err(format!("Unknown output format: '{other}'")),
53 }
54 }
55}
56
57pub trait CliRender: serde::Serialize + Sized {
58 fn render_item(&self, format: ItemFormat) -> String {
59 match format {
60 ItemFormat::Json => serde_json::to_string_pretty(self).unwrap(),
61 ItemFormat::Yaml => serde_yaml::to_string(self).unwrap(),
62 ItemFormat::Table => self.render_item_table(),
63 }
64 }
65
66 fn render_item_table(&self) -> String;
67
68 fn render_list(items: &[Self], format: ListFormat) -> String {
69 match format {
70 ListFormat::Json => serde_json::to_string_pretty(items).unwrap(),
71 ListFormat::Yaml => serde_yaml::to_string(items).unwrap(),
72 ListFormat::Table => Self::render_list_table(items),
73 ListFormat::ItemTable => {
74 let mut out = String::new();
75
76 for item in items {
77 out.push_str(&item.render_item_table());
78 out.push_str("\n\n");
79 }
80
81 out
82 }
83 }
84 }
85
86 fn render_list_table(items: &[Self]) -> String;
87}