uv-sbom 2.0.1

SBOM generation tool for uv projects - Generate CycloneDX SBOMs from uv.lock files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
mod adapters;
mod application;
mod cli;
mod i18n;
mod ports;
mod sbom_generation;
mod shared;

use adapters::outbound::console::StderrProgressReporter;
use adapters::outbound::filesystem::FileSystemReader;
use adapters::outbound::network::{CachingPyPiLicenseRepository, OsvClient, PyPiLicenseRepository};
use application::dto::{OutputFormat, SbomRequest};
use application::factories::{FormatterFactory, PresenterFactory, PresenterType};
use application::read_models::SbomReadModelBuilder;
use application::use_cases::GenerateSbomUseCase;
use clap::Parser;
use cli::Args;
use i18n::Messages;
use owo_colors::OwoColorize;
use ports::outbound::ProjectConfigReader;
use sbom_generation::domain::license_policy::{LicensePolicy, UnknownLicenseHandling};
use sbom_generation::domain::vulnerability::Severity;
use shared::error::ExitCode;
use shared::security::validate_directory_path;
use shared::Result;
use std::collections::HashSet;
use std::path::PathBuf;
use std::process;
use uv_sbom::config::{self, ConfigFile, IgnoreCve};

#[tokio::main]
async fn main() {
    // Parse command-line arguments first to catch argument errors early
    let args = match Args::try_parse() {
        Ok(args) => args,
        Err(e) => {
            // Print the error message (clap formats these nicely)
            let _ = e.print();

            // Use exit code 0 for help/version, exit code 2 for actual argument errors
            let exit_code = if e.use_stderr() {
                ExitCode::InvalidArguments
            } else {
                ExitCode::Success
            };
            process::exit(exit_code.as_i32());
        }
    };

    // Handle --init before normal flow
    if args.init {
        let dir = args.path.as_deref().unwrap_or(".");
        let dir_path = std::path::Path::new(dir);
        match config::generate_config_template(dir_path) {
            Ok(abs_path) => {
                eprintln!(
                    "Created {} in {}",
                    config::CONFIG_FILENAME,
                    abs_path.parent().unwrap_or(dir_path).display()
                );
                process::exit(ExitCode::Success.as_i32());
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                process::exit(ExitCode::ApplicationError.as_i32());
            }
        }
    }

    // Run the main application logic
    match run(args).await {
        Ok(has_vulnerabilities) => {
            if has_vulnerabilities {
                process::exit(ExitCode::VulnerabilitiesDetected.as_i32());
            }
            process::exit(ExitCode::Success.as_i32());
        }
        Err(e) => {
            eprintln!("\n❌ An error occurred:\n");
            eprintln!("{}", e);

            // Display error chain
            let mut source = e.source();
            while let Some(err) = source {
                eprintln!("\nCaused by: {}", err);
                source = err.source();
            }

            eprintln!();
            process::exit(ExitCode::ApplicationError.as_i32());
        }
    }
}

