Skip to main content

mockforge_plugin_registry/
config.rs

1//! Registry configuration management
2
3use crate::{RegistryConfig, Result};
4use std::path::PathBuf;
5use tokio::fs;
6
7/// Load registry configuration from file
8pub async fn load_config() -> Result<RegistryConfig> {
9    let config_path = get_config_path();
10
11    if !config_path.exists() {
12        return Ok(RegistryConfig::default());
13    }
14
15    let contents = fs::read_to_string(&config_path).await?;
16    let config: RegistryConfig =
17        toml::from_str(&contents).map_err(|e| crate::RegistryError::Storage(e.to_string()))?;
18
19    Ok(config)
20}
21
22/// Save registry configuration to file
23pub async fn save_config(config: &RegistryConfig) -> Result<()> {
24    let config_path = get_config_path();
25
26    if let Some(parent) = config_path.parent() {
27        fs::create_dir_all(parent).await?;
28    }
29
30    let contents =
31        toml::to_string_pretty(config).map_err(|e| crate::RegistryError::Storage(e.to_string()))?;
32
33    fs::write(&config_path, contents).await?;
34
35    Ok(())
36}
37
38/// Get configuration file path
39fn get_config_path() -> PathBuf {
40    let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("mockforge");
41
42    config_dir.join("registry.toml")
43}
44
45/// Set registry URL
46pub async fn set_registry_url(url: String) -> Result<()> {
47    let mut config = load_config().await?;
48    config.url = url;
49    save_config(&config).await
50}
51
52/// Set API token
53pub async fn set_token(token: String) -> Result<()> {
54    let mut config = load_config().await?;
55    config.token = Some(token);
56    save_config(&config).await
57}
58
59/// Clear API token
60pub async fn clear_token() -> Result<()> {
61    let mut config = load_config().await?;
62    config.token = None;
63    save_config(&config).await
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[tokio::test]
71    async fn test_default_config() {
72        let config = RegistryConfig::default();
73        assert_eq!(config.url, "https://registry.mockforge.dev");
74        assert_eq!(config.timeout, 30);
75    }
76}