comply 0.1.1

REUSE Specification compliance tool and library: lint, annotate, and fix SPDX license headers
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
// SPDX-FileCopyrightText: COMPLY contributors
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::{Path, PathBuf};

use crate::error::Error;

mod dep5;
mod glob;
mod reuse_toml;

pub use dep5::Dep5Document;

pub(crate) use glob::{glob_match, glob_to_regex};

/// The licensing that applies to one file, after any REUSE.toml annotation has
/// been combined with the file's own header according to its precedence.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Licensing {
    /// Copyright notices, in the order REUSE reports them.
    pub copyrights: Vec<String>,
    /// SPDX license expression, if anything declared one.
    pub license: Option<String>,
}

/// Precedence of an annotation per REUSE spec 3.3.
///
/// The discriminants are the sort rank, ascending, so ordering a set of
/// annotations is a cast rather than a `match`. That is not a micro-
/// optimisation: the `match` this replaced lived in a small function the
/// optimiser folded away on some targets but not others, so its arms measured
/// as covered on arm64 and uncovered on the `x86_64` CI runner, and the 100%
/// gate failed on a line every test executes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum Precedence {
    /// File's own header takes precedence, REUSE.toml is fallback.
    #[default]
    Closest = 0,
    /// Always aggregate with file's own licensing info.
    Aggregate = 1,
    /// Override any file-local licensing info.
    Override = 2,
}

/// An annotation for a set of files, specifying copyright and licensing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Annotation {
    /// Glob pattern matching the files (e.g. `"src/**"`).
    pub path: String,
    /// SPDX copyright text lines.
    pub copyright: Vec<String>,
    /// SPDX license identifier (e.g. `"MIT OR Apache-2.0"`).
    pub license: String,
    /// Precedence of this annotation.
    pub precedence: Precedence,
}

/// Traversal switches, each overridable from `[tool.comply.walk]`.
///
/// These were hardcoded at the one `WalkBuilder` call site. They are choices
/// about what counts as a project file, so they belong beside `ignore` in the
/// manifest rather than baked into the binary. Anything a project does not name
/// keeps the default below.
// Six bools trips `struct_excessive_bools`, which exists to discourage
// boolean-blind parameter lists. These are not parameters: each one maps 1:1
// onto a `WalkBuilder` setter of the same name, and grouping or re-typing them
// would hide that correspondence rather than clarify it.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WalkOptions {
    /// Skip dotfiles. Off by default -- a hidden file still needs a license.
    pub hidden: bool,
    /// Apply `.gitignore` files.
    pub git_ignore: bool,
    /// Apply the user's global excludes file.
    pub git_global: bool,
    /// Apply `.git/info/exclude`.
    pub git_exclude: bool,
    /// Only apply gitignore rules inside an actual repository.
    pub require_git: bool,
    /// Follow symlinks. Off by default -- the target is covered in its own
    /// right, and writing through a link edits a file nobody named.
    pub follow_links: bool,
}

impl WalkOptions {
    /// The built-in defaults, spelled out as a const so `ConfigBuilder::new`
    /// stays usable in const context.
    pub const DEFAULT: Self = Self {
        hidden: false,
        git_ignore: true,
        git_global: true,
        git_exclude: true,
        require_git: false,
        follow_links: false,
    };
}

