sbom_tools/config/
file.rs1use super::types::AppConfig;
6use std::path::{Path, PathBuf};
7
8const 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#[must_use]
30pub fn discover_config_file(explicit_path: Option<&Path>) -> Option<PathBuf> {
31 if let Some(path) = explicit_path {
33 if path.exists() {
34 return Some(path.to_path_buf());
35 }
36 }
37
38 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 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 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 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
70fn 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
81fn 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#[derive(Debug)]
102pub enum ConfigFileError {
103 NotFound(PathBuf),
105 Io(std::io::Error),
107 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
145pub 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#[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
171impl AppConfig {
176 pub fn merge(&mut self, other: &Self) {
180 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 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 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 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 if other.graph_diff.enabled {
229 self.graph_diff = other.graph_diff.clone();
230 }
231
232 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 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 if other.tui.theme != "dark" {
253 self.tui.theme.clone_from(&other.tui.theme);
254 }
255
256 if other.enrichment.is_some() {
258 self.enrichment.clone_from(&other.enrichment);
259 }
260 }
261
262 #[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#[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#[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#[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}