File: lib.rs

package info (click to toggle)
rust-upstream-ontologist 0.3.11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: xml: 186; python: 13; sh: 12; makefile: 2
file content (4387 lines) | stat: -rw-r--r-- 153,848 bytes parent folder | download | duplicates (4)
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
// pyo3 macros use a gil-refs feature
#![allow(unexpected_cfgs)]
#![deny(missing_docs)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]

use futures::stream::StreamExt;
use futures::Stream;
use lazy_regex::regex;
use log::{debug, warn};
use percent_encoding::utf8_percent_encode;
#[cfg(feature = "pyo3")]
use pyo3::{
    exceptions::{PyRuntimeError, PyTypeError, PyValueError},
    prelude::*,
    types::PyDict,
};
use reqwest::header::HeaderMap;
use serde::ser::SerializeSeq;
use std::cmp::Ordering;
use std::fs::File;
use std::io::Read;
use std::pin::Pin;
use std::str::FromStr;

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

static USER_AGENT: &str = concat!("upstream-ontologist/", env!("CARGO_PKG_VERSION"));

/// Functionality for extrapolating upstream metadata from various sources
pub mod extrapolate;
/// Support for various code forges (GitHub, GitLab, etc.)
pub mod forges;
/// Homepage URL detection and validation
pub mod homepage;
/// HTTP utilities for fetching remote resources
pub mod http;
/// Various metadata providers for different programming languages and ecosystems
pub mod providers;
/// README file parsing and metadata extraction
pub mod readme;
/// Integration with Repology package repository aggregator
pub mod repology;
/// Version control system utilities and URL handling
pub mod vcs;
/// Command-line interface for version control operations
pub mod vcs_command;

#[cfg(all(test, feature="setup-cfg", feature="pyo3", feature="debian", feature="python-pkginfo", feature="pyproject-toml", feature="r-description", feature="dist-ini"))]
mod upstream_tests {
    include!(concat!(env!("OUT_DIR"), "/upstream_tests.rs"));
}

#[cfg(test)]
mod readme_tests {
    include!(concat!(env!("OUT_DIR"), "/readme_tests.rs"));
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
/// Certainty levels for the data
pub enum Certainty {
    /// This datum is possibly correct, but it is a guess
    Possible,

    /// This datum is likely to be correct, but we are not sure
    Likely,

    /// We're confident about this datum, but there is a chance it is wrong
    Confident,

    /// We're certain about this datum
    Certain,
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// Origin of the data
pub enum Origin {
    /// Read from a file
    Path(PathBuf),

    /// Read from a URL
    Url(url::Url),

    /// Other origin; described by a string
    Other(String),
}

impl std::fmt::Display for Origin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Origin::Path(path) => write!(f, "{}", path.display()),
            Origin::Url(url) => write!(f, "{}", url),
            Origin::Other(s) => write!(f, "{}", s),
        }
    }
}

impl From<&std::path::Path> for Origin {
    fn from(path: &std::path::Path) -> Self {
        Origin::Path(path.to_path_buf())
    }
}

impl From<std::path::PathBuf> for Origin {
    fn from(path: std::path::PathBuf) -> Self {
        Origin::Path(path)
    }
}

impl From<url::Url> for Origin {
    fn from(url: url::Url) -> Self {
        Origin::Url(url)
    }
}

#[cfg(feature = "pyo3")]
impl<'py> IntoPyObject<'py> for &Origin {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        match self {
            Origin::Path(path) => Ok(path.to_str().unwrap().into_pyobject(py)?.into_any()),
            Origin::Url(url) => Ok(url.to_string().into_pyobject(py)?.into_any()),
            Origin::Other(s) => Ok(s.into_pyobject(py)?.into_any()),
        }
    }
}

#[cfg(feature = "pyo3")]
impl<'py> IntoPyObject<'py> for Origin {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        match self {
            Origin::Path(path) => Ok(path.to_str().unwrap().into_pyobject(py)?.into_any()),
            Origin::Url(url) => Ok(url.to_string().into_pyobject(py)?.into_any()),
            Origin::Other(s) => Ok(s.into_pyobject(py)?.into_any()),
        }
    }
}

#[cfg(feature = "pyo3")]
impl<'py> FromPyObject<'_, 'py> for Origin {
    type Error = PyErr;

    fn extract(ob: pyo3::Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        if let Ok(path) = ob.extract::<PathBuf>() {
            Ok(Origin::Path(path))
        } else if let Ok(s) = ob.extract::<String>() {
            Ok(Origin::Other(s))
        } else {
            Err(PyTypeError::new_err("expected str or Path"))
        }
    }
}

impl FromStr for Certainty {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "certain" => Ok(Certainty::Certain),
            "confident" => Ok(Certainty::Confident),
            "likely" => Ok(Certainty::Likely),
            "possible" => Ok(Certainty::Possible),
            _ => Err(format!("unknown certainty: {}", s)),
        }
    }
}

impl std::fmt::Display for Certainty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Certainty::Certain => write!(f, "certain"),
            Certainty::Confident => write!(f, "confident"),
            Certainty::Likely => write!(f, "likely"),
            Certainty::Possible => write!(f, "possible"),
        }
    }
}

#[cfg(feature = "pyo3")]
impl<'py> FromPyObject<'_, 'py> for Certainty {
    type Error = PyErr;

    fn extract(ob: pyo3::Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        let o: String = ob.extract::<String>()?;
        o.parse().map_err(PyValueError::new_err)
    }
}

/// Represents a person (author, maintainer, etc.) with optional contact information
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Person {
    /// The person's name
    pub name: Option<String>,
    /// The person's email address
    pub email: Option<String>,
    /// The person's URL (e.g., personal website, profile)
    pub url: Option<String>,
}

impl serde::ser::Serialize for Person {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        let mut map = serde_yaml::Mapping::new();
        if let Some(name) = &self.name {
            map.insert(
                serde_yaml::Value::String("name".to_string()),
                serde_yaml::Value::String(name.to_string()),
            );
        }
        if let Some(email) = &self.email {
            map.insert(
                serde_yaml::Value::String("email".to_string()),
                serde_yaml::Value::String(email.to_string()),
            );
        }
        if let Some(url) = &self.url {
            map.insert(
                serde_yaml::Value::String("url".to_string()),
                serde_yaml::Value::String(url.to_string()),
            );
        }
        let tag = serde_yaml::value::TaggedValue {
            tag: serde_yaml::value::Tag::new("!Person"),
            value: serde_yaml::Value::Mapping(map),
        };
        tag.serialize(serializer)
    }
}

impl<'a> serde::de::Deserialize<'a> for Person {
    fn deserialize<D>(deserializer: D) -> Result<Person, D::Error>
    where
        D: serde::de::Deserializer<'a>,
    {
        let value = serde_yaml::Value::deserialize(deserializer)?;
        if let serde_yaml::Value::Mapping(map) = value {
            let mut name = None;
            let mut email = None;
            let mut url = None;
            for (k, v) in map {
                match k {
                    serde_yaml::Value::String(k) => match k.as_str() {
                        "name" => {
                            if let serde_yaml::Value::String(s) = v {
                                name = Some(s);
                            }
                        }
                        "email" => {
                            if let serde_yaml::Value::String(s) = v {
                                email = Some(s);
                            }
                        }
                        "url" => {
                            if let serde_yaml::Value::String(s) = v {
                                url = Some(s);
                            }
                        }
                        n => {
                            return Err(serde::de::Error::custom(format!("unknown key: {}", n)));
                        }
                    },
                    n => {
                        return Err(serde::de::Error::custom(format!(
                            "expected string key, got {:?}",
                            n
                        )));
                    }
                }
            }
            Ok(Person { name, email, url })
        } else {
            Err(serde::de::Error::custom("expected mapping"))
        }
    }
}

impl std::fmt::Display for Person {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name.as_ref().unwrap_or(&"".to_string()))?;
        if let Some(email) = &self.email {
            write!(f, " <{}>", email)?;
        }
        if let Some(url) = &self.url {
            write!(f, " ({})", url)?;
        }
        Ok(())
    }
}

impl From<&str> for Person {
    fn from(text: &str) -> Self {
        let mut text = text.replace(" at ", "@");
        text = text.replace(" -at- ", "@");
        text = text.replace(" -dot- ", ".");
        text = text.replace("[AT]", "@");

        if text.contains('(') && text.ends_with(')') {
            if let Some((p1, p2)) = text[..text.len() - 1].split_once('(') {
                if p2.starts_with("https://") || p2.starts_with("http://") {
                    let url = p2.to_string();
                    if let Some((name, email)) = parseaddr(p1) {
                        Person {
                            name: Some(name),
                            email: Some(email),
                            url: Some(url),
                        }
                    } else {
                        Person {
                            name: Some(p1.to_string()),
                            url: Some(url),
                            ..Default::default()
                        }
                    }
                } else if p2.contains('@') {
                    Person {
                        name: Some(p1.to_string()),
                        email: Some(p2.to_string()),
                        ..Default::default()
                    }
                } else {
                    Person {
                        name: Some(text.to_string()),
                        ..Default::default()
                    }
                }
            } else {
                Person {
                    name: Some(text.to_string()),
                    ..Default::default()
                }
            }
        } else if text.contains('<') {
            if let Some((name, email)) = parseaddr(text.as_str()) {
                return Person {
                    name: Some(name),
                    email: Some(email),
                    ..Default::default()
                };
            } else {
                Person {
                    name: Some(text.to_string()),
                    ..Default::default()
                }
            }
        } else if text.contains('@') && !text.contains(' ') {
            return Person {
                email: Some(text),
                ..Default::default()
            };
        } else {
            Person {
                name: Some(text),
                ..Default::default()
            }
        }
    }
}

#[cfg(feature = "pyo3")]
impl<'py> IntoPyObject<'py> for &Person {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        let m = PyModule::import(py, "upstream_ontologist")?;
        let person_cls = m.getattr("Person")?;
        person_cls.call1((self.name.as_ref(), self.email.as_ref(), self.url.as_ref()))
    }
}

fn parseaddr(text: &str) -> Option<(String, String)> {
    let re = regex!(r"(.*?)\s*<([^<>]+)>");
    if let Some(captures) = re.captures(text) {
        let name = captures.get(1).map(|m| m.as_str().trim().to_string());
        let email = captures.get(2).map(|m| m.as_str().trim().to_string());
        if let (Some(name), Some(email)) = (name, email) {
            return Some((name, email));
        }
    }
    None
}

#[cfg(feature = "pyo3")]
impl<'py> FromPyObject<'_, 'py> for Person {
    type Error = PyErr;

    fn extract(ob: pyo3::Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        let name = ob.getattr("name")?.extract::<Option<String>>()?;
        let email = ob.getattr("email")?.extract::<Option<String>>()?;
        let url = ob.getattr("url")?.extract::<Option<String>>()?;
        Ok(Person { name, email, url })
    }
}

/// Represents various types of upstream metadata for a software project
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UpstreamDatum {
    /// Name of the project.
    ///
    /// This is a brief name of the project, as it would be used in a URL.
    /// Generally speaking it would be lowercase, and may contain dashes or underscores.
    /// It would commonly be the name of the repository.
    Name(String),

    /// URL to project homepage.
    ///
    /// This is the URL to the project's homepage, which may be a website or a
    /// repository. It is not a URL to a specific file or page, but rather the main
    /// entry point for the project.
    Homepage(String),

    /// URL to the project's source code repository.
    ///
    /// This is the URL to the project's source code repository, as it would be used
    /// in a command line tool to clone the repository. It may be a URL to a specific
    /// branch or tag, but it is generally the URL to the main repository.
    Repository(String),

    /// URL to browse the project's source code repository
    ///
    /// This is the URL to the project's source code repository, as it would be used
    /// in a web browser to browse the repository. It may be a URL to a specific
    /// branch or tag, but it is generally the URL to the main repository.
    RepositoryBrowse(String),

    /// Long description of the project
    ///
    /// This is a long description of the project, which may be several paragraphs
    /// long. It is generally a more detailed description of the project than the
    /// summary.
    Description(String),

    /// Short summary of the project (one line)
    ///
    /// This is a short summary of the project, which is generally one line long.
    /// It is generally a brief description of the project, and may be used in
    /// search results or in a list of projects.
    Summary(String),

    /// License name or SPDX identifier
    ///
    /// This is the name of the license under which the project is released. It may
    /// be a full license name, or it may be an SPDX identifier (preferred).
    ///
    /// See <https://spdx.org/licenses/> for a list of SPDX identifiers.
    License(String),

    /// List of authors
    ///
    /// This is a list of authors of the project, which may be a list of names,
    /// email addresses, or URLs.
    Author(Vec<Person>),

    /// List of maintainers
    ///
    /// This is a list of maintainers of the project, which may be a list of names,
    /// email addresses, or URLs.
    Maintainer(Person),

    /// URL of the project's issue tracker
    ///
    /// This is the URL to the project's issue tracker, which may be a bug tracker,
    /// feature tracker, or other type of issue tracker. It is not a URL to a
    /// specific issue, but rather the main entry point for the issue tracker.
    BugDatabase(String),

    /// URL to submit a new bug
    ///
    /// This is the URL to submit a new bug to the project's issue tracker. It
    /// may be a URL to a specific page or form.
    ///
    /// It can also be an email address (mailto:...), in which case it is the email address to send
    /// the bug report to.
    BugSubmit(String),

    /// URL to the project's contact page or email address
    ///
    /// This is the URL to the project's contact page, which may be a web page or
    /// an email address. It is not a URL to a specific file or page, but rather
    /// the main entry point for the contact page.
    Contact(String),

    /// Cargo crate name
    ///
    /// If the project is a Rust crate, this is the name of the crate on
    /// crates.io. It is not a URL to the crate, but rather the name of the
    /// crate.
    CargoCrate(String),

    /// Name of the security page name
    ///
    /// This would be the name of a markdown file in the source directory
    /// that contains security information about the project. It is not a URL to
    /// a specific file or page, but rather the name of the file.
    SecurityMD(String),

    /// URL to the security page or email address
    ///
    /// This is the URL to the project's security page, which may be a web page or
    /// an email address. It is not a URL to a specific file or page, but rather
    /// the main entry point for the security page.
    ///
    /// It can also be an email address (mailto:...), in which case it is the email address to send
    /// the security report to.
    SecurityContact(String),

    /// Last version of the project
    ///
    /// This is the last version of the project, which would generally be a version string
    ///
    /// There is no guarantee that this is the last version of the project.
    ///
    /// There is no guarantee about which versioning scheme is used, e.g. it may be
    /// a semantic version, a date-based version, or a commit hash.
    Version(String),

    /// List of keywords
    ///
    /// This is a list of keywords that describe the project. It may be a list of
    /// words, phrases, or tags.
    Keywords(Vec<String>),

    /// Copyright notice
    ///
    /// This is the copyright notice for the project, which may be a list of
    /// copyright holders, years, or other information.
    Copyright(String),

    /// URL to the project's documentation
    ///
    /// This is the URL to the project's documentation, which may be a web page or
    /// a file. It is not a URL to a specific file or page, but rather the main
    /// entry point for the documentation.
    Documentation(String),

    /// URL to the project's API documentation
    ///
    /// This is the URL to the project's API documentation, which may be a web page or
    /// a file. It is not a URL to a specific file or page, but rather the main
    /// entry point for the API documentation.
    APIDocumentation(String),

    /// Go import path
    ///
    /// If this is a Go project, this is the import path for the project. It is not a URL
    /// to the project, but rather the import path.
    GoImportPath(String),

    /// URL to the project's download page
    ///
    /// This is the URL to the project's download page, which may be a web page or
    /// a file. It is not a URL to a specific file or page, but rather the main
    /// entry point for the download page.
    Download(String),

    /// URL to the project's wiki
    ///
    /// This is the URL to the project's wiki.
    Wiki(String),

    /// URL to the project's mailing list
    ///
    /// This is the URL to the project's mailing list, which may be a web page or
    /// an email address. It is not a URL to a specific file or page, but rather
    /// the main entry point for the mailing list.
    ///
    /// It can also be an email address (mailto:...), in which case it is the email address to send
    /// email to to subscribe to the mailing list.
    MailingList(String),

    /// SourceForge project name
    ///
    /// This is the name of the project on SourceForge. It is not a URL to the
    /// project, but rather the name of the project.
    SourceForgeProject(String),

    /// If this project is provided by a specific archive, this is the name of the archive.
    ///
    /// E.g. "CRAN", "CPAN", "PyPI", "RubyGems", "NPM", etc.
    Archive(String),

    /// URL to a demo instance
    ///
    /// This is the URL to a demo instance of the project. This instance will be loaded
    /// with sample data, and will be used to demonstrate the project. It is not
    /// a full instance of the project - the Webservice field should be used for that.
    Demo(String),

    /// PHP PECL package name
    ///
    /// If this is a PHP project, this is the name of the package on PECL. It is not a URL
    /// to the package, but rather the name of the package.
    PeclPackage(String),

    /// Description of funding sources
    ///
    /// This is a description of the funding sources for the project. It may be a
    /// URL to a page that describes the funding sources, or it may be a list of
    /// funding sources.
    ///
    /// Note that this is different from the Donation field, which is a URL to a
    /// donation page.
    Funding(String),

    /// URL to the changelog
    ///
    /// This is the URL to the project's changelog, which may be a web page or
    /// a file. No guarantee is made about the format of the changelog, but it is
    /// generally a file that contains a list of changes made to the project.
    Changelog(String),

    /// Haskell package name
    ///
    /// If this is a Haskell project, this is the name of the package on Hackage. It is not a URL
    /// to the package, but rather the name of the package.
    HaskellPackage(String),

    /// Debian ITP (Intent To Package) bug number
    ///
    /// This is the bug number of the ITP bug in the Debian bug tracker. It is not a URL
    /// to the bug, but rather the bug number.
    DebianITP(i32),

    /// List of URLs to screenshots
    ///
    /// This is a list of URLs to screenshots of the project. It will be a list of
    /// URLs, which may be web pages or images.
    Screenshots(Vec<String>),

    /// Name of registry
    Registry(Vec<(String, String)>),

    /// Recommended way to cite the software
    ///
    /// This is the recommended way to cite the software, which may be a URL or a
    /// DOI.
    CiteAs(String),

    /// Link for donations (e.g. Paypal, Libera, etc)
    ///
    /// This is a URL to a donation page, which should be a web page.
    /// It is different from the Funding field, which describes
    /// the funding the project has received.
    Donation(String),

    /// Link to a life instance of the webservice
    ///
    /// This is the URL to the live instance of the project. This should generally
    /// be the canonical instance of the project.
    ///
    /// For demo instances, see the Demo field.
    Webservice(String),

    /// Name of the buildsystem used
    ///
    /// This is the name of the buildsystem used by the project. E.g. "make", "cmake",
    /// "meson", etc
    BuildSystem(String),

    /// FAQ
    ///
    /// This is the URL to the project's FAQ, which may be a web page or a file.
    FAQ(String),
}

