jtool_core/
config.rs

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/// Top-level configuration
10#[derive(Debug, Clone, Serialize, Deserialize, Default)]
11pub struct Config {
12    /// Default server to use when none specified
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub default_server: Option<String>,
15
16    /// Named server configurations
17    #[serde(default)]
18    pub servers: HashMap<String, ServerConfig>,
19
20    /// User preferences
21    #[serde(default)]
22    pub preferences: Preferences,
23}
24
25/// Configuration for a single server
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct ServerConfig {
28    /// Server URL (e.g., "http://localhost:8888")
29    pub url: String,
30
31    /// Authentication token
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub token: Option<String>,
34
35    /// Human-readable description
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub description: Option<String>,
38}
39
40/// User preferences
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct Preferences {
43    /// Show timestamps in output
44    #[serde(default)]
45    pub show_timestamps: bool,
46
47    /// Show message types in output
48    #[serde(default)]
49    pub show_message_types: bool,
50
51    /// Use colors in output
52    #[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    /// Get the default configuration directory
72    pub fn config_dir() -> Result<PathBuf, CoreError> {
73        // First check JTOOL_CONFIG_DIR environment variable
74        if let Ok(dir) = std::env::var("JTOOL_CONFIG_DIR") {
75            return Ok(PathBuf::from(dir));
76        }
77
78        // Try to match Python's location: ~/.jtool/
79        if let Some(home) = directories::BaseDirs::new() {
80            let jtool_dir = home.home_dir().join(".jtool");
81            return Ok(jtool_dir);
82        }
83
84        // Fallback to platform-specific config dir
85        ProjectDirs::from("", "", "jtool")
86            .map(|dirs| dirs.config_dir().to_path_buf())
87            .ok_or(CoreError::NoHomeDirectory)
88    }
89
90    /// Get the default configuration file path
91    pub fn default_config_path() -> Result<PathBuf, CoreError> {
92        Ok(Self::config_dir()?.join("config.toml"))
93    }
94
95    /// Load configuration from the default location
96    pub fn load() -> Result<Self, CoreError> {
97        let path = Self::default_config_path()?;
98        Self::load_from_file(&path)
99    }
100
101    /// Load configuration from a specific file
102    pub fn load_from_file(path: &Path) -> Result<Self, CoreError> {
103        debug!("Loading config from: {:?}", path);
104
105        // If file doesn't exist, try to load from Python's JSON format
106        if !path.exists() {
107            // Check for Python's config.json in the same directory
108            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    /// Load configuration from Python's JSON format (for migration)
127    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        // Python format has "servers" as an array, not object
134        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                    // Generate a name from URL or use index
144                    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                        // Extract hostname from URL
154                        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                    // First server becomes default
174                    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    /// Save configuration to the default location
187    pub fn save(&self) -> Result<(), CoreError> {
188        let path = Self::default_config_path()?;
189        self.save_to_file(&path)
190    }
191
192    /// Save configuration to a specific file
193    pub fn save_to_file(&self, path: &Path) -> Result<(), CoreError> {
194        // Ensure parent directory exists
195        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    /// Add or update a server configuration
205    pub fn add_server(&mut self, name: String, server: ServerConfig) {
206        // If this is the first server, make it default
207        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    /// Get a server configuration by name
214    pub fn get_server(&self, name: &str) -> Option<&ServerConfig> {
215        self.servers.get(name)
216    }
217
218    /// Get the default server configuration
219    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    /// List all server names
226    pub fn list_servers(&self) -> Vec<&String> {
227        self.servers.keys().collect()
228    }
229}