impl Default for WalkOptions {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Whether `haystack` already declares every identifier in `needle`.
///
/// `fix` re-reads the header it wrote, so aggregating without this check grows
/// the expression by one `AND` per run -- a file was observed carrying
/// `MIT OR Apache-2.0 AND MIT OR Apache-2.0 AND BSD-3-Clause AND BSD-3-Clause`.
///
/// Identifier sets rather than string equality, because the two sides are
/// written by different hands: `MIT AND BSD-3-Clause` already covers `MIT`,
/// which a textual comparison cannot see. When either side does not parse there
/// are no identifiers to compare, and the raw text is the only answer left.
fn already_covers(haystack: &str, needle: &str) -> bool {
    let (Ok(have), Ok(want)) = (crate::spdx::parse(haystack), crate::spdx::parse(needle)) else {
        return haystack == needle;
    };

    let have = have.identifiers();
    want.identifiers().iter().all(|id| have.contains(id))
}

/// A comment syntax a project declares in `[[tool.comply.comment-styles]]`.
///
/// One rule covers every extension or filename that shares a syntax -- eleven
/// extensions share `#` among the built-ins, so a table per key would mean
/// eleven near-identical blocks.
///
/// `close` empty means a line style. `line` is the per-line prefix inside a
/// block, which is what a C-style `/* * */` header needs and what nothing else
/// here can express.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommentStyleRule {
    /// Extensions this rule claims, without the leading dot.
    pub extensions: Vec<String>,
    /// Exact filenames this rule claims, for files that carry no extension.
    pub filenames: Vec<String>,
    /// Opening delimiter, or the whole prefix for a line style.
    pub open: String,
    /// Prefix repeated on each header line inside a block; often empty.
    pub line: String,
    /// Closing delimiter; empty for a line style.
    pub close: String,
}

/// Parsed REUSE configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// Annotations from REUSE.toml.
    pub annotations: Vec<Annotation>,
    /// Default license for files without explicit annotation.
    pub default_license: Option<String>,
    /// Default copyright for files without explicit annotation.
    pub default_copyright: Vec<String>,
    /// Glob patterns for files to ignore during REUSE analysis.
    pub ignore: Vec<String>,
    /// SPDX-PackageName (root-level REUSE.toml metadata).
    pub spdx_package_name: Option<String>,
    /// SPDX-PackageSupplier (root-level REUSE.toml metadata).
    pub spdx_package_supplier: Option<String>,
    /// Custom glob patterns for source files (extends default classification).
    pub source_patterns: Vec<String>,
    /// Traversal switches from `[tool.comply.walk]`.
    pub walk: WalkOptions,
    /// Comment syntaxes from `[[tool.comply.comment-styles]]`, in parse order.
    ///
    /// Order is the identity: a `CommentStyle::Custom(i)` indexes straight into
    /// this list, which is what keeps the style `Copy`.
    pub comment_styles: Vec<CommentStyleRule>,
}

impl Config {
    /// Find the first existing config file among the three allowed names:
    /// `.reuse.toml`, `reuse.toml`, `REUSE.toml`.
    fn find_config(root: &Path) -> Option<PathBuf> {
        let candidates = [".reuse.toml", "reuse.toml", "REUSE.toml"];
        for name in &candidates {
            let path = root.join(name);
            if path.exists() {
                return Some(path);
            }
        }
        None
    }

    /// Load config from `REUSE.toml` (or `.reuse.toml` / `reuse.toml` fallbacks)
    /// in the project root.
    ///
    /// Per REUSE Specification 3.3, REUSE.toml and `.reuse/dep5` are mutually
    /// exclusive. If a REUSE.toml variant exists, `.reuse/dep5` is ignored.
    #[allow(clippy::missing_errors_doc)]
    pub fn load(root: &Path) -> Result<Self, Error> {
        let dep5_path = root.join(".reuse/dep5");

        if let Some(path) = Self::find_config(root) {
            // REUSE 3.3: a project declares licensing through REUSE.toml or
            // DEP5, never both -- merging them would silently invent a
            // precedence the spec does not define.
            if dep5_path.exists() {
                return Err(Error::Serde(format!(
                    "{} and .reuse/dep5 both declare licensing; \
                     REUSE 3.3 allows only one of them",
                    path.file_name()
                        .unwrap_or(path.as_os_str())
                        .to_string_lossy()
                )));
            }
            return Self::from_toml(&path);
        }

        if dep5_path.exists() {
            let annotations = Self::from_dep5(&dep5_path)?;
            return Ok(Self {
                annotations,
                default_license: None,
                default_copyright: vec![],
                ignore: vec![],
                spdx_package_name: None,
                spdx_package_supplier: None,
                source_patterns: vec![],
                walk: WalkOptions::default(),
                comment_styles: vec![],
            });
        }

        Ok(Self {
            annotations: vec![],
            default_license: None,
            default_copyright: vec![],
            ignore: vec![],
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: vec![],
            walk: WalkOptions::default(),
            comment_styles: vec![],
        })
    }