/// Upstream datum with additional metadata about its origin and certainty
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct UpstreamDatumWithMetadata {
    /// The upstream datum itself
    pub datum: UpstreamDatum,
    /// Where this datum was obtained from
    pub origin: Option<Origin>,
    /// How certain we are about this datum
    pub certainty: Option<Certainty>,
}

fn known_bad_url(value: &str) -> bool {
    if value.contains("${") {
        return true;
    }
    false
}

impl UpstreamDatum {
    /// Returns the field name for this datum type
    pub fn field(&self) -> &'static str {
        match self {
            UpstreamDatum::Summary(..) => "Summary",
            UpstreamDatum::Description(..) => "Description",
            UpstreamDatum::Name(..) => "Name",
            UpstreamDatum::Homepage(..) => "Homepage",
            UpstreamDatum::Repository(..) => "Repository",
            UpstreamDatum::RepositoryBrowse(..) => "Repository-Browse",
            UpstreamDatum::License(..) => "License",
            UpstreamDatum::Author(..) => "Author",
            UpstreamDatum::BugDatabase(..) => "Bug-Database",
            UpstreamDatum::BugSubmit(..) => "Bug-Submit",
            UpstreamDatum::Contact(..) => "Contact",
            UpstreamDatum::CargoCrate(..) => "Cargo-Crate",
            UpstreamDatum::SecurityMD(..) => "Security-MD",
            UpstreamDatum::SecurityContact(..) => "Security-Contact",
            UpstreamDatum::Version(..) => "Version",
            UpstreamDatum::Keywords(..) => "Keywords",
            UpstreamDatum::Maintainer(..) => "Maintainer",
            UpstreamDatum::Copyright(..) => "Copyright",
            UpstreamDatum::Documentation(..) => "Documentation",
            UpstreamDatum::APIDocumentation(..) => "API-Documentation",
            UpstreamDatum::GoImportPath(..) => "Go-Import-Path",
            UpstreamDatum::Download(..) => "Download",
            UpstreamDatum::Wiki(..) => "Wiki",
            UpstreamDatum::MailingList(..) => "MailingList",
            UpstreamDatum::SourceForgeProject(..) => "SourceForge-Project",
            UpstreamDatum::Archive(..) => "Archive",
            UpstreamDatum::Demo(..) => "Demo",
            UpstreamDatum::PeclPackage(..) => "Pecl-Package",
            UpstreamDatum::HaskellPackage(..) => "Haskell-Package",
            UpstreamDatum::Funding(..) => "Funding",
            UpstreamDatum::Changelog(..) => "Changelog",
            UpstreamDatum::DebianITP(..) => "Debian-ITP",
            UpstreamDatum::Screenshots(..) => "Screenshots",
            UpstreamDatum::Registry(..) => "Registry",
            UpstreamDatum::CiteAs(..) => "Cite-As",
            UpstreamDatum::Donation(..) => "Donation",
            UpstreamDatum::Webservice(..) => "Webservice",
            UpstreamDatum::BuildSystem(..) => "BuildSystem",
            UpstreamDatum::FAQ(..) => "FAQ",
        }
    }

    /// Returns the string value if this datum contains a simple string
    pub fn as_str(&self) -> Option<&str> {
        match self {
            UpstreamDatum::Name(s) => Some(s),
            UpstreamDatum::Homepage(s) => Some(s),
            UpstreamDatum::Repository(s) => Some(s),
            UpstreamDatum::RepositoryBrowse(s) => Some(s),
            UpstreamDatum::Description(s) => Some(s),
            UpstreamDatum::Summary(s) => Some(s),
            UpstreamDatum::License(s) => Some(s),
            UpstreamDatum::BugDatabase(s) => Some(s),
            UpstreamDatum::BugSubmit(s) => Some(s),
            UpstreamDatum::Contact(s) => Some(s),
            UpstreamDatum::CargoCrate(s) => Some(s),
            UpstreamDatum::SecurityMD(s) => Some(s),
            UpstreamDatum::SecurityContact(s) => Some(s),
            UpstreamDatum::Version(s) => Some(s),
            UpstreamDatum::Documentation(s) => Some(s),
            UpstreamDatum::APIDocumentation(s) => Some(s),
            UpstreamDatum::GoImportPath(s) => Some(s),
            UpstreamDatum::Download(s) => Some(s),
            UpstreamDatum::Wiki(s) => Some(s),
            UpstreamDatum::MailingList(s) => Some(s),
            UpstreamDatum::SourceForgeProject(s) => Some(s),
            UpstreamDatum::Archive(s) => Some(s),
            UpstreamDatum::Demo(s) => Some(s),
            UpstreamDatum::PeclPackage(s) => Some(s),
            UpstreamDatum::HaskellPackage(s) => Some(s),
            UpstreamDatum::Author(..) => None,
            UpstreamDatum::Maintainer(..) => None,
            UpstreamDatum::Keywords(..) => None,
            UpstreamDatum::Copyright(c) => Some(c),
            UpstreamDatum::Funding(f) => Some(f),
            UpstreamDatum::Changelog(c) => Some(c),
            UpstreamDatum::Screenshots(..) => None,
            UpstreamDatum::DebianITP(_c) => None,
            UpstreamDatum::CiteAs(c) => Some(c),
            UpstreamDatum::Registry(_) => None,
            UpstreamDatum::Donation(d) => Some(d),
            UpstreamDatum::Webservice(w) => Some(w),
            UpstreamDatum::BuildSystem(b) => Some(b),
            UpstreamDatum::FAQ(f) => Some(f),
        }
    }

    /// Converts the datum to a URL if applicable
    pub fn to_url(&self) -> Option<url::Url> {
        match self {
            UpstreamDatum::Name(..) => None,
            UpstreamDatum::Homepage(s) => Some(s.parse().ok()?),
            UpstreamDatum::Repository(s) => Some(s.parse().ok()?),
            UpstreamDatum::RepositoryBrowse(s) => Some(s.parse().ok()?),
            UpstreamDatum::Description(..) => None,
            UpstreamDatum::Summary(..) => None,
            UpstreamDatum::License(..) => None,
            UpstreamDatum::BugDatabase(s) => Some(s.parse().ok()?),
            UpstreamDatum::BugSubmit(s) => Some(s.parse().ok()?),
            UpstreamDatum::Contact(..) => None,
            UpstreamDatum::CargoCrate(s) => Some(s.parse().ok()?),
            UpstreamDatum::SecurityMD(..) => None,
            UpstreamDatum::SecurityContact(..) => None,
            UpstreamDatum::Version(..) => None,
            UpstreamDatum::Documentation(s) => Some(s.parse().ok()?),
            UpstreamDatum::APIDocumentation(s) => Some(s.parse().ok()?),
            UpstreamDatum::GoImportPath(_s) => None,
            UpstreamDatum::Download(s) => Some(s.parse().ok()?),
            UpstreamDatum::Wiki(s) => Some(s.parse().ok()?),
            UpstreamDatum::MailingList(s) => Some(s.parse().ok()?),
            UpstreamDatum::SourceForgeProject(s) => Some(s.parse().ok()?),
            UpstreamDatum::Archive(s) => Some(s.parse().ok()?),
            UpstreamDatum::Demo(s) => Some(s.parse().ok()?),
            UpstreamDatum::PeclPackage(_s) => None,
            UpstreamDatum::HaskellPackage(_s) => None,
            UpstreamDatum::Author(..) => None,
            UpstreamDatum::Maintainer(..) => None,
            UpstreamDatum::Keywords(..) => None,
            UpstreamDatum::Copyright(..) => None,
            UpstreamDatum::Funding(s) => Some(s.parse().ok()?),
            UpstreamDatum::Changelog(s) => Some(s.parse().ok()?),
            UpstreamDatum::Screenshots(..) => None,
            UpstreamDatum::DebianITP(_c) => None,
            UpstreamDatum::Registry(_r) => None,
            UpstreamDatum::CiteAs(_c) => None,
            UpstreamDatum::Donation(_d) => None,
            UpstreamDatum::Webservice(w) => Some(w.parse().ok()?),
            UpstreamDatum::BuildSystem(_) => None,
            UpstreamDatum::FAQ(f) => Some(f.parse().ok()?),
        }
    }

    /// Returns the person if this datum contains person information
    pub fn as_person(&self) -> Option<&Person> {
        match self {
            UpstreamDatum::Maintainer(p) => Some(p),
            _ => None,
        }
    }

    /// Checks if this datum is known to be a bad guess based on common patterns
    pub fn known_bad_guess(&self) -> bool {
        match self {
            UpstreamDatum::BugDatabase(s) | UpstreamDatum::BugSubmit(s) => {
                if known_bad_url(s) {
                    return true;
                }
                let url = match Url::parse(s) {
                    Ok(url) => url,
                    Err(_) => return false,
                };
                if url.host_str() == Some("bugzilla.gnome.org") {
                    return true;
                }
                if url.host_str() == Some("bugs.freedesktop.org") {
                    return true;
                }
                if url.path().ends_with("/sign_in") {
                    return true;
                }
            }
            UpstreamDatum::Repository(s) => {
                if known_bad_url(s) {
                    return true;
                }
                let url = match Url::parse(s) {
                    Ok(url) => url,
                    Err(_) => return false,
                };
                if url.host_str() == Some("anongit.kde.org") {
                    return true;
                }
                if url.host_str() == Some("git.gitorious.org") {
                    return true;
                }
                if url.path().ends_with("/sign_in") {
                    return true;
                }
            }
            UpstreamDatum::Homepage(s) => {
                let url = match Url::parse(s) {
                    Ok(url) => url,
                    Err(_) => return false,
                };

                if url.host_str() == Some("pypi.org") {
                    return true;
                }
                if url.host_str() == Some("rubygems.org") {
                    return true;
                }
            }
            UpstreamDatum::RepositoryBrowse(s) => {
                if known_bad_url(s) {
                    return true;
                }
                let url = match Url::parse(s) {
                    Ok(url) => url,
                    Err(_) => return false,
                };
                if url.host_str() == Some("cgit.kde.org") {
                    return true;
                }
                if url.path().ends_with("/sign_in") {
                    return true;
                }
            }
            UpstreamDatum::Author(authors) => {
                for a in authors {
                    if let Some(name) = &a.name {
                        let lc = name.to_lowercase();
                        if lc.contains("unknown") {
                            return true;
                        }
                        if lc.contains("maintainer") {
                            return true;
                        }
                        if lc.contains("contributor") {
                            return true;
                        }
                    }
                }
            }
            UpstreamDatum::Name(s) => {
                let lc = s.to_lowercase();
                if lc.contains("unknown") {
                    return true;
                }
                if lc == "package" {
                    return true;
                }
            }
            UpstreamDatum::Version(s) => {
                let lc = s.to_lowercase();
                if ["devel", "unknown"].contains(&lc.as_str()) {
                    return true;
                }
            }
            _ => (),
        }
        false
    }
}

