jtool-core 0.3.0

core library for jtool
Documentation
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};

/// Top-level configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    /// Default server to use when none specified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_server: Option<String>,

    /// Named server configurations
    #[serde(default)]
    pub servers: HashMap<String, ServerConfig>,

    /// User preferences
    #[serde(default)]
    pub preferences: Preferences,
}

/// Configuration for a single server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// Server URL (e.g., "http://localhost:8888")
    pub url: String,

    /// Authentication token
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,

    /// Human-readable description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// User preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Preferences {
    /// Show timestamps in output
    #[serde(default)]
    pub show_timestamps: bool,

    /// Show message types in output
    #[serde(default)]
    pub show_message_types: bool,

    /// Use colors in output
    #[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 {
    /// Get the default configuration directory
    pub fn config_dir() -> Result<PathBuf, CoreError> {
        // First check JTOOL_CONFIG_DIR environment variable
        if let Ok(dir) = std::env::var("JTOOL_CONFIG_DIR") {
            return Ok(PathBuf::from(dir));
        }

        // Try to match Python's location: ~/.jtool/
        if let Some(home) = directories::BaseDirs::new() {
            let jtool_dir = home.home_dir().join(".jtool");
            return Ok(jtool_dir);
        }

        // Fallback to platform-specific config dir
        ProjectDirs::from("", "", "jtool")
            .map(|dirs| dirs.config_dir().to_path_buf())
            .ok_or(CoreError::NoHomeDirectory)
    }

    /// Get the default configuration file path
    pub fn default_config_path() -> Result<PathBuf, CoreError> {
        Ok(Self::config_dir()?.join("config.toml"))
    }

    /// Load configuration from the default location
    pub fn load() -> Result<Self, CoreError> {
        let path = Self::default_config_path()?;
        Self::load_from_file(&path)
    }

    /// Load configuration from a specific file
    pub fn load_from_file(path: &Path) -> Result<Self, CoreError> {
        debug!("Loading config from: {:?}", path);

        // If file doesn't exist, try to load from Python's JSON format
        if !path.exists() {
            // Check for Python's config.json in the same directory
            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)
    }

    /// Load configuration from Python's JSON format (for migration)
    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();

        // Python format has "servers" as an array, not object
        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();

                    // Generate a name from URL or use index
                    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 {
                        // Extract hostname from URL
                        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}")),
                    };

                    // First server becomes default
                    if index == 0 && config.default_server.is_none() {
                        config.default_server = Some(name.clone());
                    }

                    config.servers.insert(name, server_config);
                }
            }
        }

        Ok(config)
    }

    /// Save configuration to the default location
    pub fn save(&self) -> Result<(), CoreError> {
        let path = Self::default_config_path()?;
        self.save_to_file(&path)
    }

    /// Save configuration to a specific file
    pub fn save_to_file(&self, path: &Path) -> Result<(), CoreError> {
        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        let contents = toml::to_string_pretty(self)?;
        fs::write(path, contents)?;
        Ok(())
    }

    /// Add or update a server configuration
    pub fn add_server(&mut self, name: String, server: ServerConfig) {
        // If this is the first server, make it default
        if self.servers.is_empty() && self.default_server.is_none() {
            self.default_server = Some(name.clone());
        }
        self.servers.insert(name, server);
    }

    /// Get a server configuration by name
    pub fn get_server(&self, name: &str) -> Option<&ServerConfig> {
        self.servers.get(name)
    }

    /// Get the default server configuration
    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)))
    }

    /// List all server names
    pub fn list_servers(&self) -> Vec<&String> {
        self.servers.keys().collect()
    }
}