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
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Bound;
use indexmap::IndexSet;
use itertools::Itertools;
use owo_colors::OwoColorize;
use pubgrub::{DerivationTree, Derived, External, Map, Range, ReportFormatter, Term};
use rustc_hash::FxHashMap;
use uv_configuration::{IndexStrategy, NoBinary, NoBuild};
use uv_distribution_types::{
IncompatibleDist, IncompatibleSource, IncompatibleWheel, Index, IndexCapabilities,
IndexLocations, IndexMetadata, IndexUrl, RequiresPython,
};
use uv_normalize::PackageName;
use uv_pep440::{Version, VersionSpecifier, VersionSpecifiers};
use uv_pep508::{MarkerEnvironment, MarkerExpression, MarkerTree, MarkerValueVersion};
use uv_platform_tags::{AbiTag, IncompatibleTag, LanguageTag, PlatformTag, Tags};
use crate::candidate_selector::CandidateSelector;
use crate::error::{ErrorTree, PrefixMatch};
use crate::exclude_newer::EffectiveExcludeNewerSource;
use crate::fork_indexes::ForkIndexes;
use crate::fork_urls::ForkUrls;
use crate::prerelease::AllowPrerelease;
use crate::pubgrub::{PubGrubPackage, PubGrubPackageInner, PubGrubPython};
use crate::python_requirement::{PythonRequirement, PythonRequirementSource};
use crate::resolver::{
MetadataUnavailable, UnavailableErrorChain, UnavailablePackage, UnavailableReason,
UnavailableVersion,
};
use crate::{
ExcludeNewerValue, Flexibility, InMemoryIndex, Options, ResolverEnvironment, VersionsResponse,
};
#[derive(Debug)]
pub(crate) struct PubGrubReportFormatter<'a> {
/// See [`crate::error::NoSolutionError::included_versions`].
pub(crate) included_versions: &'a FxHashMap<PackageName, BTreeSet<Version>>,
/// See [`crate::error::NoSolutionError::available_versions`].
pub(crate) available_versions: &'a FxHashMap<PackageName, BTreeSet<Version>>,
/// The Python requirement for the resolution.
pub(crate) python_requirement: &'a PythonRequirement,
/// The members of the workspace.
pub(crate) workspace_members: &'a BTreeSet<PackageName>,
/// The compatible tags for the resolution.
pub(crate) tags: Option<&'a Tags>,
}
impl ReportFormatter<PubGrubPackage, Range<Version>, UnavailableReason>
for PubGrubReportFormatter<'_>
{
type Output = String;
fn format_external(
&self,
external: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
) -> Self::Output {
match external {
External::NotRoot(package, version) => {
format!("we are solving dependencies of {package} {version}")
}
External::NoVersions(package, set) => {
if matches!(
&**package,
PubGrubPackageInner::Python(PubGrubPython::Target)
) {
let target = self.python_requirement.target();
return format!(
"the requested {package} version ({target}) does not satisfy {}",
self.compatible_range(package, set)
);
}
if matches!(
&**package,
PubGrubPackageInner::Python(PubGrubPython::Installed)
) {
let installed = self.python_requirement.exact();
return format!(
"the current {package} version ({installed}) does not satisfy {}",
self.compatible_range(package, set)
);
}
if set == &Range::full() {
format!("there are no versions of {package}")
} else if set.as_singleton().is_some() {
format!("there is no version of {package}{set}")
} else {
let complement = set.complement();
let range =
// Note that sometimes we do not have a range of included versions, e.g.,
// when a package is from a non-registry source. In that case, we cannot
// perform further simplification of the range.
if let Some(included_versions) = package.name().and_then(|name| self.included_versions.get(name)) {
update_availability_range(&complement, included_versions)
} else {
complement
};
if range.is_empty() {
return format!("there are no versions of {package}");
}
if range.iter().count() == 1 {
format!(
"only {} is available",
self.availability_range(package, &range)
)
} else {
format!(
"only the following versions of {} {}",
package,
self.availability_range(package, &range)
)
}
}
}
External::Custom(package, set, reason) => {
if let Some(root) = self.format_root(package) {
format!("{root} cannot be used because {reason}")
} else {
match reason {
UnavailableReason::Package(reason) => {
let message = reason.singular_message();
format!("{}{}", package, Padded::new(" ", &message, ""))
}
UnavailableReason::Version(reason) => {
let range = self.compatible_range(package, set);
let message = if range.plural() {
reason.plural_message()
} else {
reason.singular_message()
};
let context = reason.context_message(
self.tags,
self.python_requirement.target().abi_tag(),
);
if let Some(context) = context {
format!("{}{}{}", range, Padded::new(" ", &message, " "), context)
} else {
format!("{}{}", range, Padded::new(" ", &message, ""))
}
}
}
}
}
External::FromDependencyOf(package, package_set, dependency, dependency_set) => {
if package.name_no_root() == dependency.name_no_root() {
if let Some(member) = self.format_workspace_member(package) {
return format!(
"{member} depends on itself at an incompatible version ({})",
PackageRange::dependency(dependency, dependency_set, None)
);
}
}
if let Some(root) = self.format_root_requires(package) {
return format!(
"{root} {}",
self.dependency_range(dependency, dependency_set)
);
}
format!(
"{}",
self.compatible_range(package, package_set)
.depends_on(dependency, dependency_set),
)
}
}
}
/// Try to print terms of an incompatibility in a human-readable way.
fn format_terms(&self, terms: &Map<PubGrubPackage, Term<Range<Version>>>) -> String {
let mut terms_vec: Vec<_> = terms.iter().collect();
// We avoid relying on hashmap iteration order here by always sorting
// by package first.
terms_vec.sort_by(|&(pkg1, _), &(pkg2, _)| pkg1.cmp(pkg2));
match terms_vec.as_slice() {
[] => "the requirements are unsatisfiable".into(),
[(root, _)] if matches!(&**(*root), PubGrubPackageInner::Root(_)) => {
let root = self.format_root(root).unwrap();
format!("{root} are unsatisfiable")
}
[(package, Term::Positive(range))]
if matches!(&**(*package), PubGrubPackageInner::Package { .. }) =>
{
if let Some(member) = self.format_workspace_member(package) {
format!("{member}'s requirements are unsatisfiable")
} else {
format!("{} cannot be used", self.compatible_range(package, range))
}
}
[(package, Term::Negative(range))]
if matches!(&**(*package), PubGrubPackageInner::Package { .. }) =>
{
format!("{} must be used", self.compatible_range(package, range))
}
[(p1, Term::Positive(r1)), (p2, Term::Negative(r2))] => self.format_external(
&External::FromDependencyOf((*p1).clone(), r1.clone(), (*p2).clone(), r2.clone()),
),
[(p1, Term::Negative(r1)), (p2, Term::Positive(r2))] => self.format_external(
&External::FromDependencyOf((*p2).clone(), r2.clone(), (*p1).clone(), r1.clone()),
),
slice => {
let mut result = String::new();
let str_terms: Vec<_> = slice
.iter()
.map(|(p, t)| format!("{}", PackageTerm::new(p, t, self)))
.collect();
for (index, term) in str_terms.iter().enumerate() {
result.push_str(term);
match str_terms.len().cmp(&2) {
Ordering::Equal if index == 0 => {
result.push_str(" and ");
}
Ordering::Greater if index + 1 < str_terms.len() => {
result.push_str(", ");
}
_ => (),
}
}
if slice.len() == 1 {
result.push_str(" cannot be used");
} else {
result.push_str(" are incompatible");
}
result
}
}
}
/// Simplest case, we just combine two external incompatibilities.
fn explain_both_external(
&self,
external1: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
external2: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
let external = self.format_both_external(external1, external2);
let terms = self.format_terms(current_terms);
format!(
"Because {}we can conclude that {}",
Padded::from_string("", &external, ", "),
Padded::from_string("", &terms, "."),
)
}
/// Both causes have already been explained so we use their refs.
fn explain_both_ref(
&self,
ref_id1: usize,
derived1: &Derived<PubGrubPackage, Range<Version>, UnavailableReason>,
ref_id2: usize,
derived2: &Derived<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
// TODO: order should be chosen to make it more logical.
let derived1_terms = self.format_terms(&derived1.terms);
let derived2_terms = self.format_terms(&derived2.terms);
let current_terms = self.format_terms(current_terms);
format!(
"Because we know from ({}) that {}and we know from ({}) that {}{}",
ref_id1,
Padded::new("", &derived1_terms, " "),
ref_id2,
Padded::new("", &derived2_terms, ", "),
Padded::new("", ¤t_terms, "."),
)
}
/// One cause is derived (already explained so one-line),
/// the other is a one-line external cause,
/// and finally we conclude with the current incompatibility.
fn explain_ref_and_external(
&self,
ref_id: usize,
derived: &Derived<PubGrubPackage, Range<Version>, UnavailableReason>,
external: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
// TODO: order should be chosen to make it more logical.
let derived_terms = self.format_terms(&derived.terms);
let external = self.format_external(external);
let current_terms = self.format_terms(current_terms);
format!(
"Because we know from ({}) that {}and {}we can conclude that {}",
ref_id,
Padded::new("", &derived_terms, " "),
Padded::new("", &external, ", "),
Padded::new("", ¤t_terms, "."),
)
}
/// Add an external cause to the chain of explanations.
fn and_explain_external(
&self,
external: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
let external = self.format_external(external);
let terms = self.format_terms(current_terms);
format!(
"And because {}we can conclude that {}",
Padded::from_string("", &external, ", "),
Padded::from_string("", &terms, "."),
)
}
/// Add an already explained incompat to the chain of explanations.
fn and_explain_ref(
&self,
ref_id: usize,
derived: &Derived<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
let derived = self.format_terms(&derived.terms);
let current = self.format_terms(current_terms);
format!(
"And because we know from ({}) that {}we can conclude that {}",
ref_id,
Padded::from_string("", &derived, ", "),
Padded::from_string("", ¤t, "."),
)
}
/// Add an already explained incompat to the chain of explanations.
fn and_explain_prior_and_external(
&self,
prior_external: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
external: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
current_terms: &Map<PubGrubPackage, Term<Range<Version>>>,
) -> String {
let external = self.format_both_external(prior_external, external);
let terms = self.format_terms(current_terms);
format!(
"And because {}we can conclude that {}",
Padded::from_string("", &external, ", "),
Padded::from_string("", &terms, "."),
)
}
}
impl PubGrubReportFormatter<'_> {
/// Return the formatting for "the root package requires", if the given
/// package is the root package.
///
/// If not given the root package, returns `None`.
fn format_root_requires(&self, package: &PubGrubPackage) -> Option<String> {
if self.is_workspace() {
if matches!(&**package, PubGrubPackageInner::Root(_)) {
if self.is_single_project_workspace() {
return Some("your project requires".to_string());
}
return Some("your workspace requires".to_string());
}
}
match &**package {
PubGrubPackageInner::Root(Some(name)) => Some(format!("{name} depends on")),
PubGrubPackageInner::Root(None) => Some("you require".to_string()),
_ => None,
}
}
/// Return the formatting for "the root package", if the given
/// package is the root package.
///
/// If not given the root package, returns `None`.
fn format_root(&self, package: &PubGrubPackage) -> Option<String> {
if self.is_workspace() {
if matches!(&**package, PubGrubPackageInner::Root(_)) {
if self.is_single_project_workspace() {
return Some("your project's requirements".to_string());
}
return Some("your workspace's requirements".to_string());
}
}
match &**package {
PubGrubPackageInner::Root(Some(_)) => Some("your requirements".to_string()),
PubGrubPackageInner::Root(None) => Some("your requirements".to_string()),
_ => None,
}
}
/// Whether the resolution error is for a workspace.
fn is_workspace(&self) -> bool {
!self.workspace_members.is_empty()
}
/// Whether the resolution error is for a workspace with a exactly one project.
fn is_single_project_workspace(&self) -> bool {
self.workspace_members.len() == 1
}
/// Return a display name for the package if it is a workspace member.
fn format_workspace_member(&self, package: &PubGrubPackage) -> Option<String> {
match &**package {
// TODO(zanieb): Improve handling of dev and extra for single-project workspaces
PubGrubPackageInner::Package {
name, extra, group, ..
} if self.workspace_members.contains(name) => {
if self.is_single_project_workspace() && extra.is_none() && group.is_none() {
Some("your project".to_string())
} else {
Some(format!("{package}"))
}
}
PubGrubPackageInner::Extra { name, .. } if self.workspace_members.contains(name) => {
Some(format!("{package}"))
}
PubGrubPackageInner::Group { name, .. } if self.workspace_members.contains(name) => {
Some(format!("{package}"))
}
_ => None,
}
}
/// Return whether the given package is the root package.
fn is_root(package: &PubGrubPackage) -> bool {
matches!(&**package, PubGrubPackageInner::Root(_))
}
/// Return whether the given package is a workspace member.
fn is_single_project_workspace_member(&self, package: &PubGrubPackage) -> bool {
match &**package {
// TODO(zanieb): Improve handling of dev and extra for single-project workspaces
PubGrubPackageInner::Package {
name, extra, group, ..
} if self.workspace_members.contains(name) => {
self.is_single_project_workspace() && extra.is_none() && group.is_none()
}
_ => false,
}
}
/// Create a [`PackageRange::compatibility`] display with this formatter attached.
fn compatible_range<'a>(
&'a self,
package: &'a PubGrubPackage,
range: &'a Range<Version>,
) -> PackageRange<'a> {
PackageRange::compatibility(package, range, Some(self))
}
/// Create a [`PackageRange::dependency`] display with this formatter attached.
fn dependency_range<'a>(
&'a self,
package: &'a PubGrubPackage,
range: &'a Range<Version>,
) -> PackageRange<'a> {
PackageRange::dependency(package, range, Some(self))
}
/// Create a [`PackageRange::availability`] display with this formatter attached.
fn availability_range<'a>(
&'a self,
package: &'a PubGrubPackage,
range: &'a Range<Version>,
) -> PackageRange<'a> {
PackageRange::availability(package, range, Some(self))
}
/// Format two external incompatibilities, combining them if possible.
fn format_both_external(
&self,
external1: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
external2: &External<PubGrubPackage, Range<Version>, UnavailableReason>,
) -> String {
match (external1, external2) {
(
External::FromDependencyOf(package1, package_set1, dependency1, dependency_set1),
External::FromDependencyOf(package2, _, dependency2, dependency_set2),
) if package1 == package2 => {
let dependency1 = self.dependency_range(dependency1, dependency_set1);
let dependency2 = self.dependency_range(dependency2, dependency_set2);
if let Some(root) = self.format_root_requires(package1) {
return format!(
"{root} {}and {}",
Padded::new("", &dependency1, " "),
dependency2,
);
}
format!(
"{}",
self.compatible_range(package1, package_set1)
.depends_on(dependency1.package, dependency_set1)
.and(dependency2.package, dependency_set2),
)
}
(.., External::FromDependencyOf(package, _, dependency, _))
if Self::is_root(package)
&& self.is_single_project_workspace_member(dependency) =>
{
self.format_external(external1)
}
(External::FromDependencyOf(package, _, dependency, _), ..)
if Self::is_root(package)
&& self.is_single_project_workspace_member(dependency) =>
{
self.format_external(external2)
}
_ => {
let external1 = self.format_external(external1);
let external2 = self.format_external(external2);
format!(
"{}and {}",
Padded::from_string("", &external1, " "),
&external2,
)
}
}
}
/// Generate the [`PubGrubHints`] for a derivation tree.
///
/// The [`PubGrubHints`] help users resolve errors by providing additional context or modifying
/// their requirements.
pub(crate) fn generate_hints(
&self,
derivation_tree: &ErrorTree,
index: &InMemoryIndex,
selector: &CandidateSelector,
index_locations: &IndexLocations,
index_capabilities: &IndexCapabilities,
available_indexes: &FxHashMap<PackageName, BTreeSet<IndexUrl>>,
unavailable_packages: &FxHashMap<PackageName, UnavailablePackage>,
incomplete_packages: &FxHashMap<PackageName, BTreeMap<Version, MetadataUnavailable>>,
fork_urls: &ForkUrls,
fork_indexes: &ForkIndexes,
env: &ResolverEnvironment,
current_environment: &MarkerEnvironment,
tags: Option<&Tags>,
workspace_members: &BTreeSet<PackageName>,
options: &Options,
inherited_exclude_newer_ranges: &FxHashMap<PackageName, Range<Version>>,
output_hints: &mut IndexSet<PubGrubHint>,
) {
// Check for disjoint target hints (only applicable to universal resolution).
if let Some(markers) = env.fork_markers() {
// TODO(konsti): This is a crude approximation to telling the user the difference
// between their Python version and the relevant Python version range from the marker.
let current_python_version = current_environment.python_version().version.clone();
let current_python_marker = MarkerTree::expression(MarkerExpression::Version {
key: MarkerValueVersion::PythonVersion,
specifier: VersionSpecifier::equals_version(current_python_version.clone()),
});
if markers.is_disjoint(current_python_marker) {
output_hints.insert(PubGrubHint::DisjointPythonVersion {
python_version: current_python_version,
});
} else if !markers.evaluate(current_environment, &[]) {
output_hints.insert(PubGrubHint::DisjointEnvironment);
}
}
match derivation_tree {
DerivationTree::External(External::Custom(package, set, reason)) => {
if let Some(name) = package.name_no_root() {
// Check for no versions due to pre-release options.
if !fork_urls.contains_key(name) {
self.prerelease_hint(name, set, selector, env, options, output_hints);
}
// Check for no versions due to no `--find-links` flat index.
Self::index_hints(
name,
set,
selector,
index_locations,
index_capabilities,
available_indexes,
unavailable_packages,
incomplete_packages,
output_hints,
);
if let UnavailableReason::Version(UnavailableVersion::IncompatibleDist(
incompatibility,
)) = reason
{
match incompatibility {
// Check for unavailable versions due to `--no-build` or `--no-binary`.
IncompatibleDist::Wheel(IncompatibleWheel::NoBinary) => {
output_hints.insert(PubGrubHint::NoBinary {
package: name.clone(),
option: options.build_options.no_binary().clone(),
});
}
IncompatibleDist::Source(IncompatibleSource::NoBuild) => {
output_hints.insert(PubGrubHint::NoBuild {
package: name.clone(),
option: options.build_options.no_build().clone(),
});
}
// Check for unavailable versions due to incompatible tags.
IncompatibleDist::Wheel(IncompatibleWheel::Tag(tag)) => {
if let Some(hint) = self.tag_hint(
name,
set,
*tag,
index,
selector,
fork_indexes,
env,
tags,
) {
output_hints.insert(hint);
}
}
_ => {}
}
}
}
}
DerivationTree::External(External::NoVersions(package, set)) => {
if let Some(name) = package.name_no_root() {
// Check for no versions due to pre-release options.
if !fork_urls.contains_key(name) {
self.prerelease_hint(name, set, selector, env, options, output_hints);
}
// Check for no versions due to no `--find-links` flat index.
Self::index_hints(
name,
set,
selector,
index_locations,
index_capabilities,
available_indexes,
unavailable_packages,
incomplete_packages,
output_hints,
);
let exclude_newer = if let Some(index) = fork_indexes.get(name) {
options
.exclude_newer
.exclude_newer_package_for_index_with_source(
name,
index_locations.exclude_newer_for(index.url()),
)
} else {
options
.exclude_newer
.exclude_newer_package(name)
.map(|exclude_newer| {
let source = if options.exclude_newer.package.contains_key(name) {
EffectiveExcludeNewerSource::Package
} else {
EffectiveExcludeNewerSource::Global
};
(exclude_newer, source)
})
};
if let Some((exclude_newer, source)) = exclude_newer {
// Check if there are no included versions in the requested
// range, but there are still available versions in that range
// (i.e., they were filtered out by `exclude-newer`).
let no_included_in_set = self
.included_versions
.get(name)
.is_none_or(|versions| !versions.iter().any(|v| set.contains(v)));
let available_has_versions_in_set = self
.available_versions
.get(name)
.is_some_and(|versions| versions.iter().any(|v| set.contains(v)));
if no_included_in_set && available_has_versions_in_set {
let version_hint_set =
inherited_exclude_newer_ranges.get(name).map_or_else(
|| set.clone(),
|exclude_newer_range| set.union(exclude_newer_range),
);
let matching_version = self.exclude_newer_version_hint(
name,
&version_hint_set,
index,
fork_indexes,
);
output_hints.insert(PubGrubHint::ExcludeNewer {
package: name.clone(),
source,
exclude_newer,
matching_version,
});
}
}
}
}
DerivationTree::External(External::FromDependencyOf(
package,
package_set,
dependency,
dependency_set,
)) => {
// Check for a dependency on a workspace package by a non-workspace package.
// Generally, this indicates that the workspace package is shadowing a transitive
// dependency name.
if let (Some(package_name), Some(dependency_name)) =
(package.name(), dependency.name())
{
if workspace_members.contains(dependency_name)
&& !workspace_members.contains(package_name)
{
output_hints.insert(PubGrubHint::DependsOnWorkspacePackage {
package: package_name.clone(),
dependency: dependency_name.clone(),
workspace: self.is_workspace() && !self.is_single_project_workspace(),
});
}
if package_name == dependency_name
&& (dependency.extra().is_none() || package.extra() == dependency.extra())
&& (dependency.group().is_none() || dependency.group() == package.group())
&& workspace_members.contains(package_name)
{
output_hints.insert(PubGrubHint::DependsOnItself {
package: package_name.clone(),
workspace: self.is_workspace() && !self.is_single_project_workspace(),
});
}
}
// Check for no versions due to `Requires-Python`.
if matches!(
&**dependency,
PubGrubPackageInner::Python(PubGrubPython::Target)
) {
if let Some(name) = package.name() {
output_hints.insert(PubGrubHint::RequiresPython {
source: self.python_requirement.source(),
requires_python: self.python_requirement.target().clone(),
name: name.clone(),
package_set: package_set.clone(),
package_requires_python: dependency_set.clone(),
});
}
}
}
DerivationTree::External(External::NotRoot(..)) => {}
DerivationTree::Derived(derived) => {
let cause1_exclude_newer_ranges =
Self::subtree_exclude_newer_ranges(&derived.cause1);
let cause2_exclude_newer_ranges =
Self::subtree_exclude_newer_ranges(&derived.cause2);
let mut cause1_inherited_exclude_newer_ranges =
inherited_exclude_newer_ranges.clone();
for (name, range) in &cause2_exclude_newer_ranges {
cause1_inherited_exclude_newer_ranges
.entry(name.clone())
.and_modify(|existing| *existing = existing.union(range))
.or_insert_with(|| range.clone());
}
let mut cause2_inherited_exclude_newer_ranges =
inherited_exclude_newer_ranges.clone();
for (name, range) in &cause1_exclude_newer_ranges {
cause2_inherited_exclude_newer_ranges
.entry(name.clone())
.and_modify(|existing| *existing = existing.union(range))
.or_insert_with(|| range.clone());
}
self.generate_hints(
&derived.cause1,
index,
selector,
index_locations,
index_capabilities,
available_indexes,
unavailable_packages,
incomplete_packages,
fork_urls,
fork_indexes,
env,
current_environment,
tags,
workspace_members,
options,
&cause1_inherited_exclude_newer_ranges,
output_hints,
);
self.generate_hints(
&derived.cause2,
index,
selector,
index_locations,
index_capabilities,
available_indexes,
unavailable_packages,
incomplete_packages,
fork_urls,
fork_indexes,
env,
current_environment,
tags,
workspace_members,
options,
&cause2_inherited_exclude_newer_ranges,
output_hints,
);
}
}
}
/// Collect the version ranges in `derivation_tree` that were excluded solely by
/// `exclude-newer`, grouped by package name.
fn subtree_exclude_newer_ranges(
derivation_tree: &ErrorTree,
) -> FxHashMap<PackageName, Range<Version>> {
fn collect(
derivation_tree: &ErrorTree,
exclude_newer_ranges: &mut FxHashMap<PackageName, Range<Version>>,
) {
match derivation_tree {
DerivationTree::External(External::Custom(package, versions, reason)) => {
if matches!(
reason,
UnavailableReason::Version(UnavailableVersion::IncompatibleDist(
IncompatibleDist::Wheel(IncompatibleWheel::ExcludeNewer(_))
| IncompatibleDist::Source(IncompatibleSource::ExcludeNewer(_))
))
) {
if let Some(name) = package.name() {
exclude_newer_ranges
.entry(name.clone())
.and_modify(|set| *set = set.union(versions))
.or_insert_with(|| versions.clone());
}
}
}
DerivationTree::External(_) => {}
DerivationTree::Derived(derived) => {
collect(&derived.cause1, exclude_newer_ranges);
collect(&derived.cause2, exclude_newer_ranges);
}
}
}
let mut exclude_newer_ranges = FxHashMap::default();
collect(derivation_tree, &mut exclude_newer_ranges);
exclude_newer_ranges
}
/// Return the latest version in `set` that is available for resolver error reporting,
/// along with the earliest known publish date for that version.
fn exclude_newer_version_hint(
&self,
name: &PackageName,
set: &Range<Version>,
index: &InMemoryIndex,
fork_indexes: &ForkIndexes,
) -> Option<ExcludeNewerVersionDetail> {
let version = self.available_versions.get(name).and_then(|versions| {
versions
.iter()
.rfind(|version| set.contains(version))
.cloned()
})?;
let response = if let Some(url) = fork_indexes.get(name).map(IndexMetadata::url) {
index.explicit().get(&(name.clone(), url.clone()))
} else {
index.implicit().get(name)
}?;
let VersionsResponse::Found(version_maps) = &*response else {
return None;
};
let publish_date = version_maps
.iter()
.filter_map(|version_map| {
version_map.get(&version).and_then(|prioritized| {
prioritized
.files()
.filter_map(|file| file.upload_time_utc_ms)
.min()
})
})
.min()
.and_then(|upload_time| {
Some(
jiff::Timestamp::from_millisecond(upload_time)
.ok()?
.to_string(),
)
});
Some(ExcludeNewerVersionDetail {
version,
publish_date,
singleton: set.as_singleton().is_some(),
})
}
/// Generate a [`PubGrubHint`] for a package that doesn't have any wheels matching the current
/// Python version, ABI, or platform.
fn tag_hint(
&self,
name: &PackageName,
set: &Range<Version>,
tag: IncompatibleTag,
index: &InMemoryIndex,
selector: &CandidateSelector,
fork_indexes: &ForkIndexes,
env: &ResolverEnvironment,
tags: Option<&Tags>,
) -> Option<PubGrubHint> {
let response = if let Some(url) = fork_indexes.get(name).map(IndexMetadata::url) {
index.explicit().get(&(name.clone(), url.clone()))
} else {
index.implicit().get(name)
}?;
let VersionsResponse::Found(version_maps) = &*response else {
return None;
};
let candidate = selector.select_no_preference(name, set, version_maps, env)?;
let prioritized = candidate.prioritized()?;
match tag {
IncompatibleTag::Invalid => None,
IncompatibleTag::Python => {
let best = tags.and_then(Tags::python_tag);
let tags = prioritized.python_tags().collect::<BTreeSet<_>>();
if tags.is_empty() {
None
} else {
Some(PubGrubHint::LanguageTags {
package: name.clone(),
version: candidate.version().clone(),
tags,
best,
})
}
}
IncompatibleTag::Abi
| IncompatibleTag::FreethreadedAbi
| IncompatibleTag::AbiPythonVersion => {
let best = tags.and_then(Tags::abi_tag);
let tags = prioritized
.abi_tags()
// Ignore `none`, which is universally compatible.
//
// As an example, `none` can appear here if we're solving for Python 3.13, and
// the distribution includes a wheel for `cp312-none-macosx_11_0_arm64`.
//
// In that case, the wheel isn't compatible, but when solving for Python 3.13,
// the `cp312` Python tag _can_ be compatible (e.g., for `cp312-abi3-macosx_11_0_arm64.whl`),
// so this is considered an ABI incompatibility rather than Python incompatibility.
.filter(|tag| *tag != AbiTag::None)
.collect::<BTreeSet<_>>();
if tags.is_empty() {
None
} else {
Some(PubGrubHint::AbiTags {
package: name.clone(),
version: candidate.version().clone(),
tags,
best,
})
}
}
IncompatibleTag::Platform => {
// We don't want to report all available platforms, since it's plausible that there
// are wheels for the current platform, but at a different ABI. For example, when
// solving for Python 3.13 on macOS, `cp312-cp312-macosx_11_0_arm64` could be
// available along with `cp313-cp313-manylinux2014`. In this case, we'd consider
// the distribution to be platform-incompatible, since `cp313-cp313` matches the
// compatible wheel tags. But showing `macosx_11_0_arm64` here would be misleading.
//
// So, instead, we only show the platforms that are linked to otherwise-compatible
// wheels (e.g., `manylinux2014` in `cp313-cp313-manylinux2014`). In other words,
// we only show platforms for ABI-compatible wheels.
let tags = prioritized
.platform_tags(self.tags?)
.cloned()
.collect::<BTreeSet<_>>();
if tags.is_empty() {
None
} else {
Some(PubGrubHint::PlatformTags {
package: name.clone(),
version: candidate.version().clone(),
tags,
})
}
}
}
}
fn index_hints(
name: &PackageName,
set: &Range<Version>,
selector: &CandidateSelector,
index_locations: &IndexLocations,
index_capabilities: &IndexCapabilities,
available_indexes: &FxHashMap<PackageName, BTreeSet<IndexUrl>>,
unavailable_packages: &FxHashMap<PackageName, UnavailablePackage>,
incomplete_packages: &FxHashMap<PackageName, BTreeMap<Version, MetadataUnavailable>>,
hints: &mut IndexSet<PubGrubHint>,
) {
let no_find_links = index_locations.flat_indexes().peekable().peek().is_none();
// Add hints due to the package being entirely unavailable.
match unavailable_packages.get(name) {
Some(UnavailablePackage::NoIndex) => {
if no_find_links {
hints.insert(PubGrubHint::NoIndex);
}
}
Some(UnavailablePackage::Offline) => {
hints.insert(PubGrubHint::Offline);
}
Some(UnavailablePackage::InvalidMetadata(reason)) => {
hints.insert(PubGrubHint::InvalidPackageMetadata {
package: name.clone(),
reason: reason.clone(),
});
}
Some(UnavailablePackage::InvalidStructure(reason)) => {
hints.insert(PubGrubHint::InvalidPackageStructure {
package: name.clone(),
reason: reason.clone(),
});
}
Some(UnavailablePackage::NotFound) => {}
None => {}
}
// Add hints due to the package being unavailable at specific versions.
if let Some(versions) = incomplete_packages.get(name) {
for (version, incomplete) in versions.iter().rev() {
if set.contains(version) {
match incomplete {
MetadataUnavailable::Offline => {
hints.insert(PubGrubHint::Offline);
}
MetadataUnavailable::InvalidMetadata(reason) => {
hints.insert(PubGrubHint::InvalidVersionMetadata {
package: name.clone(),
version: version.clone(),
reason: reason.to_string(),
});
}
MetadataUnavailable::InconsistentMetadata(reason) => {
hints.insert(PubGrubHint::InconsistentVersionMetadata {
package: name.clone(),
version: version.clone(),
reason: reason.to_string(),
});
}
MetadataUnavailable::InvalidStructure(reason) => {
hints.insert(PubGrubHint::InvalidVersionStructure {
package: name.clone(),
version: version.clone(),
reason: reason.to_string(),
});
}
MetadataUnavailable::RequiresPython(requires_python, python_version) => {
hints.insert(PubGrubHint::IncompatibleBuildRequirement {
package: name.clone(),
version: version.clone(),
requires_python: requires_python.clone(),
python_version: python_version.clone(),
});
}
}
break;
}
}
}
// Add hints due to the package being available on an index, but not at the correct version,
// with subsequent indexes that were _not_ queried.
if matches!(selector.index_strategy(), IndexStrategy::FirstIndex) {
// Do not include the hint if the set is "all versions". This is an unusual but valid
// case in which a package returns a 200 response, but without any versions or
// distributions for the package.
if !set
.iter()
.all(|range| matches!(range, (Bound::Unbounded, Bound::Unbounded)))
{
if let Some(found_index) = available_indexes.get(name).and_then(BTreeSet::first) {
// Determine whether the index is the last-available index. If not, then some
// indexes were not queried, and could contain a compatible version.
if let Some(next_index) = index_locations
.indexes()
.map(Index::url)
.skip_while(|url| *url != found_index)
.nth(1)
{
hints.insert(PubGrubHint::UncheckedIndex {
name: name.clone(),
range: set.clone(),
found_index: found_index.clone(),
next_index: next_index.clone(),
});
}
}
}
}
// Add hints due to an index returning an unauthorized response.
for index in index_locations.allowed_indexes() {
if index_capabilities.unauthorized(&index.url) {
hints.insert(PubGrubHint::UnauthorizedIndex {
index: index.url.clone(),
});
}
if index_capabilities.forbidden(&index.url) {
hints.insert(PubGrubHint::ForbiddenIndex {
index: index.url.clone(),
});
}
}
}
fn prerelease_hint(
&self,
name: &PackageName,
set: &Range<Version>,
selector: &CandidateSelector,
env: &ResolverEnvironment,
options: &Options,
hints: &mut IndexSet<PubGrubHint>,
) {
if selector.prerelease_strategy().allows(name, env) == AllowPrerelease::Yes {
return;
}
let any_prerelease = set.iter().any(|(start, end)| {
// Ignore, e.g., `>=2.4.dev0,<2.5.dev0`, which is the desugared form of `==2.4.*`.
if PrefixMatch::from_range(start, end).is_some() {
return false;
}
let is_pre1 = match start {
Bound::Included(version) => version.any_prerelease(),
Bound::Excluded(version) => version.any_prerelease(),
Bound::Unbounded => false,
};
if is_pre1 {
return true;
}
let is_pre2 = match end {
Bound::Included(version) => version.any_prerelease(),
Bound::Excluded(version) => version.any_prerelease(),
Bound::Unbounded => false,
};
if is_pre2 {
return true;
}
false
});
if any_prerelease {
// A pre-release marker appeared in the version requirements.
match options.flexibility {
Flexibility::Configurable => {
hints.insert(PubGrubHint::PrereleaseRequested {
name: name.clone(),
range: set.clone(),
});
}
Flexibility::Fixed => {
hints.insert(PubGrubHint::BuildPrereleaseRequested {
name: name.clone(),
range: set.clone(),
});
}
}
} else if let Some(version) = self.included_versions.get(name).and_then(|versions| {
versions
.iter()
.rev()
.filter(|version| version.any_prerelease())
.find(|version| set.contains(version))
}) {
// There are pre-release versions available for the package.
match options.flexibility {
Flexibility::Configurable => {
hints.insert(PubGrubHint::PrereleaseAvailable {
package: name.clone(),
version: version.clone(),
});
}
Flexibility::Fixed => {
hints.insert(PubGrubHint::BuildPrereleaseAvailable {
package: name.clone(),
version: version.clone(),
});
}
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct ExcludeNewerVersionDetail {
version: Version,
publish_date: Option<String>,
singleton: bool,
}
#[derive(Debug, Clone)]
pub(crate) enum PubGrubHint {
/// There are pre-release versions available for a package, but pre-releases weren't enabled
/// for that package.
///
PrereleaseAvailable {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
},
/// The resolver runs with fixed options (e.g., for build environments) and requires explicit
/// pre-release opt-in for a package that only has pre-releases available.
BuildPrereleaseAvailable {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
},
/// A requirement included a pre-release marker, but pre-releases weren't enabled for that
/// package.
PrereleaseRequested {
name: PackageName,
// excluded from `PartialEq` and `Hash`
range: Range<Version>,
},
/// A requirement included a pre-release marker, but the resolver runs with fixed options
/// (e.g., for build environments) and cannot enable pre-releases automatically.
BuildPrereleaseRequested {
name: PackageName,
// excluded from `PartialEq` and `Hash`
range: Range<Version>,
},
/// Requirements were unavailable due to lookups in the index being disabled and no extra
/// index was provided via `--find-links`
NoIndex,
/// A package was not found in the registry, but network access was disabled.
Offline,
/// Metadata for a package could not be parsed.
InvalidPackageMetadata {
package: PackageName,
// excluded from `PartialEq` and `Hash`
reason: UnavailableErrorChain,
},
/// The structure of a package was invalid (e.g., multiple `.dist-info` directories).
InvalidPackageStructure {
package: PackageName,
// excluded from `PartialEq` and `Hash`
reason: UnavailableErrorChain,
},
/// Metadata for a package version could not be parsed.
InvalidVersionMetadata {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
reason: String,
},
/// Metadata for a package version was inconsistent (e.g., the package name did not match that
/// of the file).
InconsistentVersionMetadata {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
reason: String,
},
/// The structure of a package version was invalid (e.g., multiple `.dist-info` directories).
InvalidVersionStructure {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
reason: String,
},
/// The source distribution has a `requires-python` requirement that is not met by the installed
/// Python version (and static metadata is not available).
IncompatibleBuildRequirement {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
requires_python: VersionSpecifiers,
// excluded from `PartialEq` and `Hash`
python_version: Version,
},
/// The `Requires-Python` requirement was not satisfied.
RequiresPython {
source: PythonRequirementSource,
requires_python: RequiresPython,
// excluded from `PartialEq` and `Hash`
name: PackageName,
// excluded from `PartialEq` and `Hash`
package_set: Range<Version>,
// excluded from `PartialEq` and `Hash`
package_requires_python: Range<Version>,
},
/// A non-workspace package depends on a workspace package, which is likely shadowing a
/// transitive dependency.
DependsOnWorkspacePackage {
package: PackageName,
dependency: PackageName,
workspace: bool,
},
/// A package depends on itself at an incompatible version.
DependsOnItself {
package: PackageName,
workspace: bool,
},
/// A package was available on an index, but not at the correct version, and at least one
/// subsequent index was not queried. As such, a compatible version may be available on
/// one of the remaining indexes.
UncheckedIndex {
name: PackageName,
// excluded from `PartialEq` and `Hash`
range: Range<Version>,
// excluded from `PartialEq` and `Hash`
found_index: IndexUrl,
// excluded from `PartialEq` and `Hash`
next_index: IndexUrl,
},
/// No wheels are available for a package, and using source distributions was disabled.
NoBuild {
package: PackageName,
// excluded from `PartialEq` and `Hash`
option: NoBuild,
},
/// No source distributions are available for a package, and using pre-built wheels was disabled.
NoBinary {
package: PackageName,
// excluded from `PartialEq` and `Hash`
option: NoBinary,
},
/// An index returned an Unauthorized (401) response.
UnauthorizedIndex { index: IndexUrl },
/// An index returned a Forbidden (403) response.
ForbiddenIndex { index: IndexUrl },
/// None of the available wheels for a package have a compatible Python language tag (e.g.,
/// `cp310` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
LanguageTags {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
tags: BTreeSet<LanguageTag>,
// excluded from `PartialEq` and `Hash`
best: Option<LanguageTag>,
},
/// None of the available wheels for a package have a compatible ABI tag (e.g., `abi3` in
/// `cp310-abi3-manylinux_2_17_x86_64.whl`).
AbiTags {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
tags: BTreeSet<AbiTag>,
// excluded from `PartialEq` and `Hash`
best: Option<AbiTag>,
},
/// None of the available wheels for a package have a compatible platform tag (e.g.,
/// `manylinux_2_17_x86_64` in `cp310-abi3-manylinux_2_17_x86_64.whl`).
PlatformTags {
package: PackageName,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
tags: BTreeSet<PlatformTag>,
},
/// Versions of a package were excluded by `exclude-newer`.
ExcludeNewer {
package: PackageName,
source: EffectiveExcludeNewerSource,
// excluded from `PartialEq` and `Hash`
exclude_newer: ExcludeNewerValue,
// excluded from `PartialEq` and `Hash`
matching_version: Option<ExcludeNewerVersionDetail>,
},
/// The resolution failed for a Python version that is different from the current Python version.
DisjointPythonVersion {
// excluded from `PartialEq` and `Hash`
python_version: Version,
},
/// The resolution failed for an environment that is different from the current environment.
DisjointEnvironment,
}
/// This private enum mirrors [`PubGrubHint`] but only includes fields that should be
/// used for `Eq` and `Hash` implementations. It is used to derive `PartialEq` and
/// `Hash` implementations for [`PubGrubHint`].
#[derive(PartialEq, Eq, Hash)]
enum PubGrubHintCore {
PrereleaseAvailable {
package: PackageName,
},
BuildPrereleaseAvailable {
package: PackageName,
},
PrereleaseRequested {
package: PackageName,
},
BuildPrereleaseRequested {
package: PackageName,
},
NoIndex,
Offline,
InvalidPackageMetadata {
package: PackageName,
},
InvalidPackageStructure {
package: PackageName,
},
InvalidVersionMetadata {
package: PackageName,
},
InconsistentVersionMetadata {
package: PackageName,
},
InvalidVersionStructure {
package: PackageName,
},
IncompatibleBuildRequirement {
package: PackageName,
},
RequiresPython {
source: PythonRequirementSource,
requires_python: RequiresPython,
},
DependsOnWorkspacePackage {
package: PackageName,
dependency: PackageName,
workspace: bool,
},
DependsOnItself {
package: PackageName,
workspace: bool,
},
UncheckedIndex {
package: PackageName,
},
UnauthorizedIndex {
index: IndexUrl,
},
ForbiddenIndex {
index: IndexUrl,
},
NoBuild {
package: PackageName,
},
NoBinary {
package: PackageName,
},
LanguageTags {
package: PackageName,
},
AbiTags {
package: PackageName,
},
PlatformTags {
package: PackageName,
},
ExcludeNewer {
package: PackageName,
source: EffectiveExcludeNewerSource,
},
DisjointPythonVersion,
DisjointEnvironment,
}
impl From<PubGrubHint> for PubGrubHintCore {
#[inline]
fn from(hint: PubGrubHint) -> Self {
match hint {
PubGrubHint::PrereleaseAvailable { package, .. } => {
Self::PrereleaseAvailable { package }
}
PubGrubHint::BuildPrereleaseAvailable { package, .. } => {
Self::BuildPrereleaseAvailable { package }
}
PubGrubHint::PrereleaseRequested { name: package, .. } => {
Self::PrereleaseRequested { package }
}
PubGrubHint::BuildPrereleaseRequested { name: package, .. } => {
Self::BuildPrereleaseRequested { package }
}
PubGrubHint::NoIndex => Self::NoIndex,
PubGrubHint::Offline => Self::Offline,
PubGrubHint::InvalidPackageMetadata { package, .. } => {
Self::InvalidPackageMetadata { package }
}
PubGrubHint::InvalidPackageStructure { package, .. } => {
Self::InvalidPackageStructure { package }
}
PubGrubHint::InvalidVersionMetadata { package, .. } => {
Self::InvalidVersionMetadata { package }
}
PubGrubHint::InconsistentVersionMetadata { package, .. } => {
Self::InconsistentVersionMetadata { package }
}
PubGrubHint::InvalidVersionStructure { package, .. } => {
Self::InvalidVersionStructure { package }
}
PubGrubHint::IncompatibleBuildRequirement { package, .. } => {
Self::IncompatibleBuildRequirement { package }
}
PubGrubHint::RequiresPython {
source,
requires_python,
..
} => Self::RequiresPython {
source,
requires_python,
},
PubGrubHint::DependsOnWorkspacePackage {
package,
dependency,
workspace,
} => Self::DependsOnWorkspacePackage {
package,
dependency,
workspace,
},
PubGrubHint::DependsOnItself { package, workspace } => {
Self::DependsOnItself { package, workspace }
}
PubGrubHint::UncheckedIndex { name: package, .. } => Self::UncheckedIndex { package },
PubGrubHint::UnauthorizedIndex { index } => Self::UnauthorizedIndex { index },
PubGrubHint::ForbiddenIndex { index } => Self::ForbiddenIndex { index },
PubGrubHint::NoBuild { package, .. } => Self::NoBuild { package },
PubGrubHint::NoBinary { package, .. } => Self::NoBinary { package },
PubGrubHint::LanguageTags { package, .. } => Self::LanguageTags { package },
PubGrubHint::AbiTags { package, .. } => Self::AbiTags { package },
PubGrubHint::PlatformTags { package, .. } => Self::PlatformTags { package },
PubGrubHint::ExcludeNewer {
package, source, ..
} => Self::ExcludeNewer { package, source },
PubGrubHint::DisjointPythonVersion { .. } => Self::DisjointPythonVersion,
PubGrubHint::DisjointEnvironment => Self::DisjointEnvironment,
}
}
}
impl std::hash::Hash for PubGrubHint {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let core = PubGrubHintCore::from(self.clone());
core.hash(state);
}
}
impl PartialEq for PubGrubHint {
fn eq(&self, other: &Self) -> bool {
let core = PubGrubHintCore::from(self.clone());
let other_core = PubGrubHintCore::from(other.clone());
core == other_core
}
}
impl Eq for PubGrubHint {}
impl std::fmt::Display for PubGrubHint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::PrereleaseAvailable { package, version } => {
write!(
f,
"{}{} Pre-releases are available for `{}` in the requested range (e.g., {}), but pre-releases weren't enabled (try: `{}`)",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
version.cyan(),
"--prerelease=allow".green(),
)
}
Self::BuildPrereleaseAvailable { package, version } => {
let spec = format!("{package}>={version}");
write!(
f,
"{}{} Only pre-releases of `{}` (e.g., {}) match these build requirements, and build environments can't enable pre-releases automatically. Add `{}` to `build-system.requires`, `[tool.uv.extra-build-dependencies]`, or supply it via `uv build --build-constraint`.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
version.cyan(),
spec.cyan(),
)
}
Self::PrereleaseRequested { name, range } => {
write!(
f,
"{}{} `{}` was requested with a pre-release marker (e.g., {}), but pre-releases weren't enabled (try: `{}`)",
"hint".bold().cyan(),
":".bold(),
name.cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), range, None).cyan(),
"--prerelease=allow".green(),
)
}
Self::BuildPrereleaseRequested { name, range } => {
write!(
f,
"{}{} `{}` was requested with a pre-release marker (e.g., {}), but build environments can't opt into pre-releases automatically. Add `{}` to `build-system.requires`, `[tool.uv.extra-build-dependencies]`, or supply it via `uv build --build-constraint`.",
"hint".bold().cyan(),
":".bold(),
name.cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), range, None).cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), range, None).cyan(),
)
}
Self::NoIndex => {
write!(
f,
"{}{} Packages were unavailable because index lookups were disabled and no additional package locations were provided (try: `{}`)",
"hint".bold().cyan(),
":".bold(),
"--find-links <uri>".green(),
)
}
Self::Offline => {
write!(
f,
"{}{} Packages were unavailable because the network was disabled. When the network is disabled, registry packages may only be read from the cache.",
"hint".bold().cyan(),
":".bold(),
)
}
Self::InvalidPackageMetadata { package, reason } => {
write!(
f,
"{}{} Metadata for `{}` could not be parsed.\n{}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
textwrap::indent(reason.to_string().as_str(), " ")
)
}
Self::InvalidPackageStructure { package, reason } => {
write!(
f,
"{}{} The structure of `{}` was invalid\n{}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
textwrap::indent(reason.to_string().as_str(), " ")
)
}
Self::InvalidVersionMetadata {
package,
version,
reason,
} => {
write!(
f,
"{}{} Metadata for `{}` ({}) could not be parsed:\n{}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
textwrap::indent(reason, " ")
)
}
Self::InvalidVersionStructure {
package,
version,
reason,
} => {
write!(
f,
"{}{} The structure of `{}` ({}) was invalid:\n{}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
textwrap::indent(reason, " ")
)
}
Self::InconsistentVersionMetadata {
package,
version,
reason,
} => {
write!(
f,
"{}{} Metadata for `{}` ({}) was inconsistent:\n{}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
textwrap::indent(reason, " ")
)
}
Self::RequiresPython {
source: PythonRequirementSource::RequiresPython,
requires_python,
name,
package_set,
package_requires_python,
} => {
write!(
f,
"{}{} The `requires-python` value ({}) includes Python versions that are not supported by your dependencies (e.g., {} only supports {}). Consider using a more restrictive `requires-python` value (like {}).",
"hint".bold().cyan(),
":".bold(),
requires_python.cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), package_set, None)
.cyan(),
package_requires_python.cyan(),
package_requires_python.cyan(),
)
}
Self::RequiresPython {
source: PythonRequirementSource::PythonVersion,
requires_python,
name,
package_set,
package_requires_python,
} => {
write!(
f,
"{}{} The `--python-version` value ({}) includes Python versions that are not supported by your dependencies (e.g., {} only supports {}). Consider using a higher `--python-version` value.",
"hint".bold().cyan(),
":".bold(),
requires_python.cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), package_set, None)
.cyan(),
package_requires_python.cyan(),
)
}
Self::RequiresPython {
source: PythonRequirementSource::Interpreter,
requires_python: _,
name,
package_set,
package_requires_python,
} => {
write!(
f,
"{}{} The Python interpreter uses a Python version that is not supported by your dependencies (e.g., {} only supports {}). Consider passing a `--python-version` value to raise the minimum supported version.",
"hint".bold().cyan(),
":".bold(),
PackageRange::compatibility(&PubGrubPackage::base(name), package_set, None)
.cyan(),
package_requires_python.cyan(),
)
}
Self::IncompatibleBuildRequirement {
package,
version,
requires_python,
python_version,
} => {
write!(
f,
"{}{} The source distribution for `{}` ({}) does not include static metadata. Generating metadata for this package requires Python {}, but Python {} is installed.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
requires_python.cyan(),
python_version.cyan(),
)
}
Self::DependsOnWorkspacePackage {
package,
dependency,
workspace,
} => {
let your_project = if *workspace {
"one of your workspace members"
} else {
"your project"
};
let the_project = if *workspace {
"the workspace member"
} else {
"the project"
};
write!(
f,
"{}{} The package `{}` depends on the package `{}` but the name is shadowed by {your_project}. Consider changing the name of {the_project}.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
dependency.cyan(),
)
}
Self::DependsOnItself { package, workspace } => {
let project = if *workspace {
"workspace member"
} else {
"project"
};
write!(
f,
"{}{} The {project} `{}` depends on itself at an incompatible version. This is likely a mistake. If you intended to depend on a third-party package named `{}`, consider renaming the {project} `{}` to avoid creating a conflict.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
package.cyan(),
package.cyan(),
)
}
Self::UncheckedIndex {
name,
range,
found_index,
next_index,
} => {
write!(
f,
"{}{} `{}` was found on {}, but not at the requested version ({}). A compatible version may be available on a subsequent index (e.g., {}). By default, uv will only consider versions that are published on the first index that contains a given package, to avoid dependency confusion attacks. If all indexes are equally trusted, use `{}` to consider all versions from all indexes, regardless of the order in which they were defined.",
"hint".bold().cyan(),
":".bold(),
name.cyan(),
found_index.without_credentials().cyan(),
PackageRange::compatibility(&PubGrubPackage::base(name), range, None).cyan(),
next_index.cyan(),
"--index-strategy unsafe-best-match".green(),
)
}
Self::UnauthorizedIndex { index } => {
write!(
f,
"{}{} An index URL ({}) could not be queried due to a lack of valid authentication credentials ({}).",
"hint".bold().cyan(),
":".bold(),
index.without_credentials().cyan(),
"401 Unauthorized".red(),
)
}
Self::ForbiddenIndex { index } => {
write!(
f,
"{}{} An index URL ({}) returned a {} error. This could indicate lack of valid authentication credentials, or the package may not exist on this index.",
"hint".bold().cyan(),
":".bold(),
index.without_credentials().cyan(),
"403 Forbidden".red(),
)
}
Self::NoBuild { package, option } => {
let option = match option {
NoBuild::All => "for all packages (i.e., with `--no-build`)".to_string(),
NoBuild::Packages(_) => {
format!("for `{package}` (i.e., with `--no-build-package {package}`)")
}
NoBuild::None => unreachable!(),
};
write!(
f,
"{}{} Wheels are required for `{}` because building from source is disabled {option}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
)
}
Self::NoBinary { package, option } => {
let option = match option {
NoBinary::All => "for all packages (i.e., with `--no-binary`)".to_string(),
NoBinary::Packages(_) => {
format!("for `{package}` (i.e., with `--no-binary-package {package}`)")
}
NoBinary::None => unreachable!(),
};
write!(
f,
"{}{} A source distribution is required for `{}` because using pre-built wheels is disabled {option}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
)
}
Self::LanguageTags {
package,
version,
tags,
best,
} => {
if let Some(best) = best {
let s = if tags.len() == 1 { "" } else { "s" };
let best = if let Some(pretty) = best.pretty() {
format!("{} (`{}`)", pretty.cyan(), best.cyan())
} else {
format!("{}", best.cyan())
};
write!(
f,
"{}{} You require {}, but we only found wheels for `{}` ({}) with the following Python implementation tag{s}: {}",
"hint".bold().cyan(),
":".bold(),
best,
package.cyan(),
format!("v{version}").cyan(),
tags.iter()
.map(|tag| format!("`{}`", tag.cyan()))
.join(", "),
)
} else {
let s = if tags.len() == 1 { "" } else { "s" };
write!(
f,
"{}{} Wheels are available for `{}` ({}) with the following Python implementation tag{s}: {}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
tags.iter()
.map(|tag| format!("`{}`", tag.cyan()))
.join(", "),
)
}
}
Self::AbiTags {
package,
version,
tags,
best,
} => {
if let Some(best) = best {
let s = if tags.len() == 1 { "" } else { "s" };
let best = if let Some(pretty) = best.pretty() {
format!("{} (`{}`)", pretty.cyan(), best.cyan())
} else {
format!("{}", best.cyan())
};
write!(
f,
"{}{} You require {}, but we only found wheels for `{}` ({}) with the following Python ABI tag{s}: {}",
"hint".bold().cyan(),
":".bold(),
best,
package.cyan(),
format!("v{version}").cyan(),
tags.iter()
.map(|tag| format!("`{}`", tag.cyan()))
.join(", "),
)
} else {
let s = if tags.len() == 1 { "" } else { "s" };
write!(
f,
"{}{} Wheels are available for `{}` ({}) with the following Python ABI tag{s}: {}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
tags.iter()
.map(|tag| format!("`{}`", tag.cyan()))
.join(", "),
)
}
}
Self::PlatformTags {
package,
version,
tags,
} => {
let s = if tags.len() == 1 { "" } else { "s" };
write!(
f,
"{}{} Wheels are available for `{}` ({}) on the following platform{s}: {}",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
format!("v{version}").cyan(),
tags.iter()
.map(|tag| format!("`{}`", tag.cyan()))
.join(", "),
)
}
Self::ExcludeNewer {
package,
source,
exclude_newer,
matching_version,
} => {
let latest = match matching_version {
Some(ExcludeNewerVersionDetail {
version,
publish_date: Some(publish_date),
singleton: true,
}) => format!(
" The requested version, {}, was published at {}.",
format!("v{version}").cyan(),
publish_date.cyan()
),
Some(ExcludeNewerVersionDetail {
version: _,
publish_date: None,
singleton: true,
}) => String::new(),
Some(ExcludeNewerVersionDetail {
version,
publish_date: Some(publish_date),
singleton: false,
}) => format!(
" The latest version satisfying the requirement is {}, published at {}.",
format!("v{version}").cyan(),
publish_date.cyan()
),
Some(ExcludeNewerVersionDetail {
version,
publish_date: None,
singleton: false,
}) => format!(
" The latest version satisfying the requirement is {}.",
format!("v{version}").cyan()
),
None => String::new(),
};
match source {
EffectiveExcludeNewerSource::Package => write!(
f,
"{}{} `{}` was filtered by `{}` to only include packages uploaded \
before {}.{latest} Consider removing the setting or updating it to a later date.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
"exclude-newer-package".green(),
exclude_newer.cyan(),
),
EffectiveExcludeNewerSource::Global => write!(
f,
"{}{} `{}` was filtered by `{}` to only include packages uploaded \
before {}.{latest} Consider using `{}` to override the cutoff for this package.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
"exclude-newer".green(),
exclude_newer.cyan(),
"exclude-newer-package".green(),
),
EffectiveExcludeNewerSource::Index => write!(
f,
"{}{} `{}` was filtered by the index-specific `{}` setting to only include \
packages uploaded before {}.{latest} Consider updating that index's cutoff, setting \
it to `false`, or using `{}` to override the cutoff for this package.",
"hint".bold().cyan(),
":".bold(),
package.cyan(),
"exclude-newer".green(),
exclude_newer.cyan(),
"exclude-newer-package".green(),
),
}
}
Self::DisjointPythonVersion { python_version } => {
write!(
f,
"{}{} While the active Python version is {}, \
the resolution failed for other Python versions supported by your \
project. Consider limiting your project's supported Python versions \
using `requires-python`.",
"hint".bold().cyan(),
":".bold(),
python_version.cyan(),
)
}
Self::DisjointEnvironment => {
write!(
f,
"{}{} The resolution failed for an environment that is not the current one, \
consider limiting the environments with `tool.uv.environments`.",
"hint".bold().cyan(),
":".bold(),
)
}
}
}
}
/// A [`Term`] and [`PubGrubPackage`] combination for display.
struct PackageTerm<'a> {
package: &'a PubGrubPackage,
term: &'a Term<Range<Version>>,
formatter: &'a PubGrubReportFormatter<'a>,
}
impl std::fmt::Display for PackageTerm<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.term {
Term::Positive(set) => {
write!(f, "{}", self.formatter.compatible_range(self.package, set))
}
Term::Negative(set) => {
if let Some(version) = set.as_singleton() {
// Note we do not handle the "root" package here but we should never
// be displaying that the root package is inequal to some version
let package = self.package;
write!(f, "{package}!={version}")
} else {
write!(
f,
"{}",
self.formatter
.compatible_range(self.package, &set.complement())
)
}
}
}
}
}
impl PackageTerm<'_> {
/// Create a new [`PackageTerm`] from a [`PubGrubPackage`] and a [`Term`].
fn new<'a>(
package: &'a PubGrubPackage,
term: &'a Term<Range<Version>>,
formatter: &'a PubGrubReportFormatter<'a>,
) -> PackageTerm<'a> {
PackageTerm {
package,
term,
formatter,
}
}
}
/// The kind of version ranges being displayed in [`PackageRange`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PackageRangeKind {
Dependency,
Compatibility,
Available,
}
/// A [`Range`] and [`PubGrubPackage`] combination for display.
#[derive(Debug)]
struct PackageRange<'a> {
package: &'a PubGrubPackage,
range: &'a Range<Version>,
kind: PackageRangeKind,
formatter: Option<&'a PubGrubReportFormatter<'a>>,
}
impl PackageRange<'_> {
fn compatibility<'a>(
package: &'a PubGrubPackage,
range: &'a Range<Version>,
formatter: Option<&'a PubGrubReportFormatter<'a>>,
) -> PackageRange<'a> {
PackageRange {
package,
range,
kind: PackageRangeKind::Compatibility,
formatter,
}
}
fn dependency<'a>(
package: &'a PubGrubPackage,
range: &'a Range<Version>,
formatter: Option<&'a PubGrubReportFormatter<'a>>,
) -> PackageRange<'a> {
PackageRange {
package,
range,
kind: PackageRangeKind::Dependency,
formatter,
}
}
fn availability<'a>(
package: &'a PubGrubPackage,
range: &'a Range<Version>,
formatter: Option<&'a PubGrubReportFormatter<'a>>,
) -> PackageRange<'a> {
PackageRange {
package,
range,
kind: PackageRangeKind::Available,
formatter,
}
}
/// Returns a boolean indicating if the predicate following this package range should
/// be singular or plural e.g. if false use "<range> depends on <...>" and
/// if true use "<range> depend on <...>"
fn plural(&self) -> bool {
// If a workspace member, always use the singular form (otherwise, it'd be "all versions of")
if self
.formatter
.and_then(|formatter| formatter.format_workspace_member(self.package))
.is_some()
{
return false;
}
let mut segments = self.range.iter();
if let Some(segment) = segments.next() {
// A single unbounded compatibility segment is always plural ("all versions of").
if self.kind == PackageRangeKind::Compatibility {
if matches!(segment, (Bound::Unbounded, Bound::Unbounded)) {
return true;
}
}
// Otherwise, multiple segments are always plural.
segments.next().is_some()
} else {
// An empty range is always singular.
false
}
}
}
/// Create a range with improved segments for reporting the available versions for a package.
fn update_availability_range(
range: &Range<Version>,
available_versions: &BTreeSet<Version>,
) -> Range<Version> {
/// Whether a (normalized) version is contained in a set of versions.
///
/// Unfortunately, we need to normalize the version because when we extract it from the range it
/// may have `min` or `max` set but the values in `available_versions` will never have `min` or
/// `max`.
fn version_contained_in(version: &Version, versions: &BTreeSet<Version>) -> bool {
if versions.contains(version) {
return true;
}
// It's a little unfortunate we perform a clone here and throw away the value, but the
// performance implications during an error report seem negligible and it makes the
// calling code simpler.
let version = version.clone().with_min(None).with_max(None);
versions.contains(&version)
}
let mut new_range = Range::empty();
// Construct an available range to help guide simplification. Note this is not strictly correct,
// as the available range should have many holes in it. However, for this use-case it should be
// okay — we just may avoid simplifying some segments _inside_ the available range.
let (available_range, first_available, last_available) =
match (available_versions.first(), available_versions.last()) {
// At least one version is available
(Some(first), Some(last)) => {
let range = Range::<Version>::from_range_bounds((
Bound::Included(first.clone()),
Bound::Included(last.clone()),
));
// If only one version is available, return this as the bound immediately
if first == last {
return range;
}
(range, first, last)
}
// SAFETY: If there's only a single item, `first` and `last` should both
// return `Some`.
(Some(_), None) | (None, Some(_)) => unreachable!(),
// No versions are available; nothing to do
(None, None) => return Range::empty(),
};
for segment in range.iter() {
let (lower, upper) = segment;
let segment_range = Range::from_range_bounds((lower.clone(), upper.clone()));
// Drop the segment if it's disjoint with the available range, e.g., if the segment is
// `foo>999`, and the available versions are all `<10` it's useless to show.
if segment_range.is_disjoint(&available_range) {
continue;
}
// Replace the segment if it's captured by the available range, e.g., if the segment is
// `foo<1000` and the available versions are all `<10` we can simplify to `foo<10`.
if available_range.subset_of(&segment_range) {
// If the segment only has a lower or upper bound, only take the relevant part of the
// available range. This avoids replacing `foo<100` with `foo>1,<2`, instead using
// `foo<2` to avoid extra noise.
if matches!(lower, Bound::Unbounded) {
new_range = new_range.union(&Range::from_range_bounds((
Bound::Unbounded,
Bound::Included(last_available.clone()),
)));
} else if matches!(upper, Bound::Unbounded) {
new_range = new_range.union(&Range::from_range_bounds((
Bound::Included(first_available.clone()),
Bound::Unbounded,
)));
} else {
new_range = new_range.union(&available_range);
}
continue;
}
// If the bound is inclusive, and the version is _not_ available, change it to an exclusive
// bound to avoid confusion, e.g., if the segment is `foo<=10` and the available versions
// do not include `foo 10`, we should instead say `foo<10`.
let lower = match lower {
Bound::Included(version) if !version_contained_in(version, available_versions) => {
Bound::Excluded(version.clone())
}
_ => (*lower).clone(),
};
let upper = match upper {
Bound::Included(version) if !version_contained_in(version, available_versions) => {
Bound::Excluded(version.clone())
}
_ => (*upper).clone(),
};
// Note this repeated-union construction is not particularly efficient, but there's not
// better API exposed by PubGrub. Since we're just generating an error message, it's
// probably okay, but we should investigate a better upstream API.
new_range = new_range.union(&Range::from_range_bounds((lower, upper)));
}
new_range
}
impl std::fmt::Display for PackageRange<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Exit early for the root package — the range is not meaningful
if let Some(root) = self
.formatter
.and_then(|formatter| formatter.format_root(self.package))
{
return write!(f, "{root}");
}
// Exit early for workspace members, only a single version is available
if let Some(member) = self
.formatter
.and_then(|formatter| formatter.format_workspace_member(self.package))
{
return write!(f, "{member}");
}
let package = self.package;
if self.range.is_empty() {
return write!(f, "{package} ∅");
}
let segments: Vec<_> = self.range.iter().collect();
if segments.len() > 1 {
match self.kind {
PackageRangeKind::Dependency => write!(f, "one of:")?,
PackageRangeKind::Compatibility => write!(f, "all of:")?,
PackageRangeKind::Available => write!(f, "are available:")?,
}
}
for (lower, upper) in &segments {
if segments.len() > 1 {
write!(f, "\n ")?;
}
match (lower, upper) {
(Bound::Unbounded, Bound::Unbounded) => match self.kind {
PackageRangeKind::Dependency => write!(f, "{package}")?,
PackageRangeKind::Compatibility => write!(f, "all versions of {package}")?,
PackageRangeKind::Available => write!(f, "{package}")?,
},
(Bound::Unbounded, Bound::Included(v)) => write!(f, "{package}<={v}")?,
(Bound::Unbounded, Bound::Excluded(v)) => write!(f, "{package}<{v}")?,
(Bound::Included(v), Bound::Unbounded) => write!(f, "{package}>={v}")?,
(Bound::Included(v), Bound::Included(b)) => {
if v == b {
write!(f, "{package}=={v}")?;
} else {
write!(f, "{package}>={v},<={b}")?;
}
}
(Bound::Included(v), Bound::Excluded(b)) => {
if let Some(prefix) = PrefixMatch::from_range(lower, upper) {
write!(f, "{package}{prefix}")?;
} else {
write!(f, "{package}>={v},<{b}")?;
}
}
(Bound::Excluded(v), Bound::Unbounded) => write!(f, "{package}>{v}")?,
(Bound::Excluded(v), Bound::Included(b)) => write!(f, "{package}>{v},<={b}")?,
(Bound::Excluded(v), Bound::Excluded(b)) => write!(f, "{package}>{v},<{b}")?,
}
}
if segments.len() > 1 {
writeln!(f)?;
}
Ok(())
}
}
impl PackageRange<'_> {
fn depends_on<'a>(
&'a self,
package: &'a PubGrubPackage,
range: &'a Range<Version>,
) -> DependsOn<'a> {
DependsOn {
package: self,
dependency1: PackageRange {
package,
range,
kind: PackageRangeKind::Dependency,
formatter: self.formatter,
},
dependency2: None,
}
}
}
/// A representation of A depends on B (and C).
#[derive(Debug)]
struct DependsOn<'a> {
package: &'a PackageRange<'a>,
dependency1: PackageRange<'a>,
dependency2: Option<PackageRange<'a>>,
}
impl<'a> DependsOn<'a> {
/// Adds an additional dependency.
///
/// Note this overwrites previous calls to `DependsOn::and`.
fn and(mut self, package: &'a PubGrubPackage, range: &'a Range<Version>) -> Self {
self.dependency2 = Some(PackageRange {
package,
range,
kind: PackageRangeKind::Dependency,
formatter: self.package.formatter,
});
self
}
}
impl std::fmt::Display for DependsOn<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", Padded::new("", self.package, " "))?;
if self.package.plural() {
write!(f, "depend on ")?;
} else {
write!(f, "depends on ")?;
}
match self.dependency2 {
Some(ref dependency2) => write!(
f,
"{}and{}",
Padded::new("", &self.dependency1, " "),
Padded::new(" ", &dependency2, "")
)?,
None => write!(f, "{}", self.dependency1)?,
}
Ok(())
}
}
/// Inserts the given padding on the left and right sides of the content if
/// the content does not start and end with whitespace respectively.
#[derive(Debug)]
struct Padded<'a, T: std::fmt::Display> {
left: &'a str,
content: &'a T,
right: &'a str,
}
impl<'a, T: std::fmt::Display> Padded<'a, T> {
fn new(left: &'a str, content: &'a T, right: &'a str) -> Self {
Padded {
left,
content,
right,
}
}
}
impl<'a> Padded<'a, String> {
fn from_string(left: &'a str, content: &'a String, right: &'a str) -> Self {
Padded {
left,
content,
right,
}
}
}
impl<T: std::fmt::Display> std::fmt::Display for Padded<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut result = String::new();
let content = self.content.to_string();
if let Some(char) = content.chars().next() {
if !char.is_whitespace() {
result.push_str(self.left);
}
}
result.push_str(&content);
if let Some(char) = content.chars().last() {
if !char.is_whitespace() {
result.push_str(self.right);
}
}
write!(f, "{result}")
}
}