impl std::fmt::Display for UpstreamDatum {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UpstreamDatum::Name(s) => write!(f, "Name: {}", s),
            UpstreamDatum::Homepage(s) => write!(f, "Homepage: {}", s),
            UpstreamDatum::Repository(s) => write!(f, "Repository: {}", s),
            UpstreamDatum::RepositoryBrowse(s) => write!(f, "RepositoryBrowse: {}", s),
            UpstreamDatum::Description(s) => write!(f, "Description: {}", s),
            UpstreamDatum::Summary(s) => write!(f, "Summary: {}", s),
            UpstreamDatum::License(s) => write!(f, "License: {}", s),
            UpstreamDatum::BugDatabase(s) => write!(f, "BugDatabase: {}", s),
            UpstreamDatum::BugSubmit(s) => write!(f, "BugSubmit: {}", s),
            UpstreamDatum::Contact(s) => write!(f, "Contact: {}", s),
            UpstreamDatum::CargoCrate(s) => write!(f, "CargoCrate: {}", s),
            UpstreamDatum::SecurityMD(s) => write!(f, "SecurityMD: {}", s),
            UpstreamDatum::SecurityContact(s) => write!(f, "SecurityContact: {}", s),
            UpstreamDatum::Version(s) => write!(f, "Version: {}", s),
            UpstreamDatum::Documentation(s) => write!(f, "Documentation: {}", s),
            UpstreamDatum::APIDocumentation(s) => write!(f, "API-Documentation: {}", s),
            UpstreamDatum::GoImportPath(s) => write!(f, "GoImportPath: {}", s),
            UpstreamDatum::Download(s) => write!(f, "Download: {}", s),
            UpstreamDatum::Wiki(s) => write!(f, "Wiki: {}", s),
            UpstreamDatum::MailingList(s) => write!(f, "MailingList: {}", s),
            UpstreamDatum::SourceForgeProject(s) => write!(f, "SourceForgeProject: {}", s),
            UpstreamDatum::Archive(s) => write!(f, "Archive: {}", s),
            UpstreamDatum::Demo(s) => write!(f, "Demo: {}", s),
            UpstreamDatum::PeclPackage(s) => write!(f, "PeclPackage: {}", s),
            UpstreamDatum::Author(authors) => {
                write!(
                    f,
                    "Author: {}",
                    authors
                        .iter()
                        .map(|a| a.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            UpstreamDatum::Maintainer(maintainer) => {
                write!(f, "Maintainer: {}", maintainer)
            }
            UpstreamDatum::Keywords(keywords) => {
                write!(
                    f,
                    "Keywords: {}",
                    keywords
                        .iter()
                        .map(|a| a.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            UpstreamDatum::Copyright(s) => {
                write!(f, "Copyright: {}", s)
            }
            UpstreamDatum::Funding(s) => {
                write!(f, "Funding: {}", s)
            }
            UpstreamDatum::Changelog(s) => {
                write!(f, "Changelog: {}", s)
            }
            UpstreamDatum::DebianITP(s) => {
                write!(f, "DebianITP: {}", s)
            }
            UpstreamDatum::HaskellPackage(p) => {
                write!(f, "HaskellPackage: {}", p)
            }
            UpstreamDatum::Screenshots(s) => {
                write!(f, "Screenshots: {}", s.join(", "))
            }
            UpstreamDatum::Registry(r) => {
                write!(f, "Registry:")?;
                for (k, v) in r {
                    write!(f, "  - Name: {}", k)?;
                    write!(f, "    Entry: {}", v)?;
                }
                Ok(())
            }
            UpstreamDatum::CiteAs(c) => {
                write!(f, "Cite-As: {}", c)
            }
            UpstreamDatum::Donation(d) => {
                write!(f, "Donation: {}", d)
            }
            UpstreamDatum::Webservice(w) => {
                write!(f, "Webservice: {}", w)
            }
            UpstreamDatum::BuildSystem(bs) => {
                write!(f, "BuildSystem: {}", bs)
            }
            UpstreamDatum::FAQ(faq) => {
                write!(f, "FAQ: {}", faq)
            }
        }
    }
}

impl serde::ser::Serialize for UpstreamDatum {
    fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            UpstreamDatum::Name(s) => serializer.serialize_str(s),
            UpstreamDatum::Homepage(s) => serializer.serialize_str(s),
            UpstreamDatum::Repository(s) => serializer.serialize_str(s),
            UpstreamDatum::RepositoryBrowse(s) => serializer.serialize_str(s),
            UpstreamDatum::Description(s) => serializer.serialize_str(s),
            UpstreamDatum::Summary(s) => serializer.serialize_str(s),
            UpstreamDatum::License(s) => serializer.serialize_str(s),
            UpstreamDatum::BugDatabase(s) => serializer.serialize_str(s),
            UpstreamDatum::BugSubmit(s) => serializer.serialize_str(s),
            UpstreamDatum::Contact(s) => serializer.serialize_str(s),
            UpstreamDatum::CargoCrate(s) => serializer.serialize_str(s),
            UpstreamDatum::SecurityMD(s) => serializer.serialize_str(s),
            UpstreamDatum::SecurityContact(s) => serializer.serialize_str(s),
            UpstreamDatum::Version(s) => serializer.serialize_str(s),
            UpstreamDatum::Documentation(s) => serializer.serialize_str(s),
            UpstreamDatum::APIDocumentation(s) => serializer.serialize_str(s),
            UpstreamDatum::GoImportPath(s) => serializer.serialize_str(s),
            UpstreamDatum::Download(s) => serializer.serialize_str(s),
            UpstreamDatum::Wiki(s) => serializer.serialize_str(s),
            UpstreamDatum::MailingList(s) => serializer.serialize_str(s),
            UpstreamDatum::SourceForgeProject(s) => serializer.serialize_str(s),
            UpstreamDatum::Archive(s) => serializer.serialize_str(s),
            UpstreamDatum::Demo(s) => serializer.serialize_str(s),
            UpstreamDatum::PeclPackage(s) => serializer.serialize_str(s),
            UpstreamDatum::Author(authors) => {
                let mut seq = serializer.serialize_seq(Some(authors.len()))?;
                for a in authors {
                    seq.serialize_element(a)?;
                }
                seq.end()
            }
            UpstreamDatum::Maintainer(maintainer) => maintainer.serialize(serializer),
            UpstreamDatum::Keywords(keywords) => {
                let mut seq = serializer.serialize_seq(Some(keywords.len()))?;
                for a in keywords {
                    seq.serialize_element(a)?;
                }
                seq.end()
            }
            UpstreamDatum::Copyright(s) => serializer.serialize_str(s),
            UpstreamDatum::Funding(s) => serializer.serialize_str(s),
            UpstreamDatum::Changelog(s) => serializer.serialize_str(s),
            UpstreamDatum::DebianITP(s) => serializer.serialize_i32(*s),
            UpstreamDatum::HaskellPackage(p) => serializer.serialize_str(p),
            UpstreamDatum::Screenshots(s) => {
                let mut seq = serializer.serialize_seq(Some(s.len()))?;
                for s in s {
                    seq.serialize_element(s)?;
                }
                seq.end()
            }
            UpstreamDatum::CiteAs(c) => serializer.serialize_str(c),
            UpstreamDatum::Registry(r) => {
                let mut l = serializer.serialize_seq(Some(r.len()))?;
                for (k, v) in r {
                    let mut m = serde_yaml::Mapping::new();
                    m.insert(
                        serde_yaml::Value::String("Name".to_string()),
                        serde_yaml::to_value(k).unwrap(),
                    );
                    m.insert(
                        serde_yaml::Value::String("Entry".to_string()),
                        serde_yaml::to_value(v).unwrap(),
                    );
                    l.serialize_element(&m)?;
                }
                l.end()
            }
            UpstreamDatum::Donation(d) => serializer.serialize_str(d),
            UpstreamDatum::Webservice(w) => serializer.serialize_str(w),
            UpstreamDatum::BuildSystem(bs) => serializer.serialize_str(bs),
            UpstreamDatum::FAQ(faq) => serializer.serialize_str(faq),
        }
    }
}

/// Collection of upstream metadata with convenience methods for accessing specific fields
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct UpstreamMetadata(Vec<UpstreamDatumWithMetadata>);

impl UpstreamMetadata {
    /// Creates a new empty UpstreamMetadata instance
    pub fn new() -> Self {
        UpstreamMetadata(Vec::new())
    }

    /// Returns true if the metadata collection is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of metadata items
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Sorts the metadata items by field name
    pub fn sort(&mut self) {
        self.0.sort_by(|a, b| a.datum.field().cmp(b.datum.field()));
    }

    /// Creates a new UpstreamMetadata from a vector of data
    pub fn from_data(data: Vec<UpstreamDatumWithMetadata>) -> Self {
        Self(data)
    }

    /// Returns a mutable reference to the underlying data vector
    pub fn mut_items(&mut self) -> &mut Vec<UpstreamDatumWithMetadata> {
        &mut self.0
    }

    /// Returns an iterator over the metadata items
    pub fn iter(&self) -> impl Iterator<Item = &UpstreamDatumWithMetadata> {
        self.0.iter()
    }

    /// Returns a mutable iterator over the metadata items
    pub fn mut_iter(&mut self) -> impl Iterator<Item = &mut UpstreamDatumWithMetadata> {
        self.0.iter_mut()
    }

    /// Gets a metadata item by field name
    pub fn get(&self, field: &str) -> Option<&UpstreamDatumWithMetadata> {
        self.0.iter().find(|d| d.datum.field() == field)
    }

    /// Gets a mutable reference to a metadata item by field name
    pub fn get_mut(&mut self, field: &str) -> Option<&mut UpstreamDatumWithMetadata> {
        self.0.iter_mut().find(|d| d.datum.field() == field)
    }

    /// Inserts a new metadata item
    pub fn insert(&mut self, datum: UpstreamDatumWithMetadata) {
        self.0.push(datum);
    }

    /// Checks if a field exists in the metadata
    pub fn contains_key(&self, field: &str) -> bool {
        self.get(field).is_some()
    }

    /// Removes metadata items that are known to be bad guesses
    pub fn discard_known_bad(&mut self) {
        self.0.retain(|d| !d.datum.known_bad_guess());
    }

    /// Updates the metadata with new items, returning the replaced items
    pub fn update(
        &mut self,
        new_items: impl Iterator<Item = UpstreamDatumWithMetadata>,
    ) -> Vec<UpstreamDatumWithMetadata> {
        update_from_guesses(&mut self.0, new_items)
    }

    /// Removes and returns a metadata item by field name
    pub fn remove(&mut self, field: &str) -> Option<UpstreamDatumWithMetadata> {
        let index = self.0.iter().position(|d| d.datum.field() == field)?;
        Some(self.0.remove(index))
    }

    /// Gets the project name
    pub fn name(&self) -> Option<&str> {
        self.get("Name").and_then(|d| d.datum.as_str())
    }

    /// Gets the project homepage URL
    pub fn homepage(&self) -> Option<&str> {
        self.get("Homepage").and_then(|d| d.datum.as_str())
    }

    /// Gets the repository URL
    pub fn repository(&self) -> Option<&str> {
        self.get("Repository").and_then(|d| d.datum.as_str())
    }

    /// Gets the repository browse URL
    pub fn repository_browse(&self) -> Option<&str> {
        self.get("Repository-Browse").and_then(|d| d.datum.as_str())
    }

    /// Gets the project description
    pub fn description(&self) -> Option<&str> {
        self.get("Description").and_then(|d| d.datum.as_str())
    }

    /// Gets the project summary
    pub fn summary(&self) -> Option<&str> {
        self.get("Summary").and_then(|d| d.datum.as_str())
    }

    /// Gets the project license
    pub fn license(&self) -> Option<&str> {
        self.get("License").and_then(|d| d.datum.as_str())
    }

    /// Gets the list of authors
    pub fn author(&self) -> Option<&Vec<Person>> {
        self.get("Author").map(|d| match &d.datum {
            UpstreamDatum::Author(authors) => authors,
            _ => unreachable!(),
        })
    }

    /// Gets the maintainer information
    pub fn maintainer(&self) -> Option<&Person> {
        self.get("Maintainer").map(|d| match &d.datum {
            UpstreamDatum::Maintainer(maintainer) => maintainer,
            _ => unreachable!(),
        })
    }

    /// Gets the bug database URL
    pub fn bug_database(&self) -> Option<&str> {
        self.get("Bug-Database").and_then(|d| d.datum.as_str())
    }

    /// Gets the bug submission URL or email
    pub fn bug_submit(&self) -> Option<&str> {
        self.get("Bug-Submit").and_then(|d| d.datum.as_str())
    }

    /// Gets the contact information
    pub fn contact(&self) -> Option<&str> {
        self.get("Contact").and_then(|d| d.datum.as_str())
    }

    /// Gets the Cargo crate name
    pub fn cargo_crate(&self) -> Option<&str> {
        self.get("Cargo-Crate").and_then(|d| d.datum.as_str())
    }

    /// Gets the security markdown file name
    pub fn security_md(&self) -> Option<&str> {
        self.get("Security-MD").and_then(|d| d.datum.as_str())
    }

    /// Gets the security contact information
    pub fn security_contact(&self) -> Option<&str> {
        self.get("Security-Contact").and_then(|d| d.datum.as_str())
    }

    /// Gets the project version
    pub fn version(&self) -> Option<&str> {
        self.get("Version").and_then(|d| d.datum.as_str())
    }

    /// Gets the list of keywords
    pub fn keywords(&self) -> Option<&Vec<String>> {
        self.get("Keywords").map(|d| match &d.datum {
            UpstreamDatum::Keywords(keywords) => keywords,
            _ => unreachable!(),
        })
    }

    /// Gets the documentation URL
    pub fn documentation(&self) -> Option<&str> {
        self.get("Documentation").and_then(|d| d.datum.as_str())
    }

    /// Gets the API documentation URL
    pub fn api_documentation(&self) -> Option<&str> {
        self.get("API-Documentation").and_then(|d| d.datum.as_str())
    }

    /// Gets the Go import path
    pub fn go_import_path(&self) -> Option<&str> {
        self.get("Go-Import-Path").and_then(|d| d.datum.as_str())
    }

    /// Gets the download URL
    pub fn download(&self) -> Option<&str> {
        self.get("Download").and_then(|d| d.datum.as_str())
    }

    /// Gets the wiki URL
    pub fn wiki(&self) -> Option<&str> {
        self.get("Wiki").and_then(|d| d.datum.as_str())
    }

    /// Gets the mailing list URL or email
    pub fn mailing_list(&self) -> Option<&str> {
        self.get("MailingList").and_then(|d| d.datum.as_str())
    }

    /// Gets the SourceForge project name
    pub fn sourceforge_project(&self) -> Option<&str> {
        self.get("SourceForge-Project")
            .and_then(|d| d.datum.as_str())
    }

    /// Gets the archive name (e.g., CRAN, PyPI)
    pub fn archive(&self) -> Option<&str> {
        self.get("Archive").and_then(|d| d.datum.as_str())
    }

    /// Gets the demo URL
    pub fn demo(&self) -> Option<&str> {
        self.get("Demo").and_then(|d| d.datum.as_str())
    }

    /// Gets the PECL package name
    pub fn pecl_package(&self) -> Option<&str> {
        self.get("Pecl-Package").and_then(|d| d.datum.as_str())
    }

    /// Gets the Haskell package name
    pub fn haskell_package(&self) -> Option<&str> {
        self.get("Haskell-Package").and_then(|d| d.datum.as_str())
    }

    /// Gets funding information
    pub fn funding(&self) -> Option<&str> {
        self.get("Funding").and_then(|d| d.datum.as_str())
    }

    /// Gets the changelog URL
    pub fn changelog(&self) -> Option<&str> {
        self.get("Changelog").and_then(|d| d.datum.as_str())
    }

    /// Gets the Debian ITP bug number
    pub fn debian_itp(&self) -> Option<i32> {
        self.get("Debian-ITP").and_then(|d| match &d.datum {
            UpstreamDatum::DebianITP(itp) => Some(*itp),
            _ => unreachable!(),
        })
    }

    /// Gets the list of screenshot URLs
    pub fn screenshots(&self) -> Option<&Vec<String>> {
        self.get("Screenshots").map(|d| match &d.datum {
            UpstreamDatum::Screenshots(screenshots) => screenshots,
            _ => unreachable!(),
        })
    }

    /// Gets the donation URL
    pub fn donation(&self) -> Option<&str> {
        self.get("Donation").and_then(|d| d.datum.as_str())
    }

    /// Gets the citation information
    pub fn cite_as(&self) -> Option<&str> {
        self.get("Cite-As").and_then(|d| d.datum.as_str())
    }

    /// Gets the registry entries
    pub fn registry(&self) -> Option<&Vec<(String, String)>> {
        self.get("Registry").map(|d| match &d.datum {
            UpstreamDatum::Registry(registry) => registry,
            _ => unreachable!(),
        })
    }

    /// Gets the webservice URL
    pub fn webservice(&self) -> Option<&str> {
        self.get("Webservice").and_then(|d| d.datum.as_str())
    }

    /// Gets the build system name
    pub fn buildsystem(&self) -> Option<&str> {
        self.get("BuildSystem").and_then(|d| d.datum.as_str())
    }

    /// Gets the copyright information
    pub fn copyright(&self) -> Option<&str> {
        self.get("Copyright").and_then(|d| d.datum.as_str())
    }

    /// Gets the FAQ URL
    pub fn faq(&self) -> Option<&str> {
        self.get("FAQ").and_then(|d| d.datum.as_str())
    }
}

impl std::ops::Index<&str> for UpstreamMetadata {
    type Output = UpstreamDatumWithMetadata;

    fn index(&self, index: &str) -> &Self::Output {
        self.get(index).unwrap()
    }
}

impl Default for UpstreamMetadata {
    fn default() -> Self {
        UpstreamMetadata::new()
    }
}

impl Iterator for UpstreamMetadata {
    type Item = UpstreamDatumWithMetadata;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop()
    }
}

impl From<UpstreamDatum> for UpstreamDatumWithMetadata {
    fn from(d: UpstreamDatum) -> Self {
        UpstreamDatumWithMetadata {
            datum: d,
            certainty: None,
            origin: None,
        }
    }
}

impl From<Vec<UpstreamDatumWithMetadata>> for UpstreamMetadata {
    fn from(v: Vec<UpstreamDatumWithMetadata>) -> Self {
        UpstreamMetadata(v)
    }
}

impl From<Vec<UpstreamDatum>> for UpstreamMetadata {
    fn from(v: Vec<UpstreamDatum>) -> Self {
        UpstreamMetadata(
            v.into_iter()
                .map(|d| UpstreamDatumWithMetadata {
                    datum: d,
                    certainty: None,
                    origin: None,
                })
                .collect(),
        )
    }
}

impl From<UpstreamMetadata> for Vec<UpstreamDatumWithMetadata> {
    fn from(v: UpstreamMetadata) -> Self {
        v.0
    }
}

impl From<UpstreamMetadata> for Vec<UpstreamDatum> {
    fn from(v: UpstreamMetadata) -> Self {
        v.0.into_iter().map(|d| d.datum).collect()
    }
}

impl serde::ser::Serialize for UpstreamMetadata {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        let mut map = serde_yaml::Mapping::new();
        for datum in &self.0 {
            map.insert(
                serde_yaml::Value::String(datum.datum.field().to_string()),
                serde_yaml::to_value(datum).unwrap(),
            );
        }
        map.serialize(serializer)
    }
}

#[cfg(feature = "pyo3")]
impl<'py> IntoPyObject<'py> for &UpstreamDatumWithMetadata {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        let m = PyModule::import(py, "upstream_ontologist.guess")?;

        let cls = m.getattr("UpstreamDatum")?;

        let (field, py_datum) = self
            .datum
            .into_pyobject(py)?
            .extract::<(String, Bound<PyAny>)>()?;

        let kwargs = pyo3::types::PyDict::new(py);
        kwargs.set_item("certainty", self.certainty.map(|x| x.to_string()))?;
        kwargs.set_item("origin", self.origin.as_ref())?;

        cls.call((field, py_datum), Some(&kwargs))
    }
}

impl serde::ser::Serialize for UpstreamDatumWithMetadata {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        UpstreamDatum::serialize(&self.datum, serializer)
    }
}

/// Trait for providing upstream metadata
pub trait UpstreamDataProvider {
    /// Provides upstream metadata from a given path
    fn provide(
        path: &std::path::Path,
        trust_package: bool,
    ) -> dyn Iterator<Item = (UpstreamDatum, Certainty)>;
}

/// Errors that can occur when loading JSON from HTTP
#[derive(Debug)]
pub enum HTTPJSONError {
    /// HTTP request error
    HTTPError(reqwest::Error),
    /// Request timed out
    Timeout(tokio::time::Duration),
    /// HTTP error response
    Error {
        /// The URL that failed
        url: reqwest::Url,
        /// HTTP status code
        status: u16,
        /// The response object
        response: Box<reqwest::Response>,
    },
}

impl std::fmt::Display for HTTPJSONError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            HTTPJSONError::HTTPError(e) => write!(f, "{}", e),
            HTTPJSONError::Timeout(timeout) => write!(f, "Timeout after {:?}", timeout),
            HTTPJSONError::Error {
                url,
                status,
                response: _,
            } => write!(f, "HTTP error {} for {}:", status, url,),
        }
    }
}

/// Loads JSON data from a URL with optional timeout
pub async fn load_json_url(
    http_url: &Url,
    timeout: Option<std::time::Duration>,
) -> Result<serde_json::Value, HTTPJSONError> {
    let mut headers = HeaderMap::new();
    headers.insert(reqwest::header::ACCEPT, "application/json".parse().unwrap());

    if let Some(hostname) = http_url.host_str() {
        if hostname == "github.com" || hostname == "raw.githubusercontent.com" {
            if let Ok(token) = std::env::var("GITHUB_TOKEN") {
                headers.insert(
                    reqwest::header::WWW_AUTHENTICATE,
                    format!("Bearer {}", token).parse().unwrap(),
                );
            }
        }
    }

    let client = crate::http::build_client()
        .default_headers(headers)
        .build()
        .map_err(HTTPJSONError::HTTPError)?;

    let http_url: reqwest::Url = Into::<String>::into(http_url.clone()).parse().unwrap();

    let request = client
        .get(http_url)
        .build()
        .map_err(HTTPJSONError::HTTPError)?;

    let timeout = timeout.unwrap_or(std::time::Duration::from_secs(30));

    let response = tokio::time::timeout(timeout, client.execute(request))
        .await
        .map_err(|_| HTTPJSONError::Timeout(timeout))?
        .map_err(HTTPJSONError::HTTPError)?;

    if !response.status().is_success() {
        return Err(HTTPJSONError::Error {
            url: response.url().clone(),
            status: response.status().as_u16(),
            response: Box::new(response),
        });
    }

    let json_contents: serde_json::Value =
        response.json().await.map_err(HTTPJSONError::HTTPError)?;

    Ok(json_contents)
}