/// Runs the main application logic.
///
/// Returns `Ok(true)` if vulnerabilities were detected above threshold,
/// `Ok(false)` if no vulnerabilities (or all below threshold),
/// or `Err` for application errors.
async fn run(args: Args) -> Result<bool> {
    // Display startup banner
    display_banner();

    let locale = args.lang;
    let msgs = Messages::for_locale(locale);

    // Warn if deprecated --check-cve flag is used
    if args.check_cve {
        eprintln!("Warning: --check-cve is deprecated and will be removed in a future release. CVE checking is now enabled by default. Use --no-check-cve to opt out.");
    }

    // Warn if CVE check is active with JSON format
    if !args.no_check_cve && args.format == OutputFormat::Json {
        eprintln!("{}", msgs.warn_check_cve_no_effect);
        eprintln!("   Vulnerability data is not included in JSON output.");
        eprintln!("   Use --format markdown to see vulnerability report.");
        eprintln!();
    }

    // Warn if check_license is used with JSON format
    if args.check_license && args.format == OutputFormat::Json {
        eprintln!("{}", msgs.warn_check_license_no_effect);
        eprintln!("   License compliance data is not included in JSON output.");
        eprintln!("   Use --format markdown to see license compliance report.");
        eprintln!();
    }

    // Warn if verify_links is used with JSON format
    if args.verify_links && args.format == OutputFormat::Json {
        eprintln!("{}", msgs.warn_verify_links_no_effect);
        eprintln!("   PyPI link verification only applies to Markdown output.");
        eprintln!("   Use --format markdown to use link verification.");
        eprintln!();
    }

    // Validate project directory
    let project_dir = args.path.as_deref().unwrap_or(".");
    let project_path = PathBuf::from(project_dir);

    validate_project_path(&project_path)?;

    // Load config file (explicit path or auto-discovery)
    let config = load_config(&args, &project_path)?;

    // Merge CLI and config values
    let merged = merge_config(&args, &config);

    // Create adapters (Dependency Injection)
    let lockfile_reader = FileSystemReader::new();
    let project_config_reader = FileSystemReader::new();
    let pypi_repository = PyPiLicenseRepository::new()?;
    let license_repository = CachingPyPiLicenseRepository::new(pypi_repository);
    let progress_reporter = StderrProgressReporter::new(locale);

    // Create vulnerability repository if CVE check is requested
    let vulnerability_repository = if merged.check_cve {
        Some(OsvClient::new()?)
    } else {
        None
    };

    // Create use case with injected dependencies
    let use_case = GenerateSbomUseCase::new(
        lockfile_reader,
        project_config_reader,
        license_repository,
        progress_reporter,
        vulnerability_repository,
        locale,
    );

    // Pre-flight check for --suggest-fix
    let suggest_fix = resolve_suggest_fix(merged.suggest_fix, &project_path);

    // Create request using builder pattern
    let include_dependency_info = matches!(merged.format, OutputFormat::Markdown);
    let request = SbomRequest::builder()
        .project_path(project_path.clone())
        .include_dependency_info(include_dependency_info)
        .exclude_patterns(merged.exclude_patterns)
        .dry_run(args.dry_run)
        .check_cve(merged.check_cve)
        .severity_threshold_opt(merged.severity_threshold)
        .cvss_threshold_opt(merged.cvss_threshold)
        .ignore_cves(merged.ignore_cves)
        .check_license(merged.check_license)
        .license_policy(merged.license_policy)
        .suggest_fix(suggest_fix)
        .locale(locale)
        .build()?;

    // Re-bind locale from the validated request to ensure consistency
    let locale = request.locale;

    // Execute use case
    let response = use_case.execute(request).await?;

    // Skip output generation for dry-run mode
    if args.dry_run {
        return Ok(false);
    }

    // Display progress message
    eprintln!(
        "{}",
        FormatterFactory::progress_message(merged.format, locale)
    );

    // Determine project component for CycloneDX metadata
    let project_reader = FileSystemReader::new();
    let project_component_info = project_reader
        .read_project_name(&project_path)
        .ok()
        .and_then(|name| {
            let version = response
                .enriched_packages
                .iter()
                .find(|ep| ep.package.name() == name)
                .map(|ep| ep.package.version().to_string());
            version.map(|v| (name, v))
        });

    // Build read model first so we can extract package names for verification
    let read_model = SbomReadModelBuilder::build_with_project(
        response.enriched_packages,
        &response.metadata,
        response.dependency_graph.as_ref(),
        response.vulnerability_check_result.as_ref(),
        response.license_compliance_result.as_ref(),
        project_component_info
            .as_ref()
            .map(|(n, v)| (n.as_str(), v.as_str())),
        response.upgrade_recommendations.as_deref(),
    );

    // Verify PyPI links if requested
    let verified_packages = if args.verify_links && merged.format == OutputFormat::Markdown {
        eprintln!("{}", msgs.progress_verifying_links);
        let pypi_verifier = PyPiLicenseRepository::new()?;
        let package_names: Vec<String> = read_model
            .components
            .iter()
            .map(|c| c.name.clone())
            .collect();
        Some(pypi_verifier.verify_packages(&package_names).await)
    } else {
        None
    };

    // Create formatter using factory with optional verified packages
    let formatter = FormatterFactory::create(merged.format, verified_packages, locale);
    let formatted_output = formatter.format(&read_model)?;

    // Create presenter using factory
    let presenter_type = if let Some(output_path) = args.output {
        PresenterType::File(PathBuf::from(output_path))
    } else {
        PresenterType::Stdout
    };

    let presenter = PresenterFactory::create(presenter_type);
    presenter.present(&formatted_output)?;

    // Determine if vulnerabilities or license violations were detected
    let has_issues =
        response.has_vulnerabilities_above_threshold || response.has_license_violations;

    Ok(has_issues)
}

