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                "npm".to_string(),
90                "maven".to_string(),
91            ],
92            exclude_patterns: vec!["**/.git".to_string(), "**/vendor".to_string()],
93            min_age_days: 7,
94            max_depth: 10,
95            parallel_jobs: 4,
96        }
97    }
98}
99
100impl Default for ScannerConfig {
101    fn default() -> Self {
102        Self {
103            parallel_threads: 0,
104            cross_filesystems: false,
105            use_cache: true,
106            cache_ttl: 3600,
107        }
108    }
109}
110
111impl Default for TuiConfig {
112    fn default() -> Self {
113        Self {
114            color_scheme: "auto".to_string(),
115            show_hidden: false,
116            default_sort: "size".to_string(),
117            large_dir_threshold: 1024 * 1024 * 1024, // 1 GB
118        }
119    }
120}
121
122impl Config {
123    /// Load configuration from file, falling back to defaults
124    pub fn load(config_path: Option<&Path>) -> Result<Self> {
125        // If explicit path provided, it must exist
126        if let Some(path) = config_path {
127            return Self::load_from_file(path);
128        }
129
130        // Try XDG config locations
131        if let Some(path) = Self::find_config_file() {
132            return Self::load_from_file(&path);
133        }
134
135        // No config file found, use defaults
136        Ok(Self::default())
137    }
138
139    /// Find config file in standard locations
140    fn find_config_file() -> Option<PathBuf> {
141        // Try XDG_CONFIG_HOME first
142        if let Some(config_dir) = dirs::config_dir() {
143            let path = config_dir.join("rusty-sweeper").join("config.toml");
144            if path.exists() {
145                return Some(path);
146            }
147        }
148
149        // Try system-wide config
150        let system_path = PathBuf::from("/etc/rusty-sweeper/config.toml");
151        if system_path.exists() {
152            return Some(system_path);
153        }
154
155        None
156    }
157
158    /// Load config from a specific file
159    fn load_from_file(path: &Path) -> Result<Self> {
160        let contents = std::fs::read_to_string(path).map_err(|e| ConfigError::ReadError {
161            path: path.to_path_buf(),
162            source: e,
163        })?;
164
165        let config: Config = toml::from_str(&contents).map_err(|e| ConfigError::ParseError {
166            path: path.to_path_buf(),
167            source: e,
168        })?;
169
170        config.validate()?;
171        Ok(config)
172    }
173
174    /// Validate configuration values
175    pub fn validate(&self) -> Result<()> {
176        if self.monitor.warn_threshold > 100 {
177            return Err(ConfigError::Invalid("warn_threshold must be 0-100".to_string()).into());
178        }
179        if self.monitor.critical_threshold > 100 {
180            return Err(
181                ConfigError::Invalid("critical_threshold must be 0-100".to_string()).into(),
182            );
183        }
184        if self.monitor.warn_threshold >= self.monitor.critical_threshold {
185            return Err(ConfigError::Invalid(
186                "warn_threshold must be less than critical_threshold".to_string(),
187            )
188            .into());
189        }
190        Ok(())
191    }
192
193    /// Get the default config file path (for --config help text)
194    pub fn default_path() -> Option<PathBuf> {
195        dirs::config_dir().map(|d| d.join("rusty-sweeper").join("config.toml"))
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn default_config_is_valid() {
205        let config = Config::default();
206        assert_eq!(config.monitor.warn_threshold, 80);
207        assert_eq!(config.monitor.critical_threshold, 90);
208    }
209
210    #[test]
211    fn config_serializes_to_toml() {
212        let config = Config::default();
213        let toml_str = toml::to_string_pretty(&config).unwrap();
214        assert!(toml_str.contains("[monitor]"));
215    }
216
217    #[test]
218    fn default_thresholds_are_valid() {
219        let config = MonitorConfig::default();
220        assert!(config.warn_threshold < config.critical_threshold);
221        assert!(config.critical_threshold <= 100);
222    }
223
224    #[test]
225    fn default_cleaner_has_common_project_types() {
226        let config = CleanerConfig::default();
227        assert!(config.project_types.contains(&"cargo".to_string()));
228        assert!(config.project_types.contains(&"npm".to_string()));
229    }
230
231    #[test]
232    fn load_returns_defaults_when_no_file() {
233        let config = Config::load(None).unwrap();
234        assert_eq!(config.monitor.interval, 300);
235    }
236
237    #[test]
238    fn load_fails_on_invalid_explicit_path() {
239        let result = Config::load(Some(Path::new("/nonexistent/config.toml")));
240        assert!(result.is_err());
241    }
242
243    #[test]
244    fn validate_catches_invalid_thresholds() {
245        let mut config = Config::default();
246        config.monitor.warn_threshold = 95;
247        config.monitor.critical_threshold = 90;
248        assert!(config.validate().is_err());
249    }
250}