use crate::error::CoreError;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, warn};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
#[serde(skip_serializing_if = "Option::is_none")]
pub default_server: Option<String>,
#[serde(default)]
pub servers: HashMap<String, ServerConfig>,
#[serde(default)]
pub preferences: Preferences,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Preferences {
#[serde(default)]
pub show_timestamps: bool,
#[serde(default)]
pub show_message_types: bool,
#[serde(default = "default_true")]
pub color: bool,
}
impl Default for Preferences {
fn default() -> Self {
Self {
show_timestamps: false,
show_message_types: false,
color: true,
}
}
}
fn default_true() -> bool {
true
}
impl Config {
pub fn config_dir() -> Result<PathBuf, CoreError> {
if let Ok(dir) = std::env::var("JTOOL_CONFIG_DIR") {
return Ok(PathBuf::from(dir));
}
if let Some(home) = directories::BaseDirs::new() {
let jtool_dir = home.home_dir().join(".jtool");
return Ok(jtool_dir);
}
ProjectDirs::from("", "", "jtool")
.map(|dirs| dirs.config_dir().to_path_buf())
.ok_or(CoreError::NoHomeDirectory)
}
pub fn default_config_path() -> Result<PathBuf, CoreError> {
Ok(Self::config_dir()?.join("config.toml"))
}
pub fn load() -> Result<Self, CoreError> {
let path = Self::default_config_path()?;
Self::load_from_file(&path)
}
pub fn load_from_file(path: &Path) -> Result<Self, CoreError> {
debug!("Loading config from: {:?}", path);
if !path.exists() {
let json_path = path.with_file_name("config.json");
if json_path.exists() {
debug!(
"Found Python config at {:?}, attempting migration",
json_path
);
return Self::load_from_python_json(&json_path);
}
warn!("Config file not found at {:?}, using defaults", path);
return Ok(Self::default());
}
let contents = fs::read_to_string(path)?;
let config = toml::from_str(&contents)?;
Ok(config)
}
pub fn load_from_python_json(path: &Path) -> Result<Self, CoreError> {
let contents = fs::read_to_string(path)?;
let json: serde_json::Value = serde_json::from_str(&contents)?;
let mut config = Config::default();
if let Some(servers_array) = json.get("servers").and_then(|s| s.as_array()) {
for (index, server_json) in servers_array.iter().enumerate() {
if let Some(server_obj) = server_json.as_object() {
let url = server_obj
.get("url")
.and_then(|u| u.as_str())
.unwrap_or("http://localhost:8888")
.to_string();
let name = if url.contains("localhost") || url.contains("127.0.0.1") {
format!(
"local_{}",
server_obj
.get("port")
.and_then(|p| p.as_u64())
.unwrap_or(8888)
)
} else {
url.split("//")
.nth(1)
.and_then(|s| s.split(':').next())
.unwrap_or("server")
.to_string()
};
let server_config = ServerConfig {
url,
token: server_obj
.get("token")
.and_then(|t| t.as_str())
.map(|s| s.to_string()),
description: server_obj
.get("notebook_dir")
.and_then(|d| d.as_str())
.map(|s| format!("Notebook dir: {s}")),
};
if index == 0 && config.default_server.is_none() {
config.default_server = Some(name.clone());
}
config.servers.insert(name, server_config);
}
}
}
Ok(config)
}
pub fn save(&self) -> Result<(), CoreError> {
let path = Self::default_config_path()?;
self.save_to_file(&path)
}
pub fn save_to_file(&self, path: &Path) -> Result<(), CoreError> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let contents = toml::to_string_pretty(self)?;
fs::write(path, contents)?;
Ok(())
}
pub fn add_server(&mut self, name: String, server: ServerConfig) {
if self.servers.is_empty() && self.default_server.is_none() {
self.default_server = Some(name.clone());
}
self.servers.insert(name, server);
}
pub fn get_server(&self, name: &str) -> Option<&ServerConfig> {
self.servers.get(name)
}
pub fn get_default_server(&self) -> Option<(&String, &ServerConfig)> {
self.default_server
.as_ref()
.and_then(|name| self.servers.get(name).map(|config| (name, config)))
}
pub fn list_servers(&self) -> Vec<&String> {
self.servers.keys().collect()
}
}