yozefu_app/configuration/
internal_config.rs1use std::{collections::HashMap, fs, path::PathBuf};
4
5use chrono::Local;
6use lib::Error;
7
8use crate::configuration::{ConsumerConfig, SchemaRegistryConfig, Workspace};
9
10use super::{Configuration, yozefu_config::YozefuConfig};
11
12#[derive(Debug, Clone)]
13pub struct InternalConfig {
14 pub specific: YozefuConfig,
15 workspace: Workspace,
16 output_file: PathBuf,
17}
18
19impl Configuration for InternalConfig {
20 fn kafka_config_map(&self) -> HashMap<String, String> {
21 let mut config_map: HashMap<String, String> = self
22 .workspace
23 .config()
24 .default_kafka_config
25 .clone()
26 .into_iter()
27 .collect();
28 config_map.extend(self.specific.kafka_config_map());
29 config_map
30 }
31}
32
33impl InternalConfig {
34 pub fn new(specific: YozefuConfig, workspace: Workspace) -> Self {
35 let directory = match &specific.export_directory {
36 Some(e) => e,
37 None => &workspace.config().export_directory,
38 }
39 .clone();
40
41 let output_file = directory.join(format!(
42 "export-{}.json",
43 Local::now()
45 .to_rfc3339_opts(chrono::SecondsFormat::Secs, false)
46 .replace(':', "-"),
47 ));
48
49 let output_file = std::path::absolute(output_file)
50 .expect("Failed to get absolute path for the export file");
51
52 Self {
53 specific,
54 workspace,
55 output_file,
56 }
57 }
58
59 pub fn url_template_of(&self, cluster: &str) -> String {
61 match &self.specific.url_template() {
62 Some(url) => url.to_string(),
63 None => self.workspace.config().url_template_of(cluster),
64 }
65 }
66
67 pub fn cluster(&self) -> &str {
68 self.specific.cluster()
69 }
70
71 pub fn consumer_config(&self, cluster: &str) -> ConsumerConfig {
73 self.workspace.config().consumer_config_of(cluster)
74 }
75
76 pub fn schema_registry_config_of(&self, cluster: &str) -> Option<SchemaRegistryConfig> {
78 match &self.specific.schema_registry() {
79 Some(schema_registry) => Some(schema_registry.clone()),
80 None => self.workspace.config().schema_registry_config_of(cluster),
81 }
82 }
83
84 pub fn output_file(&self) -> &PathBuf {
86 &self.output_file
87 }
88
89 pub fn workspace(&self) -> &Workspace {
90 &self.workspace
91 }
92
93 pub fn history(&self) -> &[String] {
94 &self.workspace.config().history
95 }
96
97 pub fn push_history(&mut self, prompt: &str) {
98 self.workspace.config.history.push(prompt.to_string());
99 self.workspace.config.history.dedup();
100 }
101
102 pub fn initial_query(&self) -> &str {
103 &self.workspace.config.initial_query
104 }
105
106 pub fn theme(&self) -> &str {
107 &self.workspace.config.theme
108 }
109
110 pub fn save_config(&mut self) -> Result<(), Error> {
111 let history = &self.workspace.config.history;
112 if history.len() > 1000 {
113 self.workspace.config.history = history.iter().skip(500).cloned().collect();
114 }
115 fs::write(
116 &self.workspace.config.path,
117 serde_json::to_string_pretty(&self.workspace.config)?,
118 )?;
119 Ok(())
120 }
121}