fn xmlparse_simplify_namespaces(path: &Path, namespaces: &[&str]) -> Option<xmltree::Element> {
    let namespaces = namespaces
        .iter()
        .map(|ns| format!("{{{}{}}}", ns, ns))
        .collect::<Vec<_>>();
    let mut f = std::fs::File::open(path).unwrap();
    let mut buf = Vec::new();
    f.read_to_end(&mut buf).ok()?;
    let mut tree = xmltree::Element::parse(std::io::Cursor::new(buf)).ok()?;
    simplify_namespaces(&mut tree, &namespaces);
    Some(tree)
}

fn simplify_namespaces(element: &mut xmltree::Element, namespaces: &[String]) {
    use xmltree::XMLNode;
    element.prefix = None;
    if let Some(namespace) = namespaces.iter().find(|&ns| element.name.starts_with(ns)) {
        element.name = element.name[namespace.len()..].to_string();
    }
    for child in &mut element.children {
        if let XMLNode::Element(ref mut child_element) = child {
            simplify_namespaces(child_element, namespaces);
        }
    }
}

/// Errors that can occur when canonicalizing URLs
pub enum CanonicalizeError {
    /// URL is invalid with reason
    InvalidUrl(Url, String),
    /// URL cannot be verified with reason
    Unverifiable(Url, String),
    /// Request was rate limited
    RateLimited(Url),
}

#[derive(Debug)]
/// Error when manipulating URL path segments
pub struct PathSegmentError;

/// Checks if a URL is canonical by following redirects
pub async fn check_url_canonical(url: &Url) -> Result<Url, CanonicalizeError> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Err(CanonicalizeError::Unverifiable(
            url.clone(),
            format!("Unsupported scheme {}", url.scheme()),
        ));
    }

    let client = crate::http::build_client()
        .build()
        .map_err(|e| CanonicalizeError::Unverifiable(url.clone(), format!("HTTP error {}", e)))?;

    let response =
        client.get(url.as_str()).send().await.map_err(|e| {
            CanonicalizeError::Unverifiable(url.clone(), format!("HTTP error {}", e))
        })?;

    match response.status() {
        status if status.is_success() => Ok(response.url().clone()),
        status if status == reqwest::StatusCode::TOO_MANY_REQUESTS => {
            Err(CanonicalizeError::RateLimited(url.clone()))
        }
        status if status == reqwest::StatusCode::NOT_FOUND => Err(CanonicalizeError::InvalidUrl(
            url.clone(),
            format!("Not found: {}", response.status()),
        )),
        status if status.is_server_error() => Err(CanonicalizeError::Unverifiable(
            url.clone(),
            format!("Server down: {}", response.status()),
        )),
        _ => Err(CanonicalizeError::Unverifiable(
            url.clone(),
            format!("Unknown HTTP error {}", response.status()),
        )),
    }
}

/// Creates a new URL with the specified path segments
pub fn with_path_segments(url: &Url, path_segments: &[&str]) -> Result<Url, PathSegmentError> {
    let mut url = url.clone();
    url.path_segments_mut()
        .map_err(|_| PathSegmentError)?
        .clear()
        .extend(path_segments.iter().copied());
    Ok(url)
}

/// Trait for different code forges (GitHub, GitLab, etc.)
#[async_trait::async_trait]
pub trait Forge: Send + Sync {
    /// Whether the repository browse URL can be used as homepage
    fn repository_browse_can_be_homepage(&self) -> bool;

    /// Returns the name of the forge
    fn name(&self) -> &'static str;

    /// Derives the bug database URL from a bug submission URL
    fn bug_database_url_from_bug_submit_url(&self, _url: &Url) -> Option<Url> {
        None
    }

    /// Derives the bug submission URL from a bug database URL
    fn bug_submit_url_from_bug_database_url(&self, _url: &Url) -> Option<Url> {
        None
    }

    /// Checks if a bug database URL is canonical
    async fn check_bug_database_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        Err(CanonicalizeError::Unverifiable(
            url.clone(),
            "Not implemented".to_string(),
        ))
    }

    /// Checks if a bug submission URL is canonical
    async fn check_bug_submit_url_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        Err(CanonicalizeError::Unverifiable(
            url.clone(),
            "Not implemented".to_string(),
        ))
    }

    /// Gets the bug database URL from an issue URL
    fn bug_database_from_issue_url(&self, _url: &Url) -> Option<Url> {
        None
    }

    /// Gets the bug database URL from a repository URL
    fn bug_database_url_from_repo_url(&self, _url: &Url) -> Option<Url> {
        None
    }

    /// Gets the repository URL from a merge request URL
    fn repo_url_from_merge_request_url(&self, _url: &Url) -> Option<Url> {
        None
    }

    /// Extends metadata with forge-specific information
    async fn extend_metadata(
        &self,
        _metadata: &mut Vec<UpstreamDatumWithMetadata>,
        _project: &str,
        _max_certainty: Option<Certainty>,
    ) {
    }
}

/// GitHub forge implementation
pub struct GitHub;

impl Default for GitHub {
    fn default() -> Self {
        Self::new()
    }
}

impl GitHub {
    /// Creates a new GitHub forge instance
    pub fn new() -> Self {
        Self
    }
}

#[async_trait::async_trait]
impl Forge for GitHub {
    fn name(&self) -> &'static str {
        "GitHub"
    }

    fn repository_browse_can_be_homepage(&self) -> bool {
        true
    }

    fn bug_database_url_from_bug_submit_url(&self, url: &Url) -> Option<Url> {
        assert_eq!(url.host(), Some(url::Host::Domain("github.com")));
        let path_elements = url.path_segments().unwrap().collect::<Vec<_>>();

        if path_elements.len() != 3 && path_elements.len() != 4 {
            return None;
        }
        if path_elements[2] != "issues" {
            return None;
        }

        let mut url = url.clone();

        url.set_scheme("https").expect("valid scheme");

        Some(with_path_segments(&url, &path_elements[0..3]).unwrap())
    }

    fn bug_submit_url_from_bug_database_url(&self, url: &Url) -> Option<Url> {
        assert_eq!(url.host(), Some(url::Host::Domain("github.com")));
        let path_elements = url.path_segments().unwrap().collect::<Vec<_>>();

        if path_elements.len() != 3 {
            return None;
        }
        if path_elements[2] != "issues" {
            return None;
        }

        let mut url = url.clone();
        url.set_scheme("https").expect("valid scheme");
        url.path_segments_mut().unwrap().push("new");
        Some(url)
    }

    async fn check_bug_database_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        assert_eq!(url.host(), Some(url::Host::Domain("github.com")));
        let path_elements = url.path_segments().unwrap().collect::<Vec<_>>();

        if path_elements.len() != 3 {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitHub URL with missing path elements".to_string(),
            ));
        }
        if path_elements[2] != "issues" {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitHub URL with missing path elements".to_string(),
            ));
        }

        let api_url = Url::parse(&format!(
            "https://api.github.com/repos/{}/{}",
            path_elements[0], path_elements[1]
        ))
        .unwrap();

        let response = match reqwest::get(api_url).await {
            Ok(response) => response,
            Err(e) if e.status() == Some(reqwest::StatusCode::NOT_FOUND) => {
                return Err(CanonicalizeError::InvalidUrl(
                    url.clone(),
                    format!("Project does not exist {}", e),
                ));
            }
            Err(e) if e.status() == Some(reqwest::StatusCode::FORBIDDEN) => {
                // Probably rate limited
                warn!("Unable to verify bug database URL {}: {}", url, e);
                return Err(CanonicalizeError::RateLimited(url.clone()));
            }
            Err(e) => {
                return Err(CanonicalizeError::Unverifiable(
                    url.clone(),
                    format!("Unable to verify bug database URL: {}", e),
                ));
            }
        };
        let data = response.json::<serde_json::Value>().await.map_err(|e| {
            CanonicalizeError::Unverifiable(
                url.clone(),
                format!("Unable to verify bug database URL: {}", e),
            )
        })?;

        if data["has_issues"].as_bool() != Some(true) {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "Project does not have issues enabled".to_string(),
            ));
        }

        if data.get("archived").unwrap_or(&serde_json::Value::Null)
            == &serde_json::Value::Bool(true)
        {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "Project is archived".to_string(),
            ));
        }

        let mut url = Url::parse(data["html_url"].as_str().ok_or_else(|| {
            CanonicalizeError::Unverifiable(
                url.clone(),
                "Unable to verify bug database URL: no html_url".to_string(),
            )
        })?)
        .map_err(|e| {
            CanonicalizeError::Unverifiable(
                url.clone(),
                format!("Unable to verify bug database URL: {}", e),
            )
        })?;

        url.set_scheme("https").expect("valid scheme");
        url.path_segments_mut()
            .expect("path segments")
            .push("issues");

        Ok(url)
    }

    async fn check_bug_submit_url_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        let mut path_segments = url.path_segments().unwrap().collect::<Vec<_>>();
        path_segments.pop();
        let db_url = with_path_segments(url, &path_segments).unwrap();
        let mut canonical_db_url = self.check_bug_database_canonical(&db_url).await?;
        canonical_db_url.set_scheme("https").expect("valid scheme");
        canonical_db_url
            .path_segments_mut()
            .expect("path segments")
            .push("new");
        Ok(canonical_db_url)
    }

    fn bug_database_from_issue_url(&self, url: &Url) -> Option<Url> {
        let path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 2 || path_elements[1] != "issues" {
            return None;
        }
        let mut url = url.clone();
        url.set_scheme("https").unwrap();
        Some(with_path_segments(&url, &path_elements[0..3]).unwrap())
    }

    fn bug_database_url_from_repo_url(&self, url: &Url) -> Option<Url> {
        let mut path = url
            .path_segments()
            .into_iter()
            .take(2)
            .flatten()
            .collect::<Vec<&str>>();
        path[1] = path[1].strip_suffix(".git").unwrap_or(path[1]);
        path.push("issues");

        let mut url = url.clone();
        url.set_scheme("https").unwrap();
        Some(with_path_segments(&url, path.as_slice()).unwrap())
    }

    fn repo_url_from_merge_request_url(&self, url: &Url) -> Option<Url> {
        let path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 2 || path_elements[1] != "issues" {
            return None;
        }
        let mut url = url.clone();
        url.set_scheme("https").expect("valid scheme");
        Some(with_path_segments(&url, &path_elements[0..2]).unwrap())
    }
}

static DEFAULT_ASCII_SET: percent_encoding::AsciiSet = percent_encoding::CONTROLS
    .add(b'/')
    .add(b'?')
    .add(b'#')
    .add(b'%');

/// GitLab forge implementation
pub struct GitLab;

impl Default for GitLab {
    fn default() -> Self {
        Self::new()
    }
}

impl GitLab {
    /// Creates a new GitLab forge instance
    pub fn new() -> Self {
        Self
    }
}

#[async_trait::async_trait]
impl Forge for GitLab {
    fn name(&self) -> &'static str {
        "GitLab"
    }

    fn repository_browse_can_be_homepage(&self) -> bool {
        true
    }

    fn bug_database_url_from_bug_submit_url(&self, url: &Url) -> Option<Url> {
        let mut path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();

        if path_elements.len() < 2 {
            return None;
        }
        if path_elements[path_elements.len() - 2] != "issues" {
            return None;
        }
        if path_elements[path_elements.len() - 1] != "new" {
            path_elements.pop();
        }

        Some(with_path_segments(url, &path_elements[0..path_elements.len() - 3]).unwrap())
    }

    fn bug_submit_url_from_bug_database_url(&self, url: &Url) -> Option<Url> {
        let path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();

        if path_elements.len() < 2 {
            return None;
        }
        if path_elements[path_elements.len() - 1] != "issues" {
            return None;
        }

        let mut url = url.clone();
        url.path_segments_mut().expect("path segments").push("new");

        Some(url)
    }

    async fn check_bug_database_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        let host = url
            .host()
            .ok_or_else(|| CanonicalizeError::InvalidUrl(url.clone(), "no host".to_string()))?;
        let mut path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 2 || path_elements[path_elements.len() - 1] != "issues" {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitLab URL with missing path elements".to_string(),
            ));
        }

        path_elements.pop();

        let proj = path_elements.join("/");
        let proj_segment = utf8_percent_encode(proj.as_str(), &DEFAULT_ASCII_SET);
        let api_url = Url::parse(&format!(
            "https://{}/api/v4/projects/{}",
            host, proj_segment
        ))
        .map_err(|_| {
            CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitLab URL with invalid project path".to_string(),
            )
        })?;
        match load_json_url(&api_url, None).await {
            Ok(data) => {
                // issues_enabled is only provided when the user is authenticated,
                // so if we're not then we just fall back to checking the canonical URL
                let issues_enabled = data
                    .get("issues_enabled")
                    .unwrap_or(&serde_json::Value::Null);
                if issues_enabled.as_bool() == Some(false) {
                    return Err(CanonicalizeError::InvalidUrl(
                        url.clone(),
                        "Project does not have issues enabled".to_string(),
                    ));
                }

                let mut canonical_url = Url::parse(data["web_url"].as_str().unwrap()).unwrap();
                canonical_url
                    .path_segments_mut()
                    .unwrap()
                    .extend(&["-", "issues"]);
                if issues_enabled.as_bool() == Some(true) {
                    return Ok(canonical_url);
                }

                check_url_canonical(&canonical_url).await
            }
            Err(HTTPJSONError::Error { status, .. })
                if status == reqwest::StatusCode::NOT_FOUND =>
            {
                Err(CanonicalizeError::InvalidUrl(
                    url.clone(),
                    "Project not found".to_string(),
                ))
            }
            Err(e) => Err(CanonicalizeError::Unverifiable(
                url.clone(),
                format!("Unable to verify bug database URL: {:?}", e),
            )),
        }
    }

    async fn check_bug_submit_url_canonical(&self, url: &Url) -> Result<Url, CanonicalizeError> {
        let path_elements = url
            .path_segments()
            .expect("valid segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 2 || path_elements[path_elements.len() - 2] != "issues" {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitLab URL with missing path elements".to_string(),
            ));
        }

        if path_elements[path_elements.len() - 1] != "new" {
            return Err(CanonicalizeError::InvalidUrl(
                url.clone(),
                "GitLab URL with missing path elements".to_string(),
            ));
        }

        let db_url = with_path_segments(url, &path_elements[0..path_elements.len() - 1]).unwrap();
        let mut canonical_db_url = self.check_bug_database_canonical(&db_url).await?;
        canonical_db_url
            .path_segments_mut()
            .expect("valid segments")
            .push("new");
        Ok(canonical_db_url)
    }

    fn bug_database_from_issue_url(&self, url: &Url) -> Option<Url> {
        let path_elements = url
            .path_segments()
            .expect("valid segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 2
            || path_elements[path_elements.len() - 2] != "issues"
            || path_elements[path_elements.len() - 1]
                .parse::<u32>()
                .is_err()
        {
            return None;
        }
        Some(with_path_segments(url, &path_elements[0..path_elements.len() - 1]).unwrap())
    }

    fn bug_database_url_from_repo_url(&self, url: &Url) -> Option<Url> {
        let mut url = url.clone();
        let last = url
            .path_segments()
            .expect("valid segments")
            .next_back()
            .unwrap()
            .to_string();
        url.path_segments_mut()
            .unwrap()
            .pop()
            .push(last.trim_end_matches(".git"))
            .push("issues");
        Some(url)
    }

    fn repo_url_from_merge_request_url(&self, url: &Url) -> Option<Url> {
        let path_elements = url
            .path_segments()
            .expect("path segments")
            .collect::<Vec<_>>();
        if path_elements.len() < 3
            || path_elements[path_elements.len() - 2] != "merge_requests"
            || path_elements[path_elements.len() - 1]
                .parse::<u32>()
                .is_err()
        {
            return None;
        }
        Some(with_path_segments(url, &path_elements[0..path_elements.len() - 2]).unwrap())
    }
}

/// Extracts upstream metadata from a Travis CI configuration file
pub fn guess_from_travis_yml(
    path: &Path,
    _settings: &GuesserSettings,
) -> std::result::Result<Vec<UpstreamDatumWithMetadata>, ProviderError> {
    let mut file = File::open(path)?;

    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    let data: serde_yaml::Value =
        serde_yaml::from_str(&contents).map_err(|e| ProviderError::ParseError(e.to_string()))?;

    let mut ret = Vec::new();

    if let Some(go_import_path) = data.get("go_import_path") {
        if let Some(go_import_path) = go_import_path.as_str() {
            ret.push(UpstreamDatumWithMetadata {
                datum: UpstreamDatum::GoImportPath(go_import_path.to_string()),
                certainty: Some(Certainty::Certain),
                origin: Some(path.into()),
            });
        }
    }

    Ok(ret)
}

