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        && path.exists()
34    {
35        return Some(path.to_path_buf());
36    }
37
38    // 2. Search current directory
39    if let Ok(cwd) = std::env::current_dir()
40        && let Some(path) = find_config_in_dir(&cwd)
41    {
42        return Some(path);
43    }
44
45    // 3. Search git root (if in a repo)
46    if let Some(git_root) = find_git_root()
47        && let Some(path) = find_config_in_dir(&git_root)
48    {
49        return Some(path);
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        && let Some(path) = find_config_in_dir(&home)
63    {
64        return Some(path);
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
183                .fuzzy_preset
184                .clone_from(&other.matching.fuzzy_preset);
185        }
186        if other.matching.threshold.is_some() {
187            self.matching.threshold = other.matching.threshold;
188        }
189        if other.matching.include_unchanged {
190            self.matching.include_unchanged = true;
191        }
192
193        // Output config - only override if explicitly set
194        if other.output.format != crate::reports::ReportFormat::Auto {
195            self.output.format = other.output.format;
196        }
197        if other.output.file.is_some() {
198            self.output.file.clone_from(&other.output.file);
199        }
200        if other.output.no_color {
201            self.output.no_color = true;
202        }
203        if other.output.export_template.is_some() {
204            self.output
205                .export_template
206                .clone_from(&other.output.export_template);
207        }
208
209        // Filtering config
210        if other.filtering.only_changes {
211            self.filtering.only_changes = true;
212        }
213        if other.filtering.min_severity.is_some() {
214            self.filtering
215                .min_severity
216                .clone_from(&other.filtering.min_severity);
217        }
218
219        // Behavior config (booleans - if set to true, override)
220        if other.behavior.fail_on_vuln {
221            self.behavior.fail_on_vuln = true;
222        }
223        if other.behavior.fail_on_change {
224            self.behavior.fail_on_change = true;
225        }
226        if other.behavior.quiet {
227            self.behavior.quiet = true;
228        }
229        if other.behavior.explain_matches {
230            self.behavior.explain_matches = true;
231        }
232        if other.behavior.recommend_threshold {
233            self.behavior.recommend_threshold = true;
234        }
235
236        // Graph diff config
237        if other.graph_diff.enabled {
238            self.graph_diff = other.graph_diff.clone();
239        }
240
241        // Rules config
242        if other.rules.rules_file.is_some() {
243            self.rules.rules_file.clone_from(&other.rules.rules_file);
244        }
245        if other.rules.dry_run {
246            self.rules.dry_run = true;
247        }
248
249        // Ecosystem rules config
250        if other.ecosystem_rules.config_file.is_some() {
251            self.ecosystem_rules
252                .config_file
253                .clone_from(&other.ecosystem_rules.config_file);
254        }
255        if other.ecosystem_rules.disabled {
256            self.ecosystem_rules.disabled = true;
257        }
258        if other.ecosystem_rules.detect_typosquats {
259            self.ecosystem_rules.detect_typosquats = true;
260        }
261
262        // TUI config
263        if other.tui.theme != "dark" {
264            self.tui.theme.clone_from(&other.tui.theme);
265        }
266
267        // Enrichment config
268        if other.enrichment.is_some() {
269            self.enrichment.clone_from(&other.enrichment);
270        }
271    }
272
273    /// Load from file and merge with CLI overrides.
274    #[must_use]
275    pub fn from_file_with_overrides(
276        config_path: Option<&Path>,
277        cli_overrides: &Self,
278    ) -> (Self, Option<PathBuf>) {
279        let (mut config, loaded_from) = load_or_default(config_path);
280        config.merge(cli_overrides);
281        (config, loaded_from)
282    }
283}
284
285// ============================================================================
286// Example Config Generation
287// ============================================================================
288
289/// Generate an example config file content.
290#[must_use]
291pub fn generate_example_config() -> String {
292    let example = AppConfig::default();
293    format!(
294        r"# SBOM Diff Configuration
295# Place this file at .sbom-tools.yaml in your project root or ~/.config/sbom-tools/
296
297{}
298",
299        serde_yaml_ng::to_string(&example).unwrap_or_default()
300    )
301}
302
303/// Generate a commented example config with all options.
304#[must_use]
305pub fn generate_full_example_config() -> String {
306    r"# SBOM Diff Configuration File
307# ==============================
308#
309# This file configures sbom-tools behavior. Place it at:
310#   - .sbom-tools.yaml in your project root
311#   - ~/.config/sbom-tools/sbom-tools.yaml for global config
312#
313# CLI arguments always override file settings.
314
315# Matching configuration
316matching:
317  # Preset: strict, balanced, permissive, security-focused
318  fuzzy_preset: balanced
319  # Custom threshold (0.0-1.0), overrides preset
320  # threshold: 0.85
321  # Include unchanged components in output
322  include_unchanged: false
323
324# Output configuration
325output:
326  # Format: auto, json, text, sarif, markdown, html
327  format: auto
328  # Output file path (omit for stdout)
329  # file: report.json
330  # Disable colored output
331  no_color: false
332
333# Filtering options
334filtering:
335  # Only show items with changes
336  only_changes: false
337  # Minimum severity filter: critical, high, medium, low, info
338  # min_severity: high
339
340# Behavior flags
341behavior:
342  # Exit with code 2 if new vulnerabilities are introduced
343  fail_on_vuln: false
344  # Exit with code 1 if any changes detected
345  fail_on_change: false
346  # Suppress non-essential output
347  quiet: false
348  # Show detailed match explanations
349  explain_matches: false
350  # Recommend optimal matching threshold
351  recommend_threshold: false
352
353# Graph-aware diffing
354graph_diff:
355  enabled: false
356  detect_reparenting: true
357  detect_depth_changes: true
358
359# Custom matching rules
360rules:
361  # Path to matching rules YAML file
362  # rules_file: ./matching-rules.yaml
363  dry_run: false
364
365# Ecosystem-specific rules
366ecosystem_rules:
367  # Path to ecosystem rules config
368  # config_file: ./ecosystem-rules.yaml
369  disabled: false
370  detect_typosquats: false
371
372# TUI configuration
373tui:
374  # Theme: dark, light, high-contrast
375  theme: dark
376  show_line_numbers: true
377  mouse_enabled: true
378  initial_threshold: 0.8
379
380# Enrichment configuration (optional)
381# enrichment:
382#   enabled: true
383#   provider: osv
384#   cache_ttl: 3600
385#   max_concurrent: 10
386"
387    .to_string()
388}
389
390// ============================================================================
391// Tests
392// ============================================================================
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397    use std::io::Write;
398    use tempfile::TempDir;
399
400    #[test]
401    fn test_find_config_in_dir() {
402        let tmp = TempDir::new().unwrap();
403        let config_path = tmp.path().join(".sbom-tools.yaml");
404        std::fs::write(&config_path, "matching:\n  fuzzy_preset: strict\n").unwrap();
405
406        let found = find_config_in_dir(tmp.path());
407        assert_eq!(found, Some(config_path));
408    }
409
410    #[test]
411    fn test_find_config_in_dir_not_found() {
412        let tmp = TempDir::new().unwrap();
413        let found = find_config_in_dir(tmp.path());
414        assert_eq!(found, None);
415    }
416
417    #[test]
418    fn test_load_config_file() {
419        let tmp = TempDir::new().unwrap();
420        let config_path = tmp.path().join("config.yaml");
421
422        let yaml = r#"
423matching:
424  fuzzy_preset: strict
425  threshold: 0.9
426behavior:
427  fail_on_vuln: true
428"#;
429        std::fs::write(&config_path, yaml).unwrap();
430
431        let config = load_config_file(&config_path).unwrap();
432        assert_eq!(config.matching.fuzzy_preset, "strict");
433        assert_eq!(config.matching.threshold, Some(0.9));
434        assert!(config.behavior.fail_on_vuln);
435    }
436
437    #[test]
438    fn test_load_config_file_not_found() {
439        let result = load_config_file(Path::new("/nonexistent/config.yaml"));
440        assert!(matches!(result, Err(ConfigFileError::NotFound(_))));
441    }
442
443    #[test]
444    fn test_config_merge() {
445        let mut base = AppConfig::default();
446        let override_config = AppConfig {
447            matching: super::super::types::MatchingConfig {
448                fuzzy_preset: "strict".to_string(),
449                threshold: Some(0.95),
450                include_unchanged: false,
451            },
452            behavior: super::super::types::BehaviorConfig {
453                fail_on_vuln: true,
454                ..Default::default()
455            },
456            ..AppConfig::default()
457        };
458
459        base.merge(&override_config);
460
461        assert_eq!(base.matching.fuzzy_preset, "strict");
462        assert_eq!(base.matching.threshold, Some(0.95));
463        assert!(base.behavior.fail_on_vuln);
464    }
465
466    #[test]
467    fn test_generate_example_config() {
468        let example = generate_example_config();
469        assert!(example.contains("matching:"));
470        assert!(example.contains("fuzzy_preset"));
471    }
472
473    #[test]
474    fn test_discover_explicit_path() {
475        let tmp = TempDir::new().unwrap();
476        let config_path = tmp.path().join("custom-config.yaml");
477        let mut file = std::fs::File::create(&config_path).unwrap();
478        writeln!(file, "matching:\n  fuzzy_preset: strict").unwrap();
479
480        let discovered = discover_config_file(Some(&config_path));
481        assert_eq!(discovered, Some(config_path));
482    }
483}