provenant-cli 1.0.8

Fast Rust scanner for licenses, copyrights, 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
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
// SPDX-FileCopyrightText: nexB Inc. and others
// ScanCode is a trademark of nexB Inc.
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0
// Derived from ScanCode Toolkit (Apache-2.0); modified. See NOTICE.

use super::*;

#[test]
fn test_prose_copyright_word_without_proper_holder_is_not_detected() {
    // Prose that merely uses the word "copyright" as a common noun, with no
    // proper-noun/company/year holder, must not become a copyright — mirroring
    // ScanCode's grammar, which has no `<COPY> <NN>` production. The span
    // fallbacks (which run when the grammar builds no node) must not sweep the
    // surrounding common-noun prose into a copyright.
    for prose in [
        "Thanks to Jim Meyering for doing the copyright paperwork.",
        "The whole point is that the copyright and the source code would then be shared.",
        "2. E. I. du Pont de Nemours and Company copyright (ImageMagick was originally based on their code).",
    ] {
        let (copyrights, _holders, _authors) = detect_copyrights_from_text(prose);
        assert!(
            copyrights.is_empty(),
            "prose produced copyrights: {copyrights:?} for {prose:?}"
        );
    }
}

#[test]
fn test_prose_copyright_spanning_a_sentence_boundary_is_not_detected() {
    // Article prose that discusses copyright (github/opensource.guide legal.md and
    // its translations) has a bare `copyright` token sweep the rest of the
    // sentence — and across the sentence period into the next one — into a
    // copyright/holder. ScanCode emits nothing. A real notice never crosses a
    // sentence boundary (`... by default. That is ...`).
    for prose in [
        "that work is under exclusive copyright by default. That is, the law assumes you have a say.",
        "who holds copyright can get complicated and confusing very quickly. Switching to a new license.",
        "you aren't the sole copyright holder. If you're the sole contributor you own it.",
        "hai una licenza copyright esclusivo per impostazione predefinita. Cioè, la legge presuppone.",
        "non puoi semplicemente cambiare la licenza del tuo progetto MIT. In sostanza vale questo.",
    ] {
        let (copyrights, holders, _authors) = detect_copyrights_from_text(prose);
        assert!(
            copyrights.is_empty(),
            "prose produced copyrights: {copyrights:?} for {prose:?}"
        );
        assert!(
            holders.is_empty(),
            "prose produced holders: {holders:?} for {prose:?}"
        );
    }
}

#[test]
fn test_notices_before_a_following_sentence_are_kept() {
    // The sentence-boundary junk rule must keep genuine notices whose holder is
    // named before the boundary: a year-range notice (`1994-1999. The MITRE ...`),
    // and a lowercase collective-agent holder (`by the original authors. ...`).
    for (text, expected) in [
        (
            "Copyright (c) 1994-1999. The MITRE Corporation makes no representations.",
            "MITRE",
        ),
        (
            "Copyright by the original authors. Redistribution is permitted.",
            "original authors",
        ),
    ] {
        let (copyrights, _holders, _authors) = detect_copyrights_from_text(text);
        assert!(
            copyrights.iter().any(|c| c.copyright.contains(expected)),
            "expected {expected:?} kept in {copyrights:?} for {text:?}"
        );
    }
}

#[test]
fn test_notice_with_trailing_email_tld_and_second_copyright_is_kept() {
    // A period after an email TLD that precedes a second `Copyright` clause is not
    // a prose sentence boundary; the whole notice must survive.
    let text = "Pascal Andre, andre@chimay.via.ecp.fr. Copyright (c) 1995, Pascal Andre";
    let (copyrights, _holders, _authors) = detect_copyrights_from_text(text);
    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright.contains("Pascal Andre")),
        "expected the Pascal Andre notice to survive: {copyrights:?}"
    );
}

#[test]
fn test_lowercase_copyright_with_proper_holder_still_detected() {
    // The span guard must not suppress legitimate lowercase notices that carry a
    // real holder: proper noun, company, "by <name>", or an all-caps acronym.
    for (text, expected) in [
        (
            "This program is copyrighted by the Free Software Foundation.",
            "Free Software Foundation",
        ),
        ("This code is copyright CERN.", "CERN"),
        (
            "The following reference appears in all the copies: Scilab (c)INRIA-ENPC.",
            "INRIA-ENPC",
        ),
    ] {
        let (copyrights, _holders, _authors) = detect_copyrights_from_text(text);
        assert!(
            copyrights.iter().any(|c| c.copyright.contains(expected)),
            "expected holder {expected:?} missing in {copyrights:?} for {text:?}"
        );
    }
}