/// Extracts upstream metadata from environment variables
pub fn guess_from_environment() -> std::result::Result<Vec<UpstreamDatumWithMetadata>, ProviderError>
{
    let mut results = Vec::new();
    if let Ok(url) = std::env::var("UPSTREAM_BRANCH_URL") {
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Repository(url),
            certainty: Some(Certainty::Certain),
            origin: Some(Origin::Other("environment".to_string())),
        });
    }
    Ok(results)
}

fn find_datum<'a>(
    metadata: &'a [UpstreamDatumWithMetadata],
    field: &str,
) -> Option<&'a UpstreamDatumWithMetadata> {
    metadata.iter().find(|d| d.datum.field() == field)
}

fn set_datum(metadata: &mut Vec<UpstreamDatumWithMetadata>, datum: UpstreamDatumWithMetadata) {
    if let Some(idx) = metadata
        .iter()
        .position(|d| d.datum.field() == datum.datum.field())
    {
        metadata[idx] = datum;
    } else {
        metadata.push(datum);
    }
}

/// Updates metadata collection with new guesses based on certainty levels
pub fn update_from_guesses(
    metadata: &mut Vec<UpstreamDatumWithMetadata>,
    new_items: impl Iterator<Item = UpstreamDatumWithMetadata>,
) -> Vec<UpstreamDatumWithMetadata> {
    let mut changed = vec![];
    for datum in new_items {
        let current_datum = find_datum(metadata, datum.datum.field());
        if current_datum.is_none() || datum.certainty > current_datum.unwrap().certainty {
            changed.push(datum.clone());
            set_datum(metadata, datum);
        }
    }
    changed
}

fn possible_fields_missing(
    upstream_metadata: &[UpstreamDatumWithMetadata],
    fields: &[&str],
    _field_certainty: Certainty,
) -> bool {
    for field in fields {
        match find_datum(upstream_metadata, field) {
            Some(datum) if datum.certainty != Some(Certainty::Certain) => return true,
            None => return true,
            _ => (),
        }
    }
    false
}

async fn extend_from_external_guesser<
    F: Fn() -> Fut,
    Fut: std::future::Future<Output = Vec<UpstreamDatum>>,
>(
    metadata: &mut Vec<UpstreamDatumWithMetadata>,
    max_certainty: Option<Certainty>,
    supported_fields: &[&str],
    new_items: F,
) {
    if max_certainty.is_some()
        && !possible_fields_missing(metadata, supported_fields, max_certainty.unwrap())
    {
        return;
    }

    let new_items = new_items()
        .await
        .into_iter()
        .map(|item| UpstreamDatumWithMetadata {
            datum: item,
            certainty: max_certainty,
            origin: None,
        });

    update_from_guesses(metadata, new_items);
}

/// SourceForge forge implementation
pub struct SourceForge;

impl Default for SourceForge {
    fn default() -> Self {
        Self::new()
    }
}

impl SourceForge {
    /// Creates a new SourceForge forge instance
    pub fn new() -> Self {
        Self
    }
}

#[async_trait::async_trait]
impl Forge for SourceForge {
    fn name(&self) -> &'static str {
        "SourceForge"
    }
    fn repository_browse_can_be_homepage(&self) -> bool {
        false
    }

    fn bug_database_url_from_bug_submit_url(&self, url: &Url) -> Option<Url> {
        let mut segments = url.path_segments()?;
        if segments.next() != Some("p") {
            return None;
        }
        let project = segments.next()?;
        if segments.next() != Some("bugs") {
            return None;
        }
        with_path_segments(url, &["p", project, "bugs"]).ok()
    }

    async fn extend_metadata(
        &self,
        metadata: &mut Vec<UpstreamDatumWithMetadata>,
        project: &str,
        max_certainty: Option<Certainty>,
    ) {
        let subproject = find_datum(metadata, "Name").and_then(|f| match f.datum {
            UpstreamDatum::Name(ref name) => Some(name.to_string()),
            _ => None,
        });

        extend_from_external_guesser(
            metadata,
            max_certainty,
            &["Homepage", "Name", "Repository", "Bug-Database"],
            || async {
                crate::forges::sourceforge::guess_from_sf(project, subproject.as_deref()).await
            },
        )
        .await
    }
}

/// Launchpad forge implementation
pub struct Launchpad;

impl Default for Launchpad {
    fn default() -> Self {
        Self::new()
    }
}

impl Launchpad {
    /// Creates a new Launchpad forge instance
    pub fn new() -> Self {
        Self
    }
}

impl Forge for Launchpad {
    fn name(&self) -> &'static str {
        "launchpad"
    }

    fn repository_browse_can_be_homepage(&self) -> bool {
        false
    }
    fn bug_database_url_from_bug_submit_url(&self, url: &Url) -> Option<Url> {
        if url.host_str()? != "bugs.launchpad.net" {
            return None;
        }

        let mut segments = url.path_segments()?;
        let project = segments.next()?;

        with_path_segments(url, &[project]).ok()
    }

    fn bug_submit_url_from_bug_database_url(&self, url: &Url) -> Option<Url> {
        if url.host_str()? != "bugs.launchpad.net" {
            return None;
        }

        let mut segments = url.path_segments()?;
        let project = segments.next()?;

        with_path_segments(url, &[project, "+filebug"]).ok()
    }
}

/// Determines which forge a URL belongs to
pub async fn find_forge(url: &Url, net_access: Option<bool>) -> Option<Box<dyn Forge>> {
    if url.host_str()? == "sourceforge.net" {
        return Some(Box::new(SourceForge::new()));
    }

    if url.host_str()?.ends_with(".launchpad.net") {
        return Some(Box::new(Launchpad::new()));
    }

    if url.host_str()? == "github.com" {
        return Some(Box::new(GitHub::new()));
    }

    if vcs::is_gitlab_site(url.host_str()?, net_access).await {
        return Some(Box::new(GitLab::new()));
    }

    None
}

/// Checks if a bug database URL is canonical
pub async fn check_bug_database_canonical(
    url: &Url,
    net_access: Option<bool>,
) -> Result<Url, CanonicalizeError> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge
            .bug_database_url_from_bug_submit_url(url)
            .ok_or(CanonicalizeError::Unverifiable(
                url.clone(),
                "no bug database URL found".to_string(),
            ))
    } else {
        Err(CanonicalizeError::Unverifiable(
            url.clone(),
            "unknown forge".to_string(),
        ))
    }
}

/// Derives a bug submission URL from a bug database URL
pub async fn bug_submit_url_from_bug_database_url(
    url: &Url,
    net_access: Option<bool>,
) -> Option<Url> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge.bug_submit_url_from_bug_database_url(url)
    } else {
        None
    }
}

/// Derives a bug database URL from a bug submission URL
pub async fn bug_database_url_from_bug_submit_url(
    url: &Url,
    net_access: Option<bool>,
) -> Option<Url> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge.bug_database_url_from_bug_submit_url(url)
    } else {
        None
    }
}

/// Guesses the bug database URL from a repository URL
pub async fn guess_bug_database_url_from_repo_url(
    url: &Url,
    net_access: Option<bool>,
) -> Option<Url> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge.bug_database_url_from_repo_url(url)
    } else {
        None
    }
}

/// Extracts the repository URL from a merge request URL
pub async fn repo_url_from_merge_request_url(url: &Url, net_access: Option<bool>) -> Option<Url> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge.repo_url_from_merge_request_url(url)
    } else {
        None
    }
}

/// Extracts the bug database URL from an issue URL
pub async fn bug_database_from_issue_url(url: &Url, net_access: Option<bool>) -> Option<Url> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge.bug_database_from_issue_url(url)
    } else {
        None
    }
}

/// Checks if a bug submission URL is canonical
pub async fn check_bug_submit_url_canonical(
    url: &Url,
    net_access: Option<bool>,
) -> Result<Url, CanonicalizeError> {
    if let Some(forge) = find_forge(url, net_access).await {
        forge
            .bug_submit_url_from_bug_database_url(url)
            .ok_or(CanonicalizeError::Unverifiable(
                url.clone(),
                "no bug submit URL found".to_string(),
            ))
    } else {
        Err(CanonicalizeError::Unverifiable(
            url.clone(),
            "unknown forge".to_string(),
        ))
    }
}

/// Extracts the PECL package name from a URL
pub fn extract_pecl_package_name(url: &str) -> Option<String> {
    let pecl_regex = regex!(r"https?://pecl\.php\.net/package/(.*)");
    if let Some(captures) = pecl_regex.captures(url) {
        return captures.get(1).map(|m| m.as_str().to_string());
    }
    None
}

/// Extracts the Hackage package name from a URL
pub fn extract_hackage_package(url: &str) -> Option<String> {
    let hackage_regex = regex!(r"https?://hackage\.haskell\.org/package/([^/]+)/.*");
    if let Some(captures) = hackage_regex.captures(url) {
        return captures.get(1).map(|m| m.as_str().to_string());
    }
    None
}

/// Obtain metadata from a URL related to the project
pub fn metadata_from_url(url: &str, origin: &Origin) -> Vec<UpstreamDatumWithMetadata> {
    let mut results = Vec::new();
    if let Some(sf_project) = crate::forges::sourceforge::extract_sf_project_name(url) {
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::SourceForgeProject(sf_project),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Archive("SourceForge".to_string()),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
    }

    if let Some(pecl_package) = extract_pecl_package_name(url) {
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::PeclPackage(pecl_package),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Archive("Pecl".to_string()),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
    }

    if let Some(haskell_package) = extract_hackage_package(url) {
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::HaskellPackage(haskell_package),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
        results.push(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Archive("Hackage".to_string()),
            certainty: Some(Certainty::Certain),
            origin: Some(origin.clone()),
        });
    }
    results
}

/// Fetches metadata from the Repology API for a given source package
pub async fn get_repology_metadata(srcname: &str, repo: Option<&str>) -> Option<serde_json::Value> {
    let repo = repo.unwrap_or("debian_unstable");
    let url = format!(
        "https://repology.org/tools/project-by?repo={}&name_type=srcname'
           '&target_page=api_v1_project&name={}",
        repo, srcname
    );

    match load_json_url(&Url::parse(url.as_str()).unwrap(), None).await {
        Ok(json) => Some(json),
        Err(HTTPJSONError::Error { status: 404, .. }) => None,
        Err(e) => {
            debug!("Failed to load repology metadata: {:?}", e);
            None
        }
    }
}

/// Guesses upstream metadata from a file or directory path
pub fn guess_from_path(
    path: &Path,
    _settings: &GuesserSettings,
) -> std::result::Result<Vec<UpstreamDatumWithMetadata>, ProviderError> {
    let basename = path.file_name().and_then(|s| s.to_str());
    let mut ret = Vec::new();
    if let Some(basename_str) = basename {
        let re = regex!(r"(.*)-([0-9.]+)");
        if let Some(captures) = re.captures(basename_str) {
            if let Some(name) = captures.get(1) {
                ret.push(UpstreamDatumWithMetadata {
                    datum: UpstreamDatum::Name(name.as_str().to_string()),
                    certainty: Some(Certainty::Possible),
                    origin: Some(path.into()),
                });
            }
            if let Some(version) = captures.get(2) {
                ret.push(UpstreamDatumWithMetadata {
                    datum: UpstreamDatum::Version(version.as_str().to_string()),
                    certainty: Some(Certainty::Possible),
                    origin: Some(path.into()),
                });
            }
        } else {
            ret.push(UpstreamDatumWithMetadata {
                datum: UpstreamDatum::Name(basename_str.to_string()),
                certainty: Some(Certainty::Possible),
                origin: Some(path.into()),
            });
        }
    }
    Ok(ret)
}

#[cfg(feature = "pyo3")]
impl<'py> FromPyObject<'_, 'py> for UpstreamDatum {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        let (field, val): (String, Bound<'py, PyAny>) = if let Ok((field, val)) =
            obj.extract::<(String, Bound<'py, PyAny>)>()
        {
            (field, val)
        } else if let Ok(datum) = obj.getattr("datum") {
            let field = datum.getattr("field")?.extract::<String>()?;
            let val = datum.getattr("value")?;
            (field, val)
        } else if obj.hasattr("field")? && obj.hasattr("value")? {
            let field = obj.getattr("field")?.extract::<String>()?;
            let val = obj.getattr("value")?;
            (field, val)
        } else {
            return Err(PyTypeError::new_err((
                format!("Expected a tuple of (field, value) or an object with field and value attributesm, found {:?}", obj),
            )));
        };

        match field.as_str() {
            "Name" => Ok(UpstreamDatum::Name(val.extract::<String>()?)),
            "Version" => Ok(UpstreamDatum::Version(val.extract::<String>()?)),
            "Homepage" => Ok(UpstreamDatum::Homepage(val.extract::<String>()?)),
            "Bug-Database" => Ok(UpstreamDatum::BugDatabase(val.extract::<String>()?)),
            "Bug-Submit" => Ok(UpstreamDatum::BugSubmit(val.extract::<String>()?)),
            "Contact" => Ok(UpstreamDatum::Contact(val.extract::<String>()?)),
            "Repository" => Ok(UpstreamDatum::Repository(val.extract::<String>()?)),
            "Repository-Browse" => Ok(UpstreamDatum::RepositoryBrowse(val.extract::<String>()?)),
            "License" => Ok(UpstreamDatum::License(val.extract::<String>()?)),
            "Description" => Ok(UpstreamDatum::Description(val.extract::<String>()?)),
            "Summary" => Ok(UpstreamDatum::Summary(val.extract::<String>()?)),
            "Cargo-Crate" => Ok(UpstreamDatum::CargoCrate(val.extract::<String>()?)),
            "Security-MD" => Ok(UpstreamDatum::SecurityMD(val.extract::<String>()?)),
            "Security-Contact" => Ok(UpstreamDatum::SecurityContact(val.extract::<String>()?)),
            "Keywords" => Ok(UpstreamDatum::Keywords(val.extract::<Vec<String>>()?)),
            "Copyright" => Ok(UpstreamDatum::Copyright(val.extract::<String>()?)),
            "Documentation" => Ok(UpstreamDatum::Documentation(val.extract::<String>()?)),
            "API-Documentation" => Ok(UpstreamDatum::APIDocumentation(val.extract::<String>()?)),
            "Go-Import-Path" => Ok(UpstreamDatum::GoImportPath(val.extract::<String>()?)),
            "Download" => Ok(UpstreamDatum::Download(val.extract::<String>()?)),
            "Wiki" => Ok(UpstreamDatum::Wiki(val.extract::<String>()?)),
            "MailingList" => Ok(UpstreamDatum::MailingList(val.extract::<String>()?)),
            "Funding" => Ok(UpstreamDatum::Funding(val.extract::<String>()?)),
            "SourceForge-Project" => {
                Ok(UpstreamDatum::SourceForgeProject(val.extract::<String>()?))
            }
            "Archive" => Ok(UpstreamDatum::Archive(val.extract::<String>()?)),
            "Demo" => Ok(UpstreamDatum::Demo(val.extract::<String>()?)),
            "Pecl-Package" => Ok(UpstreamDatum::PeclPackage(val.extract::<String>()?)),
            "Haskell-Package" => Ok(UpstreamDatum::HaskellPackage(val.extract::<String>()?)),
            "Author" => Ok(UpstreamDatum::Author(val.extract::<Vec<Person>>()?)),
            "Maintainer" => Ok(UpstreamDatum::Maintainer(val.extract::<Person>()?)),
            "Changelog" => Ok(UpstreamDatum::Changelog(val.extract::<String>()?)),
            "Screenshots" => Ok(UpstreamDatum::Screenshots(val.extract::<Vec<String>>()?)),
            "Cite-As" => Ok(UpstreamDatum::CiteAs(val.extract::<String>()?)),
            "Registry" => {
                let v = val.extract::<Vec<Bound<'py, PyAny>>>()?;
                let mut registry = Vec::new();
                for item in v {
                    let name = item.get_item("Name")?.extract::<String>()?;
                    let entry = item.get_item("Entry")?.extract::<String>()?;
                    registry.push((name, entry));
                }
                Ok(UpstreamDatum::Registry(registry))
            }
            "Donation" => Ok(UpstreamDatum::Donation(val.extract::<String>()?)),
            "Webservice" => Ok(UpstreamDatum::Webservice(val.extract::<String>()?)),
            "BuildSystem" => Ok(UpstreamDatum::BuildSystem(val.extract::<String>()?)),
            "FAQ" => Ok(UpstreamDatum::FAQ(val.extract::<String>()?)),
            _ => Err(PyRuntimeError::new_err(format!("Unknown field: {}", field))),
        }
    }
}

