provenant-cli 0.0.33

Rust-based ScanCode-compatible scanner for licenses, package metadata, SBOMs, and provenance data.
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
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{Result, anyhow};
use serde::Deserialize;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use crate::assembly;
use crate::models::{
    DiagnosticSeverity, FileInfo, FileType, LicenseIndexProvenance, LicenseReference,
    LicenseRuleReference, Package, TopLevelDependency, TopLevelLicenseDetection,
};
use crate::output_schema::{
    OutputFileInfo, OutputLicenseReference, OutputLicenseRuleReference, OutputMatch, OutputPackage,
    OutputTopLevelDependency, OutputTopLevelLicenseDetection,
};
use crate::scanner::ProcessResult;

type JsonInputParts = (
    ProcessResult,
    assembly::AssemblyResult,
    Vec<TopLevelLicenseDetection>,
    Vec<LicenseReference>,
    Vec<LicenseRuleReference>,
    Vec<String>,
    Option<String>,
    Option<LicenseIndexProvenance>,
);

#[cfg(test)]
#[path = "json_input_test.rs"]
mod json_input_test;

#[derive(Deserialize, Clone)]
pub(crate) struct JsonHeaderExtraDataInput {
    #[serde(default)]
    spdx_license_list_version: Option<String>,
    #[serde(default)]
    license_index_provenance: Option<LicenseIndexProvenance>,
}

#[derive(Deserialize)]
pub(crate) struct JsonHeaderInput {
    #[serde(default)]
    errors: Vec<String>,
    #[serde(default)]
    warnings: Vec<String>,
    #[serde(default)]
    extra_data: Option<JsonHeaderExtraDataInput>,
}

#[derive(Deserialize)]
pub(crate) struct JsonScanInput {
    #[serde(default)]
    pub(crate) headers: Vec<JsonHeaderInput>,
    #[serde(default)]
    pub(crate) files: Vec<OutputFileInfo>,
    #[serde(default)]
    pub(crate) packages: Vec<OutputPackage>,
    #[serde(default)]
    pub(crate) dependencies: Vec<OutputTopLevelDependency>,
    #[serde(default)]
    pub(crate) license_detections: Vec<OutputTopLevelLicenseDetection>,
    #[serde(default)]
    pub(crate) license_references: Vec<OutputLicenseReference>,
    #[serde(default)]
    pub(crate) license_rule_references: Vec<OutputLicenseRuleReference>,
    #[serde(default)]
    pub(crate) excluded_count: usize,
}

impl JsonScanInput {
    pub(crate) fn directory_count(&self) -> usize {
        self.files
            .iter()
            .filter(|file| file.file_type == FileType::Directory)
            .count()
    }

    pub(crate) fn file_count(&self) -> usize {
        self.files
            .iter()
            .filter(|file| file.file_type == FileType::File)
            .count()
    }

    pub(crate) fn file_size_count(&self) -> u64 {
        self.files
            .iter()
            .filter(|file| file.file_type == FileType::File)
            .map(|file| file.size)
            .sum()
    }

