iggy_cli/commands/binary_context/
get_contexts.rs1use async_trait::async_trait;
20use comfy_table::Table;
21use tracing::{Level, event};
22
23use crate::commands::cli_command::{CliCommand, PRINT_TARGET};
24use iggy_common::Client;
25
26use super::common::ContextManager;
27
28pub enum GetContextsOutput {
29 Table,
30 List,
31}
32
33pub struct GetContextsCmd {
34 output: GetContextsOutput,
35}
36
37impl GetContextsCmd {
38 pub fn new(output: GetContextsOutput) -> Self {
39 Self { output }
40 }
41
42 fn format_name(name: &str, active_context_key: &str) -> String {
43 if name.eq(active_context_key) {
44 format!("{name}*")
45 } else {
46 name.to_string()
47 }
48 }
49}
50
51impl Default for GetContextsCmd {
52 fn default() -> Self {
53 GetContextsCmd {
54 output: GetContextsOutput::Table,
55 }
56 }
57}
58
59#[async_trait]
60impl CliCommand for GetContextsCmd {
61 fn explain(&self) -> String {
62 let mode = match self.output {
63 GetContextsOutput::Table => "table",
64 GetContextsOutput::List => "list",
65 };
66 format!("list contexts in {mode} mode")
67 }
68
69 fn login_required(&self) -> bool {
70 false
71 }
72
73 fn connection_required(&self) -> bool {
74 false
75 }
76
77 async fn execute_cmd(&mut self, _client: &dyn Client) -> anyhow::Result<(), anyhow::Error> {
78 let mut context_mgr = ContextManager::default();
79 let contexts_map = context_mgr.get_contexts().await?;
80 let active_context_key = context_mgr.get_active_context_key().await?;
81
82 match self.output {
83 GetContextsOutput::Table => {
84 let mut table = Table::new();
85 table.set_header(vec!["Name"]);
86
87 contexts_map.iter().for_each(|(name, _)| {
88 let printed_name = GetContextsCmd::format_name(name, &active_context_key);
89 table.add_row(vec![printed_name]);
90 });
91
92 event!(target: PRINT_TARGET, Level::INFO, "{table}");
93 }
94 GetContextsOutput::List => contexts_map.iter().for_each(|(name, _)| {
95 let printed_name = GetContextsCmd::format_name(name, &active_context_key);
96 event!(target: PRINT_TARGET, Level::INFO, printed_name);
97 }),
98 }
99
100 return Ok(());
101 }
102}