fn display_banner() {
    let version = env!("CARGO_PKG_VERSION");
    eprintln!(
        "{} {} {}",
        "🚀".bright_yellow(),
        "uv-sbom".bright_cyan().bold(),
        format!("v{}", version).bright_green()
    );
    eprintln!();
}

/// Merged configuration after combining CLI arguments and config file values.
struct MergedConfig {
    format: OutputFormat,
    exclude_patterns: Vec<String>,
    check_cve: bool,
    severity_threshold: Option<Severity>,
    cvss_threshold: Option<f32>,
    ignore_cves: Vec<IgnoreCve>,
    check_license: bool,
    license_policy: Option<LicensePolicy>,
    suggest_fix: bool,
}

/// Load a config file from an explicit path or via auto-discovery.
fn load_config(args: &Args, project_path: &std::path::Path) -> Result<Option<ConfigFile>> {
    if let Some(ref config_path) = args.config {
        let path = std::path::Path::new(config_path);
        let cfg = config::load_config_from_path(path)?;
        eprintln!("📄 Loaded config from: {}", path.display());
        Ok(Some(cfg))
    } else {
        let cfg = config::discover_config(project_path)?;
        if cfg.is_some() {
            eprintln!("📄 Auto-discovered config file in project directory.");
        }
        Ok(cfg)
    }
}

