1use crate::error::CoreError;
2use directories::ProjectDirs;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::fs;
6use std::path::{Path, PathBuf};
7use tracing::{debug, warn};
8
9#[derive(Debug, Clone, Serialize, Deserialize, Default)]
11pub struct Config {
12 #[serde(skip_serializing_if = "Option::is_none")]
14 pub default_server: Option<String>,
15
16 #[serde(default)]
18 pub servers: HashMap<String, ServerConfig>,
19
20 #[serde(default)]
22 pub preferences: Preferences,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct ServerConfig {
28 pub url: String,
30
31 #[serde(skip_serializing_if = "Option::is_none")]
33 pub token: Option<String>,
34
35 #[serde(skip_serializing_if = "Option::is_none")]
37 pub description: Option<String>,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct Preferences {
43 #[serde(default)]
45 pub show_timestamps: bool,
46
47 #[serde(default)]
49 pub show_message_types: bool,
50
51 #[serde(default = "default_true")]
53 pub color: bool,
54}
55
56impl Default for Preferences {
57 fn default() -> Self {
58 Self {
59 show_timestamps: false,
60 show_message_types: false,
61 color: true,
62 }
63 }
64}
65
66fn default_true() -> bool {
67 true
68}
69
70impl Config {
71 pub fn config_dir() -> Result<PathBuf, CoreError> {
73 if let Ok(dir) = std::env::var("JTOOL_CONFIG_DIR") {
75 return Ok(PathBuf::from(dir));
76 }
77
78 if let Some(home) = directories::BaseDirs::new() {
80 let jtool_dir = home.home_dir().join(".jtool");
81 return Ok(jtool_dir);
82 }
83
84 ProjectDirs::from("", "", "jtool")
86 .map(|dirs| dirs.config_dir().to_path_buf())
87 .ok_or(CoreError::NoHomeDirectory)
88 }
89
90 pub fn default_config_path() -> Result<PathBuf, CoreError> {
92 Ok(Self::config_dir()?.join("config.toml"))
93 }
94
95 pub fn load() -> Result<Self, CoreError> {
97 let path = Self::default_config_path()?;
98 Self::load_from_file(&path)
99 }
100
101 pub fn load_from_file(path: &Path) -> Result<Self, CoreError> {
103 debug!("Loading config from: {:?}", path);
104
105 if !path.exists() {
107 let json_path = path.with_file_name("config.json");
109 if json_path.exists() {
110 debug!(
111 "Found Python config at {:?}, attempting migration",
112 json_path
113 );
114 return Self::load_from_python_json(&json_path);
115 }
116
117 warn!("Config file not found at {:?}, using defaults", path);
118 return Ok(Self::default());
119 }
120
121 let contents = fs::read_to_string(path)?;
122 let config = toml::from_str(&contents)?;
123 Ok(config)
124 }
125
126 pub fn load_from_python_json(path: &Path) -> Result<Self, CoreError> {
128 let contents = fs::read_to_string(path)?;
129 let json: serde_json::Value = serde_json::from_str(&contents)?;
130
131 let mut config = Config::default();
132
133 if let Some(servers_array) = json.get("servers").and_then(|s| s.as_array()) {
135 for (index, server_json) in servers_array.iter().enumerate() {
136 if let Some(server_obj) = server_json.as_object() {
137 let url = server_obj
138 .get("url")
139 .and_then(|u| u.as_str())
140 .unwrap_or("http://localhost:8888")
141 .to_string();
142
143 let name = if url.contains("localhost") || url.contains("127.0.0.1") {
145 format!(
146 "local_{}",
147 server_obj
148 .get("port")
149 .and_then(|p| p.as_u64())
150 .unwrap_or(8888)
151 )
152 } else {
153 url.split("//")
155 .nth(1)
156 .and_then(|s| s.split(':').next())
157 .unwrap_or("server")
158 .to_string()
159 };
160
161 let server_config = ServerConfig {
162 url,
163 token: server_obj
164 .get("token")
165 .and_then(|t| t.as_str())
166 .map(|s| s.to_string()),
167 description: server_obj
168 .get("notebook_dir")
169 .and_then(|d| d.as_str())
170 .map(|s| format!("Notebook dir: {s}")),
171 };
172
173 if index == 0 && config.default_server.is_none() {
175 config.default_server = Some(name.clone());
176 }
177
178 config.servers.insert(name, server_config);
179 }
180 }
181 }
182
183 Ok(config)
184 }
185
186 pub fn save(&self) -> Result<(), CoreError> {
188 let path = Self::default_config_path()?;
189 self.save_to_file(&path)
190 }
191
192 pub fn save_to_file(&self, path: &Path) -> Result<(), CoreError> {
194 if let Some(parent) = path.parent() {
196 fs::create_dir_all(parent)?;
197 }
198
199 let contents = toml::to_string_pretty(self)?;
200 fs::write(path, contents)?;
201 Ok(())
202 }
203
204 pub fn add_server(&mut self, name: String, server: ServerConfig) {
206 if self.servers.is_empty() && self.default_server.is_none() {
208 self.default_server = Some(name.clone());
209 }
210 self.servers.insert(name, server);
211 }
212
213 pub fn get_server(&self, name: &str) -> Option<&ServerConfig> {
215 self.servers.get(name)
216 }
217
218 pub fn get_default_server(&self) -> Option<(&String, &ServerConfig)> {
220 self.default_server
221 .as_ref()
222 .and_then(|name| self.servers.get(name).map(|config| (name, config)))
223 }
224
225 pub fn list_servers(&self) -> Vec<&String> {
227 self.servers.keys().collect()
228 }
229}