#[test]
fn test_unicode_break_test_data_lines_do_not_produce_holders() {
    // Unicode Character Database segmentation-test data (unicode-org/icu4x
    // WordBreakTest.txt / GraphemeBreakTest.txt) embeds the copyright codepoint
    // `00A9`/`©` as literal test input on lines dense with the break markers
    // `÷`/`×`. The genuine file header notice is kept; the data lines are not
    // turned into holders/copyrights.
    let input = concat!(
        "# \u{00a9} 2025 Unicode\u{00ae}, Inc.\n",
        "\u{00f7} 0009 \u{00d7} 0308 \u{00f7} 00A9 \u{00f7} # \u{00f7} [0.2] SIGN (ExtPict) \u{00d7} [9.0] COMBINING DIAERESIS\n",
        "\u{00f7} 000D \u{00f7} 00A9 \u{00f7} # \u{00f7} [0.2] (CR) \u{00f7} [3.1] COPYRIGHT SIGN (ExtPict)\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);

    // The real header notice survives.
    assert!(
        holders.iter().any(|h| h.holder.contains("Unicode")),
        "expected the header holder to survive: {holders:?}"
    );
    // No break-test data line becomes a holder or copyright.
    assert!(
        !holders
            .iter()
            .any(|h| h.holder.contains('\u{00f7}') || h.holder.contains('\u{00d7}')),
        "segmentation data leaked into holders: {holders:?}"
    );
    assert!(
        !copyrights
            .iter()
            .any(|c| c.copyright.contains('\u{00f7}') || c.copyright.contains('\u{00d7}')),
        "segmentation data leaked into copyrights: {copyrights:?}"
    );
}

#[test]
fn test_bpe_tokenizer_data_lines_do_not_produce_copyrights_or_holders() {
    // Hugging Face subword-tokenizer artifacts: merges.txt BPE pairs and
    // vocab.json token:id entries embed the `©` symbol and the literal
    // `copyright` token. They must not be surfaced as copyright/holder notices.
    let input = concat!(
        "é goo gle</w> fren ch</w>\n",
        "âģ ©</w> f ren st y</w>\n",
        "\"©\": 102,\n",
        "\"copyright</w>\": 15778,\n",
    );

    let (copyrights, holders, authors) = detect_copyrights_from_text(input);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_hf_tokenizer_json_suppresses_merges_but_keeps_outside_notice() {
    // A Hugging Face tokenizer.json embeds a BPE "merges" array of mojibake
    // byte-pairs (junk) but is a larger document. Only the merges array is
    // suppressed: a genuine notice elsewhere in the same file is preserved.
    let input = concat!(
        "{\n",
        "  \"copyright\": \"Copyright 2024 Acme Inc.\",\n",
        "  \"model\": {\n",
        "    \"type\": \"BPE\",\n",
        "    \"vocab\": { \"a\": 0 },\n",
        "    \"merges\": [\n",
        "      \"pok é\",\n",
        "      \"Â ©\",\n",
        "      \"Ú ©\"\n",
        "    ]\n",
        "  }\n",
        "}\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);

    // The real notice survives.
    assert!(
        copyrights.iter().any(|c| c.copyright.contains("Acme Inc")),
        "expected the real notice to be detected: {copyrights:?}"
    );
    // None of the BPE merge mojibake pairs leak through as notices.
    assert!(
        !copyrights.iter().any(|c| c.copyright.contains('©')),
        "merge-table junk leaked into copyrights: {copyrights:?}"
    );
    assert!(
        !holders.iter().any(|h| h.holder.contains('©')),
        "merge-table junk leaked into holders: {holders:?}"
    );
}

#[test]
fn test_compact_tokenizer_json_keeps_outside_notice() {
    // A compact (single-line) tokenizer.json cannot be split by line, so the
    // merge-span filter is not applied and a real notice on that line is not
    // dropped. (Junk suppression for genuine merge data still relies on the
    // per-line fragment checks; preserving a real notice takes priority.)
    let input = r#"{"copyright":"Copyright 2024 Acme Inc.","model":{"type":"BPE","vocab":{"a":0},"merges":["pok é"," ©"]}}"#;

    let (copyrights, _holders, _authors) = detect_copyrights_from_text(input);

    assert!(
        copyrights.iter().any(|c| c.copyright.contains("Acme Inc")),
        "compact tokenizer.json must keep the real notice: {copyrights:?}"
    );
}

#[test]
fn test_bpe_merges_table_produces_no_copyrights() {
    // A full BPE merges.txt (header + two-token merge rules) embeds `©` and
    // mojibake byte pairs that are not copyright notices.
    let input = concat!(
        "#version: 0.2\n",
        "i n\n",
        "t h\n",
        "Â ©\n",
        "pok é\n",
        "Ú ©\n",
    );

    let (copyrights, holders, authors) = detect_copyrights_from_text(input);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_swift_convention_c_signatures_do_not_produce_copyrights_or_holders() {
    let input = concat!(
        "let invokeSuperSetter: @convention(c) (NSObject, AnyClass, Selector, AnyObject?) -> Void = { object, superclass, selector, delegate in\n",
        "typealias Setter = @convention(c) (NSObject, Selector, AnyObject?) -> Void\n",
    );

    let (copyrights, holders, authors) = detect_copyrights_from_text(input);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_busybox_env_modified_by_line_does_not_absorb_correct_usage_bullet() {
    let content = "* Modified by Vladimir Oleynik <dzo@simtreas.ru> (C) 2003\n* - correct \"-\" option usage\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);

    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright == "Vladimir Oleynik <dzo@simtreas.ru> (c) 2003"),
        "copyrights: {:#?}",
        copyrights.iter().map(|c| &c.copyright).collect::<Vec<_>>()
    );
    assert!(
        !copyrights.iter().any(|c| c.copyright.contains("- correct")),
        "copyrights: {:#?}",
        copyrights.iter().map(|c| &c.copyright).collect::<Vec<_>>()
    );
    assert!(
        holders.iter().any(|h| h.holder == "Vladimir Oleynik"),
        "holders: {:#?}",
        holders.iter().map(|h| &h.holder).collect::<Vec<_>>()
    );
}

#[test]
fn test_copyright_span_does_not_absorb_following_author_line() {
    let input = "Copyright (c) Ian F. Darwin 1986\nSoftware written by Ian F. Darwin and others;";
    let (_c, holders, _authors) = detect_copyrights_from_text(input);
    let hs: Vec<String> = holders.into_iter().map(|h| h.holder).collect();
    assert!(hs.iter().any(|h| h == "Ian F. Darwin"), "holders: {hs:#?}");
    assert!(
        !hs.iter().any(|h| h == "Ian F. Darwin Software"),
        "holders: {hs:#?}"
    );
}

#[test]
fn test_copyright_span_does_not_absorb_following_lint_directive_line() {
    let input = concat!(
        "// (c) Example Corp. and affiliates. Confidential and proprietary.\n",
        "// @lint-ignore-every FBOBJCIMPORTORDER1 METHOD_BRACKETSMETHOD_BRACKETS\n",
    );

    let (copyrights, _holders, _authors) = detect_copyrights_from_text(input);
    let values: Vec<String> = copyrights.into_iter().map(|c| c.copyright).collect();

    assert!(
        values
            .iter()
            .any(|c| c == "(c) Example Corp. and affiliates. Confidential and proprietary"),
        "copyrights: {values:#?}"
    );
    assert!(
        !values.iter().any(|c| c.contains("@lint-ignore-every")),
        "copyrights: {values:#?}"
    );
}

#[test]
fn test_html_comment_copyright_does_not_absorb_following_body_text() {
    let input = concat!(
        "<!-- Copyright 2008 ABCD, LLC. -->\n",
        "<html>\n",
        "<body>\n",
        "Periodic Manager\n",
        "</body>\n",
        "</html>\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    let cs: Vec<String> = copyrights.into_iter().map(|c| c.copyright).collect();
    let hs: Vec<String> = holders.into_iter().map(|h| h.holder).collect();

    assert!(
        cs.iter().any(|c| c == "Copyright 2008 ABCD, LLC."),
        "copyrights: {cs:#?}"
    );
    assert!(
        !cs.iter().any(|c| c.contains("Periodic Manager")),
        "copyrights: {cs:#?}"
    );
    assert!(hs.iter().any(|h| h == "ABCD, LLC."), "holders: {hs:#?}");
    assert!(
        !hs.iter().any(|h| h.contains("Periodic Manager")),
        "holders: {hs:#?}"
    );
}

#[test]
fn test_html_comment_noise_does_not_extend_plain_copyright_line() {
    let input = concat!(
        "Copyright 2024 Example Corp.\n",
        "<!-- sponsors end -->\n",
        "<div>body</div>\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    let cs: Vec<String> = copyrights.into_iter().map(|c| c.copyright).collect();
    let hs: Vec<String> = holders.into_iter().map(|h| h.holder).collect();

    assert!(
        cs.iter().any(|c| c == "Copyright 2024 Example Corp."),
        "copyrights: {cs:#?}"
    );
    assert!(
        !cs.iter()
            .any(|c| c.contains("sponsors end") || c.contains("body")),
        "copyrights: {cs:#?}"
    );
    assert!(hs.iter().any(|h| h == "Example Corp."), "holders: {hs:#?}");
}

#[test]
fn test_consecutive_html_comment_copyright_lines_keep_continuation_only() {
    let input = concat!(
        "<!-- Copyright 2024 Example Corp. -->\n",
        "<!-- All rights reserved. -->\n",
        "<!-- sponsors end -->\n",
        "<div>body</div>\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    let cs: Vec<String> = copyrights.into_iter().map(|c| c.copyright).collect();
    let hs: Vec<String> = holders.into_iter().map(|h| h.holder).collect();

    assert!(
        cs.iter().any(|c| c == "Copyright 2024 Example Corp."),
        "copyrights: {cs:#?}"
    );
    assert!(
        !cs.iter()
            .any(|c| c.contains("sponsors end") || c.contains("body")),
        "copyrights: {cs:#?}"
    );
    assert!(hs.iter().any(|h| h == "Example Corp."), "holders: {hs:#?}");
}

#[test]
fn test_detect_arch_floppy_h_bare_1995_dropped_for_x86() {
    let content =
        "* Copyright (C) 1995\n */\n#ifndef _ASM_X86_FLOPPY_H\n#define _ASM_X86_FLOPPY_H\n";
    let (copyrights, _holders, _authors) = detect_copyrights_from_text(content);
    assert!(copyrights.is_empty());
}

#[test]
fn test_detect_changelog_single_timestamp_is_ignored() {
    let content = "updated year in copyright\n\n2008-01-26 11:46  vruppert\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(copyrights.is_empty());
    assert!(holders.is_empty());
}

#[test]
fn test_drop_obfuscated_email_year_only_copyright() {
    let content = "Copyright (C) 2008 <srinivasa.deevi at conexant dot com>\n";
    let (copyrights, _holders, _authors) = detect_copyrights_from_text(content);
    assert!(copyrights.is_empty());
}

#[test]
fn test_glide_3dfx_copyright_notice_does_not_trigger_for_notice_s_plural() {
    let content = "copyright notice(s)\n";
    let (copyrights, _holders, _authors) = detect_copyrights_from_text(content);
    assert!(!copyrights.iter().any(|c| {
        c.copyright
            .to_ascii_lowercase()
            .contains("copyright notice")
    }));
}

#[test]
fn test_copyright_notice_of_prose_does_not_emit_xerox_holder() {
    let content = "the above copyright notice of Xerox Corporation,";
    let (copyrights, holders, authors) = detect_copyrights_from_text(content);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:#?}");
    assert!(holders.is_empty(), "holders: {holders:#?}");
    assert!(authors.is_empty(), "authors: {authors:#?}");
}

#[test]
fn test_play_header_does_not_emit_bare_c_from_year_shadow() {
    let content = "Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);

    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright.contains("The Play Framework Contributors")),
        "copyrights: {copyrights:?}"
    );
    assert!(
        !copyrights.iter().any(|c| c.copyright == "(c) from 2022"),
        "copyrights: {copyrights:?}"
    );
    assert!(
        holders
            .iter()
            .any(|h| h.holder.contains("The Play Framework Contributors")),
        "holders: {holders:?}"
    );
}

#[test]
fn test_drop_symbol_year_only_copyright() {
    let input = "Copyright © 2021\nCopyright (c) 2017\n";
    let (c, _h, _a) = detect_copyrights_from_text(input);
    assert!(
        !c.iter().any(|cr| cr.copyright == "Copyright (c) 2021"),
        "Expected © year-only to be dropped, got: {:?}",
        c.iter().map(|cr| &cr.copyright).collect::<Vec<_>>()
    );
    assert!(
        c.iter().any(|cr| cr.copyright == "Copyright (c) 2017"),
        "Expected non-© year-only to be kept, got: {:?}",
        c.iter().map(|cr| &cr.copyright).collect::<Vec<_>>()
    );
}

#[test]
fn test_c_sign_path_fragment_is_not_detected_as_copyright() {
    let input = "(C)Ljoptsimple/AbstractOptionSpec";
    let (c, h, a) = detect_copyrights_from_text(input);
    assert!(c.is_empty(), "copyrights: {c:#?}");
    assert!(h.is_empty(), "holders: {h:#?}");
    assert!(a.is_empty(), "authors: {a:#?}");
}

#[test]
fn test_copyright_scan_phrase_is_not_detected_as_copyright() {
    let input = "Measures the end-to-end composer copyright scan";
    let (c, h, a) = detect_copyrights_from_text(input);
    assert!(c.is_empty(), "copyrights: {c:#?}");
    assert!(h.is_empty(), "holders: {h:#?}");
    assert!(a.is_empty(), "authors: {a:#?}");
}

#[test]
fn test_generated_annotation_line_is_not_absorbed_into_copyright() {
    let input = "/* Copyright (C) 2024 Acme Corp.\n * @generated by protobuf */";
    let (c, h, _a) = detect_copyrights_from_text(input);
    assert!(
        c.iter()
            .any(|cr| cr.copyright == "Copyright (c) 2024 Acme Corp."),
        "copyrights: {c:#?}"
    );
    assert!(
        !c.iter().any(|cr| cr.copyright.contains("@generated")),
        "copyrights: {c:#?}"
    );
    assert!(
        h.iter().any(|holder| holder.holder == "Acme Corp."),
        "holders: {h:#?}"
    );
}

#[test]
fn test_detect_no_copyright() {
    let (c, h, a) = detect_copyrights_from_text("This is just some random code.");
    assert!(c.is_empty());
    assert!(h.is_empty());
    assert!(a.is_empty());
}

#[test]
fn test_detect_junk_filtered() {
    let (c, _h, _a) = detect_copyrights_from_text("Copyright (c)");
    assert!(
        c.is_empty(),
        "Bare 'Copyright (c)' should be filtered as junk"
    );
}

#[test]
fn test_detect_filters_code_like_c_marker_lines() {
    let text = "(c) (const unsigned char*)ptr\n(c) c ? foo : bar\n(c) c & 0x3f\n(c) flags |= 0x80";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_windows_versioninfo_line_is_not_detected_as_copyright_or_holder() {
    let text = "Copyright (c) 2050 VALUE OriginalFilename NativeConsoleApp.exe";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_dtd_declaration_line_is_not_detected_as_copyright_or_holder() {
    let text = "copyright <!ELEMENT A ( PCDATA) > aaaa";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_copyright_property_access_line_is_not_detected_as_copyright_or_holder() {
    let text = "Copyright clone.Copyright.Text";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_unicode_escape_c_marker_line_is_not_detected_as_copyright_or_holder() {
    let text = "(c) HeaderType.Content u00AD u00AE";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);

    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_regexoptions_holder_token_is_not_detected() {
    let text = "RegexOptions.None";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_encoding_ascii_holder_token_is_not_detected() {
    let text = "Some-Header3 Encoding.ASCII";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_api_member_access_holder_token_is_not_detected() {
    let text = "FeedUtils.CloneTextContent";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_marshal_api_holder_token_is_not_detected() {
    let text = "Marshal.GetObjectForIUnknown(i) ComObject obj";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_console_writeline_holder_token_is_not_detected() {
    let text = "header Console.WriteLine $'.NET Xml Serialization Generation Utility";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_file_reference_prose_copyright_token_is_not_detected() {
    let text = "copyright and update THIRD-PARTY-NOTICES.TXT.";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_detect_copyright_does_not_absorb_unexpected_as_represented() {
    let text = "Copyright 1993 United States Government as represented by the\nDirector, National Security Agency.";
    let (c, h, _a) = detect_copyrights_from_text(text);
    assert!(
        c.iter()
            .any(|cr| cr.copyright == "Copyright 1993 United States Government"),
        "Should keep only government without continuation: {:?}",
        c
    );
    assert!(
        h.iter().any(|hd| hd.holder == "United States Government"),
        "Should keep only government holder without continuation: {:?}",
        h
    );
}

#[test]
fn test_doc_doc_no_overabsorb() {
    let input = "are copyrighted by Douglas C. Schmidt and his research group at Washington University, University of California, Irvine, and Vanderbilt University, Copyright (c) 1993-2008, all rights reserved.";
    let (c, _h, _a) = detect_copyrights_from_text(input);
    assert!(
        c.iter().any(|cr| cr.copyright == "copyrighted by Douglas C. Schmidt and his research group at Washington University, University of California, Irvine, and Vanderbilt University, Copyright (c) 1993-2008"),
        "Should merge trailing Copyright (c) clause, got: {:?}",
        c
    );
}

#[test]
fn test_meta_sdk_license_false_positive_detector_drops_legal_prose_fragments() {
    let input = concat!(
        "Copyright © Meta Platform Technologies, LLC and its affiliates. All rights reserved.\n",
        "1.2.5 alter, restrict, or interfere with the normal operation or functionality of the SDK, the MPT hardware or software, or MPT Approved Products, including, but not limited to: (a) the behavior of the “Meta Quest button” and “XBox button” implemented by the MPT system software; (b) any on-screen messages or information; (c) the behavior of the proximity sensor in the MPT hardware implemented by the MPT system software; (d) any MPT hardware or software security features; (e) any end user's settings; and (f) Health and Safety Warnings;\n",
        "1.3 Distribution and Sublicense Restrictions. The redistribution and sublicense rights under this Section are further subject to the following restrictions: (1) redistribution of sample source code or other materials must include the following copyright notice: “Copyright © Meta Platform Technologies, LLC and its affiliates. All rights reserved;” and (2) if the sample source code or other materials include a \"License\" or \"Notice\" text file, you must provide a copy of the License or Notice file with the sample code.\n",
        "3.1 Ownership. As between you and MPT, MPT and/or its affiliates or licensors own all rights, title, and interest, including all Intellectual Property Rights (defined below), in and to the SDK (including associated MPT content and sample code) and all derivatives thereof. MPT reserves all rights not expressly granted under the License. As between you and MPT, you and/or your licensors own all rights, title, and interest in and to your Application, (excluding our SDK), including all Intellectual Property Rights. “Intellectual Property Rights” means any and all worldwide rights under applicable laws of patent, copyright, trade secret, trademark, rights of publicity and privacy, and other proprietary rights.\n",
        "3.4 Brand Attribution. This Agreement does not grant you or any third party permission to use our trade names, trademarks, service marks, logos, domain names, and other distinctive brand features (collectively, “Brand Features”) except as required for reasonable and customary use in describing the origin of the SDK or reproduction of the copyright notice as required under the License grant.\n",
        "7.4.2 If you reside in the US or your business is located in the US: You and we agree to arbitrate any claim, cause of action, or dispute between you and us that arises out of or relates to any access or use of the SDK for business or commercial purposes (“commercial claim”). This provision does not cover any commercial claims relating to violations of your or our intellectual property rights, including, but not limited to, copyright infringement, patent infringement, trademark infringement, violations of the brand guidelines, violations of your or our confidential information or trade secrets, or efforts to interfere with our products or engage with our products in unauthorized ways (for example, automated ways).\n",
    );

    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    let copyright_values: Vec<&str> = copyrights.iter().map(|c| c.copyright.as_str()).collect();
    let holder_values: Vec<&str> = holders.iter().map(|h| h.holder.as_str()).collect();

    assert!(
        copyright_values
            .contains(&"Copyright (c) Meta Platform Technologies, LLC and its affiliates"),
        "copyrights: {copyright_values:#?}"
    );
    assert!(
        holder_values.contains(&"Meta Platform Technologies, LLC and its affiliates"),
        "holders: {holder_values:#?}"
    );
    assert_eq!(
        copyright_values
            .iter()
            .filter(|value| **value
                == "Copyright (c) Meta Platform Technologies, LLC and its affiliates")
            .count(),
        1,
        "copyrights: {copyright_values:#?}"
    );
    assert_eq!(
        holder_values
            .iter()
            .filter(|value| **value == "Meta Platform Technologies, LLC and its affiliates")
            .count(),
        1,
        "holders: {holder_values:#?}"
    );
    assert!(
        !copyright_values
            .iter()
            .any(|value| value
                .contains("rights of publicity and privacy, and other proprietary rights")),
        "copyrights: {copyright_values:#?}"
    );
    for unexpected in [
        "as required",
        "infringement, patent infringement, trademark infringement, violations of the brand guidelines, violations of your or our confidential",
        "the behavior of the proximity sensor in the MPT hardware implemented by the MPT system software",
        "Copyright",
    ] {
        assert!(
            !holder_values.contains(&unexpected),
            "unexpected holder {unexpected:?} in {holder_values:#?}"
        );
    }
}

#[test]
fn test_dnf_copr_command_does_not_produce_copyright() {
    let text = concat!(
        "If you used restic from copr previously, remove the copr repo as follows:\n",
        "   $ dnf copr remove copart/restic\n",
        "For RHEL7/CentOS there is a copr repository available:\n",
        "    $ yum copr enable copart/restic\n",
    );
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_bash_array_expansion_does_not_produce_copyright() {
    let text = concat!(
        "if __restic_contains_word '${words[c]}' '${two_word_flags[@]}'; then\n",
        "elif __restic_contains_word '${words[c]}' '${must_have_one_noun[@]}'; then\n",
        "elif __restic_contains_word '${words[c]}' '${commands[@]}'; then\n",
        "elif __restic_contains_word '${words[c]}' '${command_aliases[@]}'; then\n",
    );
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_author_of_work_does_not_produce_author() {
    let text = "We've added the ability to use rclone to store backup data on all\nbackends that it supports. This was done in collaboration with\nNick, the author of rclone.\n";
    let (copyrights, holders, authors) = detect_copyrights_from_text(text);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:?}");
    assert!(holders.is_empty(), "holders: {holders:?}");
    assert!(
        !authors.iter().any(|a| a.author == "rclone"),
        "authors should not contain 'rclone': {authors:?}"
    );
}

#[test]
fn test_copyright_holder_placeholder_and_code_fragments_do_not_emit_detections() {
    let input = concat!(
        "Copyright (c) 2014 PulseAudio's COPYRIGHT HOLDER
",
        "PulseAudio's COPYRIGHT HOLDER
",
        "copyright sections were added
",
        "pa_log_debug(\"Copyright: %s\", d->Copyright)\n",
        "PA_REFCNT_INIT(c); c->core = core
",
        "applying to the plugin. If
",
        "applies the
",
        "s d- Copyright
",
        "c- core core
",
    );
    let (copyrights, holders, authors) = detect_copyrights_from_text(input);
    assert!(copyrights.is_empty(), "copyrights: {copyrights:#?}");
    assert!(holders.is_empty(), "holders: {holders:#?}");
    assert!(authors.is_empty(), "authors: {authors:#?}");
}

#[test]
fn test_pulseaudio_ladspa_rfc_and_contact_fragments_do_not_emit_junk() {
    let input = concat!(
        "copyright applying to the plugin. If
",
        "sections were added
",
        "Copyright 2009 Nokia Corporation Contact: Maemo Multimedia <multimedia@maemo.org>
",
    );
    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    let copyright_values: Vec<&str> = copyrights.iter().map(|c| c.copyright.as_str()).collect();
    let holder_values: Vec<&str> = holders.iter().map(|h| h.holder.as_str()).collect();
    assert!(
        copyright_values.contains(&"Copyright 2009 Nokia Corporation"),
        "copyrights: {copyright_values:?}"
    );
    assert!(
        !copyright_values
            .iter()
            .any(|v| v.contains("applying to the plugin")
                || v.contains("sections were added")
                || v.contains("Contact:")),
        "copyrights: {copyright_values:?}"
    );
    assert!(
        holder_values.contains(&"Nokia Corporation"),
        "holders: {holder_values:?}"
    );
    assert!(
        !holder_values
            .iter()
            .any(|v| v.contains("sections were added") || v.contains("Contact:")),
        "holders: {holder_values:?}"
    );
}

#[test]
fn test_xml_copyright_element_tag_is_not_detected_as_copyright() {
    // Wayland protocol descriptions (glfw's vendored deps/wayland/*.xml) wrap
    // notices in a `<copyright>` element. The bare tag opener must not itself be
    // surfaced as a copyright/holder, while the real notices inside it are kept.
    let input = concat!(
        "  <copyright>\n",
        "    Copyright \u{00a9} 2014 Jonas \u{00c5}dahl\n",
        "  </copyright>\n",
    );
    let (copyrights, holders, _authors) = detect_copyrights_from_text(input);
    assert!(
        !copyrights.iter().any(|c| c.copyright == "<copyright>"),
        "bare XML tag leaked into copyrights: {copyrights:?}"
    );
    assert!(
        !holders.iter().any(|h| h.holder == "<copyright>"),
        "bare XML tag leaked into holders: {holders:?}"
    );
    assert!(
        copyrights.iter().any(|c| c.copyright.contains("Jonas")),
        "expected the real notice to survive: {copyrights:?}"
    );
}

#[test]
fn test_javadoc_author_with_html_anchor_is_extracted() {
    // Java Javadoc `@author` tags frequently wrap the name in an HTML anchor with
    // an http(s) href (eclipse-vertx/vert.x uses
    // `@author <a href="http://tfox.org">Tim Fox</a>` across hundreds of files).
    // The href is a homepage link, not the name; the author resolves to the name.
    for (text, expected) in [
        (
            " * @author <a href=\"http://tfox.org\">Tim Fox</a>",
            "Tim Fox",
        ),
        (
            " * @author <a href=\"https://github.com/cescoffier\">Clement Escoffier</a>",
            "Clement Escoffier",
        ),
        // Plain-text name followed by a trailing handle/homepage anchor.
        (
            " * @author Francesco Guardiani <a href=\"https://slinkydeveloper.github.io/\">@slinkydeveloper</a>",
            "Francesco Guardiani",
        ),
        // Plain-text name followed by a bare social handle (no anchor).
        (
            " * @author Francesco Guardiani @slinkydeveloper",
            "Francesco Guardiani",
        ),
    ] {
        let (_c, _h, authors) = detect_copyrights_from_text(text);
        let vals: Vec<&String> = authors.iter().map(|a| &a.author).collect();
        assert!(
            vals.iter().any(|a| a.as_str() == expected),
            "expected {expected:?} in {vals:?} for {text:?}"
        );
    }
}

#[test]
fn test_changelog_update_copyright_year_bullet_not_detected() {
    let content = r#"- Update LICENSE's copyright year. ([#7246](https://github.com/crystal-lang/crystal/pull/7246), thanks @matiasgarciaisaia)
- Bump NOTICE copyright year ([#15318], thanks @straight-shoota)
- Update copyright year ([#16550], thanks @HertzDevil)
"#;
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");
}

#[test]
fn test_alphabetic_list_label_is_not_a_copyright_sign() {
    // `(C)` is also the third label of an alphabetic list, so RFC and other
    // specification prose puts one at the head of an ordinary sentence
    // (RFC 1123 §5.3.7, shipped in erlang/otp). A bare `(c)` notice names its
    // holder right after the marker; enumerated prose puts a common noun there
    // and only reaches a proper noun (`Internet`, `SMTP`) deeper into the
    // sentence, which the span fallback used to accept as the holder anchor.
    let content = "\
         (A)  Blah
         (B)  Bleh
         (C)  From the Internet side, the gateway SHOULD accept all
              valid address formats in SMTP commands and in RFC-822
              headers, and all valid RFC-822 messages.  Although a
              gateway must accept an RFC-822 explicit source route
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");

    // The list label alone — with no `(A)`/`(B)` siblings in view — is rejected
    // on the same grounds, so a fragment or a lone clause is covered too.
    let (copyrights, holders, _authors) =
        detect_copyrights_from_text("(c)  From the Internet side, the gateway SHOULD accept all\n");
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");
}

#[test]
fn test_bare_c_sign_notices_naming_a_holder_are_kept() {
    // The list-label rule must not touch a real bare `(c)` notice: the holder
    // follows the marker directly, behind a year, or behind a leading
    // determiner such as `The`/`by`.
    for (text, expected) in [
        (
            "(c) Free Software Foundation, Inc.",
            "Free Software Foundation, Inc.",
        ),
        ("(C) 2004 Acme Corporation", "Acme Corporation"),
        ("(C) IBM Corp", "IBM Corp"),
        ("(c) by John Doe <john@example.com>", "John Doe"),
    ] {
        let (copyrights, holders, _authors) = detect_copyrights_from_text(text);
        assert!(!copyrights.is_empty(), "no copyright for {text:?}");
        let vals: Vec<&String> = holders.iter().map(|h| &h.holder).collect();
        assert!(
            vals.iter().any(|h| h.as_str() == expected),
            "expected holder {expected:?} in {vals:?} for {text:?}"
        );
    }
}

#[test]
fn test_holder_warranty_disclaimer_clauses_are_not_copyrights() {
    // The all-caps W3C disclaimers, which name the holder as a verb's subject.
    let content = "\
<p>THIS SOFTWARE AND DOCUMENTATION IS PROVIDED \"AS IS,\" AND
COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE.</p>

<p>COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT,
SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE
SOFTWARE OR DOCUMENTATION.</p>
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");
}

#[test]
fn test_dtd_markup_declaration_comments_are_not_authors() {
    // Erlang edoc modules embed the edoc DTD in comments, where `author` names an
    // element in a content model. The refined values ("copyright?",
    // "EMPTY !ATTLIST") no longer carry the declaration marker, so the raw source
    // line is what identifies them.
    let content = "\
%% @author Richard Carlsson <carlsson.richard@gmail.com>
%%
%% <!ELEMENT module (args?, description?, author*, copyright?,
%%                   version?, since?, deprecated?, see*, reference*,
%%                   functions)>
%% <!ELEMENT author EMPTY>
%% <!ATTLIST author
%%   name CDATA #REQUIRED
%%   email CDATA #IMPLIED>
";
    let (_copyrights, _holders, authors) = detect_copyrights_from_text(content);
    let vals: Vec<&String> = authors.iter().map(|a| &a.author).collect();
    assert_eq!(
        vals,
        vec!["Richard Carlsson <carlsson.richard@gmail.com>"],
        "expected only the tagged author, got {vals:?}"
    );
}

#[test]
fn test_author_label_closing_a_sentence_does_not_name_the_next_sentence() {
    // A lowercase `contributors.`/`et al.` that ends a sentence is no label for the
    // capitalized words after the period: those open a new sentence, or — in an RFC
    // running footer — a new column.
    for text in [
        "   The most active people have been Tom Taylor and Kevin Boyle, but\n   many other people have been regular\n   contributors.  Brian Rosen did tremendous service in putting together\n   the Megaco interoperability tests.\n",
        "   many other people have been regular contributors.\n   Brian Rosen did tremendous service in putting together the tests.\n",
        "Groves, et al.              Standards Track                   [Page 169]\n",
    ] {
        let (_copyrights, _holders, authors) = detect_copyrights_from_text(text);
        let vals: Vec<&String> = authors.iter().map(|a| &a.author).collect();
        assert!(
            vals.is_empty(),
            "prose produced authors: {vals:?} for {text:?}"
        );
    }
}

#[test]
fn test_labels_that_really_introduce_an_author_are_kept() {
    // The sentence-final-label rule must keep a trailing collective author and a
    // capitalized `Authors.` heading that does introduce the names beside it.
    for (text, expected) in [
        (
            "This product includes software developed by Jane Doe and its contributors.\n",
            "Jane Doe and its contributors",
        ),
        ("Authors.  Jane Doe wrote this.\n", "Jane Doe wrote"),
    ] {
        let (_copyrights, _holders, authors) = detect_copyrights_from_text(text);
        let vals: Vec<&String> = authors.iter().map(|a| &a.author).collect();
        assert!(
            vals.iter().any(|a| a.as_str() == expected),
            "expected author {expected:?} in {vals:?} for {text:?}"
        );
    }
}

#[test]
fn test_holder_drops_a_trailing_see_cross_reference() {
    let content = "## Copyright (C) 2022 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    let vals: Vec<&String> = holders.iter().map(|h| &h.holder).collect();
    assert_eq!(
        vals,
        vec!["The ORT Project Authors"],
        "expected the bare holder, got {vals:?}"
    );
    // The statement itself keeps the whole notice, reference and all.
    assert!(
        copyrights.iter().any(|c| c.copyright
            == "Copyright (c) 2022 The ORT Project Authors (see https://github.com/oss-review-toolkit/ort/blob/main/NOTICE )"),
        "expected the full statement, got {copyrights:?}"
    );
}

#[test]
fn test_pattern_match_binding_lines_are_not_copyrights() {
    // Erlang pattern matching binds a `Copyright` variable, so the word is an
    // identifier and the next line's variable is not its holder.
    let content = "\
classify_copyright_result(Filename) ->
    lists:foldl(fun (Copyright, Acc) ->
                        #{<<\"statement\">> := CopyrightSt} = Copyright,
                        #{<<\"path\">> := Path} = Location,
                        Acc#{Path => CopyrightSt}
                    end, #{}, Copyrights).
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");

    // A real notice being assigned on such a line is kept, dated or not: the
    // quotes, or a year, say the words are text rather than an identifier.
    for (text, expected) in [
        (
            "\tnotice := \"Copyright (c) 2020 Acme Corp. All rights reserved.\"\n",
            "Copyright (c) 2020 Acme Corp.",
        ),
        (
            "\tnotice := \"Copyright Acme Corp. All rights reserved.\"\n",
            "Copyright Acme Corp.",
        ),
        (
            "\tnotice := \"Say \\\" then Copyright Acme Corp. All rights reserved.\"\n",
            "Copyright Acme Corp.",
        ),
    ] {
        let (copyrights, holders, _authors) = detect_copyrights_from_text(text);
        assert!(
            copyrights.iter().any(|c| c.copyright == expected),
            "expected {expected:?} for {text:?}, got {copyrights:?}"
        );
        assert!(
            holders.iter().any(|h| h.holder == "Acme Corp."),
            "expected the assigned holder for {text:?}, got {holders:?}"
        );
    }
}

#[test]
fn test_sigil_quoted_map_keys_do_not_rescue_a_pattern_match_binding_line() {
    // Erlang's `~"..."` binary sigil quotes a map *key* here, so the quoted word
    // names a field and the line still binds variables rather than text.
    let content = "\
restore_from_cache(Files, [#{ ~\"scanner\" := Scanner, ~\"summary\" := Summary} | T]) ->
    #{ ~\"copyrights\" := Copyrights, ~\"licenses\" := Licenses} = Summary,
    ok.
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");

    // A quoted notice on such a line carries more than the bare marker, so it is
    // still read as assigned text.
    let assigned = "    #{ ~\"notice\" := \"Copyright Acme Corp. All rights reserved.\" },\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(assigned);
    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright == "Copyright Acme Corp."),
        "expected the assigned notice, got {copyrights:?}"
    );
    assert!(
        holders.iter().any(|h| h.holder == "Acme Corp."),
        "expected the assigned holder, got {holders:?}"
    );
}

#[test]
fn test_erlang_format_string_that_builds_a_notice_is_not_a_notice() {
    // A `~p`/`~n` control sequence makes the surrounding words a template, and
    // the literal year it interpolates around does not make it a real notice.
    let content = "\
      %% Copyright Ericsson AB 2020-~p. All Rights Reserved.
\t\" * Portions created by Ericsson are Copyright 2007, Ericsson AB.~n\"
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");

    // The same file's own dated header stays a notice, tildes elsewhere or not.
    let header = "\
      %% Copyright Ericsson AB 1996-2026. All Rights Reserved.
    io:format(\"~ts~n\", [Chars]).
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(header);
    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright == "Copyright Ericsson AB 1996-2026"),
        "expected the header notice, got {copyrights:?}"
    );
    assert!(
        holders.iter().any(|h| h.holder == "Ericsson AB"),
        "expected the header holder, got {holders:?}"
    );
}

#[test]
fn test_table_of_contents_dot_leader_line_is_not_an_author() {
    // RFC 3525 table of contents: the `Authors'` label heads a dot-leader run and
    // a page number, and the collected span also picks up the next entry's first
    // word. ScanCode emits nothing.
    let input = concat!(
        "   Acknowledgments...............................................211\n",
        "   Authors' Addresses............................................212\n",
        "   Full Copyright Statement......................................213\n",
    );
    let (_copyrights, _holders, authors) = detect_copyrights_from_text(input);

    assert!(authors.is_empty(), "authors: {authors:?}");
}

#[test]
fn test_notice_format_documentation_is_not_a_notice() {
    // Documentation *about* the required header: prose that states the rule, and
    // template lines whose year slot is a `YYYY` placeholder. The last line
    // quotes the template mid-sentence, so refinement drops the placeholder and
    // only the raw line still shows that the notice is a template.
    let content = "\
The copyright notice must start with `Copyright`, and can have as prefix the SPDX annotation `SPDX-FileCopyrightText: `
followed by the holders of the copyright, as follows:

1. To be used exclusively by OTP team
   - `Copyright Ericsson AB YYYY. All Rights Reserved.`
   - `Copyright Ericsson AB YYYY-YYYY. All Rights Reserved.`

> For any contributions made by the Erlang/OTP team, the copyright statement must
> be `Copyright Ericsson AB YYYY. All Rights Reserved.`. The `license-header.es` script
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");
}

#[test]
fn test_real_notices_beside_the_format_documentation_are_kept() {
    // The same document carries genuine notices, dated and undated, which the
    // template and prose rules must leave untouched.
    let content = "\
Copyright Ericsson AB 2025. All Rights Reserved.
SPDX-FileCopyrightText: Copyright (C) 2019 The ORT Project Authors
Copyright (c) Meta Platforms, Inc. and affiliates.
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert_eq!(
        copyrights
            .iter()
            .map(|c| c.copyright.as_str())
            .collect::<Vec<_>>(),
        vec![
            "Copyright Ericsson AB 2025",
            "Copyright (c) 2019 The ORT Project Authors",
            "Copyright (c) Meta Platforms, Inc. and affiliates",
        ],
        "expected the real notices, got {copyrights:?}"
    );
    assert_eq!(
        holders
            .iter()
            .map(|h| h.holder.as_str())
            .collect::<Vec<_>>(),
        vec![
            "Ericsson AB",
            "The ORT Project Authors",
            "Meta Platforms, Inc. and affiliates",
        ],
        "expected the real holders, got {holders:?}"
    );
}

#[test]
fn test_compliance_tooling_prose_and_format_strings_are_not_notices() {
    // An Erlang compliance script: a comment about running a copyright *scanner*,
    // and a diagnostic format string whose `~ts`/`~n` directives make its words a
    // template. Only the file's own header notice is a notice.
    let content = "\
%% Copyright Ericsson AB 2024-2026. All Rights Reserved.
%%
%% Ignore copyright detection heuristics of REUSE tool in this file.
%%    throw({warn, \"Invalid Copyright: '~ts' in '~ts for ~ts~n'\", [C, Filename, Regex]});
";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert_eq!(
        copyrights
            .iter()
            .map(|c| c.copyright.as_str())
            .collect::<Vec<_>>(),
        vec!["Copyright Ericsson AB 2024-2026"],
        "expected only the header notice, got {copyrights:?}"
    );
    assert_eq!(
        holders
            .iter()
            .map(|h| h.holder.as_str())
            .collect::<Vec<_>>(),
        vec!["Ericsson AB"],
        "expected only the header holder, got {holders:?}"
    );
}

#[test]
fn test_placeholder_elsewhere_on_the_line_does_not_condemn_a_genuine_notice() {
    // The placeholder must fill this notice's own year slot: an unrelated one
    // further along the line leaves an undated but genuine notice alone.
    let content = "# Copyright Acme Corp. Release dates in this file use the YYYY format.\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert_eq!(
        copyrights
            .iter()
            .map(|c| c.copyright.as_str())
            .collect::<Vec<_>>(),
        vec!["Copyright Acme Corp."],
        "expected the undated notice, got {copyrights:?}"
    );
    assert_eq!(
        holders
            .iter()
            .map(|h| h.holder.as_str())
            .collect::<Vec<_>>(),
        vec!["Acme Corp."],
        "expected the undated holder, got {holders:?}"
    );
}

#[test]
fn test_unrelated_year_on_the_line_does_not_excuse_a_quoted_template() {
    // The year that matters is the detection's own: a real year elsewhere in the
    // prose must not make the quoted template read as a dated notice.
    let content = "> In 2025 the notice must read `Copyright Acme AB YYYY. All Rights Reserved.`\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights.is_empty(),
        "unexpected copyrights: {copyrights:?}"
    );
    assert!(holders.is_empty(), "unexpected holders: {holders:?}");
}

#[test]
fn test_line_that_asserts_and_then_templates_the_same_notice_keeps_the_assertion() {
    // A detection records only its line, so when the value occurs twice the
    // placeholder cannot be pinned to one of them; the assertion wins.
    let content = "# Copyright Acme AB. New files must read Copyright Acme AB YYYY.\n";
    let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
    assert!(
        copyrights
            .iter()
            .any(|c| c.copyright == "Copyright Acme AB"),
        "expected the asserted notice, got {copyrights:?}"
    );
    assert!(
        holders.iter().any(|h| h.holder == "Acme AB"),
        "expected the asserted holder, got {holders:?}"
    );
}

#[test]
fn test_template_is_recognized_however_its_notice_is_spaced_or_punctuated() {
    // The year slot is read off the source line, so a template survives none of
    // the spellings that refinement would normalize away in the value.
    for content in [
        "# Copyright  Acme  AB  YYYY.\n",
        "# Copyright Acme AB, YYYY.\n",
        "> the notice must read `Copyright  Acme  AB  YYYY. All Rights Reserved.`. See below\n",
        "> the notice must read `Copyright Acme AB, YYYY. All Rights Reserved.`. See below\n",
        "> the notice must read `\u{a9} Acme  AB YYYY. All Rights Reserved.`. See below\n",
    ] {
        let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
        assert!(
            copyrights.is_empty(),
            "template produced copyrights {copyrights:?} for {content:?}"
        );
        assert!(
            holders.is_empty(),
            "template produced holders {holders:?} for {content:?}"
        );
    }
}

#[test]
fn test_placeholder_prose_behind_any_punctuation_keeps_the_notice() {
    // The year slot ends where the notice does — at a lowercase prose word, or at
    // a sentence or clause boundary — so no punctuation and no title-cased prose
    // can pull an unrelated `YYYY` into the notice.
    for content in [
        "# Copyright Acme Corp; dates use YYYY\n",
        "# Copyright Acme Corp: dates use YYYY\n",
        "# Copyright Acme Corp \u{2014} dates use YYYY\n",
        "# Copyright Acme Corp (dates use YYYY)\n",
        "# Copyright Acme Corp. Release Dates Use YYYY\n",
        "# Copyright Acme Corp; Dates Use YYYY\n",
        "# Copyright Acme Corp: Dates Use YYYY\n",
    ] {
        let (copyrights, holders, _authors) = detect_copyrights_from_text(content);
        assert!(
            copyrights.iter().any(|c| c.copyright.contains("Acme Corp")),
            "expected the notice, got {copyrights:?} for {content:?}"
        );
        assert!(
            holders.iter().any(|h| h.holder.contains("Acme Corp")),
            "expected the holder, got {holders:?} for {content:?}"
        );
    }
}