Skip to main content

pipedash_core/infrastructure/config/
migration.rs

1use std::path::Path;
2
3use super::loader::{
4    ConfigLoader,
5    Platform,
6};
7use super::schema::PipedashConfig;
8use crate::domain::{
9    DomainError,
10    DomainResult,
11};
12
13pub struct ConfigMigrator;
14
15impl ConfigMigrator {
16    pub async fn migrate_if_needed(data_dir: &Path) -> DomainResult<PipedashConfig> {
17        let config_path = data_dir.join("config.toml");
18
19        if config_path.exists() {
20            ConfigLoader::load(&config_path).map_err(|e| {
21                DomainError::InvalidConfig(format!("Failed to load config.toml: {}", e))
22            })
23        } else {
24            let platform = Platform::detect();
25            ConfigLoader::load_or_create(&config_path, platform)
26                .map_err(|e| DomainError::InvalidConfig(format!("Failed to create config: {}", e)))
27        }
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use tempfile::TempDir;
34
35    use super::*;
36
37    #[tokio::test]
38    async fn test_migrate_creates_config_if_missing() {
39        let temp_dir = TempDir::new().unwrap();
40
41        let config = ConfigMigrator::migrate_if_needed(temp_dir.path())
42            .await
43            .unwrap();
44
45        let toml_path = temp_dir.path().join("config.toml");
46        assert!(toml_path.exists());
47
48        assert!(config.general.metrics_enabled);
49    }
50
51    #[tokio::test]
52    async fn test_migrate_loads_existing_config() {
53        let temp_dir = TempDir::new().unwrap();
54        let config_path = temp_dir.path().join("config.toml");
55
56        let content = r#"
57[general]
58metrics_enabled = false
59default_refresh_interval = 120
60
61[storage]
62backend = "postgres"
63
64[storage.postgres]
65connection_string = "postgres://localhost/test"
66"#;
67        std::fs::write(&config_path, content).unwrap();
68
69        let config = ConfigMigrator::migrate_if_needed(temp_dir.path())
70            .await
71            .unwrap();
72
73        assert!(!config.general.metrics_enabled);
74        assert_eq!(config.general.default_refresh_interval, 120);
75        assert!(config.storage.backend.requires_postgres());
76    }
77}