    pub(crate) fn into_parts(self) -> Result<JsonInputParts> {
        let imported_header_warnings: Vec<String> = self
            .headers
            .iter()
            .flat_map(|header| header.warnings.iter().cloned())
            .collect();
        let imported_header_errors: Vec<String> = self
            .headers
            .iter()
            .flat_map(|header| header.errors.iter().cloned())
            .collect();
        let _discarded_warning_count: usize = self
            .headers
            .iter()
            .map(|header| header.warnings.len())
            .sum();
        let mut files = self
            .files
            .iter()
            .map(FileInfo::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert file from JSON: {}", e))?;
        restore_imported_warning_severities(
            &mut files,
            &imported_header_warnings,
            &imported_header_errors,
        );
        let packages = self
            .packages
            .iter()
            .map(Package::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert package from JSON: {}", e))?;
        let dependencies = self
            .dependencies
            .iter()
            .map(TopLevelDependency::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert dependency from JSON: {}", e))?;
        let license_detections = self
            .license_detections
            .iter()
            .map(TopLevelLicenseDetection::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert license detection from JSON: {}", e))?;
        let license_references = self
            .license_references
            .iter()
            .map(LicenseReference::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert license reference from JSON: {}", e))?;
        let license_rule_references = self
            .license_rule_references
            .iter()
            .map(LicenseRuleReference::try_from)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| anyhow!("Failed to convert license rule reference from JSON: {}", e))?;

        let imported_spdx_license_list_version =
            consistent_header_value(self.headers.iter().filter_map(|header| {
                header
                    .extra_data
                    .as_ref()
                    .and_then(|extra_data| extra_data.spdx_license_list_version.clone())
            }));
        let imported_license_index_provenance =
            consistent_header_value(self.headers.iter().filter_map(|header| {
                header
                    .extra_data
                    .as_ref()
                    .and_then(|extra_data| extra_data.license_index_provenance.clone())
            }));

        let preserved_header_errors = self
            .headers
            .into_iter()
            .flat_map(
                |JsonHeaderInput {
                     errors,
                     warnings: _,
                     extra_data: _,
                 }| errors,
            )
            .filter(|error| !is_imported_file_summary_error(error, &files))
            .collect();

        Ok((
            ProcessResult {
                files,
                excluded_count: self.excluded_count,
            },
            assembly::AssemblyResult {
                packages,
                dependencies,
            },
            license_detections,
            license_references,
            license_rule_references,
            preserved_header_errors,
            imported_spdx_license_list_version,
            imported_license_index_provenance,
        ))
    }
}

fn consistent_header_value<T>(mut values: impl Iterator<Item = T>) -> Option<T>
where
    T: PartialEq,
{
    let first = values.next()?;
    values.all(|value| value == first).then_some(first)
}

fn is_imported_file_summary_error(error: &str, files: &[FileInfo]) -> bool {
    files
        .iter()
        .filter(|file| !file.scan_errors.is_empty())
        .any(|file| header_error_matches_file_summary(error, &file.path))
}

fn header_error_matches_file_summary(error: &str, path: &str) -> bool {
    let first_line = error.lines().next().unwrap_or(error).trim();

    first_line == format!("Path: {path}") || first_line.ends_with(&format!(": {path}"))
}

fn restore_imported_warning_severities(
    files: &mut [FileInfo],
    imported_header_warnings: &[String],
    imported_header_errors: &[String],
) {
    for file in files {
        if file.scan_errors.is_empty() {
            continue;
        }

        let warning_summary = imported_header_warnings
            .iter()
            .any(|warning| header_error_matches_file_summary(warning, &file.path));
        let error_summary = imported_header_errors
            .iter()
            .any(|error| header_error_matches_file_summary(error, &file.path));

        if warning_summary && !error_summary {
            for diagnostic in &mut file.scan_diagnostics {
                diagnostic.severity = DiagnosticSeverity::Warning;
            }
        }
    }
}

pub(crate) fn load_and_merge_json_inputs(
    input_paths: &[String],
    strip_root: bool,
    full_root: bool,
) -> Result<JsonScanInput> {
    let mut merged: Option<JsonScanInput> = None;
    let input_count = input_paths.len();
    for (index, input_path) in input_paths.iter().enumerate() {
        let mut loaded = load_scan_from_json(input_path)?;
        normalize_loaded_json_scan(&mut loaded, strip_root, full_root);
        if input_count > 1 {
            namespace_loaded_input(&mut loaded, index + 1);
        }

        if let Some(acc) = &mut merged {
            acc.files.append(&mut loaded.files);
            acc.packages.append(&mut loaded.packages);
            acc.dependencies.append(&mut loaded.dependencies);
            acc.license_detections
                .append(&mut loaded.license_detections);
            acc.license_references
                .append(&mut loaded.license_references);
            acc.license_rule_references
                .append(&mut loaded.license_rule_references);
            acc.headers.append(&mut loaded.headers);
            acc.excluded_count += loaded.excluded_count;
        } else {
            merged = Some(loaded);
        }
    }

    merged.ok_or_else(|| anyhow!("No input paths provided"))
}

fn namespace_loaded_input(loaded: &mut JsonScanInput, input_index: usize) {
    let original_paths: Vec<String> = loaded.files.iter().map(|file| file.path.clone()).collect();

    for file in &mut loaded.files {
        file.path = namespace_loaded_resource_path(&file.path, input_index);

        for package_data in &mut file.package_data {
            for file_reference in &mut package_data.file_references {
                file_reference.path =
                    namespace_loaded_resource_path(&file_reference.path, input_index);
            }
        }
    }

    for package in &mut loaded.packages {
        for datafile_path in &mut package.datafile_paths {
            *datafile_path = namespace_loaded_resource_path(datafile_path, input_index);
        }
    }

    for dependency in &mut loaded.dependencies {
        dependency.datafile_path =
            namespace_loaded_resource_path(&dependency.datafile_path, input_index);
    }

    normalize_loaded_header_paths(loaded, &original_paths);
}

fn namespace_loaded_resource_path(path: &str, input_index: usize) -> String {
    let trimmed = path.trim_matches('/');
    let relative = trimmed
        .strip_prefix("virtual_root/")
        .or_else(|| (trimmed == "virtual_root").then_some(""))
        .unwrap_or(trimmed);
    let base = format!("virtual_root/codebase-{input_index}");
    if relative.is_empty() {
        base
    } else {
        format!("{base}/{relative}")
    }
}

pub(crate) fn load_scan_from_json(path: &str) -> Result<JsonScanInput> {
    let input_path = Path::new(path);
    if !input_path.is_file() {
        return Err(anyhow!("--from-json input must be a valid file: {}", path));
    }

    let content = fs::read_to_string(input_path)?;
    let mut parsed: JsonScanInput = serde_json::from_str(&content)
        .map_err(|e| anyhow!("Input JSON scan file is not valid JSON: {path}: {e}"))?;

    backfill_imported_file_identity_fields(&mut parsed);
    synthesize_missing_directory_entries(&mut parsed);

    Ok(parsed)
}

fn backfill_imported_file_identity_fields(scan: &mut JsonScanInput) {
    for file in &mut scan.files {
        let path = Path::new(&file.path);

        if file.name.is_empty() {
            file.name = path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or_default()
                .to_string();
        }

        if file.base_name.is_empty() {
            file.base_name = path
                .file_stem()
                .and_then(|name| name.to_str())
                .unwrap_or_default()
                .to_string();
        }

        if file.extension.is_empty() {
            file.extension = path
                .extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| format!(".{ext}"))
                .unwrap_or_default();
        }
    }
}

fn synthesize_missing_directory_entries(scan: &mut JsonScanInput) {
    let mut seen_paths: HashSet<String> = scan.files.iter().map(|file| file.path.clone()).collect();
    let mut missing_dirs = Vec::new();

    for file in &scan.files {
        let mut current = Path::new(&file.path).parent();
        while let Some(parent) = current.and_then(|parent| parent.to_str()) {
            if parent.is_empty() || parent == "." {
                break;
            }
            if seen_paths.insert(parent.to_string()) {
                missing_dirs.push(parent.to_string());
            }
            current = Path::new(parent).parent();
        }
    }

    missing_dirs.sort_by_key(|path| path.matches('/').count());
    for dir_path in missing_dirs {
        scan.files.push(directory_output_json_file(&dir_path));
    }

    ensure_replay_root_directories(scan);
}

fn ensure_replay_root_directories(scan: &mut JsonScanInput) {
    let mut seen_paths: HashSet<String> = scan.files.iter().map(|file| file.path.clone()).collect();
    let mut replay_roots = HashSet::new();

    for file in &scan.files {
        let path = file.path.as_str();
        if path == "virtual_root" || path.starts_with("virtual_root/") {
            replay_roots.insert("virtual_root".to_string());
            if let Some(rest) = path.strip_prefix("virtual_root/")
                && let Some((first_component, _)) = rest.split_once('/')
                && first_component.starts_with("codebase-")
            {
                replay_roots.insert(format!("virtual_root/{first_component}"));
            }
        }
    }

    let mut replay_roots: Vec<_> = replay_roots.into_iter().collect();
    replay_roots.sort_by_key(|path| path.matches('/').count());
    for root in replay_roots {
        if seen_paths.insert(root.clone()) {
            scan.files.push(directory_output_json_file(&root));
        }
    }
}

fn directory_output_json_file(path: &str) -> OutputFileInfo {
    let path_obj = Path::new(path);
    let name = path_obj
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(path)
        .to_string();

    OutputFileInfo {
        name: name.clone(),
        base_name: name,
        extension: String::new(),
        path: path.to_string(),
        file_type: FileType::Directory,
        mime_type: None,
        file_type_label: None,
        size: 0,
        date: None,
        sha1: None,
        md5: None,
        sha256: None,
        sha1_git: None,
        programming_language: None,
        package_data: Vec::new(),
        license_expression: None,
        license_detections: Vec::new(),
        license_clues: Vec::new(),
        percentage_of_license_text: None,
        copyrights: Vec::new(),
        holders: Vec::new(),
        authors: Vec::new(),
        emails: Vec::new(),
        urls: Vec::new(),
        for_packages: Vec::new(),
        scan_errors: Vec::new(),
        license_policy: None,
        is_generated: None,
        is_binary: None,
        is_text: None,
        is_archive: None,
        is_media: None,
        is_source: None,
        is_script: None,
        files_count: None,
        dirs_count: None,
        size_count: None,
        source_count: None,
        is_legal: false,
        is_manifest: false,
        is_readme: false,
        is_top_level: false,
        is_key_file: false,
        is_community: false,
        facets: Vec::new(),
        tallies: None,
    }
}

pub(crate) fn normalize_loaded_json_scan(
    loaded: &mut JsonScanInput,
    strip_root: bool,
    full_root: bool,
) {
    let initial_paths: Vec<String> = loaded.files.iter().map(|file| file.path.clone()).collect();

    if should_prefix_loaded_paths_with_virtual_root(loaded, strip_root, full_root) {
        prefix_loaded_resource_paths_with_virtual_root(loaded);
        normalize_loaded_header_paths(loaded, &initial_paths);
    }

    let original_paths: Vec<String> = loaded.files.iter().map(|file| file.path.clone()).collect();

    if let Some(scan_root) = derive_json_scan_root(&loaded.files)
        && strip_root
    {
        normalize_output_paths(&mut loaded.files, &scan_root, true, false);
        normalize_loaded_top_level_detection_paths(loaded, &scan_root, true, false);
        normalize_output_top_level_paths(
            &mut loaded.packages,
            &mut loaded.dependencies,
            &scan_root,
            true,
        );
    }

    if full_root {
        trim_loaded_json_full_root_paths(loaded);
    }

    synthesize_missing_directory_entries(loaded);

    normalize_loaded_header_paths(loaded, &original_paths);
}

fn should_prefix_loaded_paths_with_virtual_root(
    loaded: &JsonScanInput,
    strip_root: bool,
    full_root: bool,
) -> bool {
    if strip_root || full_root || loaded.files.len() <= 1 {
        return false;
    }

    let mut saw_relative = false;
    for file in &loaded.files {
        let path = Path::new(&file.path);
        if path.is_absolute() {
            return false;
        }
        if file.path == "virtual_root" || file.path.starts_with("virtual_root/") {
            return false;
        }
        saw_relative = true;
    }

    saw_relative
}

fn prefix_loaded_resource_paths_with_virtual_root(loaded: &mut JsonScanInput) {
    for file in &mut loaded.files {
        file.path = prefix_virtual_root(&file.path);

        for package_data in &mut file.package_data {
            for file_reference in &mut package_data.file_references {
                file_reference.path = prefix_virtual_root(&file_reference.path);
            }
        }
    }

    for package in &mut loaded.packages {
        for datafile_path in &mut package.datafile_paths {
            *datafile_path = prefix_virtual_root(datafile_path);
        }
    }

    for dependency in &mut loaded.dependencies {
        dependency.datafile_path = prefix_virtual_root(&dependency.datafile_path);
    }
}

fn prefix_virtual_root(path: &str) -> String {
    let trimmed = path.trim_start_matches('/');
    if trimmed.is_empty() {
        "virtual_root".to_string()
    } else {
        format!("virtual_root/{trimmed}")
    }
}

fn derive_json_scan_root(files: &[OutputFileInfo]) -> Option<String> {
    let mut directories: Vec<&str> = files
        .iter()
        .filter(|file| file.file_type == FileType::Directory)
        .map(|file| file.path.as_str())
        .collect();
    directories.sort_by_key(|path| (path.matches('/').count(), path.len()));
    if let Some(root_dir) = directories.first() {
        return Some((*root_dir).to_string());
    }

    if files.len() == 1 {
        return files.first().map(|file| file.path.clone());
    }

    let paths: Vec<String> = files.iter().map(|file| file.path.clone()).collect();
    super::selection::common_path_prefix(&paths).map(|path| path.to_string_lossy().to_string())
}

fn trim_loaded_json_full_root_paths(loaded: &mut JsonScanInput) {
    for file in &mut loaded.files {
        trim_full_root_display_value(&mut file.path);
        for detection_match in &mut file.license_clues {
            if let Some(from_file) = detection_match.from_file.as_mut() {
                trim_full_root_display_value(from_file);
            }
        }
        for detection in &mut file.license_detections {
            for detection_match in &mut detection.matches {
                if let Some(from_file) = detection_match.from_file.as_mut() {
                    trim_full_root_display_value(from_file);
                }
            }
        }
        for package_data in &mut file.package_data {
            for file_reference in &mut package_data.file_references {
                trim_full_root_display_value(&mut file_reference.path);
            }
            for detection in &mut package_data.license_detections {
                for detection_match in &mut detection.matches {
                    if let Some(from_file) = detection_match.from_file.as_mut() {
                        trim_full_root_display_value(from_file);
                    }
                }
            }
            for detection in &mut package_data.other_license_detections {
                for detection_match in &mut detection.matches {
                    if let Some(from_file) = detection_match.from_file.as_mut() {
                        trim_full_root_display_value(from_file);
                    }
                }
            }
        }
    }

    for package in &mut loaded.packages {
        for datafile_path in &mut package.datafile_paths {
            trim_full_root_display_value(datafile_path);
        }
    }
    for dependency in &mut loaded.dependencies {
        trim_full_root_display_value(&mut dependency.datafile_path);
    }

    normalize_loaded_top_level_detection_paths(loaded, "", false, true);
}

fn trim_full_root_display_value(path: &mut String) {
    *path = path.replace('\\', "/").trim_matches('/').to_string();
}

fn normalize_loaded_top_level_detection_paths(
    loaded: &mut JsonScanInput,
    scan_root: &str,
    strip_root: bool,
    full_root: bool,
) {
    for detection in &mut loaded.license_detections {
        for detection_match in &mut detection.reference_matches {
            if let Some(from_file) = detection_match.from_file.as_mut() {
                if strip_root
                    && let Some(normalized) =
                        normalize_loaded_detection_path(from_file, scan_root, true, false)
                {
                    *from_file = normalized;
                }
                if full_root
                    && let Some(normalized) =
                        normalize_loaded_detection_path(from_file, scan_root, false, true)
                {
                    *from_file = normalized;
                }
            }
        }
    }
}

fn normalize_loaded_header_paths(loaded: &mut JsonScanInput, original_paths: &[String]) {
    let mut replacements: Vec<_> = original_paths
        .iter()
        .zip(loaded.files.iter().map(|file| file.path.as_str()))
        .filter(|(before, after)| before.as_str() != *after)
        .map(|(before, after)| (before.as_str(), after))
        .collect();
    replacements.sort_by_key(|replacement| std::cmp::Reverse(replacement.0.len()));

    for header in &mut loaded.headers {
        for error in &mut header.errors {
            normalize_loaded_header_message(error, &replacements);
        }
        for warning in &mut header.warnings {
            normalize_loaded_header_message(warning, &replacements);
        }
    }
}

fn normalize_loaded_header_message(message: &mut String, replacements: &[(&str, &str)]) {
    for (before, after) in replacements {
        if let Some(remainder) = message.strip_prefix(&format!("Path: {before}")) {
            *message = format!("Path: {after}{remainder}");
            break;
        }
        if let Some((first_line, remainder)) = message.split_once('\n')
            && first_line.ends_with(&format!(": {before}"))
        {
            *message = format!(
                "{}: {after}\n{remainder}",
                &first_line[..first_line.len() - before.len() - 2]
            );
            break;
        }
        if message.ends_with(before) {
            let prefix_len = message.len() - before.len();
            message.replace_range(prefix_len.., after);
            break;
        }
    }
}

fn normalize_loaded_detection_path(
    path: &str,
    scan_root: &str,
    strip_root: bool,
    full_root: bool,
) -> Option<String> {
    let current_path = PathBuf::from(path);

    if full_root {
        let absolute_candidate = if current_path.is_absolute() {
            current_path.clone()
        } else {
            env::current_dir()
                .map(|cwd| cwd.join(&current_path))
                .unwrap_or(current_path.clone())
        };
        let absolute = absolute_candidate
            .canonicalize()
            .unwrap_or(absolute_candidate);
        return Some(
            absolute
                .to_string_lossy()
                .replace('\\', "/")
                .trim_matches('/')
                .to_string(),
        );
    }

    if strip_root {
        let scan_root_path = Path::new(scan_root);
        let strip_base = if scan_root_path.is_file() {
            scan_root_path.parent().unwrap_or_else(|| Path::new(""))
        } else {
            scan_root_path
        };

        if current_path == scan_root_path
            && let Some(file_name) = scan_root_path.file_name().and_then(|name| name.to_str())
        {
            return Some(file_name.to_string());
        }

        if let Ok(stripped) = current_path.strip_prefix(strip_base)
            && !stripped.as_os_str().is_empty()
        {
            return Some(stripped.to_string_lossy().to_string());
        }
    }

    None
}

fn normalize_output_paths(
    files: &mut [OutputFileInfo],
    scan_root: &str,
    strip_root: bool,
    full_root: bool,
) {
    for entry in files.iter_mut() {
        if let Some(normalized_path) =
            normalize_path_value(&entry.path, scan_root, strip_root, full_root)
        {
            entry.path = normalized_path;
        }

        normalize_output_match_paths(&mut entry.license_clues, scan_root, strip_root, full_root);

        for detection in &mut entry.license_detections {
            normalize_output_match_paths(&mut detection.matches, scan_root, strip_root, full_root);
        }

        for package_data in &mut entry.package_data {
            for file_reference in &mut package_data.file_references {
                if let Some(normalized_path) =
                    normalize_path_value(&file_reference.path, scan_root, strip_root, full_root)
                {
                    file_reference.path = normalized_path;
                }
            }

            for detection in &mut package_data.license_detections {
                normalize_output_match_paths(
                    &mut detection.matches,
                    scan_root,
                    strip_root,
                    full_root,
                );
            }

            for detection in &mut package_data.other_license_detections {
                normalize_output_match_paths(
                    &mut detection.matches,
                    scan_root,
                    strip_root,
                    full_root,
                );
            }
        }
    }
}

fn normalize_output_match_paths(
    matches: &mut [OutputMatch],
    scan_root: &str,
    strip_root: bool,
    full_root: bool,
) {
    for detection_match in matches {
        if let Some(from_file) = detection_match.from_file.as_mut()
            && let Some(normalized_path) =
                normalize_path_value(from_file.as_str(), scan_root, strip_root, full_root)
        {
            *from_file = normalized_path;
        }
    }
}

fn normalize_path_value(
    path: &str,
    scan_root: &str,
    strip_root: bool,
    full_root: bool,
) -> Option<String> {
    let current_path = PathBuf::from(path);

    if full_root {
        let absolute_candidate = if current_path.is_absolute() {
            current_path.clone()
        } else {
            env::current_dir()
                .map(|cwd| cwd.join(&current_path))
                .unwrap_or(current_path.clone())
        };
        let absolute = absolute_candidate
            .canonicalize()
            .unwrap_or(absolute_candidate);
        return Some(
            absolute
                .to_string_lossy()
                .replace('\\', "/")
                .trim_matches('/')
                .to_string(),
        );
    }

    if strip_root {
        let scan_root_path = Path::new(scan_root);
        let strip_base = if scan_root_path.is_file() {
            scan_root_path.parent().unwrap_or_else(|| Path::new(""))
        } else {
            scan_root_path
        };

        if current_path == scan_root_path
            && let Some(file_name) = scan_root_path.file_name().and_then(|name| name.to_str())
        {
            return Some(file_name.to_string());
        }

        if let Some(stripped) = strip_root_prefix(&current_path, strip_base) {
            return Some(stripped.to_string_lossy().to_string());
        }
    }

    None
}

fn strip_root_prefix(path: &Path, root: &Path) -> Option<PathBuf> {
    if let Ok(stripped) = path.strip_prefix(root)
        && !stripped.as_os_str().is_empty()
    {
        return Some(stripped.to_path_buf());
    }

    let canonical_path = path.canonicalize().ok()?;
    let canonical_root = root.canonicalize().ok()?;
    let stripped = canonical_path.strip_prefix(canonical_root).ok()?;
    if stripped.as_os_str().is_empty() {
        None
    } else {
        Some(stripped.to_path_buf())
    }
}

fn normalize_output_top_level_paths(
    packages: &mut [OutputPackage],
    dependencies: &mut [OutputTopLevelDependency],
    scan_root: &str,
    strip_root: bool,
) {
    if !strip_root {
        return;
    }

    for package in packages {
        for datafile_path in &mut package.datafile_paths {
            if let Some(normalized_path) =
                normalize_path_value(datafile_path, scan_root, true, false)
            {
                *datafile_path = normalized_path;
            }
        }
    }

    for dependency in dependencies {
        if let Some(normalized_path) =
            normalize_path_value(&dependency.datafile_path, scan_root, true, false)
        {
            dependency.datafile_path = normalized_path;
        }
    }
}