#[cfg(feature = "pyo3")]
impl<'py> IntoPyObject<'py> for &UpstreamDatum {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        let field = self.field().to_string();
        let value: Bound<'py, PyAny> = match self {
            UpstreamDatum::Name(n) => n.into_pyobject(py)?.into_any(),
            UpstreamDatum::Version(v) => v.into_pyobject(py)?.into_any(),
            UpstreamDatum::Contact(c) => c.into_pyobject(py)?.into_any(),
            UpstreamDatum::Summary(s) => s.into_pyobject(py)?.into_any(),
            UpstreamDatum::License(l) => l.into_pyobject(py)?.into_any(),
            UpstreamDatum::Homepage(h) => h.into_pyobject(py)?.into_any(),
            UpstreamDatum::Description(d) => d.into_pyobject(py)?.into_any(),
            UpstreamDatum::BugDatabase(b) => b.into_pyobject(py)?.into_any(),
            UpstreamDatum::BugSubmit(b) => b.into_pyobject(py)?.into_any(),
            UpstreamDatum::Repository(r) => r.into_pyobject(py)?.into_any(),
            UpstreamDatum::RepositoryBrowse(r) => r.into_pyobject(py)?.into_any(),
            UpstreamDatum::SecurityMD(s) => s.into_pyobject(py)?.into_any(),
            UpstreamDatum::SecurityContact(s) => s.into_pyobject(py)?.into_any(),
            UpstreamDatum::CargoCrate(c) => c.into_pyobject(py)?.into_any(),
            UpstreamDatum::Keywords(ks) => ks.into_pyobject(py)?,
            UpstreamDatum::Copyright(c) => c.into_pyobject(py)?.into_any(),
            UpstreamDatum::Documentation(a) => a.into_pyobject(py)?.into_any(),
            UpstreamDatum::APIDocumentation(a) => a.into_pyobject(py)?.into_any(),
            UpstreamDatum::GoImportPath(ip) => ip.into_pyobject(py)?.into_any(),
            UpstreamDatum::Archive(a) => a.into_pyobject(py)?.into_any(),
            UpstreamDatum::Demo(d) => d.into_pyobject(py)?.into_any(),
            UpstreamDatum::Maintainer(m) => m.into_pyobject(py)?,
            UpstreamDatum::Author(a) => a.into_pyobject(py)?,
            UpstreamDatum::Wiki(w) => w.into_pyobject(py)?.into_any(),
            UpstreamDatum::Download(d) => d.into_pyobject(py)?.into_any(),
            UpstreamDatum::MailingList(m) => m.into_pyobject(py)?.into_any(),
            UpstreamDatum::SourceForgeProject(m) => m.into_pyobject(py)?.into_any(),
            UpstreamDatum::PeclPackage(p) => p.into_pyobject(py)?.into_any(),
            UpstreamDatum::Funding(p) => p.into_pyobject(py)?.into_any(),
            UpstreamDatum::Changelog(c) => c.into_pyobject(py)?.into_any(),
            UpstreamDatum::HaskellPackage(p) => p.into_pyobject(py)?.into_any(),
            UpstreamDatum::DebianITP(i) => i.into_pyobject(py)?.into_any(),
            UpstreamDatum::Screenshots(s) => s.into_pyobject(py)?,
            UpstreamDatum::CiteAs(s) => s.into_pyobject(py)?.into_any(),
            UpstreamDatum::Registry(r) => {
                let list: Result<Vec<_>, _> = r
                    .iter()
                    .map(|(name, entry)| {
                        let dict = PyDict::new(py);
                        dict.set_item("Name", name)?;
                        dict.set_item("Entry", entry)?;
                        Ok::<Bound<PyAny>, PyErr>(dict.into_any())
                    })
                    .collect();
                list?.into_pyobject(py)?
            }
            UpstreamDatum::Donation(d) => d.into_pyobject(py)?.into_any(),
            UpstreamDatum::Webservice(w) => w.into_pyobject(py)?.into_any(),
            UpstreamDatum::BuildSystem(b) => b.into_pyobject(py)?.into_any(),
            UpstreamDatum::FAQ(f) => f.into_pyobject(py)?.into_any(),
        };
        Ok((field, value).into_pyobject(py)?.into_any())
    }
}

#[cfg(feature = "pyo3")]
impl<'py> FromPyObject<'_, 'py> for UpstreamDatumWithMetadata {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        let certainty = obj.getattr("certainty")?.extract::<Option<String>>()?;
        let origin = obj.getattr("origin")?.extract::<Option<Origin>>()?;
        let datum = if obj.hasattr("datum")? {
            obj.getattr("datum")?.extract::<UpstreamDatum>()
        } else {
            obj.extract::<UpstreamDatum>()
        }?;

        Ok(UpstreamDatumWithMetadata {
            datum,
            certainty: certainty.map(|s| s.parse().unwrap()),
            origin,
        })
    }
}

/// Errors that can occur when fetching metadata from providers
#[derive(Debug)]
pub enum ProviderError {
    /// Parse error with description
    ParseError(String),
    /// I/O error
    IoError(std::io::Error),
    /// Other error with description
    Other(String),
    /// HTTP JSON fetching error
    HttpJsonError(Box<HTTPJSONError>),
    /// Extrapolation limit exceeded with limit value
    ExtrapolationLimitExceeded(usize),
}

impl std::fmt::Display for ProviderError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ProviderError::ParseError(e) => write!(f, "Parse error: {}", e),
            ProviderError::IoError(e) => write!(f, "IO error: {}", e),
            ProviderError::Other(e) => write!(f, "Other error: {}", e),
            ProviderError::HttpJsonError(e) => write!(f, "HTTP JSON error: {}", e),
            ProviderError::ExtrapolationLimitExceeded(e) => {
                write!(f, "Extrapolation limit exceeded: {}", e)
            }
        }
    }
}

impl std::error::Error for ProviderError {}

impl From<HTTPJSONError> for ProviderError {
    fn from(e: HTTPJSONError) -> Self {
        ProviderError::HttpJsonError(Box::new(e))
    }
}

impl From<std::io::Error> for ProviderError {
    fn from(e: std::io::Error) -> Self {
        ProviderError::IoError(e)
    }
}

impl From<reqwest::Error> for ProviderError {
    fn from(e: reqwest::Error) -> Self {
        ProviderError::Other(e.to_string())
    }
}

#[cfg(feature = "pyo3")]
mod py_exceptions {
    #![allow(missing_docs)]
    pyo3::create_exception!(
        upstream_ontologist,
        ParseError,
        pyo3::exceptions::PyException
    );
}
#[cfg(feature = "pyo3")]
pub use py_exceptions::ParseError;

#[cfg(feature = "pyo3")]
impl From<ProviderError> for PyErr {
    fn from(e: ProviderError) -> PyErr {
        match e {
            ProviderError::IoError(e) => e.into(),
            ProviderError::ParseError(e) => ParseError::new_err((e,)),
            ProviderError::Other(e) => PyRuntimeError::new_err((e,)),
            ProviderError::HttpJsonError(e) => PyRuntimeError::new_err((e.to_string(),)),
            ProviderError::ExtrapolationLimitExceeded(e) => {
                PyRuntimeError::new_err((e.to_string(),))
            }
        }
    }
}

/// Settings for upstream metadata guessers
#[derive(Debug, Default, Clone)]
pub struct GuesserSettings {
    /// Whether to trust the package contents and run executables
    pub trust_package: bool,
}

type GuesserFunction =
    Box<dyn FnOnce(&GuesserSettings) -> Result<Vec<UpstreamDatumWithMetadata>, ProviderError>>;

/// A guesser that can extract upstream metadata from a specific file
pub struct UpstreamMetadataGuesser {
    /// Name/path of the guesser
    pub name: std::path::PathBuf,
    /// Function that performs the guessing
    pub guess: GuesserFunction,
}

impl std::fmt::Debug for UpstreamMetadataGuesser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UpstreamMetadataGuesser")
            .field("name", &self.name)
            .finish()
    }
}

type OldAsyncGuesser = fn(
    PathBuf,
    GuesserSettings,
) -> Pin<
    Box<
        dyn std::future::Future<Output = Result<Vec<UpstreamDatumWithMetadata>, ProviderError>>
            + Send,
    >,
>;

const OLD_STATIC_GUESSERS: &[(&str, OldAsyncGuesser)] = &[
    #[cfg(feature = "debian")]
    ("debian/watch", |path, settings| {
        Box::pin(async move {
            crate::providers::debian::guess_from_debian_watch(&path, &settings).await
        })
    }),
    #[cfg(feature = "debian")]
    ("debian/control", |path, settings| {
        Box::pin(
            async move { crate::providers::debian::guess_from_debian_control(&path, &settings) },
        )
    }),
    #[cfg(feature = "debian")]
    ("debian/changelog", |path, settings| {
        Box::pin(async move {
            crate::providers::debian::guess_from_debian_changelog(&path, &settings).await
        })
    }),
    #[cfg(feature = "debian")]
    ("debian/rules", |path, settings| {
        Box::pin(async move { crate::providers::debian::guess_from_debian_rules(&path, &settings) })
    }),
    #[cfg(feature = "python-pkginfo")]
    ("PKG-INFO", |path, settings| {
        Box::pin(
            async move { crate::providers::python::guess_from_pkg_info(&path, &settings).await },
        )
    }),
    ("package.json", |path, settings| {
        Box::pin(async move {
            crate::providers::package_json::guess_from_package_json(&path, &settings)
        })
    }),
    ("composer.json", |path, settings| {
        Box::pin(async move {
            crate::providers::composer_json::guess_from_composer_json(&path, &settings)
        })
    }),
    ("package.xml", |path, settings| {
        Box::pin(
            async move { crate::providers::package_xml::guess_from_package_xml(&path, &settings) },
        )
    }),
    ("package.yaml", |path, settings| {
        Box::pin(async move {
            crate::providers::package_yaml::guess_from_package_yaml(&path, &settings)
        })
    }),
    #[cfg(feature = "dist-ini")]
    ("dist.ini", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_dist_ini(&path, &settings) })
    }),
    #[cfg(feature = "debian")]
    ("debian/copyright", |path, settings| {
        Box::pin(async move {
            crate::providers::debian::guess_from_debian_copyright(&path, &settings).await
        })
    }),
    ("META.json", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_meta_json(&path, &settings) })
    }),
    ("MYMETA.json", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_meta_json(&path, &settings) })
    }),
    ("META.yml", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_meta_yml(&path, &settings) })
    }),
    ("MYMETA.yml", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_meta_yml(&path, &settings) })
    }),
    ("configure", |path, settings| {
        Box::pin(async move { crate::providers::autoconf::guess_from_configure(&path, &settings) })
    }),
    #[cfg(feature = "r-description")]
    ("DESCRIPTION", |path, settings| {
        Box::pin(
            async move { crate::providers::r::guess_from_r_description(&path, &settings).await },
        )
    }),
    #[cfg(feature = "cargo")]
    ("Cargo.toml", |path, settings| {
        Box::pin(async move { crate::providers::rust::guess_from_cargo(&path, &settings) })
    }),
    ("pom.xml", |path, settings| {
        Box::pin(async move { crate::providers::maven::guess_from_pom_xml(&path, &settings) })
    }),
    #[cfg(feature = "git-config")]
    (".git/config", |path, settings| {
        Box::pin(async move { crate::providers::git::guess_from_git_config(&path, &settings) })
    }),
    ("debian/get-orig-source.sh", |path, settings| {
        Box::pin(async move { crate::vcs_command::guess_from_get_orig_source(&path, &settings) })
    }),
    #[cfg(feature = "pyproject-toml")]
    ("pyproject.toml", |path, settings| {
        Box::pin(
            async move { crate::providers::python::guess_from_pyproject_toml(&path, &settings) },
        )
    }),
    #[cfg(feature = "setup-cfg")]
    ("setup.cfg", |path, settings| {
        Box::pin(
            async move { crate::providers::python::guess_from_setup_cfg(&path, &settings).await },
        )
    }),
    ("go.mod", |path, settings| {
        Box::pin(async move { crate::providers::go::guess_from_go_mod(&path, &settings) })
    }),
    ("Makefile.PL", |path, settings| {
        Box::pin(async move { crate::providers::perl::guess_from_makefile_pl(&path, &settings) })
    }),
    ("wscript", |path, settings| {
        Box::pin(async move { crate::providers::waf::guess_from_wscript(&path, &settings) })
    }),
    ("AUTHORS", |path, settings| {
        Box::pin(async move { crate::providers::authors::guess_from_authors(&path, &settings) })
    }),
    ("INSTALL", |path, settings| {
        Box::pin(async move { crate::providers::guess_from_install(&path, &settings).await })
    }),
    ("pubspec.yaml", |path, settings| {
        Box::pin(
            async move { crate::providers::pubspec::guess_from_pubspec_yaml(&path, &settings) },
        )
    }),
    ("pubspec.yml", |path, settings| {
        Box::pin(
            async move { crate::providers::pubspec::guess_from_pubspec_yaml(&path, &settings) },
        )
    }),
    ("meson.build", |path, settings| {
        Box::pin(async move { crate::providers::meson::guess_from_meson(&path, &settings) })
    }),
    ("metadata.json", |path, settings| {
        Box::pin(async move {
            crate::providers::metadata_json::guess_from_metadata_json(&path, &settings)
        })
    }),
    (".travis.yml", |path, settings| {
        Box::pin(async move { crate::guess_from_travis_yml(&path, &settings) })
    }),
];

