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 monitor: MonitorConfig,
10    pub cleaner: CleanerConfig,
11    pub scanner: ScannerConfig,
12    pub tui: TuiConfig,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16#[serde(default)]
17pub struct MonitorConfig {
18    /// Check interval in seconds
19    pub interval: u64,
20    /// Warning threshold percentage (0-100)
21    pub warn_threshold: u8,
22    /// Critical threshold percentage (0-100)
23    pub critical_threshold: u8,
24    /// Mount points to monitor (empty = all)
25    pub mount_points: Vec<PathBuf>,
26    /// Notification backend: auto, dbus, notify-send, stderr
27    pub notification_backend: String,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(default)]
32pub struct CleanerConfig {
33    /// Project types to clean
34    pub project_types: Vec<String>,
35    /// Glob patterns to exclude
36    pub exclude_patterns: Vec<String>,
37    /// Minimum age in days before cleanup
38    pub min_age_days: u32,
39    /// Maximum scan depth
40    pub max_depth: usize,
41    /// Parallel clean jobs
42    pub parallel_jobs: usize,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(default)]
47pub struct ScannerConfig {
48    /// Number of parallel threads (0 = auto)
49    pub parallel_threads: usize,
50    /// Cross filesystem boundaries
51    pub cross_filesystems: bool,
52    /// Use result cache
53    pub use_cache: bool,
54    /// Cache TTL in seconds
55    pub cache_ttl: u64,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59#[serde(default)]
60pub struct TuiConfig {
61    /// Color scheme: auto, dark, light, none
62    pub color_scheme: String,
63    /// Show hidden files by default
64    pub show_hidden: bool,
65    /// Default sort order: size, name, mtime
66    pub default_sort: String,
67    /// Size threshold for large directory warning (bytes)
68    pub large_dir_threshold: u64,
69}
70
71impl Default for MonitorConfig {
72    fn default() -> Self {
73        Self {
74            interval: 300,
75            warn_threshold: 80,
76            critical_threshold: 90,
77            mount_points: vec![],
78            notification_backend: "auto".to_string(),
79        }
80    }
81}
82
83impl Default for CleanerConfig {
84    fn default() -> Self {
85        Self {
86            project_types: vec![
87                "cargo".to_string(),
88                "gradle".to_string(),
89                "maven".to_string(),
90                "npm".to_string(),
91                "go".to_string(),
92                "cmake".to_string(),
93                "python".to_string(),
94                "bazel".to_string(),
95                "dotnet".to_string(),
96            ],
97            exclude_patterns: vec!["**/.git".to_string(), "**/vendor".to_string()],
98            min_age_days: 0,
99            max_depth: 10,
100            parallel_jobs: 4,
101        }
102    }
103}
104
105impl Default for ScannerConfig {
106    fn default() -> Self {
107        Self {
108            parallel_threads: 0,
109            cross_filesystems: false,
110            use_cache: true,
111            cache_ttl: 3600,
112        }
113    }
114}
115
116impl Default for TuiConfig {
117    fn default() -> Self {
118        Self {
119            color_scheme: "auto".to_string(),
120            show_hidden: true,
121            default_sort: "size".to_string(),
122            large_dir_threshold: 1024 * 1024 * 1024, // 1 GB
123        }
124    }
125}
126
127impl Config {
128    /// Load configuration from file, falling back to defaults
129    pub fn load(config_path: Option<&Path>) -> Result<Self> {
130        // If explicit path provided, it must exist
131        if let Some(path) = config_path {
132            return Self::load_from_file(path);
133        }
134
135        // Try XDG config locations
136        if let Some(path) = Self::find_config_file() {
137            return Self::load_from_file(&path);
138        }
139
140        // No config file found, use defaults
141        Ok(Self::default())
142    }
143
144    /// Find config file in standard locations
145    fn find_config_file() -> Option<PathBuf> {
146        // Try XDG_CONFIG_HOME first
147        if let Some(config_dir) = dirs::config_dir() {
148            let path = config_dir.join("rusty-sweeper").join("config.toml");
149            if path.exists() {
150                return Some(path);
151            }
152        }
153
154        // Try system-wide config
155        let system_path = PathBuf::from("/etc/rusty-sweeper/config.toml");
156        if system_path.exists() {
157            return Some(system_path);
158        }
159
160        None
161    }
162
163    /// Load config from a specific file
164    fn load_from_file(path: &Path) -> Result<Self> {
165        let contents = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadError {
166            path: path.to_path_buf(),
167            source: e,
168        })?;
169
170        let config: Config = toml::from_str(&contents).map_err(|e| ConfigError::ParseError {
171            path: path.to_path_buf(),
172            source: e,
173        })?;
174
175        config.validate()?;
176        Ok(config)
177    }
178
179    /// Validate configuration values
180    pub fn validate(&self) -> Result<()> {
181        if self.monitor.warn_threshold > 100 {
182            return Err(ConfigError::Invalid("warn_threshold must be 0-100".to_string()).into());
183        }
184        if self.monitor.critical_threshold > 100 {
185            return Err(
186                ConfigError::Invalid("critical_threshold must be 0-100".to_string()).into(),
187            );
188        }
189        if self.monitor.warn_threshold >= self.monitor.critical_threshold {
190            return Err(ConfigError::Invalid(
191                "warn_threshold must be less than critical_threshold".to_string(),
192            )
193            .into());
194        }
195        Ok(())
196    }
197
198    /// Get the default config file path (for --config help text)
199    pub fn default_path() -> Option<PathBuf> {
200        dirs::config_dir().map(|d| d.join("rusty-sweeper").join("config.toml"))
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn default_config_is_valid() {
210        let config = Config::default();
211        assert_eq!(config.monitor.warn_threshold, 80);
212        assert_eq!(config.monitor.critical_threshold, 90);
213    }
214
215    #[test]
216    fn config_serializes_to_toml() {
217        let config = Config::default();
218        let toml_str = toml::to_string_pretty(&config).unwrap();
219        assert!(toml_str.contains("[monitor]"));
220    }
221
222    #[test]
223    fn default_thresholds_are_valid() {
224        let config = MonitorConfig::default();
225        assert!(config.warn_threshold < config.critical_threshold);
226        assert!(config.critical_threshold <= 100);
227    }
228
229    #[test]
230    fn default_cleaner_has_common_project_types() {
231        let config = CleanerConfig::default();
232        assert!(config.project_types.contains(&"cargo".to_string()));
233        assert!(config.project_types.contains(&"npm".to_string()));
234    }
235
236    #[test]
237    fn load_returns_defaults_when_no_file() {
238        let config = Config::load(None).unwrap();
239        assert_eq!(config.monitor.interval, 300);
240    }
241
242    #[test]
243    fn load_fails_on_invalid_explicit_path() {
244        let result = Config::load(Some(Path::new("/nonexistent/config.toml")));
245        assert!(result.is_err());
246    }
247
248    #[test]
249    fn validate_catches_invalid_thresholds() {
250        let mut config = Config::default();
251        config.monitor.warn_threshold = 95;
252        config.monitor.critical_threshold = 90;
253        assert!(config.validate().is_err());
254    }
255}