    /// Find annotations matching the given relative path.
    #[must_use]
    pub fn match_annotations<'a>(&'a self, rel_path: &str) -> Vec<&'a Annotation> {
        // REUSE annotation globs are always forward-slash. Normalising here
        // means no caller has to remember to do it -- and none can forget.
        let rel_path = rel_path.replace('\\', "/");
        let mut matched: Vec<&Annotation> = self
            .annotations
            .iter()
            .filter(|a| glob_match(&a.path, &rel_path))
            .collect();

        // Override last (highest precedence), then aggregate, then closest --
        // which is the discriminant order `Precedence` declares.
        matched.sort_by_key(|a| a.precedence as u8);

        matched
    }

    /// Combine a file's own header with the REUSE.toml annotation covering it,
    /// honouring that annotation's precedence (REUSE 3.3 section 2.3.2).
    ///
    /// The three modes differ in more than emphasis: `closest` falls back field
    /// by field, `aggregate` unions field by field, but `override` replaces the
    /// header outright -- so an override annotation that omits a copyright
    /// leaves the file with none.
    #[must_use]
    pub fn resolve_licensing(
        &self,
        rel_path: &str,
        header_copyrights: &[String],
        header_license: Option<&str>,
    ) -> Licensing {
        let matched = self.match_annotations(rel_path);
        let header = || Licensing {
            copyrights: header_copyrights.to_vec(),
            license: header_license.map(ToString::to_string),
        };

        let Some(anno) = matched.last() else {
            return header();
        };
        let anno_license = (!anno.license.is_empty()).then(|| anno.license.clone());

        match anno.precedence {
            Precedence::Override => Licensing {
                copyrights: anno.copyright.clone(),
                license: anno_license,
            },
            Precedence::Aggregate => {
                let mut copyrights = anno.copyright.clone();
                for c in header_copyrights {
                    if !copyrights.contains(c) {
                        copyrights.push(c.clone());
                    }
                }
                let license = match (anno_license, header_license) {
                    (Some(a), Some(h)) if !already_covers(h, &a) => Some(format!("{a} AND {h}")),
                    (Some(_), Some(h)) => Some(h.to_string()),
                    (Some(a), None) => Some(a),
                    (None, h) => h.map(ToString::to_string),
                };
                Licensing {
                    copyrights,
                    license,
                }
            }
            Precedence::Closest => Licensing {
                copyrights: if header_copyrights.is_empty() {
                    anno.copyright.clone()
                } else {
                    header_copyrights.to_vec()
                },
                license: header_license.map(ToString::to_string).or(anno_license),
            },
        }
    }

    /// Create a new `ConfigBuilder` for fluent construction.
    #[must_use]
    pub const fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }
}

/// A fluent builder for constructing `Config` instances.
#[derive(Debug, Default)]
pub struct ConfigBuilder {
    annotations: Vec<Annotation>,
    default_license: Option<String>,
    default_copyright: Vec<String>,
    ignore: Vec<String>,
    spdx_package_name: Option<String>,
    spdx_package_supplier: Option<String>,
    source_patterns: Vec<String>,
    walk: WalkOptions,
}

impl ConfigBuilder {
    const fn new() -> Self {
        Self {
            annotations: Vec::new(),
            default_license: None,
            default_copyright: Vec::new(),
            ignore: Vec::new(),
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: Vec::new(),
            walk: WalkOptions::DEFAULT,
        }
    }