fn find_guessers(path: &std::path::Path) -> Vec<Box<dyn Guesser>> {
    let mut candidates: Vec<Box<dyn Guesser>> = Vec::new();

    let path = path.canonicalize().unwrap();

    for (name, cb) in OLD_STATIC_GUESSERS {
        let subpath = path.join(name);
        if subpath.exists() {
            candidates.push(Box::new(PathGuesser {
                name: name.to_string(),
                subpath: subpath.clone(),
                cb: Box::new(move |p, s| Box::pin(cb(p.to_path_buf(), s.clone()))),
            }));
        }
    }

    for name in ["SECURITY.md", ".github/SECURITY.md", "docs/SECURITY.md"].iter() {
        if path.join(name).exists() {
            let subpath = path.join(name);
            candidates.push(Box::new(PathGuesser {
                name: name.to_string(),
                subpath: subpath.clone(),
                cb: Box::new(|p, s| {
                    let name = name.to_string();
                    Box::pin(async move {
                        crate::providers::security_md::guess_from_security_md(&name, &p, &s)
                    })
                }),
            }));
        }
    }

    let mut found_pkg_info = path.join("PKG-INFO").exists();
    #[cfg(feature = "python-pkginfo")]
    for entry in std::fs::read_dir(&path).unwrap() {
        let entry = entry.unwrap();
        let filename = entry.file_name().to_string_lossy().to_string();
        if filename.ends_with(".egg-info") {
            candidates.push(Box::new(PathGuesser {
                name: format!("{}/PKG-INFO", filename),
                subpath: entry.path().join("PKG-INFO"),
                cb: Box::new(|p, s| {
                    Box::pin(
                        async move { crate::providers::python::guess_from_pkg_info(&p, &s).await },
                    )
                }),
            }));
            found_pkg_info = true;
        } else if filename.ends_with(".dist-info") {
            candidates.push(Box::new(PathGuesser {
                name: format!("{}/METADATA", filename),
                subpath: entry.path().join("METADATA"),
                cb: Box::new(|p, s| {
                    Box::pin(
                        async move { crate::providers::python::guess_from_pkg_info(&p, &s).await },
                    )
                }),
            }));
            found_pkg_info = true;
        }
    }

    #[cfg(feature = "pyo3")]
    if !found_pkg_info && path.join("setup.py").exists() {
        candidates.push(Box::new(PathGuesser {
            name: "setup.py".to_string(),
            subpath: path.join("setup.py"),
            cb: Box::new(|path, s| {
                Box::pin(async move {
                    crate::providers::python::guess_from_setup_py(&path, s.trust_package).await
                })
            }),
        }));
    }

    for entry in std::fs::read_dir(&path).unwrap() {
        let entry = entry.unwrap();

        if entry.file_name().to_string_lossy().ends_with(".gemspec") {
            candidates.push(Box::new(PathGuesser {
                name: entry.file_name().to_string_lossy().to_string(),
                subpath: entry.path(),
                cb: Box::new(|p, s| {
                    Box::pin(
                        async move { crate::providers::ruby::guess_from_gemspec(&p, &s).await },
                    )
                }),
            }));
        }
    }

    // TODO(jelmer): Perhaps scan all directories if no other primary project information file has been found?
    #[cfg(feature = "r-description")]
    for entry in std::fs::read_dir(&path).unwrap() {
        let entry = entry.unwrap();
        let path = entry.path();

        if entry.file_type().unwrap().is_dir() {
            let description_name = format!("{}/DESCRIPTION", entry.file_name().to_string_lossy());
            if path.join(&description_name).exists() {
                candidates.push(Box::new(PathGuesser {
                    name: description_name,
                    subpath: path.join("DESCRIPTION"),
                    cb: Box::new(|p, s| {
                        Box::pin(async move {
                            crate::providers::r::guess_from_r_description(&p, &s).await
                        })
                    }),
                }));
            }
        }
    }

    let mut doap_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            let filename = entry.file_name().to_string_lossy().to_string();
            if filename.ends_with(".doap")
                || (filename.ends_with(".xml") && filename.starts_with("doap_XML_"))
            {
                Some(entry.file_name())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if doap_filenames.len() == 1 {
        let doap_filename = doap_filenames.remove(0);
        candidates.push(Box::new(PathGuesser {
            name: doap_filename.to_string_lossy().to_string(),
            subpath: path.join(&doap_filename),
            cb: Box::new(|p, s| {
                Box::pin(
                    async move { crate::providers::doap::guess_from_doap(&p, s.trust_package) },
                )
            }),
        }));
    } else if doap_filenames.len() > 1 {
        log::warn!(
            "Multiple DOAP files found: {:?}, ignoring all.",
            doap_filenames
        );
    }

    let mut metainfo_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            if entry
                .file_name()
                .to_string_lossy()
                .ends_with(".metainfo.xml")
            {
                Some(entry.file_name())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if metainfo_filenames.len() == 1 {
        let metainfo_filename = metainfo_filenames.remove(0);
        candidates.push(Box::new(PathGuesser {
            name: metainfo_filename.to_string_lossy().to_string(),
            subpath: path.join(&metainfo_filename),
            cb: Box::new(|p, s| {
                Box::pin(async move {
                    crate::providers::metainfo::guess_from_metainfo(&p, s.trust_package)
                })
            }),
        }));
    } else if metainfo_filenames.len() > 1 {
        log::warn!(
            "Multiple metainfo files found: {:?}, ignoring all.",
            metainfo_filenames
        );
    }

    let mut cabal_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            if entry.file_name().to_string_lossy().ends_with(".cabal") {
                Some(entry.file_name())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if cabal_filenames.len() == 1 {
        let cabal_filename = cabal_filenames.remove(0);
        candidates.push(Box::new(PathGuesser {
            name: cabal_filename.to_string_lossy().to_string(),
            subpath: path.join(&cabal_filename),
            cb: Box::new(|path, s| {
                Box::pin(async move {
                    crate::providers::haskell::guess_from_cabal(&path, s.trust_package)
                })
            }),
        }));
    } else if cabal_filenames.len() > 1 {
        log::warn!(
            "Multiple cabal files found: {:?}, ignoring all.",
            cabal_filenames
        );
    }

    let readme_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            let filename = entry.file_name().to_string_lossy().to_string();
            if !(filename.to_lowercase().starts_with("readme")
                || filename.to_lowercase().starts_with("hacking")
                || filename.to_lowercase().starts_with("contributing"))
            {
                return None;
            }

            if filename.ends_with('~') {
                return None;
            }

            let extension = entry
                .path()
                .extension()
                .map(|s| s.to_string_lossy().to_string());

            if extension.as_deref() == Some("html")
                || extension.as_deref() == Some("pdf")
                || extension.as_deref() == Some("xml")
            {
                return None;
            }
            Some(entry.file_name())
        })
        .collect::<Vec<_>>();

    for filename in readme_filenames {
        candidates.push(Box::new(PathGuesser {
            name: filename.to_string_lossy().to_string(),
            subpath: path.join(&filename),
            cb: Box::new(|path, s| {
                Box::pin(
                    async move { crate::readme::guess_from_readme(&path, s.trust_package).await },
                )
            }),
        }));
    }

    let mut nuspec_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            if entry.file_name().to_string_lossy().ends_with(".nuspec") {
                Some(entry.file_name())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if nuspec_filenames.len() == 1 {
        let nuspec_filename = nuspec_filenames.remove(0);
        candidates.push(Box::new(PathGuesser {
            name: nuspec_filename.to_string_lossy().to_string(),
            subpath: path.join(&nuspec_filename),
            cb: Box::new(|path, s| {
                Box::pin(async move {
                    crate::providers::nuspec::guess_from_nuspec(&path, s.trust_package).await
                })
            }),
        }));
    } else if nuspec_filenames.len() > 1 {
        log::warn!(
            "Multiple nuspec files found: {:?}, ignoring all.",
            nuspec_filenames
        );
    }

    #[cfg(feature = "opam")]
    let mut opam_filenames = std::fs::read_dir(&path)
        .unwrap()
        .filter_map(|entry| {
            let entry = entry.unwrap();
            if entry.file_name().to_string_lossy().ends_with(".opam") {
                Some(entry.file_name())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    #[cfg(feature = "opam")]
    match opam_filenames.len().cmp(&1) {
        Ordering::Equal => {
            let opam_filename = opam_filenames.remove(0);
            candidates.push(Box::new(PathGuesser {
                name: opam_filename.to_string_lossy().to_string(),
                subpath: path.join(&opam_filename),
                cb: Box::new(|path, s| {
                    Box::pin(async move {
                        crate::providers::ocaml::guess_from_opam(&path, s.trust_package)
                    })
                }),
            }));
        }
        Ordering::Greater => {
            log::warn!(
                "Multiple opam files found: {:?}, ignoring all.",
                opam_filenames
            );
        }
        Ordering::Less => {}
    }

    let debian_patches = match std::fs::read_dir(path.join("debian").join("patches")) {
        Ok(patches) => patches
            .filter_map(|entry| {
                let entry = entry.unwrap();
                if entry.file_name().to_string_lossy().ends_with(".patch") {
                    Some(format!(
                        "debian/patches/{}",
                        entry.file_name().to_string_lossy()
                    ))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>(),
        Err(_) => Vec::new(),
    };

    for filename in debian_patches {
        candidates.push(Box::new(PathGuesser {
            name: filename.clone(),
            subpath: path.join(&filename),
            cb: Box::new(|path, s| {
                Box::pin(async move {
                    crate::providers::debian::guess_from_debian_patch(&path, &s).await
                })
            }),
        }));
    }

    candidates.push(Box::new(EnvironmentGuesser::new()));
    candidates.push(Box::new(PathGuesser {
        name: ".".to_string(),
        subpath: path.clone(),
        cb: Box::new(|p, s| Box::pin(async move { crate::guess_from_path(&p, &s) })),
    }));

    candidates
}

pub(crate) fn stream(
    path: &Path,
    config: &GuesserSettings,
    guessers: Vec<Box<dyn Guesser>>,
) -> impl Stream<Item = Result<UpstreamDatumWithMetadata, ProviderError>> {
    // For each of the guessers, create concurrent tasks that run the guessers in parallel
    let abspath = std::env::current_dir().unwrap().join(path);
    let config = config.clone();

    // Run guessers concurrently using buffered (no tokio::spawn required)
    futures::stream::iter(guessers)
        .map(move |mut guesser| {
            let abspath = abspath.clone();
            let config = config.clone();
            let guesser_name = guesser.name().to_string();

            async move {
                let results = match guesser.guess(&config).await {
                    Ok(results) => results,
                    Err(e) => return futures::stream::iter(vec![Err(e)]).boxed(),
                };

                futures::stream::iter(results.into_iter().map(move |mut datum| {
                    rewrite_upstream_datum(&guesser_name, &mut datum, &abspath);
                    Ok(datum)
                }))
                .boxed()
            }
        })
        .buffered(10) // Run up to 10 guessers concurrently while preserving order
        .flatten()
}

fn rewrite_upstream_datum(
    guesser_name: &str,
    datum: &mut UpstreamDatumWithMetadata,
    abspath: &std::path::Path,
) {
    log::trace!("{}: {:?}", guesser_name, datum);
    datum.origin = datum
        .origin
        .clone()
        .or(Some(Origin::Other(guesser_name.to_string())));
    if let Some(Origin::Path(p)) = datum.origin.as_ref() {
        if let Ok(suffix) = p.strip_prefix(abspath) {
            if suffix.to_str().unwrap().is_empty() {
                datum.origin = Some(Origin::Path(PathBuf::from_str(".").unwrap()));
            } else {
                datum.origin = Some(Origin::Path(PathBuf::from_str(".").unwrap().join(suffix)));
            }
        }
    }
}

/// Creates a stream of upstream metadata by running all applicable guessers
pub fn upstream_metadata_stream(
    path: &std::path::Path,
    trust_package: Option<bool>,
) -> impl Stream<Item = Result<UpstreamDatumWithMetadata, ProviderError>> {
    let trust_package = trust_package.unwrap_or(false);

    let guessers = find_guessers(path);

    stream(path, &GuesserSettings { trust_package }, guessers)
}

/// Extends upstream metadata with additional information from external sources
pub async fn extend_upstream_metadata(
    upstream_metadata: &mut UpstreamMetadata,
    path: &std::path::Path,
    minimum_certainty: Option<Certainty>,
    net_access: Option<bool>,
    consult_external_directory: Option<bool>,
) -> Result<(), ProviderError> {
    let net_access = net_access.unwrap_or(false);
    let consult_external_directory = consult_external_directory.unwrap_or(false);
    let minimum_certainty = minimum_certainty.unwrap_or(Certainty::Confident);

    // TODO(jelmer): Use EXTRAPOLATE_FNS mechanism for this?
    for field in [
        "Homepage",
        "Bug-Database",
        "Bug-Submit",
        "Repository",
        "Repository-Browse",
        "Download",
    ] {
        let value = match upstream_metadata.get(field) {
            Some(value) => value,
            None => continue,
        };

        if let Some(project) =
            crate::forges::sourceforge::extract_sf_project_name(value.datum.as_str().unwrap())
        {
            let certainty = Some(
                std::cmp::min(Some(Certainty::Likely), value.certainty)
                    .unwrap_or(Certainty::Likely),
            );
            upstream_metadata.insert(UpstreamDatumWithMetadata {
                datum: UpstreamDatum::Archive("SourceForge".to_string()),
                certainty,
                origin: Some(Origin::Other(format!("derived from {}", field))),
            });
            upstream_metadata.insert(UpstreamDatumWithMetadata {
                datum: UpstreamDatum::SourceForgeProject(project),
                certainty,
                origin: Some(Origin::Other(format!("derived from {}", field))),
            });
            break;
        }
    }

    let archive = upstream_metadata.get("Archive");
    if archive.is_some()
        && archive.unwrap().datum.as_str().unwrap() == "SourceForge"
        && upstream_metadata.contains_key("SourceForge-Project")
        && net_access
    {
        let sf_project = upstream_metadata
            .get("SourceForge-Project")
            .unwrap()
            .datum
            .as_str()
            .unwrap()
            .to_string();
        let sf_certainty = archive.unwrap().certainty;
        SourceForge::new()
            .extend_metadata(
                upstream_metadata.mut_items(),
                sf_project.as_str(),
                sf_certainty,
            )
            .await;
    }

    let archive = upstream_metadata.get("Archive");
    if archive.is_some()
        && archive.unwrap().datum.as_str().unwrap() == "Hackage"
        && upstream_metadata.contains_key("Hackage-Package")
        && net_access
    {
        let hackage_package = upstream_metadata
            .get("Hackage-Package")
            .unwrap()
            .datum
            .as_str()
            .unwrap()
            .to_string();
        let hackage_certainty = archive.unwrap().certainty;

        crate::providers::haskell::Hackage::new()
            .extend_metadata(
                upstream_metadata.mut_items(),
                hackage_package.as_str(),
                hackage_certainty,
            )
            .await
            .unwrap();
    }

    let archive = upstream_metadata.get("Archive");
    #[cfg(feature = "cargo")]
    if archive.is_some()
        && archive.unwrap().datum.as_str().unwrap() == "crates.io"
        && upstream_metadata.contains_key("Cargo-Crate")
        && net_access
    {
        let cargo_crate = upstream_metadata
            .get("Cargo-Crate")
            .unwrap()
            .datum
            .as_str()
            .unwrap()
            .to_string();
        let crates_io_certainty = upstream_metadata.get("Archive").unwrap().certainty;
        crate::providers::rust::CratesIo::new()
            .extend_metadata(
                upstream_metadata.mut_items(),
                cargo_crate.as_str(),
                crates_io_certainty,
            )
            .await
            .unwrap();
    }

    let archive = upstream_metadata.get("Archive");
    if archive.is_some()
        && archive.unwrap().datum.as_str().unwrap() == "Pecl"
        && upstream_metadata.contains_key("Pecl-Package")
        && net_access
    {
        let pecl_package = upstream_metadata
            .get("Pecl-Package")
            .unwrap()
            .datum
            .as_str()
            .unwrap()
            .to_string();
        let pecl_certainty = upstream_metadata.get("Archive").unwrap().certainty;
        crate::providers::php::Pecl::new()
            .extend_metadata(
                upstream_metadata.mut_items(),
                pecl_package.as_str(),
                pecl_certainty,
            )
            .await
            .unwrap();
    }

    #[cfg(feature = "debian")]
    if net_access && consult_external_directory {
        // TODO(jelmer): Don't assume debian/control exists
        let package = match debian_control::Control::from_file_relaxed(path.join("debian/control"))
        {
            Ok((control, _)) => control.source().and_then(|s| s.name()),
            Err(_) => None,
        };

        if let Some(package) = package {
            #[cfg(feature = "launchpad")]
            extend_from_lp(
                upstream_metadata.mut_items(),
                minimum_certainty,
                package.as_str(),
                None,
                None,
            )
            .await;
            crate::providers::arch::Aur::new()
                .extend_metadata(
                    upstream_metadata.mut_items(),
                    package.as_str(),
                    Some(minimum_certainty),
                )
                .await
                .unwrap();
            crate::providers::gobo::Gobo::new()
                .extend_metadata(
                    upstream_metadata.mut_items(),
                    package.as_str(),
                    Some(minimum_certainty),
                )
                .await
                .unwrap();
            extend_from_repology(
                upstream_metadata.mut_items(),
                minimum_certainty,
                package.as_str(),
            )
            .await;
        }
    }
    crate::extrapolate::extrapolate_fields(upstream_metadata, net_access, None).await?;
    Ok(())
}

/// Trait for third-party repositories that can provide upstream metadata
#[async_trait::async_trait]
pub trait ThirdPartyRepository {
    /// Returns the name of the repository
    fn name(&self) -> &'static str;
    /// Returns the list of fields this repository can provide
    fn supported_fields(&self) -> &'static [&'static str];
    /// Returns the maximum certainty level this repository can provide
    fn max_supported_certainty(&self) -> Certainty;

    /// Extends metadata with information from this repository
    async fn extend_metadata(
        &self,
        metadata: &mut Vec<UpstreamDatumWithMetadata>,
        name: &str,
        min_certainty: Option<Certainty>,
    ) -> Result<(), ProviderError> {
        if min_certainty.is_some() && min_certainty.unwrap() > self.max_supported_certainty() {
            // Don't bother if we can't meet minimum certainty
            return Ok(());
        }

        extend_from_external_guesser(
            metadata,
            Some(self.max_supported_certainty()),
            self.supported_fields(),
            || async { self.guess_metadata(name).await.unwrap() },
        )
        .await;

        Ok(())
    }

    /// Guesses metadata for a given package name
    async fn guess_metadata(&self, name: &str) -> Result<Vec<UpstreamDatum>, ProviderError>;
}

#[cfg(feature = "launchpad")]
async fn extend_from_lp(
    upstream_metadata: &mut Vec<UpstreamDatumWithMetadata>,
    minimum_certainty: Certainty,
    package: &str,
    distribution: Option<&str>,
    suite: Option<&str>,
) {
    // The set of fields that Launchpad can possibly provide:
    let lp_fields = &["Homepage", "Repository", "Name", "Download"][..];
    let lp_certainty = Certainty::Possible;

    if lp_certainty < minimum_certainty {
        // Don't bother talking to launchpad if we're not
        // speculating.
        return;
    }

    extend_from_external_guesser(upstream_metadata, Some(lp_certainty), lp_fields, || async {
        crate::providers::launchpad::guess_from_launchpad(package, distribution, suite)
            .await
            .unwrap()
    })
    .await
}

async fn extend_from_repology(
    upstream_metadata: &mut Vec<UpstreamDatumWithMetadata>,
    minimum_certainty: Certainty,
    source_package: &str,
) {
    // The set of fields that repology can possibly provide:
    let repology_fields = &["Homepage", "License", "Summary", "Download"][..];
    let certainty = Certainty::Confident;

    if certainty < minimum_certainty {
        // Don't bother talking to repology if we're not speculating.
        return;
    }

    extend_from_external_guesser(
        upstream_metadata,
        Some(certainty),
        repology_fields,
        || async {
            crate::providers::repology::guess_from_repology(source_package)
                .await
                .unwrap()
        },
    )
    .await
}

/// Fix existing upstream metadata.
pub async fn fix_upstream_metadata(upstream_metadata: &mut UpstreamMetadata) {
    if let Some(repository) = upstream_metadata.get_mut("Repository") {
        if let Some(repo_str) = repository.datum.as_str() {
            let url = crate::vcs::sanitize_url(repo_str).await;
            repository.datum = UpstreamDatum::Repository(url.to_string());
        }
    }

    if let Some(summary) = upstream_metadata.get_mut("Summary") {
        if let Some(s) = summary.datum.as_str() {
            let s = s.split_once(". ").map_or(s, |(a, _)| a);
            let s = s.trim_end().trim_end_matches('.');
            summary.datum = UpstreamDatum::Summary(s.to_string());
        }
    }
}

/// Summarize the upstream metadata into a dictionary.
///
/// # Arguments
/// * `metadata_items`: Iterator over metadata items
/// * `path`: Path to the package
/// * `trust_package`: Whether to trust the package contents and i.e. run executables in it
/// * `net_access`: Whether to allow net access
/// * `consult_external_directory`: Whether to pull in data from external (user-maintained) directories.
pub async fn summarize_upstream_metadata(
    metadata_items: impl Stream<Item = UpstreamDatumWithMetadata>,
    path: &std::path::Path,
    net_access: Option<bool>,
    consult_external_directory: Option<bool>,
    check: Option<bool>,
) -> Result<UpstreamMetadata, ProviderError> {
    let check = check.unwrap_or(false);
    let mut upstream_metadata = UpstreamMetadata::new();

    let metadata_items = metadata_items.filter_map(|item| async move {
        let bad: bool = item.datum.known_bad_guess();
        if bad {
            log::debug!("Excluding known bad item {:?}", item);
            None
        } else {
            Some(item)
        }
    });

    let metadata_items = metadata_items.collect::<Vec<_>>().await;

    upstream_metadata.update(metadata_items.into_iter());

    extend_upstream_metadata(
        &mut upstream_metadata,
        path,
        None,
        net_access,
        consult_external_directory,
    )
    .await?;

    if check {
        check_upstream_metadata(&mut upstream_metadata, None).await;
    }

    fix_upstream_metadata(&mut upstream_metadata).await;

    // Sort by name
    upstream_metadata.sort();

    Ok(upstream_metadata)
}

/// Guess upstream metadata items, in no particular order.
///
/// # Arguments
/// * `path`: Path to the package
/// * `trust_package`: Whether to trust the package contents and i.e. run executables in it
/// * `minimum_certainty`: Minimum certainty of guesses to return
pub fn guess_upstream_metadata_items(
    path: &std::path::Path,
    trust_package: Option<bool>,
    minimum_certainty: Option<Certainty>,
) -> impl Stream<Item = Result<UpstreamDatumWithMetadata, ProviderError>> {
    let items = upstream_metadata_stream(path, trust_package);

    items.filter_map(move |e| async move {
        match e {
            Err(e) => Some(Err(e)),
            Ok(UpstreamDatumWithMetadata {
                datum,
                certainty,
                origin,
            }) => {
                if minimum_certainty.is_some() && certainty < minimum_certainty {
                    None
                } else {
                    Some(Ok(UpstreamDatumWithMetadata {
                        datum,
                        certainty,
                        origin,
                    }))
                }
            }
        }
    })
}

/// Gets upstream information for a project
pub async fn get_upstream_info(
    path: &std::path::Path,
    trust_package: Option<bool>,
    net_access: Option<bool>,
    consult_external_directory: Option<bool>,
    check: Option<bool>,
) -> Result<UpstreamMetadata, ProviderError> {
    let metadata_items = upstream_metadata_stream(path, trust_package);

    let metadata_items = metadata_items.filter_map(|x| async {
        match x {
            Ok(x) => Some(x),
            Err(e) => {
                log::error!("{}", e);
                None
            }
        }
    });

    summarize_upstream_metadata(
        metadata_items,
        path,
        net_access,
        consult_external_directory,
        check,
    )
    .await
}

/// Guess the upstream metadata dictionary.
///
/// # Arguments
/// * `path`: Path to the package
/// * `trust_package`: Whether to trust the package contents and i.e. run executables in it
/// * `net_access`: Whether to allow net access
/// * `consult_external_directory`: Whether to pull in data from external (user-maintained) directories.
pub async fn guess_upstream_metadata(
    path: &std::path::Path,
    trust_package: Option<bool>,
    net_access: Option<bool>,
    consult_external_directory: Option<bool>,
    check: Option<bool>,
) -> Result<UpstreamMetadata, ProviderError> {
    let metadata_items = guess_upstream_metadata_items(path, trust_package, None);

    let metadata_items = metadata_items.filter_map(|x| async {
        match x {
            Ok(x) => Some(x),
            Err(e) => {
                log::error!("{}", e);
                None
            }
        }
    });
    summarize_upstream_metadata(
        metadata_items,
        path,
        net_access,
        consult_external_directory,
        check,
    )
    .await
}

/// Verifies that screenshot URLs are accessible
pub async fn verify_screenshots(urls: &[&str]) -> Vec<(String, Option<bool>)> {
    let mut ret = Vec::new();
    for url in urls {
        let mut request = reqwest::Request::new(reqwest::Method::GET, url.parse().unwrap());
        request.headers_mut().insert(
            reqwest::header::USER_AGENT,
            reqwest::header::HeaderValue::from_static(USER_AGENT),
        );

        match reqwest::Client::new().execute(request).await {
            Ok(response) => {
                let status = response.status();
                if status.is_success() {
                    ret.push((url.to_string(), Some(true)));
                } else if status.is_client_error() {
                    ret.push((url.to_string(), Some(false)));
                } else {
                    ret.push((url.to_string(), None));
                }
            }
            Err(e) => {
                log::debug!("Error fetching {}: {}", url, e);
                ret.push((url.to_string(), None));
            }
        }
    }

    ret
}

/// Check upstream metadata.
///
/// This will make network connections, etc.
pub async fn check_upstream_metadata(
    upstream_metadata: &mut UpstreamMetadata,
    version: Option<&str>,
) {
    let repository = upstream_metadata.get_mut("Repository");
    if let Some(repository) = repository {
        if let Some(repo_url) = repository.datum.to_url() {
            match vcs::check_repository_url_canonical(repo_url, version).await {
                Ok(canonical_url) => {
                    repository.datum = UpstreamDatum::Repository(canonical_url.to_string());
                    if repository.certainty == Some(Certainty::Confident) {
                        repository.certainty = Some(Certainty::Certain);
                    }
                    if let Some(url) = repository.datum.to_url() {
                        let derived_browse_url = vcs::browse_url_from_repo_url(
                            &vcs::VcsLocation {
                                url,
                                branch: None,
                                subpath: None,
                            },
                            Some(true),
                        )
                        .await;
                        let certainty = repository.certainty;
                        if let Some(browse_repo) = upstream_metadata.get_mut("Repository-Browse") {
                            if derived_browse_url == browse_repo.datum.to_url() {
                                browse_repo.certainty = certainty;
                            }
                        }
                    }
                }
                Err(CanonicalizeError::Unverifiable(u, _))
                | Err(CanonicalizeError::RateLimited(u)) => {
                    log::debug!("Unverifiable URL: {}", u);
                }
                Err(CanonicalizeError::InvalidUrl(u, e)) => {
                    log::debug!("Deleting invalid Repository URL {}: {}", u, e);
                    upstream_metadata.remove("Repository");
                }
            }
        } else {
            log::debug!("Repository field is not a valid URL, skipping check");
        }
    }
    let homepage = upstream_metadata.get_mut("Homepage");
    if let Some(homepage) = homepage {
        if let Some(homepage_url) = homepage.datum.to_url() {
            match check_url_canonical(&homepage_url).await {
                Ok(canonical_url) => {
                    homepage.datum = UpstreamDatum::Homepage(canonical_url.to_string());
                    if homepage.certainty >= Some(Certainty::Likely) {
                        homepage.certainty = Some(Certainty::Certain);
                    }
                }
                Err(CanonicalizeError::Unverifiable(u, _))
                | Err(CanonicalizeError::RateLimited(u)) => {
                    log::debug!("Unverifiable URL: {}", u);
                }
                Err(CanonicalizeError::InvalidUrl(u, e)) => {
                    log::debug!("Deleting invalid Homepage URL {}: {}", u, e);
                    upstream_metadata.remove("Homepage");
                }
            }
        } else {
            log::debug!("Homepage field is not a valid URL, skipping check");
        }
    }
    if let Some(repository_browse) = upstream_metadata.get_mut("Repository-Browse") {
        if let Some(browse_url) = repository_browse.datum.to_url() {
            match check_url_canonical(&browse_url).await {
                Ok(u) => {
                    repository_browse.datum = UpstreamDatum::RepositoryBrowse(u.to_string());
                    if repository_browse.certainty >= Some(Certainty::Likely) {
                        repository_browse.certainty = Some(Certainty::Certain);
                    }
                }
                Err(CanonicalizeError::InvalidUrl(u, e)) => {
                    log::debug!("Deleting invalid Repository-Browse URL {}: {}", u, e);
                    upstream_metadata.remove("Repository-Browse");
                }
                Err(CanonicalizeError::Unverifiable(u, _))
                | Err(CanonicalizeError::RateLimited(u)) => {
                    log::debug!("Unable to verify Repository-Browse URL {}", u);
                }
            }
        } else {
            log::debug!("Repository-Browse field is not a valid URL, skipping check");
        }
    }
    if let Some(bug_database) = upstream_metadata.get_mut("Bug-Database") {
        if let Some(bug_db_url) = bug_database.datum.to_url() {
            match check_bug_database_canonical(&bug_db_url, Some(true)).await {
                Ok(u) => {
                    bug_database.datum = UpstreamDatum::BugDatabase(u.to_string());
                    if bug_database.certainty >= Some(Certainty::Likely) {
                        bug_database.certainty = Some(Certainty::Certain);
                    }
                }
                Err(CanonicalizeError::InvalidUrl(u, e)) => {
                    log::debug!("Deleting invalid Bug-Database URL {}: {}", u, e);
                    upstream_metadata.remove("Bug-Database");
                }
                Err(CanonicalizeError::Unverifiable(u, _))
                | Err(CanonicalizeError::RateLimited(u)) => {
                    log::debug!("Unable to verify Bug-Database URL {}", u);
                }
            }
        } else {
            log::debug!("Bug-Database field is not a valid URL, skipping check");
        }
    }
    let bug_submit = upstream_metadata.get_mut("Bug-Submit");
    if let Some(bug_submit) = bug_submit {
        if let Some(bug_submit_url) = bug_submit.datum.to_url() {
            match check_bug_submit_url_canonical(&bug_submit_url, Some(true)).await {
                Ok(u) => {
                    bug_submit.datum = UpstreamDatum::BugSubmit(u.to_string());
                    if bug_submit.certainty >= Some(Certainty::Likely) {
                        bug_submit.certainty = Some(Certainty::Certain);
                    }
                }
                Err(CanonicalizeError::InvalidUrl(u, e)) => {
                    log::debug!("Deleting invalid Bug-Submit URL {}: {}", u, e);
                    upstream_metadata.remove("Bug-Submit");
                }
                Err(CanonicalizeError::Unverifiable(u, _))
                | Err(CanonicalizeError::RateLimited(u)) => {
                    log::debug!("Unable to verify Bug-Submit URL {}", u);
                }
            }
        } else {
            log::debug!("Bug-Submit field is not a valid URL, skipping check");
        }
    }
    let mut screenshots = upstream_metadata.get_mut("Screenshots");
    if screenshots.is_some() && screenshots.as_ref().unwrap().certainty == Some(Certainty::Likely) {
        let mut newvalue = vec![];
        screenshots.as_mut().unwrap().certainty = Some(Certainty::Certain);
        let urls = match &screenshots.as_ref().unwrap().datum {
            UpstreamDatum::Screenshots(urls) => urls,
            _ => unreachable!(),
        };
        for (url, status) in verify_screenshots(
            urls.iter()
                .map(|x| x.as_str())
                .collect::<Vec<&str>>()
                .as_slice(),
        )
        .await
        {
            match status {
                Some(true) => {
                    newvalue.push(url);
                }
                Some(false) => {}
                None => {
                    screenshots.as_mut().unwrap().certainty = Some(Certainty::Likely);
                }
            }
        }
        screenshots.as_mut().unwrap().datum = UpstreamDatum::Screenshots(newvalue);
    }
}

#[async_trait::async_trait]
pub(crate) trait Guesser: Send {
    fn name(&self) -> &str;

    /// Guess metadata from a given path.
    async fn guess(
        &mut self,
        settings: &GuesserSettings,
    ) -> Result<Vec<UpstreamDatumWithMetadata>, ProviderError>;
}

type AsyncGuesserFunction = Box<
    dyn FnMut(
            PathBuf,
            GuesserSettings,
        ) -> Pin<
            Box<
                dyn std::future::Future<
                        Output = Result<Vec<UpstreamDatumWithMetadata>, ProviderError>,
                    > + Send,
            >,
        > + Send,
>;

/// Guesser that extracts metadata from a specific file path
pub struct PathGuesser {
    name: String,
    subpath: std::path::PathBuf,
    cb: AsyncGuesserFunction,
}

#[async_trait::async_trait]
impl Guesser for PathGuesser {
    fn name(&self) -> &str {
        &self.name
    }

    async fn guess(
        &mut self,
        settings: &GuesserSettings,
    ) -> Result<Vec<UpstreamDatumWithMetadata>, ProviderError> {
        (self.cb)(self.subpath.clone(), settings.clone()).await
    }
}

/// Guesser that extracts metadata from environment variables
pub struct EnvironmentGuesser;

impl EnvironmentGuesser {
    /// Creates a new EnvironmentGuesser
    pub fn new() -> Self {
        Self
    }
}

impl Default for EnvironmentGuesser {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl Guesser for EnvironmentGuesser {
    fn name(&self) -> &str {
        "environment"
    }

    async fn guess(
        &mut self,
        _settings: &GuesserSettings,
    ) -> Result<Vec<UpstreamDatumWithMetadata>, ProviderError> {
        crate::guess_from_environment()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_upstream_metadata() {
        let mut data = UpstreamMetadata::new();
        assert_eq!(data.len(), 0);

        data.insert(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Homepage("https://example.com".to_string()),
            certainty: Some(Certainty::Certain),
            origin: None,
        });

        assert_eq!(data.len(), 1);
        assert_eq!(
            data.get("Homepage").unwrap().datum.as_str().unwrap(),
            "https://example.com"
        );

        assert_eq!(data.homepage(), Some("https://example.com"));
    }

    #[tokio::test]
    async fn test_bug_database_url_from_bug_submit_url() {
        let url = Url::parse("https://bugs.launchpad.net/bugs/+filebug").unwrap();
        assert_eq!(
            bug_database_url_from_bug_submit_url(&url, None)
                .await
                .unwrap(),
            Url::parse("https://bugs.launchpad.net/bugs").unwrap()
        );

        let url = Url::parse("https://github.com/dulwich/dulwich/issues/new").unwrap();

        assert_eq!(
            bug_database_url_from_bug_submit_url(&url, None)
                .await
                .unwrap(),
            Url::parse("https://github.com/dulwich/dulwich/issues").unwrap()
        );

        let url = Url::parse("https://sourceforge.net/p/dulwich/bugs/new").unwrap();

        assert_eq!(
            bug_database_url_from_bug_submit_url(&url, None)
                .await
                .unwrap(),
            Url::parse("https://sourceforge.net/p/dulwich/bugs").unwrap()
        );
    }

    #[test]
    fn test_person_from_str() {
        assert_eq!(
            Person::from("Foo Bar <foo@example.com>"),
            Person {
                name: Some("Foo Bar".to_string()),
                email: Some("foo@example.com".to_string()),
                url: None
            }
        );
        assert_eq!(
            Person::from("Foo Bar"),
            Person {
                name: Some("Foo Bar".to_string()),
                email: None,
                url: None
            }
        );
        assert_eq!(
            Person::from("foo@example.com"),
            Person {
                name: None,
                email: Some("foo@example.com".to_string()),
                url: None
            }
        );
        // Test person with just email (no name) - parseaddr returns empty name
        assert_eq!(
            Person::from("<foo@example.com>"),
            Person {
                name: Some("".to_string()),
                email: Some("foo@example.com".to_string()),
                url: None
            }
        );
    }

    #[test]
    fn test_upstream_metadata_accessors() {
        let mut metadata = UpstreamMetadata::default();

        // Test empty metadata
        assert_eq!(metadata.version(), None);
        assert_eq!(metadata.description(), None);
        assert_eq!(metadata.wiki(), None);
        assert_eq!(metadata.download(), None);
        assert_eq!(metadata.security_contact(), None);
        assert_eq!(metadata.donation(), None);
        assert_eq!(metadata.cite_as(), None);
        assert_eq!(metadata.webservice(), None);
        assert_eq!(metadata.copyright(), None);
        assert_eq!(metadata.sourceforge_project(), None);
        assert_eq!(metadata.pecl_package(), None);

        // Add some data and test again
        metadata.insert(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Version("1.0.0".to_string()),
            certainty: Some(Certainty::Certain),
            origin: None,
        });
        assert_eq!(metadata.version(), Some("1.0.0"));

        metadata.insert(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Description("Test description".to_string()),
            certainty: Some(Certainty::Certain),
            origin: None,
        });
        assert_eq!(metadata.description(), Some("Test description"));
    }

    #[test]
    fn test_upstream_metadata_iterators() {
        let mut metadata = UpstreamMetadata::default();

        // Test empty iterator
        assert_eq!(metadata.iter().count(), 0);
        assert_eq!(metadata.mut_iter().count(), 0);

        // Add data and test again
        metadata.insert(UpstreamDatumWithMetadata {
            datum: UpstreamDatum::Name("test".to_string()),
            certainty: Some(Certainty::Certain),
            origin: None,
        });

        assert_eq!(metadata.iter().count(), 1);
        assert_eq!(metadata.mut_iter().count(), 1);
    }

    #[test]
    fn test_extract_pecl_package_name() {
        use super::extract_pecl_package_name;

        assert_eq!(
            extract_pecl_package_name("https://pecl.php.net/package/redis"),
            Some("redis".to_string())
        );
        assert_eq!(
            extract_pecl_package_name("https://pecl.php.net/package/xdebug/2.9.0"),
            Some("xdebug/2.9.0".to_string())
        );
        assert_eq!(
            extract_pecl_package_name("https://example.com/something"),
            None
        );
    }

    #[test]
    fn test_forge_names() {
        let github = GitHub;
        assert_eq!(github.name(), "GitHub");

        let gitlab = GitLab;
        assert_eq!(gitlab.name(), "GitLab");

        let sourceforge = SourceForge;
        assert_eq!(sourceforge.name(), "SourceForge");

        let launchpad = Launchpad;
        assert_eq!(launchpad.name(), "launchpad");
    }
}