Skip to main content

sbom_tools/config/
types.rs

1//! Configuration types for sbom-tools operations.
2//!
3//! Provides structured configuration for diff, view, and multi-comparison operations.
4
5use crate::matching::FuzzyMatchConfig;
6use crate::reports::{ReportFormat, ReportType};
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use std::path::PathBuf;
10
11// ============================================================================
12// Unified Application Configuration
13// ============================================================================
14
15/// Unified application configuration that can be loaded from CLI args or config files.
16///
17/// This is the top-level configuration struct that aggregates all configuration
18/// options. It can be constructed from CLI arguments, config files, or both
19/// (with CLI overriding file settings).
20#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
21#[serde(default)]
22pub struct AppConfig {
23    /// Matching configuration (thresholds, presets)
24    pub matching: MatchingConfig,
25    /// Output configuration (format, file, colors)
26    pub output: OutputConfig,
27    /// Filtering options
28    pub filtering: FilterConfig,
29    /// Behavior flags
30    pub behavior: BehaviorConfig,
31    /// Graph-aware diffing configuration
32    pub graph_diff: GraphAwareDiffConfig,
33    /// Custom matching rules configuration
34    pub rules: MatchingRulesPathConfig,
35    /// Ecosystem-specific rules configuration
36    pub ecosystem_rules: EcosystemRulesConfig,
37    /// TUI-specific configuration
38    pub tui: TuiConfig,
39    /// Enrichment configuration (OSV, etc.)
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub enrichment: Option<EnrichmentConfig>,
42}
43
44impl AppConfig {
45    /// Create a new `AppConfig` with default values.
46    #[must_use]
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Create an `AppConfig` builder.
52    pub fn builder() -> AppConfigBuilder {
53        AppConfigBuilder::default()
54    }
55}
56
57// ============================================================================
58// Builder for AppConfig
59// ============================================================================
60
61/// Builder for constructing `AppConfig` with fluent API.
62#[derive(Debug, Default)]
63#[must_use]
64pub struct AppConfigBuilder {
65    config: AppConfig,
66}
67
68impl AppConfigBuilder {
69    /// Set the fuzzy matching preset.
70    pub fn fuzzy_preset(mut self, preset: impl Into<String>) -> Self {
71        self.config.matching.fuzzy_preset = preset.into();
72        self
73    }
74
75    /// Set the matching threshold.
76    pub const fn matching_threshold(mut self, threshold: f64) -> Self {
77        self.config.matching.threshold = Some(threshold);
78        self
79    }
80
81    /// Set the output format.
82    pub const fn output_format(mut self, format: ReportFormat) -> Self {
83        self.config.output.format = format;
84        self
85    }
86
87    /// Set the output file.
88    pub fn output_file(mut self, file: Option<PathBuf>) -> Self {
89        self.config.output.file = file;
90        self
91    }
92
93    /// Disable colored output.
94    pub const fn no_color(mut self, no_color: bool) -> Self {
95        self.config.output.no_color = no_color;
96        self
97    }
98
99    /// Include unchanged components.
100    pub const fn include_unchanged(mut self, include: bool) -> Self {
101        self.config.matching.include_unchanged = include;
102        self
103    }
104
105    /// Enable fail-on-vulnerability mode.
106    pub const fn fail_on_vuln(mut self, fail: bool) -> Self {
107        self.config.behavior.fail_on_vuln = fail;
108        self
109    }
110
111    /// Enable fail-on-change mode.
112    pub const fn fail_on_change(mut self, fail: bool) -> Self {
113        self.config.behavior.fail_on_change = fail;
114        self
115    }
116
117    /// Enable quiet mode.
118    pub const fn quiet(mut self, quiet: bool) -> Self {
119        self.config.behavior.quiet = quiet;
120        self
121    }
122
123    /// Enable graph-aware diffing.
124    pub fn graph_diff(mut self, enabled: bool) -> Self {
125        self.config.graph_diff = if enabled {
126            GraphAwareDiffConfig::enabled()
127        } else {
128            GraphAwareDiffConfig::default()
129        };
130        self
131    }
132
133    /// Set matching rules file.
134    pub fn matching_rules_file(mut self, file: Option<PathBuf>) -> Self {
135        self.config.rules.rules_file = file;
136        self
137    }
138
139    /// Set ecosystem rules file.
140    pub fn ecosystem_rules_file(mut self, file: Option<PathBuf>) -> Self {
141        self.config.ecosystem_rules.config_file = file;
142        self
143    }
144
145    /// Enable enrichment.
146    pub fn enrichment(mut self, config: EnrichmentConfig) -> Self {
147        self.config.enrichment = Some(config);
148        self
149    }
150
151    /// Build the `AppConfig`.
152    #[must_use]
153    pub fn build(self) -> AppConfig {
154        self.config
155    }
156}
157
158// ============================================================================
159// TUI Preferences (persisted)
160// ============================================================================
161
162/// TUI preferences that persist across sessions.
163#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
164pub struct TuiPreferences {
165    /// Theme name: "dark", "light", or "high-contrast"
166    pub theme: String,
167    /// Last active tab in diff mode (e.g., "summary", "components")
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub last_tab: Option<String>,
170    /// Last active tab in view mode (e.g., "overview", "tree")
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub last_view_tab: Option<String>,
173}
174
175impl Default for TuiPreferences {
176    fn default() -> Self {
177        Self {
178            theme: "dark".to_string(),
179            last_tab: None,
180            last_view_tab: None,
181        }
182    }
183}
184
185impl TuiPreferences {
186    /// Get the path to the preferences file.
187    #[must_use]
188    pub fn config_path() -> Option<PathBuf> {
189        dirs::config_dir().map(|p| p.join("sbom-tools").join("preferences.json"))
190    }
191
192    /// Load preferences from disk, or return defaults if not found.
193    #[must_use]
194    pub fn load() -> Self {
195        Self::config_path()
196            .and_then(|p| std::fs::read_to_string(p).ok())
197            .and_then(|s| serde_json::from_str(&s).ok())
198            .unwrap_or_default()
199    }
200
201    /// Save preferences to disk.
202    pub fn save(&self) -> std::io::Result<()> {
203        if let Some(path) = Self::config_path() {
204            if let Some(parent) = path.parent() {
205                std::fs::create_dir_all(parent)?;
206            }
207            let json = serde_json::to_string_pretty(self)
208                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
209            std::fs::write(path, json)?;
210        }
211        Ok(())
212    }
213}
214
215// ============================================================================
216// TUI Configuration
217// ============================================================================
218
219/// TUI-specific configuration.
220#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
221#[serde(default)]
222pub struct TuiConfig {
223    /// Theme name: "dark", "light", or "high-contrast"
224    pub theme: String,
225    /// Show line numbers in code views
226    pub show_line_numbers: bool,
227    /// Enable mouse support
228    pub mouse_enabled: bool,
229    /// Initial matching threshold for TUI threshold tuning
230    #[schemars(range(min = 0.0, max = 1.0))]
231    pub initial_threshold: f64,
232}
233
234impl Default for TuiConfig {
235    fn default() -> Self {
236        Self {
237            theme: "dark".to_string(),
238            show_line_numbers: true,
239            mouse_enabled: true,
240            initial_threshold: 0.8,
241        }
242    }
243}
244
245// ============================================================================
246// Command-specific Configuration Types
247// ============================================================================
248
249/// Configuration for diff operations
250#[derive(Debug, Clone)]
251pub struct DiffConfig {
252    /// Paths to compare
253    pub paths: DiffPaths,
254    /// Output configuration
255    pub output: OutputConfig,
256    /// Matching configuration
257    pub matching: MatchingConfig,
258    /// Filtering options
259    pub filtering: FilterConfig,
260    /// Behavior flags
261    pub behavior: BehaviorConfig,
262    /// Graph-aware diffing configuration
263    pub graph_diff: GraphAwareDiffConfig,
264    /// Custom matching rules configuration
265    pub rules: MatchingRulesPathConfig,
266    /// Ecosystem-specific rules configuration
267    pub ecosystem_rules: EcosystemRulesConfig,
268    /// Enrichment configuration (always defined, runtime feature check)
269    pub enrichment: EnrichmentConfig,
270}
271
272/// Paths for diff operation
273#[derive(Debug, Clone)]
274pub struct DiffPaths {
275    /// Path to old/baseline SBOM
276    pub old: PathBuf,
277    /// Path to new SBOM
278    pub new: PathBuf,
279}
280
281/// Configuration for view operations
282#[derive(Debug, Clone)]
283pub struct ViewConfig {
284    /// Path to SBOM file
285    pub sbom_path: PathBuf,
286    /// Output configuration
287    pub output: OutputConfig,
288    /// Whether to validate against NTIA
289    pub validate_ntia: bool,
290    /// Filter by minimum vulnerability severity (critical, high, medium, low)
291    pub min_severity: Option<String>,
292    /// Only show components with vulnerabilities
293    pub vulnerable_only: bool,
294    /// Filter by ecosystem
295    pub ecosystem_filter: Option<String>,
296    /// Exit with code 2 if vulnerabilities are present
297    pub fail_on_vuln: bool,
298    /// Enrichment configuration
299    pub enrichment: EnrichmentConfig,
300}
301
302/// Configuration for multi-diff operations
303#[derive(Debug, Clone)]
304pub struct MultiDiffConfig {
305    /// Path to baseline SBOM
306    pub baseline: PathBuf,
307    /// Paths to target SBOMs
308    pub targets: Vec<PathBuf>,
309    /// Output configuration
310    pub output: OutputConfig,
311    /// Matching configuration
312    pub matching: MatchingConfig,
313}
314
315/// Configuration for timeline analysis
316#[derive(Debug, Clone)]
317pub struct TimelineConfig {
318    /// Paths to SBOMs in chronological order
319    pub sbom_paths: Vec<PathBuf>,
320    /// Output configuration
321    pub output: OutputConfig,
322    /// Matching configuration
323    pub matching: MatchingConfig,
324}
325
326/// Configuration for query operations (searching components across multiple SBOMs)
327#[derive(Debug, Clone)]
328pub struct QueryConfig {
329    /// Paths to SBOM files to search
330    pub sbom_paths: Vec<PathBuf>,
331    /// Output configuration
332    pub output: OutputConfig,
333    /// Enrichment configuration
334    pub enrichment: EnrichmentConfig,
335    /// Maximum number of results to return
336    pub limit: Option<usize>,
337    /// Group results by SBOM source
338    pub group_by_sbom: bool,
339}
340
341/// Configuration for matrix comparison
342#[derive(Debug, Clone)]
343pub struct MatrixConfig {
344    /// Paths to SBOMs
345    pub sbom_paths: Vec<PathBuf>,
346    /// Output configuration
347    pub output: OutputConfig,
348    /// Matching configuration
349    pub matching: MatchingConfig,
350    /// Similarity threshold for clustering (0.0-1.0)
351    pub cluster_threshold: f64,
352}
353
354/// Configuration for the `vex` subcommand.
355#[derive(Debug, Clone)]
356pub struct VexConfig {
357    /// Path to SBOM file
358    pub sbom_path: PathBuf,
359    /// Paths to external VEX documents
360    pub vex_paths: Vec<PathBuf>,
361    /// Output format
362    pub output_format: ReportFormat,
363    /// Output file path (None for stdout)
364    pub output_file: Option<PathBuf>,
365    /// Suppress non-essential output
366    pub quiet: bool,
367    /// Only show actionable vulnerabilities (exclude NotAffected/Fixed)
368    pub actionable_only: bool,
369    /// Filter by VEX state
370    pub filter_state: Option<String>,
371    /// Enrichment configuration (for OSV/EOL before VEX overlay)
372    pub enrichment: EnrichmentConfig,
373}
374
375// ============================================================================
376// Sub-configuration Types
377// ============================================================================
378
379/// Output-related configuration
380#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
381#[serde(default)]
382pub struct OutputConfig {
383    /// Output format
384    pub format: ReportFormat,
385    /// Output file path (None for stdout)
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub file: Option<PathBuf>,
388    /// Report types to include
389    pub report_types: ReportType,
390    /// Disable colored output
391    pub no_color: bool,
392    /// Streaming configuration for large SBOMs
393    pub streaming: StreamingConfig,
394    /// Optional export filename template for TUI exports.
395    ///
396    /// Placeholders: `{date}` (YYYY-MM-DD), `{time}` (HHMMSS),
397    /// `{format}` (json/md/html), `{command}` (diff/view).
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub export_template: Option<String>,
400}
401
402impl Default for OutputConfig {
403    fn default() -> Self {
404        Self {
405            format: ReportFormat::Auto,
406            file: None,
407            report_types: ReportType::All,
408            no_color: false,
409            streaming: StreamingConfig::default(),
410            export_template: None,
411        }
412    }
413}
414
415/// Streaming configuration for memory-efficient processing of large SBOMs.
416///
417/// When streaming is enabled, the tool uses streaming parsers and reporters
418/// to avoid loading entire SBOMs into memory. This is essential for SBOMs
419/// with thousands of components.
420#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
421#[serde(default)]
422pub struct StreamingConfig {
423    /// Enable streaming mode automatically for files larger than this threshold (in bytes).
424    /// Default: 10 MB (`10_485_760` bytes)
425    #[schemars(range(min = 0))]
426    pub threshold_bytes: u64,
427    /// Force streaming mode regardless of file size.
428    /// Useful for testing or when processing stdin.
429    pub force: bool,
430    /// Disable streaming mode entirely (always load full SBOMs into memory).
431    pub disabled: bool,
432    /// Enable streaming for stdin input (since size is unknown).
433    /// Default: true
434    pub stream_stdin: bool,
435}
436
437impl Default for StreamingConfig {
438    fn default() -> Self {
439        Self {
440            threshold_bytes: 10 * 1024 * 1024, // 10 MB
441            force: false,
442            disabled: false,
443            stream_stdin: true,
444        }
445    }
446}
447
448impl StreamingConfig {
449    /// Check if streaming should be used for a file of the given size.
450    #[must_use]
451    pub fn should_stream(&self, file_size: Option<u64>, is_stdin: bool) -> bool {
452        if self.disabled {
453            return false;
454        }
455        if self.force {
456            return true;
457        }
458        if is_stdin && self.stream_stdin {
459            return true;
460        }
461        file_size.map_or(self.stream_stdin, |size| size >= self.threshold_bytes)
462    }
463
464    /// Create a streaming config that always streams.
465    #[must_use]
466    pub fn always() -> Self {
467        Self {
468            force: true,
469            ..Default::default()
470        }
471    }
472
473    /// Create a streaming config that never streams.
474    #[must_use]
475    pub fn never() -> Self {
476        Self {
477            disabled: true,
478            ..Default::default()
479        }
480    }
481
482    /// Set the threshold in megabytes.
483    #[must_use]
484    pub const fn with_threshold_mb(mut self, mb: u64) -> Self {
485        self.threshold_bytes = mb * 1024 * 1024;
486        self
487    }
488}
489
490/// Matching and comparison configuration
491#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
492#[serde(default)]
493pub struct MatchingConfig {
494    /// Fuzzy matching preset name
495    pub fuzzy_preset: String,
496    /// Custom matching threshold (overrides preset)
497    #[serde(skip_serializing_if = "Option::is_none")]
498    #[schemars(range(min = 0.0, max = 1.0))]
499    pub threshold: Option<f64>,
500    /// Include unchanged components in output
501    pub include_unchanged: bool,
502}
503
504impl Default for MatchingConfig {
505    fn default() -> Self {
506        Self {
507            fuzzy_preset: "balanced".to_string(),
508            threshold: None,
509            include_unchanged: false,
510        }
511    }
512}
513
514impl MatchingConfig {
515    /// Convert preset name to `FuzzyMatchConfig`
516    #[must_use]
517    pub fn to_fuzzy_config(&self) -> FuzzyMatchConfig {
518        let mut config = FuzzyMatchConfig::from_preset(&self.fuzzy_preset).unwrap_or_else(|| {
519            tracing::warn!(
520                "Unknown fuzzy preset '{}', using 'balanced'. Valid: strict, balanced, permissive",
521                self.fuzzy_preset
522            );
523            FuzzyMatchConfig::balanced()
524        });
525
526        // Apply custom threshold if specified
527        if let Some(threshold) = self.threshold {
528            config = config.with_threshold(threshold);
529        }
530
531        config
532    }
533}
534
535/// Filtering options for diff results
536#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
537#[serde(default)]
538pub struct FilterConfig {
539    /// Only show items with changes
540    pub only_changes: bool,
541    /// Minimum severity filter
542    #[serde(skip_serializing_if = "Option::is_none")]
543    pub min_severity: Option<String>,
544    /// Exclude vulnerabilities with VEX status `not_affected` or fixed
545    #[serde(alias = "exclude_vex_not_affected")]
546    pub exclude_vex_resolved: bool,
547    /// Exit with error if introduced vulnerabilities lack VEX statements
548    pub fail_on_vex_gap: bool,
549}
550
551/// Behavior flags for diff operations
552#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
553#[serde(default)]
554pub struct BehaviorConfig {
555    /// Exit with code 2 if new vulnerabilities are introduced
556    pub fail_on_vuln: bool,
557    /// Exit with code 1 if any changes detected
558    pub fail_on_change: bool,
559    /// Suppress non-essential output
560    pub quiet: bool,
561    /// Show detailed match explanations for each matched component
562    pub explain_matches: bool,
563    /// Recommend optimal matching threshold based on the SBOMs
564    pub recommend_threshold: bool,
565}
566
567/// Graph-aware diffing configuration
568#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
569#[serde(default)]
570pub struct GraphAwareDiffConfig {
571    /// Enable graph-aware diffing
572    pub enabled: bool,
573    /// Detect component reparenting
574    pub detect_reparenting: bool,
575    /// Detect depth changes
576    pub detect_depth_changes: bool,
577    /// Maximum depth to analyze (0 = unlimited)
578    pub max_depth: u32,
579    /// Minimum impact level to include in output ("low", "medium", "high", "critical")
580    pub impact_threshold: Option<String>,
581    /// Relationship type filter — only include edges matching these types (empty = all)
582    pub relation_filter: Vec<String>,
583}
584
585impl GraphAwareDiffConfig {
586    /// Create enabled graph diff options with defaults
587    #[must_use]
588    pub const fn enabled() -> Self {
589        Self {
590            enabled: true,
591            detect_reparenting: true,
592            detect_depth_changes: true,
593            max_depth: 0,
594            impact_threshold: None,
595            relation_filter: Vec::new(),
596        }
597    }
598}
599
600/// Custom matching rules configuration
601#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
602#[serde(default)]
603pub struct MatchingRulesPathConfig {
604    /// Path to matching rules YAML file
605    #[serde(skip_serializing_if = "Option::is_none")]
606    pub rules_file: Option<PathBuf>,
607    /// Dry-run mode (show what would match without applying)
608    pub dry_run: bool,
609}
610
611/// Ecosystem-specific rules configuration
612#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
613#[serde(default)]
614pub struct EcosystemRulesConfig {
615    /// Path to ecosystem rules configuration file
616    #[serde(skip_serializing_if = "Option::is_none")]
617    pub config_file: Option<PathBuf>,
618    /// Disable ecosystem-specific normalization
619    pub disabled: bool,
620    /// Enable typosquat detection warnings
621    pub detect_typosquats: bool,
622}
623
624/// Enrichment configuration for vulnerability data sources.
625///
626/// This configuration is always defined regardless of the `enrichment` feature flag.
627/// When the feature is disabled, the configuration is silently ignored at runtime.
628#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
629#[serde(default)]
630pub struct EnrichmentConfig {
631    /// Enable enrichment (if false, no enrichment is performed)
632    pub enabled: bool,
633    /// Enrichment provider ("osv", "nvd", etc.)
634    pub provider: String,
635    /// Cache time-to-live in hours
636    #[schemars(range(min = 1))]
637    pub cache_ttl_hours: u64,
638    /// Maximum concurrent requests
639    #[schemars(range(min = 1))]
640    pub max_concurrent: usize,
641    /// Cache directory for vulnerability data
642    #[serde(skip_serializing_if = "Option::is_none")]
643    pub cache_dir: Option<std::path::PathBuf>,
644    /// Bypass cache and fetch fresh vulnerability data
645    pub bypass_cache: bool,
646    /// API timeout in seconds
647    #[schemars(range(min = 1))]
648    pub timeout_secs: u64,
649    /// Enable end-of-life detection via endoflife.date API
650    pub enable_eol: bool,
651    /// Paths to external VEX documents (OpenVEX format)
652    #[serde(default, skip_serializing_if = "Vec::is_empty")]
653    pub vex_paths: Vec<std::path::PathBuf>,
654}
655
656impl Default for EnrichmentConfig {
657    fn default() -> Self {
658        Self {
659            enabled: false,
660            provider: "osv".to_string(),
661            cache_ttl_hours: 24,
662            max_concurrent: 10,
663            cache_dir: None,
664            bypass_cache: false,
665            timeout_secs: 30,
666            enable_eol: false,
667            vex_paths: Vec::new(),
668        }
669    }
670}
671
672impl EnrichmentConfig {
673    /// Create an enabled enrichment config with OSV provider.
674    #[must_use]
675    pub fn osv() -> Self {
676        Self {
677            enabled: true,
678            provider: "osv".to_string(),
679            ..Default::default()
680        }
681    }
682
683    /// Create an enabled enrichment config with custom settings.
684    #[must_use]
685    pub fn with_cache_dir(mut self, dir: std::path::PathBuf) -> Self {
686        self.cache_dir = Some(dir);
687        self
688    }
689
690    /// Set the cache TTL in hours.
691    #[must_use]
692    pub const fn with_cache_ttl_hours(mut self, hours: u64) -> Self {
693        self.cache_ttl_hours = hours;
694        self
695    }
696
697    /// Enable cache bypass (refresh).
698    #[must_use]
699    pub const fn with_bypass_cache(mut self) -> Self {
700        self.bypass_cache = true;
701        self
702    }
703
704    /// Set the API timeout in seconds.
705    #[must_use]
706    pub const fn with_timeout_secs(mut self, secs: u64) -> Self {
707        self.timeout_secs = secs;
708        self
709    }
710
711    /// Set VEX document paths.
712    #[must_use]
713    pub fn with_vex_paths(mut self, paths: Vec<std::path::PathBuf>) -> Self {
714        self.vex_paths = paths;
715        self
716    }
717}
718
719// ============================================================================
720// Builder for DiffConfig
721// ============================================================================
722
723/// Builder for `DiffConfig`
724#[derive(Debug, Default)]
725pub struct DiffConfigBuilder {
726    old: Option<PathBuf>,
727    new: Option<PathBuf>,
728    output: OutputConfig,
729    matching: MatchingConfig,
730    filtering: FilterConfig,
731    behavior: BehaviorConfig,
732    graph_diff: GraphAwareDiffConfig,
733    rules: MatchingRulesPathConfig,
734    ecosystem_rules: EcosystemRulesConfig,
735    enrichment: EnrichmentConfig,
736}
737
738impl DiffConfigBuilder {
739    #[must_use]
740    pub fn new() -> Self {
741        Self::default()
742    }
743
744    #[must_use]
745    pub fn old_path(mut self, path: PathBuf) -> Self {
746        self.old = Some(path);
747        self
748    }
749
750    #[must_use]
751    pub fn new_path(mut self, path: PathBuf) -> Self {
752        self.new = Some(path);
753        self
754    }
755
756    #[must_use]
757    pub const fn output_format(mut self, format: ReportFormat) -> Self {
758        self.output.format = format;
759        self
760    }
761
762    #[must_use]
763    pub fn output_file(mut self, file: Option<PathBuf>) -> Self {
764        self.output.file = file;
765        self
766    }
767
768    #[must_use]
769    pub const fn report_types(mut self, types: ReportType) -> Self {
770        self.output.report_types = types;
771        self
772    }
773
774    #[must_use]
775    pub const fn no_color(mut self, no_color: bool) -> Self {
776        self.output.no_color = no_color;
777        self
778    }
779
780    #[must_use]
781    pub fn fuzzy_preset(mut self, preset: String) -> Self {
782        self.matching.fuzzy_preset = preset;
783        self
784    }
785
786    #[must_use]
787    pub const fn matching_threshold(mut self, threshold: Option<f64>) -> Self {
788        self.matching.threshold = threshold;
789        self
790    }
791
792    #[must_use]
793    pub const fn include_unchanged(mut self, include: bool) -> Self {
794        self.matching.include_unchanged = include;
795        self
796    }
797
798    #[must_use]
799    pub const fn only_changes(mut self, only: bool) -> Self {
800        self.filtering.only_changes = only;
801        self
802    }
803
804    #[must_use]
805    pub fn min_severity(mut self, severity: Option<String>) -> Self {
806        self.filtering.min_severity = severity;
807        self
808    }
809
810    #[must_use]
811    pub const fn fail_on_vuln(mut self, fail: bool) -> Self {
812        self.behavior.fail_on_vuln = fail;
813        self
814    }
815
816    #[must_use]
817    pub const fn fail_on_change(mut self, fail: bool) -> Self {
818        self.behavior.fail_on_change = fail;
819        self
820    }
821
822    #[must_use]
823    pub const fn quiet(mut self, quiet: bool) -> Self {
824        self.behavior.quiet = quiet;
825        self
826    }
827
828    #[must_use]
829    pub const fn explain_matches(mut self, explain: bool) -> Self {
830        self.behavior.explain_matches = explain;
831        self
832    }
833
834    #[must_use]
835    pub const fn recommend_threshold(mut self, recommend: bool) -> Self {
836        self.behavior.recommend_threshold = recommend;
837        self
838    }
839
840    #[must_use]
841    pub fn graph_diff(mut self, enabled: bool) -> Self {
842        self.graph_diff = if enabled {
843            GraphAwareDiffConfig::enabled()
844        } else {
845            GraphAwareDiffConfig::default()
846        };
847        self
848    }
849
850    #[must_use]
851    pub fn matching_rules_file(mut self, file: Option<PathBuf>) -> Self {
852        self.rules.rules_file = file;
853        self
854    }
855
856    #[must_use]
857    pub const fn dry_run_rules(mut self, dry_run: bool) -> Self {
858        self.rules.dry_run = dry_run;
859        self
860    }
861
862    #[must_use]
863    pub fn ecosystem_rules_file(mut self, file: Option<PathBuf>) -> Self {
864        self.ecosystem_rules.config_file = file;
865        self
866    }
867
868    #[must_use]
869    pub const fn disable_ecosystem_rules(mut self, disabled: bool) -> Self {
870        self.ecosystem_rules.disabled = disabled;
871        self
872    }
873
874    #[must_use]
875    pub const fn detect_typosquats(mut self, detect: bool) -> Self {
876        self.ecosystem_rules.detect_typosquats = detect;
877        self
878    }
879
880    #[must_use]
881    pub fn enrichment(mut self, config: EnrichmentConfig) -> Self {
882        self.enrichment = config;
883        self
884    }
885
886    #[must_use]
887    pub const fn enable_enrichment(mut self, enabled: bool) -> Self {
888        self.enrichment.enabled = enabled;
889        self
890    }
891
892    pub fn build(self) -> anyhow::Result<DiffConfig> {
893        let old = self
894            .old
895            .ok_or_else(|| anyhow::anyhow!("old path is required"))?;
896        let new = self
897            .new
898            .ok_or_else(|| anyhow::anyhow!("new path is required"))?;
899
900        Ok(DiffConfig {
901            paths: DiffPaths { old, new },
902            output: self.output,
903            matching: self.matching,
904            filtering: self.filtering,
905            behavior: self.behavior,
906            graph_diff: self.graph_diff,
907            rules: self.rules,
908            ecosystem_rules: self.ecosystem_rules,
909            enrichment: self.enrichment,
910        })
911    }
912}