    /// Add an annotation to the config.
    #[must_use]
    pub fn add_annotation(mut self, annotation: Annotation) -> Self {
        self.annotations.push(annotation);
        self
    }

    /// Set the default license for files without explicit annotation.
    #[must_use]
    pub fn default_license(mut self, license: impl Into<String>) -> Self {
        self.default_license = Some(license.into());
        self
    }

    /// Add a default copyright line.
    #[must_use]
    pub fn add_default_copyright(mut self, copyright: impl Into<String>) -> Self {
        self.default_copyright.push(copyright.into());
        self
    }

    /// Set the ignore patterns for files to skip during analysis.
    #[must_use]
    pub fn ignore(mut self, patterns: Vec<String>) -> Self {
        self.ignore = patterns;
        self
    }

    /// Add a single ignore pattern.
    #[must_use]
    pub fn add_ignore(mut self, pattern: impl Into<String>) -> Self {
        self.ignore.push(pattern.into());
        self
    }

    /// Set SPDX-PackageName.
    #[must_use]
    pub fn spdx_package_name(mut self, name: impl Into<String>) -> Self {
        self.spdx_package_name = Some(name.into());
        self
    }

    /// Set SPDX-PackageSupplier.
    #[must_use]
    pub fn spdx_package_supplier(mut self, supplier: impl Into<String>) -> Self {
        self.spdx_package_supplier = Some(supplier.into());
        self
    }

    /// Add source patterns to extend default source file classification.
    #[must_use]
    pub fn source_patterns(mut self, patterns: Vec<String>) -> Self {
        self.source_patterns = patterns;
        self
    }

    /// Add a single source pattern.
    #[must_use]
    pub fn add_source_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.source_patterns.push(pattern.into());
        self
    }

    /// Consume the builder and produce a `Config`.
    #[must_use]
    pub fn build(self) -> Config {
        Config {
            annotations: self.annotations,
            default_license: self.default_license,
            default_copyright: self.default_copyright,
            ignore: self.ignore,
            spdx_package_name: self.spdx_package_name,
            spdx_package_supplier: self.spdx_package_supplier,
            source_patterns: self.source_patterns,
            walk: self.walk,
            comment_styles: Vec::new(),
        }
    }
}