/// Merge CLI arguments with config file values.
///
/// Priority: CLI > config file > defaults.
/// List fields (exclude_patterns, ignore_cves) are merged and deduplicated.
/// Scalar fields use CLI value if present, otherwise config value, otherwise default.
fn merge_config(args: &Args, config: &Option<ConfigFile>) -> MergedConfig {
    let config = match config {
        Some(c) => c,
        None => {
            // No config file — use CLI values directly
            let license_policy = if args.check_license
                && (!args.license_allow.is_empty() || !args.license_deny.is_empty())
            {
                Some(LicensePolicy::new(
                    &args.license_allow,
                    &args.license_deny,
                    UnknownLicenseHandling::default(),
                ))
            } else if args.check_license {
                Some(LicensePolicy::new(
                    &[],
                    &[],
                    UnknownLicenseHandling::default(),
                ))
            } else {
                None
            };

            return MergedConfig {
                format: args.format,
                exclude_patterns: args.exclude.clone(),
                check_cve: !args.no_check_cve,
                severity_threshold: args.severity_threshold,
                cvss_threshold: args.cvss_threshold,
                ignore_cves: args
                    .ignore_cve
                    .iter()
                    .map(|id| IgnoreCve {
                        id: id.clone(),
                        reason: None,
                    })
                    .collect(),
                check_license: args.check_license,
                license_policy,
                suggest_fix: args.suggest_fix,
            };
        }
    };

    // Merge exclude_patterns: combine both sources, deduplicate
    let exclude_patterns = merge_string_lists(&args.exclude, &config.exclude_packages);

    // Merge ignore_cves: combine both sources, deduplicate by ID
    let cli_ignore_cves: Vec<IgnoreCve> = args
        .ignore_cve
        .iter()
        .map(|id| IgnoreCve {
            id: id.clone(),
            reason: None,
        })
        .collect();
    let ignore_cves = merge_ignore_cves(&cli_ignore_cves, &config.ignore_cves);

    // Format: CLI > config > default (json)
    // Note: clap always provides a default value for format, so we check if user explicitly
    // provided it by comparing against the default. However, since clap's default_value means
    // args.format is always set, we use config only when format is json (default) and config
    // provides a different value.
    let format = if let Some(ref config_format) = config.format {
        // If user didn't explicitly pass --format, use config value
        // clap default is "json", so if args.format == Json, config might override
        // But we can't distinguish "user passed --format json" from "default json"
        // Convention: CLI always wins since clap provides the value
        if args.format != OutputFormat::Json {
            args.format
        } else {
            config_format.parse::<OutputFormat>().unwrap_or(args.format)
        }
    } else {
        args.format
    };

    // check_cve: CLI opt-out takes highest priority; otherwise use config value (default true)
    let check_cve = if args.no_check_cve {
        false
    } else {
        config.check_cve.unwrap_or(true)
    };

    // severity_threshold: CLI > config > None
    let severity_threshold = args.severity_threshold.or_else(|| {
        config
            .severity_threshold
            .as_ref()
            .and_then(|s| match s.to_lowercase().as_str() {
                "low" => Some(Severity::Low),
                "medium" => Some(Severity::Medium),
                "high" => Some(Severity::High),
                "critical" => Some(Severity::Critical),
                _ => None,
            })
    });

    // cvss_threshold: CLI > config > None
    let cvss_threshold = args
        .cvss_threshold
        .or(config.cvss_threshold.map(|v| v as f32));

    // check_license: CLI flag || config value
    let check_license = args.check_license || config.check_license.unwrap_or(false);

    // license_policy: CLI args override config entirely if any CLI args provided
    let license_policy = if check_license {
        if !args.license_allow.is_empty() || !args.license_deny.is_empty() {
            // CLI provides policy — override config entirely
            Some(LicensePolicy::new(
                &args.license_allow,
                &args.license_deny,
                UnknownLicenseHandling::default(),
            ))
        } else if let Some(ref lp_config) = config.license_policy {
            // Use config policy
            let unknown = lp_config
                .unknown
                .as_ref()
                .map(|s| match s.to_lowercase().as_str() {
                    "deny" => UnknownLicenseHandling::Deny,
                    "allow" => UnknownLicenseHandling::Allow,
                    _ => UnknownLicenseHandling::Warn,
                })
                .unwrap_or_default();
            let allow = lp_config.allow.clone().unwrap_or_default();
            let deny = lp_config.deny.clone().unwrap_or_default();
            Some(LicensePolicy::new(&allow, &deny, unknown))
        } else {
            // check_license enabled but no policy specified
            Some(LicensePolicy::new(
                &[],
                &[],
                UnknownLicenseHandling::default(),
            ))
        }
    } else {
        None
    };

    // suggest_fix: CLI flag takes priority over config value
    let suggest_fix = args.suggest_fix || config.suggest_fix.unwrap_or(false);

    MergedConfig {
        format,
        exclude_patterns,
        check_cve,
        severity_threshold,
        cvss_threshold,
        ignore_cves,
        check_license,
        license_policy,
        suggest_fix,
    }
}

/// Merge two string lists and deduplicate.
fn merge_string_lists(cli: &[String], config: &Option<Vec<String>>) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut result = Vec::new();

    // CLI values first (higher priority)
    for item in cli {
        if seen.insert(item.clone()) {
            result.push(item.clone());
        }
    }

    // Then config values
    if let Some(config_items) = config {
        for item in config_items {
            if seen.insert(item.clone()) {
                result.push(item.clone());
            }
        }
    }

    result
}

/// Merge two ignore_cves lists and deduplicate by ID (CLI entries take precedence).
fn merge_ignore_cves(cli: &[IgnoreCve], config: &Option<Vec<IgnoreCve>>) -> Vec<IgnoreCve> {
    let mut seen = HashSet::new();
    let mut result = Vec::new();

    // CLI values first (higher priority)
    for cve in cli {
        if seen.insert(cve.id.clone()) {
            result.push(cve.clone());
        }
    }

    // Then config values
    if let Some(config_cves) = config {
        for cve in config_cves {
            if seen.insert(cve.id.clone()) {
                result.push(cve.clone());
            }
        }
    }

    result
}

