Skip to main content

sbom_tools/config/
file.rs

1//! Configuration file loading and discovery.
2//!
3//! Supports loading configuration from YAML files with automatic discovery.
4
5use super::types::AppConfig;
6use std::path::{Path, PathBuf};
7
8// ============================================================================
9// Configuration File Discovery
10// ============================================================================
11
12/// Standard config file names to search for.
13const CONFIG_FILE_NAMES: &[&str] = &[
14    ".sbom-tools.yaml",
15    ".sbom-tools.yml",
16    "sbom-tools.yaml",
17    "sbom-tools.yml",
18    ".sbom-toolsrc",
19];
20
21/// Discover a config file by searching standard locations.
22///
23/// Search order:
24/// 1. Explicit path if provided
25/// 2. Current directory
26/// 3. Git repository root (if in a repo)
27/// 4. User config directory (~/.config/sbom-tools/)
28/// 5. Home directory
29#[must_use] 
30pub fn discover_config_file(explicit_path: Option<&Path>) -> Option<PathBuf> {
31    // 1. Use explicit path if provided
32    if let Some(path) = explicit_path {
33        if path.exists() {
34            return Some(path.to_path_buf());
35        }
36    }
37
38    // 2. Search current directory
39    if let Ok(cwd) = std::env::current_dir() {
40        if let Some(path) = find_config_in_dir(&cwd) {
41            return Some(path);
42        }
43    }
44
45    // 3. Search git root (if in a repo)
46    if let Some(git_root) = find_git_root() {
47        if let Some(path) = find_config_in_dir(&git_root) {
48            return Some(path);
49        }
50    }
51
52    // 4. Search user config directory
53    if let Some(config_dir) = dirs::config_dir() {
54        let sbom_config_dir = config_dir.join("sbom-tools");
55        if let Some(path) = find_config_in_dir(&sbom_config_dir) {
56            return Some(path);
57        }
58    }
59
60    // 5. Search home directory
61    if let Some(home) = dirs::home_dir() {
62        if let Some(path) = find_config_in_dir(&home) {
63            return Some(path);
64        }
65    }
66
67    None
68}
69
70/// Find a config file in a specific directory.
71fn find_config_in_dir(dir: &Path) -> Option<PathBuf> {
72    for name in CONFIG_FILE_NAMES {
73        let path = dir.join(name);
74        if path.exists() {
75            return Some(path);
76        }
77    }
78    None
79}
80
81/// Find the git repository root by walking up the directory tree.
82fn find_git_root() -> Option<PathBuf> {
83    let cwd = std::env::current_dir().ok()?;
84    let mut current = cwd.as_path();
85
86    loop {
87        let git_dir = current.join(".git");
88        if git_dir.exists() {
89            return Some(current.to_path_buf());
90        }
91
92        current = current.parent()?;
93    }
94}
95
96// ============================================================================
97// Configuration File Loading
98// ============================================================================
99
100/// Error type for config file operations.
101#[derive(Debug)]
102pub enum ConfigFileError {
103    /// File not found
104    NotFound(PathBuf),
105    /// IO error reading file
106    Io(std::io::Error),
107    /// YAML parsing error
108    Parse(serde_yaml_ng::Error),
109}
110
111impl std::fmt::Display for ConfigFileError {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        match self {
114            Self::NotFound(path) => {
115                write!(f, "Config file not found: {}", path.display())
116            }
117            Self::Io(e) => write!(f, "Failed to read config file: {e}"),
118            Self::Parse(e) => write!(f, "Failed to parse config file: {e}"),
119        }
120    }
121}
122
123impl std::error::Error for ConfigFileError {
124    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
125        match self {
126            Self::NotFound(_) => None,
127            Self::Io(e) => Some(e),
128            Self::Parse(e) => Some(e),
129        }
130    }
131}
132
133impl From<std::io::Error> for ConfigFileError {
134    fn from(err: std::io::Error) -> Self {
135        Self::Io(err)
136    }
137}
138
139impl From<serde_yaml_ng::Error> for ConfigFileError {
140    fn from(err: serde_yaml_ng::Error) -> Self {
141        Self::Parse(err)
142    }
143}
144
145/// Load an `AppConfig` from a YAML file.
146pub fn load_config_file(path: &Path) -> Result<AppConfig, ConfigFileError> {
147    if !path.exists() {
148        return Err(ConfigFileError::NotFound(path.to_path_buf()));
149    }
150
151    let content = std::fs::read_to_string(path)?;
152    let config: AppConfig = serde_yaml_ng::from_str(&content)?;
153    Ok(config)
154}
155
156/// Load config from discovered file, or return default.
157#[must_use] 
158pub fn load_or_default(explicit_path: Option<&Path>) -> (AppConfig, Option<PathBuf>) {
159    discover_config_file(explicit_path).map_or_else(
160        || (AppConfig::default(), None),
161        |path| match load_config_file(&path) {
162            Ok(config) => (config, Some(path)),
163            Err(e) => {
164                tracing::warn!("Failed to load config from {}: {}", path.display(), e);
165                (AppConfig::default(), None)
166            }
167        },
168    )
169}
170
171// ============================================================================
172// Configuration Merging
173// ============================================================================
174
175impl AppConfig {
176    /// Merge another config into this one, with `other` taking precedence.
177    ///
178    /// This is useful for layering CLI args over file config.
179    pub fn merge(&mut self, other: &Self) {
180        // Matching config
181        if other.matching.fuzzy_preset != "balanced" {
182            self.matching.fuzzy_preset.clone_from(&other.matching.fuzzy_preset);
183        }
184        if other.matching.threshold.is_some() {
185            self.matching.threshold = other.matching.threshold;
186        }
187        if other.matching.include_unchanged {
188            self.matching.include_unchanged = true;
189        }
190
191        // Output config - only override if explicitly set
192        if other.output.format != crate::reports::ReportFormat::Auto {
193            self.output.format = other.output.format;
194        }
195        if other.output.file.is_some() {
196            self.output.file.clone_from(&other.output.file);
197        }
198        if other.output.no_color {
199            self.output.no_color = true;
200        }
201
202        // Filtering config
203        if other.filtering.only_changes {
204            self.filtering.only_changes = true;
205        }
206        if other.filtering.min_severity.is_some() {
207            self.filtering.min_severity.clone_from(&other.filtering.min_severity);
208        }
209
210        // Behavior config (booleans - if set to true, override)
211        if other.behavior.fail_on_vuln {
212            self.behavior.fail_on_vuln = true;
213        }
214        if other.behavior.fail_on_change {
215            self.behavior.fail_on_change = true;
216        }
217        if other.behavior.quiet {
218            self.behavior.quiet = true;
219        }
220        if other.behavior.explain_matches {
221            self.behavior.explain_matches = true;
222        }
223        if other.behavior.recommend_threshold {
224            self.behavior.recommend_threshold = true;
225        }
226
227        // Graph diff config
228        if other.graph_diff.enabled {
229            self.graph_diff = other.graph_diff.clone();
230        }
231
232        // Rules config
233        if other.rules.rules_file.is_some() {
234            self.rules.rules_file.clone_from(&other.rules.rules_file);
235        }
236        if other.rules.dry_run {
237            self.rules.dry_run = true;
238        }
239
240        // Ecosystem rules config
241        if other.ecosystem_rules.config_file.is_some() {
242            self.ecosystem_rules.config_file.clone_from(&other.ecosystem_rules.config_file);
243        }
244        if other.ecosystem_rules.disabled {
245            self.ecosystem_rules.disabled = true;
246        }
247        if other.ecosystem_rules.detect_typosquats {
248            self.ecosystem_rules.detect_typosquats = true;
249        }
250
251        // TUI config
252        if other.tui.theme != "dark" {
253            self.tui.theme.clone_from(&other.tui.theme);
254        }
255
256        // Enrichment config
257        if other.enrichment.is_some() {
258            self.enrichment.clone_from(&other.enrichment);
259        }
260    }
261
262    /// Load from file and merge with CLI overrides.
263    #[must_use] 
264    pub fn from_file_with_overrides(
265        config_path: Option<&Path>,
266        cli_overrides: &Self,
267    ) -> (Self, Option<PathBuf>) {
268        let (mut config, loaded_from) = load_or_default(config_path);
269        config.merge(cli_overrides);
270        (config, loaded_from)
271    }
272}
273
274// ============================================================================
275// Example Config Generation
276// ============================================================================
277
278/// Generate an example config file content.
279#[must_use] 
280pub fn generate_example_config() -> String {
281    let example = AppConfig::default();
282    format!(
283        r"# SBOM Diff Configuration
284# Place this file at .sbom-tools.yaml in your project root or ~/.config/sbom-tools/
285
286{}
287",
288        serde_yaml_ng::to_string(&example).unwrap_or_default()
289    )
290}
291
292/// Generate a commented example config with all options.
293#[must_use] 
294pub fn generate_full_example_config() -> String {
295    r"# SBOM Diff Configuration File
296# ==============================
297#
298# This file configures sbom-tools behavior. Place it at:
299#   - .sbom-tools.yaml in your project root
300#   - ~/.config/sbom-tools/sbom-tools.yaml for global config
301#
302# CLI arguments always override file settings.
303
304# Matching configuration
305matching:
306  # Preset: strict, balanced, permissive, security-focused
307  fuzzy_preset: balanced
308  # Custom threshold (0.0-1.0), overrides preset
309  # threshold: 0.85
310  # Include unchanged components in output
311  include_unchanged: false
312
313# Output configuration
314output:
315  # Format: auto, json, text, sarif, markdown, html
316  format: auto
317  # Output file path (omit for stdout)
318  # file: report.json
319  # Disable colored output
320  no_color: false
321
322# Filtering options
323filtering:
324  # Only show items with changes
325  only_changes: false
326  # Minimum severity filter: critical, high, medium, low, info
327  # min_severity: high
328
329# Behavior flags
330behavior:
331  # Exit with code 2 if new vulnerabilities are introduced
332  fail_on_vuln: false
333  # Exit with code 1 if any changes detected
334  fail_on_change: false
335  # Suppress non-essential output
336  quiet: false
337  # Show detailed match explanations
338  explain_matches: false
339  # Recommend optimal matching threshold
340  recommend_threshold: false
341
342# Graph-aware diffing
343graph_diff:
344  enabled: false
345  detect_reparenting: true
346  detect_depth_changes: true
347
348# Custom matching rules
349rules:
350  # Path to matching rules YAML file
351  # rules_file: ./matching-rules.yaml
352  dry_run: false
353
354# Ecosystem-specific rules
355ecosystem_rules:
356  # Path to ecosystem rules config
357  # config_file: ./ecosystem-rules.yaml
358  disabled: false
359  detect_typosquats: false
360
361# TUI configuration
362tui:
363  # Theme: dark, light, high-contrast
364  theme: dark
365  show_line_numbers: true
366  mouse_enabled: true
367  initial_threshold: 0.8
368
369# Enrichment configuration (optional)
370# enrichment:
371#   enabled: true
372#   provider: osv
373#   cache_ttl: 3600
374#   max_concurrent: 10
375"
376    .to_string()
377}
378
379// ============================================================================
380// Tests
381// ============================================================================
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use std::io::Write;
387    use tempfile::TempDir;
388
389    #[test]
390    fn test_find_config_in_dir() {
391        let tmp = TempDir::new().unwrap();
392        let config_path = tmp.path().join(".sbom-tools.yaml");
393        std::fs::write(&config_path, "matching:\n  fuzzy_preset: strict\n").unwrap();
394
395        let found = find_config_in_dir(tmp.path());
396        assert_eq!(found, Some(config_path));
397    }
398
399    #[test]
400    fn test_find_config_in_dir_not_found() {
401        let tmp = TempDir::new().unwrap();
402        let found = find_config_in_dir(tmp.path());
403        assert_eq!(found, None);
404    }
405
406    #[test]
407    fn test_load_config_file() {
408        let tmp = TempDir::new().unwrap();
409        let config_path = tmp.path().join("config.yaml");
410
411        let yaml = r#"
412matching:
413  fuzzy_preset: strict
414  threshold: 0.9
415behavior:
416  fail_on_vuln: true
417"#;
418        std::fs::write(&config_path, yaml).unwrap();
419
420        let config = load_config_file(&config_path).unwrap();
421        assert_eq!(config.matching.fuzzy_preset, "strict");
422        assert_eq!(config.matching.threshold, Some(0.9));
423        assert!(config.behavior.fail_on_vuln);
424    }
425
426    #[test]
427    fn test_load_config_file_not_found() {
428        let result = load_config_file(Path::new("/nonexistent/config.yaml"));
429        assert!(matches!(result, Err(ConfigFileError::NotFound(_))));
430    }
431
432    #[test]
433    fn test_config_merge() {
434        let mut base = AppConfig::default();
435        let override_config = AppConfig {
436            matching: super::super::types::MatchingConfig {
437                fuzzy_preset: "strict".to_string(),
438                threshold: Some(0.95),
439                include_unchanged: false,
440            },
441            behavior: super::super::types::BehaviorConfig {
442                fail_on_vuln: true,
443                ..Default::default()
444            },
445            ..AppConfig::default()
446        };
447
448        base.merge(&override_config);
449
450        assert_eq!(base.matching.fuzzy_preset, "strict");
451        assert_eq!(base.matching.threshold, Some(0.95));
452        assert!(base.behavior.fail_on_vuln);
453    }
454
455    #[test]
456    fn test_generate_example_config() {
457        let example = generate_example_config();
458        assert!(example.contains("matching:"));
459        assert!(example.contains("fuzzy_preset"));
460    }
461
462    #[test]
463    fn test_discover_explicit_path() {
464        let tmp = TempDir::new().unwrap();
465        let config_path = tmp.path().join("custom-config.yaml");
466        let mut file = std::fs::File::create(&config_path).unwrap();
467        writeln!(file, "matching:\n  fuzzy_preset: strict").unwrap();
468
469        let discovered = discover_config_file(Some(&config_path));
470        assert_eq!(discovered, Some(config_path));
471    }
472}