// REUSE-IgnoreStart
#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;

    mod config_guards {
        use super::*;
        use tempfile::TempDir;

        fn project(files: &[(&str, &str)]) -> TempDir {
            let tmp = TempDir::new().unwrap();
            for (rel, body) in files {
                let path = tmp.path().join(rel);
                if let Some(parent) = path.parent() {
                    fs::create_dir_all(parent).unwrap();
                }
                fs::write(path, body).unwrap();
            }
            tmp
        }

        const VALID: &str = "version = 1\n";
        const DEP5: &str = concat!(
            "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n",
            "Files: src/*\nCopyright: 2026 A\nLicense: MIT\n"
        );

        #[test]
        fn a_reuse_toml_without_a_version_key_is_rejected() {
            let tmp = project(&[("REUSE.toml", "[[annotations]]\npath = [\"src/**\"]\n")]);

            let err = Config::load(tmp.path()).unwrap_err().to_string();

            assert!(
                err.contains("version"),
                "the spec makes `version` REQUIRED; got: {err}"
            );
        }

        #[test]
        fn a_reuse_toml_with_a_version_key_loads() {
            let tmp = project(&[("REUSE.toml", VALID)]);

            assert!(Config::load(tmp.path()).is_ok());
        }

        #[test]
        fn declaring_licensing_in_both_reuse_toml_and_dep5_is_rejected() {
            let tmp = project(&[("REUSE.toml", VALID), (".reuse/dep5", DEP5)]);

            // Lower-cased: `find_config` reports whichever spelling it matched,
            // and a case-insensitive filesystem may match `reuse.toml` first.
            let err = Config::load(tmp.path())
                .unwrap_err()
                .to_string()
                .to_lowercase();

            assert!(
                err.contains("reuse.toml") && err.contains("dep5"),
                "the error should name both files; got: {err}"
            );
        }

        #[test]
        fn dep5_alone_still_loads() {
            let tmp = project(&[(".reuse/dep5", DEP5)]);

            assert!(Config::load(tmp.path()).is_ok());
        }

        #[test]
        fn a_malformed_reuse_toml_names_the_file_it_could_not_parse() {
            let tmp = project(&[("REUSE.toml", "this is = = not toml\n")]);

            let err = Config::load(tmp.path())
                .unwrap_err()
                .to_string()
                .to_lowercase();

            assert!(
                err.contains("reuse.toml"),
                "a broken manifest must be named, not reported as missing copyrights; got: {err}"
            );
        }
    }

    /// Expected values in these tests are the observed output of the reference
    /// `reuse` 6.2.0 implementation on equivalent fixtures, since REUSE 3.3
    /// describes precedence in prose only.
    mod precedence {
        use super::*;

        fn config_with(precedence: Precedence, copyright: &[&str], license: &str) -> Config {
            Config::builder()
                .add_annotation(Annotation {
                    path: "src/**".into(),
                    copyright: copyright.iter().map(ToString::to_string).collect(),
                    license: license.into(),
                    precedence,
                })
                .build()
        }

        #[test]
        fn closest_prefers_the_header_field_by_field() {
            let config = config_with(Precedence::Closest, &["2026 New"], "MIT");

            // A header supplying only a copyright keeps it, and takes the
            // licence from the annotation.
            let r = config.resolve_licensing("src/a.rs", &["2001 Old".into()], None);
            assert_eq!(r.copyrights, vec!["2001 Old"]);
            assert_eq!(r.license.as_deref(), Some("MIT"));

            // ... and the mirror image: the licence is the header's, the
            // copyright comes from the annotation.
            let r = config.resolve_licensing("src/a.rs", &[], Some("GPL-3.0-only"));
            assert_eq!(r.copyrights, vec!["2026 New"]);
            assert_eq!(r.license.as_deref(), Some("GPL-3.0-only"));
        }

        #[test]
        fn closest_falls_back_entirely_when_the_file_declares_nothing() {
            let config = config_with(Precedence::Closest, &["2026 New"], "MIT");

            let r = config.resolve_licensing("src/a.rs", &[], None);

            assert_eq!(r.copyrights, vec!["2026 New"]);
            assert_eq!(r.license.as_deref(), Some("MIT"));
        }

        #[test]
        fn aggregate_unions_both_with_the_annotation_first() {
            let config = config_with(Precedence::Aggregate, &["2026 New"], "MIT");

            let r =
                config.resolve_licensing("src/a.rs", &["2001 Old".into()], Some("GPL-3.0-only"));

            assert_eq!(r.copyrights, vec!["2026 New", "2001 Old"]);
            assert_eq!(
                r.license.as_deref(),
                Some("MIT AND GPL-3.0-only"),
                "a file covered by both licences is the conjunction of them"
            );
        }

        #[test]
        fn aggregate_does_not_repeat_a_licence_the_header_already_carries() {
            // `fix` re-reads the header it wrote, so an unconditional merge
            // grows the expression on every run. Observed in the wild as
            // `MIT OR Apache-2.0 AND MIT OR Apache-2.0 AND BSD-3-Clause AND
            // BSD-3-Clause`, one `AND` per invocation.
            let config = config_with(Precedence::Aggregate, &["2026 A"], "MIT");

            let r = config.resolve_licensing("src/a.rs", &[], Some("MIT AND BSD-3-Clause"));

            assert_eq!(r.license.as_deref(), Some("MIT AND BSD-3-Clause"));
        }

        #[test]
        fn aggregate_still_adds_a_licence_the_header_lacks() {
            let config = config_with(Precedence::Aggregate, &["2026 A"], "MIT");

            let r = config.resolve_licensing("src/a.rs", &[], Some("BSD-3-Clause"));

            assert_eq!(r.license.as_deref(), Some("MIT AND BSD-3-Clause"));
        }

        #[test]
        fn an_unparseable_header_expression_falls_back_to_comparing_the_text() {
            // Neither side parses, so identifier coverage cannot be computed;
            // equality of the raw strings is the only honest answer left.
            let config = config_with(Precedence::Aggregate, &["2026 A"], "MIT AND AND");

            let same = config.resolve_licensing("src/a.rs", &[], Some("MIT AND AND"));
            let other = config.resolve_licensing("src/b.rs", &[], Some("GPL-3.0-only"));

            assert_eq!(same.license.as_deref(), Some("MIT AND AND"));
            assert_eq!(
                other.license.as_deref(),
                Some("MIT AND AND AND GPL-3.0-only")
            );
        }

        #[test]
        fn aggregate_does_not_repeat_a_copyright_both_sides_declare() {
            let config = config_with(Precedence::Aggregate, &["2026 Acme"], "MIT");

            let r = config.resolve_licensing("src/a.rs", &["2026 Acme".into()], None);

            assert_eq!(
                r.copyrights,
                vec!["2026 Acme"],
                "the same holder declared twice is still one copyright"
            );
        }

        #[test]
        fn override_replaces_the_header_wholesale() {
            let config = config_with(Precedence::Override, &["2026 New"], "MIT");

            let r =
                config.resolve_licensing("src/a.rs", &["2001 Old".into()], Some("GPL-3.0-only"));

            assert_eq!(r.copyrights, vec!["2026 New"]);
            assert_eq!(r.license.as_deref(), Some("MIT"));
        }

        #[test]
        fn override_discards_a_field_it_does_not_itself_supply() {
            // Deliberately counter-intuitive, and confirmed against `reuse`:
            // an override annotation carrying only a licence leaves the file
            // with NO copyright, which makes it non-compliant.
            let config = config_with(Precedence::Override, &[], "MIT");

            let r =
                config.resolve_licensing("src/a.rs", &["2001 Old".into()], Some("GPL-3.0-only"));

            assert!(r.copyrights.is_empty());
            assert_eq!(r.license.as_deref(), Some("MIT"));
        }

        #[test]
        fn a_file_no_annotation_matches_keeps_its_own_header() {
            let config = config_with(Precedence::Override, &["2026 New"], "MIT");

            let r =
                config.resolve_licensing("docs/x.md", &["2001 Old".into()], Some("GPL-3.0-only"));

            assert_eq!(r.copyrights, vec!["2001 Old"]);
            assert_eq!(r.license.as_deref(), Some("GPL-3.0-only"));
        }
    }

    #[test]
    fn config_builder_chain() {
        let config = Config::builder()
            .add_annotation(Annotation {
                path: "*.rs".into(),
                copyright: vec!["2026 Author".into()],
                license: "MIT".into(),
                precedence: Precedence::Closest,
            })
            .default_license("MIT")
            .add_default_copyright("2026 Project")
            .build();
        assert_eq!(config.annotations.len(), 1);
        assert_eq!(config.default_license.as_deref(), Some("MIT"));
        assert_eq!(config.default_copyright, vec!["2026 Project"]);
    }

    #[test]
    fn config_builder_with_spdx_metadata() {
        let config = Config::builder()
            .spdx_package_name("comply")
            .spdx_package_supplier("COMPLY contributors")
            .build();
        assert_eq!(config.spdx_package_name.as_deref(), Some("comply"));
        assert_eq!(
            config.spdx_package_supplier.as_deref(),
            Some("COMPLY contributors")
        );
    }

    #[test]
    fn config_builder_empty() {
        let config = Config::builder().build();
        assert!(config.annotations.is_empty());
        assert!(config.default_license.is_none());
        assert!(config.default_copyright.is_empty());
    }

    #[test]
    fn match_no_annotation() {
        let config = Config {
            annotations: vec![],
            default_license: None,
            default_copyright: vec![],
            ignore: vec![],
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: vec![],
            walk: WalkOptions::default(),
            comment_styles: vec![],
        };

        let matched = config.match_annotations("src/lib.rs");
        assert!(matched.is_empty());
    }

    #[test]
    fn parse_annotations_plural() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("REUSE.toml");
        let mut f = fs::File::create(&path).unwrap();
        writeln!(
            f,
            r#"
version = 1

[[annotations]]
path = ["src/*.rs", "src/*.py"]
SPDX-FileCopyrightText = "2026 COMPLY contributors"
SPDX-License-Identifier = "MIT OR Apache-2.0"

[[annotations]]
path = "tests/*"
SPDX-FileCopyrightText = "2026 Testers"
SPDX-License-Identifier = "MIT"
"#
        )
        .unwrap();

        let config = Config::from_toml(&path).unwrap();
        assert_eq!(config.annotations.len(), 3);
        assert_eq!(config.annotations[0].path, "src/*.rs");
        assert_eq!(config.annotations[1].path, "src/*.py");
        assert_eq!(config.annotations[2].path, "tests/*");
    }

    #[test]
    fn parse_license_id_as_list() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("REUSE.toml");
        let mut f = fs::File::create(&path).unwrap();
        writeln!(
            f,
            r#"
version = 1

[[annotations]]
path = "dual/*"
SPDX-FileCopyrightText = "2026 Author"
SPDX-License-Identifier = ["MIT", "Apache-2.0"]
"#
        )
        .unwrap();

        let config = Config::from_toml(&path).unwrap();
        assert_eq!(config.annotations.len(), 1);
        assert_eq!(config.annotations[0].license, "MIT AND Apache-2.0");
    }

    #[test]
    fn parse_aggregate_precedence() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("REUSE.toml");
        let mut f = fs::File::create(&path).unwrap();
        writeln!(
            f,
            r#"
version = 1

[[annotations]]
path = "agg/*"
SPDX-FileCopyrightText = "2026 Aggregator"
SPDX-License-Identifier = "MIT"
precedence = "aggregate"
"#
        )
        .unwrap();

        let config = Config::from_toml(&path).unwrap();
        assert_eq!(config.annotations[0].precedence, Precedence::Aggregate);
    }

    #[test]
    fn parse_both_annotation_and_annotations_merged() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("REUSE.toml");
        let mut f = fs::File::create(&path).unwrap();
        writeln!(
            f,
            r#"
version = 1

[[annotation]]
path = "old/*"
SPDX-FileCopyrightText = "2026 Old"
SPDX-License-Identifier = "MIT"

[[annotations]]
path = "new/*"
SPDX-FileCopyrightText = "2026 New"
SPDX-License-Identifier = "Apache-2.0"
"#
        )
        .unwrap();

        let config = Config::from_toml(&path).unwrap();
        assert_eq!(config.annotations.len(), 2);
        assert_eq!(config.annotations[0].path, "old/*");
        assert_eq!(config.annotations[1].path, "new/*");
    }

    #[test]
    fn load_no_config_files() {
        let dir = tempfile::tempdir().unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert!(config.annotations.is_empty());
        assert!(config.default_license.is_none());
        assert!(config.ignore.is_empty());
    }

    #[test]
    fn config_builder_ignore() {
        let config = Config::builder()
            .ignore(vec!["target/**".to_string()])
            .build();
        assert_eq!(config.ignore, vec!["target/**"]);
    }

    #[test]
    fn config_builder_add_ignore() {
        let config = Config::builder()
            .add_ignore("target/**".to_string())
            .add_ignore("node_modules/**".to_string())
            .build();
        assert_eq!(config.ignore, vec!["target/**", "node_modules/**"]);
    }

    #[test]
    fn config_builder_source_patterns() {
        let config = Config::builder()
            .source_patterns(vec!["config/**".to_string()])
            .build();
        assert_eq!(config.source_patterns, vec!["config/**"]);
    }

    #[test]
    fn config_builder_add_source_pattern() {
        let config = Config::builder()
            .add_source_pattern("config/**".to_string())
            .add_source_pattern("scripts/**".to_string())
            .build();
        assert_eq!(config.source_patterns, vec!["config/**", "scripts/**"]);
    }

    #[test]
    fn match_annotations_multiple_patterns() {
        let config = Config {
            annotations: vec![
                Annotation {
                    path: "src/**".to_string(),
                    copyright: vec!["2026 Author".into()],
                    license: "MIT".into(),
                    precedence: Precedence::Closest,
                },
                Annotation {
                    path: "tests/**".to_string(),
                    copyright: vec!["2026 Tester".into()],
                    license: "Apache-2.0".into(),
                    precedence: Precedence::Closest,
                },
            ],
            default_license: None,
            default_copyright: vec![],
            ignore: vec![],
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: vec![],
            walk: WalkOptions::default(),
            comment_styles: vec![],
        };

        let matched = config.match_annotations("src/lib.rs");
        assert_eq!(matched.len(), 1);
        assert_eq!(matched[0].license, "MIT");

        let matched = config.match_annotations("tests/integration.rs");
        assert_eq!(matched.len(), 1);
        assert_eq!(matched[0].license, "Apache-2.0");

        let matched = config.match_annotations("docs/readme.md");
        assert!(matched.is_empty());
    }

    #[test]
    fn match_annotations_precedence_order() {
        let config = Config {
            annotations: vec![
                Annotation {
                    path: "src/**".to_string(),
                    copyright: vec!["2026 Base".into()],
                    license: "MIT".into(),
                    precedence: Precedence::Closest,
                },
                Annotation {
                    path: "src/special.rs".to_string(),
                    copyright: vec!["2026 Special".into()],
                    license: "Apache-2.0".into(),
                    precedence: Precedence::Override,
                },
                Annotation {
                    path: "src/**".to_string(),
                    copyright: vec!["2026 Aggregate".into()],
                    license: "GPL-3.0".into(),
                    precedence: Precedence::Aggregate,
                },
            ],
            default_license: None,
            default_copyright: vec![],
            ignore: vec![],
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: vec![],
            walk: WalkOptions::default(),
            comment_styles: vec![],
        };

        // Override comes LAST (highest precedence value = last in sorted order)
        let matched = config.match_annotations("src/special.rs");
        assert_eq!(matched.len(), 3);
        assert_eq!(matched[0].license, "MIT"); // Closest first
        assert_eq!(matched[1].license, "GPL-3.0"); // Aggregate second
        assert_eq!(matched[2].license, "Apache-2.0"); // Override last
    }

    #[test]
    fn match_annotations_empty() {
        let config = Config {
            annotations: vec![],
            default_license: None,
            default_copyright: vec![],
            ignore: vec![],
            spdx_package_name: None,
            spdx_package_supplier: None,
            source_patterns: vec![],
            walk: WalkOptions::default(),
            comment_styles: vec![],
        };

        let matched = config.match_annotations("src/lib.rs");
        assert!(matched.is_empty());
    }

    #[test]
    fn match_annotations_normalises_windows_separators() {
        let config = Config::builder()
            .add_annotation(Annotation {
                path: "src/**".to_string(),
                copyright: vec!["2026 Acme Inc".to_string()],
                license: "MIT".to_string(),
                precedence: Precedence::Aggregate,
            })
            .build();

        let matched = config.match_annotations(r"src\main.rs");

        assert_eq!(
            matched.len(),
            1,
            "a backslash-separated path must match the same annotation"
        );
    }
}
// REUSE-IgnoreEnd