/// Resolves the effective value of `suggest_fix` after pre-flight validation.
///
/// Returns `false` immediately when `suggest_fix` is `false`.
/// When `suggest_fix` is `true`, verifies that:
/// - the `uv` CLI is available in PATH
/// - `pyproject.toml` exists in the given project directory
///
/// Prints a warning and returns `false` on the first failing condition.
fn resolve_suggest_fix(suggest_fix: bool, project_path: &std::path::Path) -> bool {
    if !suggest_fix {
        return false;
    }
    let uv_available = std::process::Command::new("uv")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if !uv_available {
        eprintln!(
            "⚠ --suggest-fix requires `uv` CLI. \
             Install it with: curl -LsSf https://astral.sh/uv/install.sh | sh"
        );
        return false;
    }
    if !project_path.join("pyproject.toml").exists() {
        eprintln!("⚠ --suggest-fix requires pyproject.toml in the project directory.");
        return false;
    }
    true
}

/// Validates that the project path is a valid directory.
///
/// This delegates to `validate_directory_path` in `shared::security`,
/// which provides comprehensive security validation including:
/// - Existence check
/// - Symlink rejection
/// - Directory type verification
/// - Path canonicalization for traversal prevention
fn validate_project_path(path: &std::path::Path) -> Result<()> {
    validate_directory_path(path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_validate_project_path_valid_directory() {
        let temp_dir = TempDir::new().unwrap();
        let result = validate_project_path(temp_dir.path());
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_project_path_nonexistent() {
        let nonexistent_path = PathBuf::from("/nonexistent/path/that/does/not/exist");
        let result = validate_project_path(&nonexistent_path);
        assert!(result.is_err());

        let err = result.unwrap_err();
        let err_string = format!("{}", err);
        assert!(err_string.contains("Directory does not exist"));
    }

    #[test]
    fn test_validate_project_path_file_not_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test_file.txt");
        fs::write(&file_path, "test content").unwrap();

        let result = validate_project_path(&file_path);
        assert!(result.is_err());

        let err = result.unwrap_err();
        let err_string = format!("{}", err);
        assert!(err_string.contains("Not a directory"));
    }

    #[test]
    fn test_validate_project_path_current_directory() {
        let current_dir = std::env::current_dir().unwrap();
        let result = validate_project_path(&current_dir);
        assert!(result.is_ok());
    }

    // --- Merge logic tests ---

    #[test]
    fn test_merge_string_lists_both_empty() {
        let result = merge_string_lists(&[], &None);
        assert!(result.is_empty());
    }

    #[test]
    fn test_merge_string_lists_cli_only() {
        let cli = vec!["a".to_string(), "b".to_string()];
        let result = merge_string_lists(&cli, &None);
        assert_eq!(result, vec!["a", "b"]);
    }

    #[test]
    fn test_merge_string_lists_config_only() {
        let config = Some(vec!["x".to_string(), "y".to_string()]);
        let result = merge_string_lists(&[], &config);
        assert_eq!(result, vec!["x", "y"]);
    }

    #[test]
    fn test_merge_string_lists_deduplication() {
        let cli = vec!["a".to_string(), "b".to_string()];
        let config = Some(vec!["b".to_string(), "c".to_string()]);
        let result = merge_string_lists(&cli, &config);
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_merge_ignore_cves_both_empty() {
        let result = merge_ignore_cves(&[], &None);
        assert!(result.is_empty());
    }

    #[test]
    fn test_merge_ignore_cves_cli_only() {
        let cli = vec![IgnoreCve {
            id: "CVE-2024-1".to_string(),
            reason: None,
        }];
        let result = merge_ignore_cves(&cli, &None);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "CVE-2024-1");
    }

    #[test]
    fn test_merge_ignore_cves_config_only() {
        let config = Some(vec![IgnoreCve {
            id: "CVE-2024-2".to_string(),
            reason: Some("reason".to_string()),
        }]);
        let result = merge_ignore_cves(&[], &config);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "CVE-2024-2");
        assert_eq!(result[0].reason.as_deref(), Some("reason"));
    }

    #[test]
    fn test_merge_ignore_cves_deduplication_cli_wins() {
        let cli = vec![IgnoreCve {
            id: "CVE-2024-1".to_string(),
            reason: Some("cli reason".to_string()),
        }];
        let config = Some(vec![
            IgnoreCve {
                id: "CVE-2024-1".to_string(),
                reason: Some("config reason".to_string()),
            },
            IgnoreCve {
                id: "CVE-2024-2".to_string(),
                reason: None,
            },
        ]);
        let result = merge_ignore_cves(&cli, &config);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].id, "CVE-2024-1");
        assert_eq!(result[0].reason.as_deref(), Some("cli reason"));
        assert_eq!(result[1].id, "CVE-2024-2");
    }

    #[test]
    fn test_merge_config_no_config_file() {
        let args = Args::parse_from(["uv-sbom"]);
        let result = merge_config(&args, &None);
        assert_eq!(result.format, OutputFormat::Json);
        assert!(result.exclude_patterns.is_empty());
        assert!(result.check_cve); // CVE check is enabled by default
        assert!(result.severity_threshold.is_none());
        assert!(result.cvss_threshold.is_none());
        assert!(result.ignore_cves.is_empty());
    }

    #[test]
    fn test_merge_config_config_provides_defaults() {
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            format: Some("markdown".to_string()),
            exclude_packages: Some(vec!["pkg-a".to_string()]),
            check_cve: Some(true),
            severity_threshold: Some("high".to_string()),
            cvss_threshold: Some(7.0),
            ignore_cves: Some(vec![IgnoreCve {
                id: "CVE-2024-1".to_string(),
                reason: Some("not applicable".to_string()),
            }]),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.format, OutputFormat::Markdown);
        assert_eq!(result.exclude_patterns, vec!["pkg-a"]);
        assert!(result.check_cve);
        assert_eq!(result.severity_threshold, Some(Severity::High));
        assert_eq!(result.cvss_threshold, Some(7.0));
        assert_eq!(result.ignore_cves.len(), 1);
        assert_eq!(result.ignore_cves[0].id, "CVE-2024-1");
    }

    #[test]
    fn test_merge_config_cli_overrides_format() {
        let args = Args::parse_from(["uv-sbom", "--format", "markdown"]);
        let config = Some(ConfigFile {
            format: Some("json".to_string()),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.format, OutputFormat::Markdown);
    }

    #[test]
    fn test_merge_config_no_check_cve_cli_flag() {
        let args = Args::parse_from(["uv-sbom", "--no-check-cve"]);
        let config = Some(ConfigFile {
            check_cve: Some(true),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(!result.check_cve);
    }

    #[test]
    fn test_merge_config_no_check_cve_overrides_config() {
        // CLI opt-out wins over config.check_cve = Some(true)
        let args = Args::parse_from(["uv-sbom", "--no-check-cve"]);
        let config = Some(ConfigFile {
            check_cve: Some(true),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(!result.check_cve);
    }

    #[test]
    fn test_merge_config_check_cve_from_config() {
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            check_cve: Some(true),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(result.check_cve);
    }

    #[test]
    fn test_merge_config_exclude_patterns_merged() {
        let args = Args::parse_from(["uv-sbom", "-e", "cli-pkg"]);
        let config = Some(ConfigFile {
            exclude_packages: Some(vec!["config-pkg".to_string(), "cli-pkg".to_string()]),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.exclude_patterns, vec!["cli-pkg", "config-pkg"]);
    }

    #[test]
    fn test_merge_config_ignore_cves_merged() {
        let args = Args::parse_from(["uv-sbom", "-i", "CVE-2024-1"]);
        let config = Some(ConfigFile {
            ignore_cves: Some(vec![
                IgnoreCve {
                    id: "CVE-2024-1".to_string(),
                    reason: Some("config reason".to_string()),
                },
                IgnoreCve {
                    id: "CVE-2024-2".to_string(),
                    reason: None,
                },
            ]),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.ignore_cves.len(), 2);
        // CLI entry takes precedence (no reason)
        assert_eq!(result.ignore_cves[0].id, "CVE-2024-1");
        assert!(result.ignore_cves[0].reason.is_none());
        assert_eq!(result.ignore_cves[1].id, "CVE-2024-2");
    }

    #[test]
    fn test_merge_config_severity_threshold_cli_wins() {
        let args = Args::parse_from(["uv-sbom", "--severity-threshold", "critical"]);
        let config = Some(ConfigFile {
            severity_threshold: Some("low".to_string()),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.severity_threshold, Some(Severity::Critical));
    }

    #[test]
    fn test_merge_config_severity_threshold_from_config() {
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            severity_threshold: Some("medium".to_string()),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.severity_threshold, Some(Severity::Medium));
    }

    #[test]
    fn test_merge_config_cvss_threshold_cli_wins() {
        let args = Args::parse_from(["uv-sbom", "--cvss-threshold", "8.5"]);
        let config = Some(ConfigFile {
            cvss_threshold: Some(5.0),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.cvss_threshold, Some(8.5));
    }

    #[test]
    fn test_merge_config_cvss_threshold_from_config() {
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            cvss_threshold: Some(6.0),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert_eq!(result.cvss_threshold, Some(6.0));
    }

    // --- suggest_fix merge tests ---

    #[test]
    fn test_merge_config_suggest_fix_from_config() {
        // suggest_fix: true in config, no CLI flag → merged value is true
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            suggest_fix: Some(true),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(result.suggest_fix);
    }

    #[test]
    fn test_merge_config_suggest_fix_cli_flag() {
        // suggest_fix: true via CLI flag (CVE enabled by default) → merged value is true
        let args = Args::parse_from(["uv-sbom", "--suggest-fix"]);
        let config = Some(ConfigFile {
            suggest_fix: Some(true),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(result.suggest_fix);
    }

    #[test]
    fn test_merge_config_suggest_fix_cli_wins_over_config_false() {
        // suggest_fix: false in config, --suggest-fix CLI flag → CLI wins, merged value is true
        let args = Args::parse_from(["uv-sbom", "--suggest-fix"]);
        let config = Some(ConfigFile {
            suggest_fix: Some(false),
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(result.suggest_fix);
    }

    #[test]
    fn test_merge_config_suggest_fix_default_false() {
        // No CLI flag, no config → default false
        let args = Args::parse_from(["uv-sbom"]);
        let config = Some(ConfigFile {
            ..Default::default()
        });
        let result = merge_config(&args, &config);
        assert!(!result.suggest_fix);
    }

    // --- resolve_suggest_fix tests ---

    #[test]
    fn test_resolve_suggest_fix_disabled() {
        let temp_dir = TempDir::new().unwrap();
        // When suggest_fix is false, always returns false without checking anything
        assert!(!resolve_suggest_fix(false, temp_dir.path()));
    }

    #[test]
    fn test_resolve_suggest_fix_missing_pyproject_toml() {
        let temp_dir = TempDir::new().unwrap();
        // No pyproject.toml in temp dir; only meaningful when uv is available
        let uv_available = std::process::Command::new("uv")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if uv_available {
            assert!(!resolve_suggest_fix(true, temp_dir.path()));
        }
    }

    #[test]
    fn test_resolve_suggest_fix_with_pyproject_toml() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(
            temp_dir.path().join("pyproject.toml"),
            "[project]\nname = \"test\"\n",
        )
        .unwrap();
        let uv_available = std::process::Command::new("uv")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        // Result should match uv availability
        assert_eq!(resolve_suggest_fix(true, temp_dir.path()), uv_available);
    }
}