Skip to main content

rusty_sweeper/
config.rs

1use crate::error::{ConfigError, Result};
2use serde::{Deserialize, Serialize};
3use std::path::{Path, PathBuf};
4
5/// Root configuration structure
6#[derive(Debug, Clone, Serialize, Deserialize, Default)]
7#[serde(default)]
8pub struct Config {
9    pub cleaner: CleanerConfig,
10    pub scanner: ScannerConfig,
11    pub tui: TuiConfig,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(default)]
16pub struct CleanerConfig {
17    /// Project types to clean
18    pub project_types: Vec<String>,
19    /// Glob patterns to exclude
20    pub exclude_patterns: Vec<String>,
21    /// Minimum age in days before cleanup
22    pub min_age_days: u32,
23    /// Maximum scan depth
24    pub max_depth: usize,
25    /// Parallel clean jobs
26    pub parallel_jobs: usize,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(default)]
31pub struct ScannerConfig {
32    /// Number of parallel threads (0 = auto)
33    pub parallel_threads: usize,
34    /// Cross filesystem boundaries
35    pub cross_filesystems: bool,
36    /// Use result cache
37    pub use_cache: bool,
38    /// Cache TTL in seconds
39    pub cache_ttl: u64,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43#[serde(default)]
44pub struct TuiConfig {
45    /// Color scheme: auto, dark, light, none
46    pub color_scheme: String,
47    /// Show hidden files by default
48    pub show_hidden: bool,
49    /// Default sort order: size, name, mtime
50    pub default_sort: String,
51    /// Size threshold for large directory warning (bytes)
52    pub large_dir_threshold: u64,
53}
54
55impl Default for CleanerConfig {
56    fn default() -> Self {
57        Self {
58            project_types: vec![
59                "cargo".to_string(),
60                "gradle".to_string(),
61                "maven".to_string(),
62                "npm".to_string(),
63                "go".to_string(),
64                "cmake".to_string(),
65                "python".to_string(),
66                "bazel".to_string(),
67                "dotnet".to_string(),
68            ],
69            exclude_patterns: vec!["**/.git".to_string(), "**/vendor".to_string()],
70            min_age_days: 0,
71            max_depth: 10,
72            parallel_jobs: 4,
73        }
74    }
75}
76
77impl Default for ScannerConfig {
78    fn default() -> Self {
79        Self {
80            parallel_threads: 0,
81            cross_filesystems: false,
82            use_cache: true,
83            cache_ttl: 3600,
84        }
85    }
86}
87
88impl Default for TuiConfig {
89    fn default() -> Self {
90        Self {
91            color_scheme: "auto".to_string(),
92            show_hidden: true,
93            default_sort: "size".to_string(),
94            large_dir_threshold: 1024 * 1024 * 1024, // 1 GB
95        }
96    }
97}
98
99impl Config {
100    /// Load configuration from file, falling back to defaults
101    pub fn load(config_path: Option<&Path>) -> Result<Self> {
102        // If explicit path provided, it must exist
103        if let Some(path) = config_path {
104            return Self::load_from_file(path);
105        }
106
107        // Try XDG config locations
108        if let Some(path) = Self::find_config_file() {
109            return Self::load_from_file(&path);
110        }
111
112        // No config file found, use defaults
113        Ok(Self::default())
114    }
115
116    /// Find config file in standard locations
117    fn find_config_file() -> Option<PathBuf> {
118        // Try XDG_CONFIG_HOME first
119        if let Some(config_dir) = dirs::config_dir() {
120            let path = config_dir.join("rusty-sweeper").join("config.toml");
121            if path.exists() {
122                return Some(path);
123            }
124        }
125
126        // Try system-wide config
127        let system_path = PathBuf::from("/etc/rusty-sweeper/config.toml");
128        if system_path.exists() {
129            return Some(system_path);
130        }
131
132        None
133    }
134
135    /// Load config from a specific file
136    fn load_from_file(path: &Path) -> Result<Self> {
137        let contents = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadError {
138            path: path.to_path_buf(),
139            source: e,
140        })?;
141
142        let config: Config = toml::from_str(&contents).map_err(|e| ConfigError::ParseError {
143            path: path.to_path_buf(),
144            source: e,
145        })?;
146
147        Ok(config)
148    }
149
150    /// Get the default config file path (for --config help text)
151    pub fn default_path() -> Option<PathBuf> {
152        dirs::config_dir().map(|d| d.join("rusty-sweeper").join("config.toml"))
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn config_serializes_to_toml() {
162        let config = Config::default();
163        let toml_str = toml::to_string_pretty(&config).unwrap();
164        assert!(toml_str.contains("[scanner]"));
165    }
166
167    #[test]
168    fn default_cleaner_has_common_project_types() {
169        let config = CleanerConfig::default();
170        assert!(config.project_types.contains(&"cargo".to_string()));
171        assert!(config.project_types.contains(&"npm".to_string()));
172    }
173
174    #[test]
175    fn load_returns_defaults_when_no_file() {
176        let config = Config::load(None).unwrap();
177        assert_eq!(config.scanner.cache_ttl, 3600);
178    }
179
180    #[test]
181    fn load_fails_on_invalid_explicit_path() {
182        let result = Config::load(Some(Path::new("/nonexistent/config.toml")));
183        assert!(result.is_err());
184    }
185}