uv-build-backend 0.0.41

This is an internal component crate of uv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
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
use itertools::Itertools;
mod metadata;
mod serde_verbatim;
mod settings;
mod source_dist;
mod wheel;

pub use metadata::{PyProjectToml, check_direct_build};
pub use settings::{BuildBackendSettings, WheelDataIncludes};
pub use source_dist::{build_source_dist, list_source_dist};
use uv_warnings::warn_user_once;
pub use wheel::{build_editable, build_wheel, list_wheel, metadata};

use std::collections::HashSet;
use std::ffi::OsStr;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use thiserror::Error;
use tracing::debug;
use walkdir::DirEntry;

use uv_fs::{Simplified, normalize_path};
use uv_globfilter::PortableGlobError;
use uv_normalize::PackageName;
use uv_pypi_types::{Identifier, IdentifierParseError};

use crate::metadata::ValidationError;
use crate::settings::ModuleName;

#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error("Failed to persist temporary file to {}", _0.user_display())]
    Persist(PathBuf, #[source] io::Error),
    #[error("Invalid metadata format in: {}", _0.user_display())]
    Toml(PathBuf, #[source] toml::de::Error),
    #[error("Invalid project metadata")]
    Validation(#[from] ValidationError),
    #[error("Invalid module name: {0}")]
    InvalidModuleName(String, #[source] IdentifierParseError),
    #[error("Unsupported glob expression in: {field}")]
    PortableGlob {
        field: String,
        #[source]
        source: PortableGlobError,
    },
    /// <https://github.com/BurntSushi/ripgrep/discussions/2927>
    #[error("Glob expressions caused to large regex in: {field}")]
    GlobSetTooLarge {
        field: String,
        #[source]
        source: globset::Error,
    },
    #[error("`pyproject.toml` must not be excluded from source distribution build")]
    PyprojectTomlExcluded,
    #[error("Failed to walk source tree: {}", root.user_display())]
    WalkDir {
        root: PathBuf,
        #[source]
        err: walkdir::Error,
    },
    #[error("Failed to write wheel zip archive")]
    Zip(#[from] zip::result::ZipError),
    #[error("Failed to write RECORD file")]
    Csv(#[from] csv::Error),
    #[error("Failed to write JSON metadata file")]
    Json(#[source] serde_json::Error),
    #[error("Expected a Python module at: {}", _0.user_display())]
    MissingInitPy(PathBuf),
    #[error("For namespace packages, `__init__.py[i]` is not allowed in parent directory: {}", _0.user_display())]
    NotANamespace(PathBuf),
    /// Either an absolute path or a parent path through `..`.
    #[error("Module root must be inside the project: {}", _0.user_display())]
    InvalidModuleRoot(PathBuf),
    /// Either an absolute path or a parent path through `..`.
    #[error("The path for the data directory {} must be inside the project: {}", name, path.user_display())]
    InvalidDataRoot { name: String, path: PathBuf },
    #[error("Virtual environments must not be added to source distributions or wheels, remove the directory or exclude it from the build: {}", _0.user_display())]
    VenvInSourceTree(PathBuf),
    #[error("Inconsistent metadata between prepare and build step: {0}")]
    InconsistentSteps(&'static str),
    #[error("Failed to write to {}", _0.user_display())]
    TarWrite(PathBuf, #[source] io::Error),
}

/// Dispatcher between writing to a directory, writing to a zip, writing to a `.tar.gz` and
/// listing files.
///
/// All paths are string types instead of path types since wheels are portable between platforms.
///
/// Contract: You must call close before dropping to obtain a valid output (dropping is fine in the
/// error case).
trait DirectoryWriter {
    /// Add a file with the given content.
    ///
    /// Files added through the method are considered generated when listing included files.
    fn write_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error>;

    /// Add the file or directory to the path.
    fn write_dir_entry(&mut self, entry: &DirEntry, target_path: &str) -> Result<(), Error> {
        if entry.file_type().is_dir() {
            self.write_directory(target_path)?;
        } else {
            self.write_file(target_path, entry.path())?;
        }
        Ok(())
    }

    /// Add a local file.
    fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error>;

    /// Create a directory.
    fn write_directory(&mut self, directory: &str) -> Result<(), Error>;

    /// Write the `RECORD` file and if applicable, the central directory.
    fn close(self, dist_info_dir: &str) -> Result<(), Error>;
}

/// Name of the file in the archive and path outside, if it wasn't generated.
pub(crate) type FileList = Vec<(String, Option<PathBuf>)>;

/// A dummy writer to collect the file names that would be included in a build.
pub(crate) struct ListWriter<'a> {
    files: &'a mut FileList,
}

impl<'a> ListWriter<'a> {
    /// Convert the writer to the collected file names.
    pub(crate) fn new(files: &'a mut FileList) -> Self {
        Self { files }
    }
}

impl DirectoryWriter for ListWriter<'_> {
    fn write_bytes(&mut self, path: &str, _bytes: &[u8]) -> Result<(), Error> {
        self.files.push((path.to_string(), None));
        Ok(())
    }

    fn write_file(&mut self, path: &str, file: &Path) -> Result<(), Error> {
        self.files
            .push((path.to_string(), Some(file.to_path_buf())));
        Ok(())
    }

    fn write_directory(&mut self, _directory: &str) -> Result<(), Error> {
        Ok(())
    }

    fn close(self, _dist_info_dir: &str) -> Result<(), Error> {
        Ok(())
    }
}

/// PEP 517 requires that the metadata directory from the prepare metadata call is identical to the
/// build wheel call. This method performs a prudence check that `METADATA` and `entry_points.txt`
/// match.
fn check_metadata_directory(
    source_tree: &Path,
    metadata_directory: Option<&Path>,
    pyproject_toml: &PyProjectToml,
) -> Result<(), Error> {
    let Some(metadata_directory) = metadata_directory else {
        return Ok(());
    };

    debug!(
        "Checking metadata directory {}",
        metadata_directory.user_display()
    );

    // `METADATA` is a mandatory file.
    let current = pyproject_toml
        .to_metadata(source_tree)?
        .core_metadata_format();
    let previous = fs_err::read_to_string(metadata_directory.join("METADATA"))?;
    if previous != current {
        return Err(Error::InconsistentSteps("METADATA"));
    }

    // `entry_points.txt` is not written if it would be empty.
    let entrypoints_path = metadata_directory.join("entry_points.txt");
    match pyproject_toml.to_entry_points()? {
        None => {
            if entrypoints_path.is_file() {
                return Err(Error::InconsistentSteps("entry_points.txt"));
            }
        }
        Some(entrypoints) => {
            if fs_err::read_to_string(&entrypoints_path)? != entrypoints {
                return Err(Error::InconsistentSteps("entry_points.txt"));
            }
        }
    }

    Ok(())
}

/// Returns the list of module names without names which would be included twice
///
/// In normal cases it should do nothing:
///
/// * `["aaa"] -> ["aaa"]`
/// * `["aaa", "bbb"] -> ["aaa", "bbb"]`
///
/// Duplicate elements are removed:
///
/// * `["aaa", "aaa"] -> ["aaa"]`
/// * `["bbb", "aaa", "bbb"] -> ["aaa", "bbb"]`
///
/// Names with more specific paths are removed in favour of more general paths:
///
/// * `["aaa.foo", "aaa"] -> ["aaa"]`
/// * `["bbb", "aaa", "bbb.foo", "ccc.foo", "ccc.foo.bar", "aaa"] -> ["aaa", "bbb.foo", "ccc.foo"]`
///
/// This does not preserve the order of the elements.
fn prune_redundant_modules(mut names: Vec<String>) -> Vec<String> {
    names.sort();
    let mut pruned = Vec::with_capacity(names.len());
    for name in names {
        if let Some(last) = pruned.last() {
            if name == *last {
                continue;
            }
            // This is a more specific (narrow) module name than what came before
            if name
                .strip_prefix(last)
                .is_some_and(|suffix| suffix.starts_with('.'))
            {
                continue;
            }
        }
        pruned.push(name);
    }
    pruned
}

/// Wraps [`prune_redundant_modules`] with a conditional warning when modules are ignored
fn prune_redundant_modules_warn(names: &[String], show_warnings: bool) -> Vec<String> {
    let pruned = prune_redundant_modules(names.to_vec());
    if show_warnings && names.len() != pruned.len() {
        let mut pruned: HashSet<_> = pruned.iter().collect();
        let ignored: Vec<_> = names.iter().filter(|name| !pruned.remove(name)).collect();
        let s = if ignored.len() == 1 { "" } else { "s" };
        warn_user_once!(
            "Ignoring redundant module name{s} in `tool.uv.build-backend.module-name`: `{}`",
            ignored.into_iter().join("`, `")
        );
    }
    pruned
}

/// Returns the source root and the module path(s) with the `__init__.py[i]`  below to it while
/// checking the project layout and names.
///
/// Some target platforms have case-sensitive filesystems, while others have case-insensitive
/// filesystems. We always lower case the package name, our default for the module, while some
/// users want uppercase letters in their module names. For example, the package name is `pil_util`,
/// but the module `PIL_util`. To make the behavior as consistent as possible across platforms as
/// possible, we require that an upper case name is given explicitly through
/// `tool.uv.build-backend.module-name`.
///
/// By default, the dist-info-normalized package name is the module name. For
/// dist-info-normalization, the rules are lowercasing, replacing `.` with `_` and
/// replace `-` with `_`. Since `.` and `-` are not allowed in identifiers, we can use a string
/// comparison with the module name.
///
/// While we recommend one module per package, it is possible to declare a list of modules.
fn find_roots(
    source_tree: &Path,
    pyproject_toml: &PyProjectToml,
    relative_module_root: &Path,
    module_name: Option<&ModuleName>,
    namespace: bool,
    show_warnings: bool,
) -> Result<(PathBuf, Vec<PathBuf>), Error> {
    let relative_module_root = normalize_path(relative_module_root);
    // Check that even if a path contains `..`, we only include files below the module root.
    let src_root = source_tree.join(&relative_module_root);
    if !normalize_path(&src_root).starts_with(normalize_path(source_tree)) {
        return Err(Error::InvalidModuleRoot(relative_module_root.to_path_buf()));
    }
    debug!("Source root: {}", src_root.user_display());

    if namespace {
        // `namespace = true` disables module structure checks.
        let modules_relative = if let Some(module_name) = module_name {
            match module_name {
                ModuleName::Name(name) => {
                    vec![name.split('.').collect::<PathBuf>()]
                }
                ModuleName::Names(names) => prune_redundant_modules_warn(names, show_warnings)
                    .into_iter()
                    .map(|name| name.split('.').collect::<PathBuf>())
                    .collect(),
            }
        } else {
            vec![PathBuf::from(
                pyproject_toml.name().as_dist_info_name().to_string(),
            )]
        };
        for module_relative in &modules_relative {
            debug!("Namespace module path: {}", module_relative.user_display());
        }
        return Ok((src_root, modules_relative));
    }

    let modules_relative = if let Some(module_name) = module_name {
        match module_name {
            ModuleName::Name(name) => vec![module_path_from_module_name(&src_root, name)?],
            ModuleName::Names(names) => prune_redundant_modules_warn(names, show_warnings)
                .into_iter()
                .map(|name| module_path_from_module_name(&src_root, &name))
                .collect::<Result<_, _>>()?,
        }
    } else {
        vec![find_module_path_from_package_name(
            &src_root,
            pyproject_toml.name(),
        )?]
    };
    for module_relative in &modules_relative {
        debug!("Module path: {}", module_relative.user_display());
    }
    Ok((src_root, modules_relative))
}

/// Infer stubs packages from package name alone.
///
/// There are potential false positives if someone had a regular package with `-stubs`.
/// The `Identifier` checks in `module_path_from_module_name` are here covered by the `PackageName`
/// validation.
fn find_module_path_from_package_name(
    src_root: &Path,
    package_name: &PackageName,
) -> Result<PathBuf, Error> {
    if let Some(stem) = package_name.to_string().strip_suffix("-stubs") {
        debug!("Building stubs package instead of a regular package");
        let module_name = PackageName::from_str(stem)
            .expect("non-empty package name prefix must be valid package name")
            .as_dist_info_name()
            .to_string();
        let module_relative = PathBuf::from(format!("{module_name}-stubs"));
        let init_pyi = src_root.join(&module_relative).join("__init__.pyi");
        if !init_pyi.is_file() {
            return Err(Error::MissingInitPy(init_pyi));
        }
        Ok(module_relative)
    } else {
        // This name is always lowercase.
        let module_relative = PathBuf::from(package_name.as_dist_info_name().to_string());
        let init_py = src_root.join(&module_relative).join("__init__.py");
        if !init_py.is_file() {
            return Err(Error::MissingInitPy(init_py));
        }
        Ok(module_relative)
    }
}

/// Determine the relative module path from an explicit module name.
fn module_path_from_module_name(src_root: &Path, module_name: &str) -> Result<PathBuf, Error> {
    // This name can be uppercase.
    let module_relative = module_name.split('.').collect::<PathBuf>();

    // Check if we have a regular module or a namespace.
    let (root_name, namespace_segments) =
        if let Some((root_name, namespace_segments)) = module_name.split_once('.') {
            (
                root_name,
                namespace_segments.split('.').collect::<Vec<&str>>(),
            )
        } else {
            (module_name, Vec::new())
        };

    // Check if we have an implementation or a stubs package.
    // For stubs for a namespace, the `-stubs` prefix must be on the root.
    let stubs = if let Some(stem) = root_name.strip_suffix("-stubs") {
        // Check that the stubs belong to a valid module.
        Identifier::from_str(stem)
            .map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
        true
    } else {
        Identifier::from_str(root_name)
            .map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
        false
    };

    // For a namespace, check that all names below the root is valid.
    for segment in namespace_segments {
        Identifier::from_str(segment)
            .map_err(|err| Error::InvalidModuleName(module_name.to_string(), err))?;
    }

    // Check that an `__init__.py[i]` exists for the module.
    let init_py =
        src_root
            .join(&module_relative)
            .join(if stubs { "__init__.pyi" } else { "__init__.py" });
    if !init_py.is_file() {
        return Err(Error::MissingInitPy(init_py));
    }

    // For a namespace, check that the directories above the lowest are namespace directories.
    for namespace_dir in module_relative.ancestors().skip(1) {
        if src_root.join(namespace_dir).join("__init__.py").exists()
            || src_root.join(namespace_dir).join("__init__.pyi").exists()
        {
            return Err(Error::NotANamespace(src_root.join(namespace_dir)));
        }
    }

    Ok(module_relative)
}

/// Error if we're adding a venv to a distribution.
pub(crate) fn error_on_venv(file_name: &OsStr, path: &Path) -> Result<(), Error> {
    // On 64-bit Unix, `lib64` is a (compatibility) symlink to lib. If we traverse `lib64` before
    // `pyvenv.cfg`, we show a generic error for symlink directories instead.
    if !(file_name == "pyvenv.cfg" || file_name == "lib64") {
        return Ok(());
    }

    let Some(parent) = path.parent() else {
        return Ok(());
    };

    if parent.join("bin").join("python").is_symlink()
        || parent.join("Scripts").join("python.exe").is_file()
    {
        return Err(Error::VenvInSourceTree(parent.to_path_buf()));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use flate2::bufread::GzDecoder;
    use fs_err::File;
    use indoc::indoc;
    use insta::assert_snapshot;
    use itertools::Itertools;
    use regex::Regex;
    use sha2::Digest;
    use std::io::{BufReader, Read};
    use std::iter;
    use tempfile::TempDir;
    use uv_distribution_filename::{SourceDistFilename, WheelFilename};
    use uv_fs::{copy_dir_all, relative_to};
    use uv_preview::PreviewFeature;

    const MOCK_UV_VERSION: &str = "1.0.0+test";

    fn format_err(err: &Error) -> String {
        let context = iter::successors(std::error::Error::source(&err), |&err| err.source())
            .map(|err| format!("  Caused by: {err}"))
            .join("\n");
        err.to_string() + "\n" + &context
    }

    /// File listings, generated archives and archive contents for both a build with
    /// source tree -> wheel
    /// and a build with
    /// source tree -> source dist -> wheel.
    #[derive(Debug, PartialEq, Eq)]
    struct BuildResults {
        source_dist_list_files: FileList,
        source_dist_filename: SourceDistFilename,
        source_dist_contents: Vec<String>,
        wheel_list_files: FileList,
        wheel_filename: WheelFilename,
        wheel_contents: Vec<String>,
    }

    /// Run both a direct wheel build and an indirect wheel build through a source distribution,
    /// while checking that directly built wheel and indirectly built wheel are the same.
    fn build(
        source_root: &Path,
        dist: &Path,
        preview_features: &[PreviewFeature],
    ) -> Result<BuildResults, Error> {
        // Build a direct wheel, capture all its properties to compare it with the indirect wheel
        // latest and remove it since it has the same filename as the indirect wheel.
        let (_name, direct_wheel_list_files) = {
            let _preview = uv_preview::test::with_features(preview_features);
            list_wheel(source_root, MOCK_UV_VERSION, false)?
        };
        let direct_wheel_filename = {
            let _preview = uv_preview::test::with_features(preview_features);
            build_wheel(source_root, dist, None, MOCK_UV_VERSION, false)?
        };
        let direct_wheel_path = dist.join(direct_wheel_filename.to_string());
        let direct_wheel_contents = wheel_contents(&direct_wheel_path);
        let direct_wheel_hash = sha2::Sha256::digest(fs_err::read(&direct_wheel_path)?);
        fs_err::remove_file(&direct_wheel_path)?;

        // Build a source distribution.
        let (_name, source_dist_list_files) =
            list_source_dist(source_root, MOCK_UV_VERSION, false)?;
        // TODO(konsti): This should run in the unpacked source dist tempdir, but we need to
        // normalize the path.
        let (_name, wheel_list_files) = {
            let _preview = uv_preview::test::with_features(preview_features);
            list_wheel(source_root, MOCK_UV_VERSION, false)?
        };
        let source_dist_filename = build_source_dist(source_root, dist, MOCK_UV_VERSION, false)?;
        let source_dist_path = dist.join(source_dist_filename.to_string());
        let source_dist_contents = sdist_contents(&source_dist_path);

        // Unpack the source distribution and build a wheel from it.
        let sdist_tree = TempDir::new()?;
        let sdist_reader = BufReader::new(File::open(&source_dist_path)?);
        let mut source_dist = tar::Archive::new(GzDecoder::new(sdist_reader));
        source_dist.unpack(sdist_tree.path())?;
        let sdist_top_level_directory = sdist_tree.path().join(format!(
            "{}-{}",
            source_dist_filename.name.as_dist_info_name(),
            source_dist_filename.version
        ));
        let wheel_filename = {
            let _preview = uv_preview::test::with_features(preview_features);
            build_wheel(
                &sdist_top_level_directory,
                dist,
                None,
                MOCK_UV_VERSION,
                false,
            )?
        };
        let wheel_contents = wheel_contents(&dist.join(wheel_filename.to_string()));

        // Check that direct and indirect wheels are identical.
        assert_eq!(direct_wheel_filename, wheel_filename);
        assert_eq!(direct_wheel_contents, wheel_contents);
        assert_eq!(direct_wheel_list_files, wheel_list_files);
        assert_eq!(
            direct_wheel_hash,
            sha2::Sha256::digest(fs_err::read(dist.join(wheel_filename.to_string()))?)
        );

        Ok(BuildResults {
            source_dist_list_files,
            source_dist_filename,
            source_dist_contents,
            wheel_list_files,
            wheel_filename,
            wheel_contents,
        })
    }

    fn build_err(source_root: &Path) -> String {
        let dist = TempDir::new().unwrap();
        let build_err = build(source_root, dist.path(), &[]).unwrap_err();
        let err_message: String = format_err(&build_err)
            .replace(&source_root.user_display().to_string(), "[TEMP_PATH]")
            .replace('\\', "/");
        err_message
    }

    fn sdist_contents(source_dist_path: &Path) -> Vec<String> {
        let sdist_reader = BufReader::new(File::open(source_dist_path).unwrap());
        let mut source_dist = tar::Archive::new(GzDecoder::new(sdist_reader));
        let mut source_dist_contents: Vec<_> = source_dist
            .entries()
            .unwrap()
            .map(|entry| {
                entry
                    .unwrap()
                    .path()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .replace('\\', "/")
            })
            .collect();
        source_dist_contents.sort();
        source_dist_contents
    }

    fn wheel_contents(direct_output_dir: &Path) -> Vec<String> {
        let wheel = zip::ZipArchive::new(File::open(direct_output_dir).unwrap()).unwrap();
        let mut wheel_contents: Vec<_> = wheel
            .file_names()
            .map(|path| path.replace('\\', "/"))
            .collect();
        wheel_contents.sort_unstable();
        wheel_contents
    }

    fn format_file_list(file_list: FileList, src: &Path) -> String {
        file_list
            .into_iter()
            .map(|(path, source)| {
                let path = path.replace('\\', "/");
                if let Some(source) = source {
                    let source = relative_to(source, src)
                        .unwrap()
                        .portable_display()
                        .to_string();
                    format!("{path} ({source})")
                } else {
                    format!("{path} (generated)")
                }
            })
            .join("\n")
    }

    /// Tests that builds are stable and include the right files and.
    ///
    /// Tests that both source tree -> source dist -> wheel and source tree -> wheel include the
    /// right files. Also checks that the resulting archives are byte-by-byte identical
    /// independent of the build path or platform, with the caveat that we cannot serialize an
    /// executable bit on Window. This ensures reproducible builds and best-effort
    /// platform-independent deterministic builds.
    #[test]
    fn built_by_uv_building() {
        let built_by_uv = Path::new("../../test/packages/built-by-uv");
        let src = TempDir::new().unwrap();
        for dir in [
            "src",
            "tests",
            "data-dir",
            "third-party-licenses",
            "assets",
            "header",
            "scripts",
        ] {
            copy_dir_all(built_by_uv.join(dir), src.path().join(dir)).unwrap();
        }
        for filename in [
            "pyproject.toml",
            "README.md",
            "uv.lock",
            "LICENSE-APACHE",
            "LICENSE-MIT",
        ] {
            fs_err::copy(built_by_uv.join(filename), src.path().join(filename)).unwrap();
        }

        // Clear executable bit on Unix to build the same archive between Unix and Windows.
        // This is a caveat to the determinism of the uv build backend: When a file has the
        // executable in the source repository, it only has the executable bit on Unix, as Windows
        // does not have the concept of the executable bit.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let path = src.path().join("scripts").join("whoami.sh");
            let metadata = fs_err::metadata(&path).unwrap();
            let mut perms = metadata.permissions();
            perms.set_mode(perms.mode() & !0o111);
            fs_err::set_permissions(&path, perms).unwrap();
        }

        // Redact the uv_build version to keep the hash stable across releases
        let pyproject_toml = fs_err::read_to_string(src.path().join("pyproject.toml")).unwrap();
        let current_requires =
            Regex::new(r#"requires = \["uv_build>=[0-9.]+,<[0-9.]+"\]"#).unwrap();
        let mocked_requires = r#"requires = ["uv_build>=1,<2"]"#;
        let pyproject_toml = current_requires.replace(pyproject_toml.as_str(), mocked_requires);
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml.as_bytes()).unwrap();

        // Add some files to be excluded
        let module_root = src.path().join("src").join("built_by_uv");
        fs_err::create_dir_all(module_root.join("__pycache__")).unwrap();
        File::create(module_root.join("__pycache__").join("compiled.pyc")).unwrap();
        File::create(module_root.join("arithmetic").join("circle.pyc")).unwrap();

        // Perform both the direct and the indirect build.
        let dist = TempDir::new().unwrap();
        let build = build(src.path(), dist.path(), &[]).unwrap();

        let source_dist_path = dist.path().join(build.source_dist_filename.to_string());
        assert_eq!(
            build.source_dist_filename.to_string(),
            "built_by_uv-0.1.0.tar.gz"
        );
        // Check that the source dist is reproducible across platforms.
        assert_snapshot!(
            format!("{:x}", sha2::Sha256::digest(fs_err::read(&source_dist_path).unwrap())),
            @"8bed1f7a8059064bcbeedb61a867cca7f63a474306011d0114280de631ac705e"
        );
        // Check both the files we report and the actual files
        assert_snapshot!(format_file_list(build.source_dist_list_files, src.path()), @"
        built_by_uv-0.1.0/PKG-INFO (generated)
        built_by_uv-0.1.0/LICENSE-APACHE (LICENSE-APACHE)
        built_by_uv-0.1.0/LICENSE-MIT (LICENSE-MIT)
        built_by_uv-0.1.0/README.md (README.md)
        built_by_uv-0.1.0/assets/data.csv (assets/data.csv)
        built_by_uv-0.1.0/header/built_by_uv.h (header/built_by_uv.h)
        built_by_uv-0.1.0/pyproject.toml (pyproject.toml)
        built_by_uv-0.1.0/scripts/whoami.sh (scripts/whoami.sh)
        built_by_uv-0.1.0/src/built_by_uv/__init__.py (src/built_by_uv/__init__.py)
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/__init__.py (src/built_by_uv/arithmetic/__init__.py)
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/circle.py (src/built_by_uv/arithmetic/circle.py)
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/pi.txt (src/built_by_uv/arithmetic/pi.txt)
        built_by_uv-0.1.0/src/built_by_uv/build-only.h (src/built_by_uv/build-only.h)
        built_by_uv-0.1.0/src/built_by_uv/cli.py (src/built_by_uv/cli.py)
        built_by_uv-0.1.0/third-party-licenses/PEP-401.txt (third-party-licenses/PEP-401.txt)
        ");
        assert_snapshot!(build.source_dist_contents.iter().join("\n"), @"
        built_by_uv-0.1.0/
        built_by_uv-0.1.0/LICENSE-APACHE
        built_by_uv-0.1.0/LICENSE-MIT
        built_by_uv-0.1.0/PKG-INFO
        built_by_uv-0.1.0/README.md
        built_by_uv-0.1.0/assets
        built_by_uv-0.1.0/assets/data.csv
        built_by_uv-0.1.0/header
        built_by_uv-0.1.0/header/built_by_uv.h
        built_by_uv-0.1.0/pyproject.toml
        built_by_uv-0.1.0/scripts
        built_by_uv-0.1.0/scripts/whoami.sh
        built_by_uv-0.1.0/src
        built_by_uv-0.1.0/src/built_by_uv
        built_by_uv-0.1.0/src/built_by_uv/__init__.py
        built_by_uv-0.1.0/src/built_by_uv/arithmetic
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/__init__.py
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/circle.py
        built_by_uv-0.1.0/src/built_by_uv/arithmetic/pi.txt
        built_by_uv-0.1.0/src/built_by_uv/build-only.h
        built_by_uv-0.1.0/src/built_by_uv/cli.py
        built_by_uv-0.1.0/third-party-licenses
        built_by_uv-0.1.0/third-party-licenses/PEP-401.txt
        ");

        let wheel_path = dist.path().join(build.wheel_filename.to_string());
        assert_eq!(
            build.wheel_filename.to_string(),
            "built_by_uv-0.1.0-py3-none-any.whl"
        );
        // Check that the wheel is reproducible across platforms.
        assert_snapshot!(
            format!("{:x}", sha2::Sha256::digest(fs_err::read(&wheel_path).unwrap())),
            @"dbe56fd8bd52184095b2e0ea3e83c95d1bc8b4aa53cf469cec5af62251b24abb"
        );
        assert_snapshot!(build.wheel_contents.join("\n"), @"
        built_by_uv-0.1.0.data/data/
        built_by_uv-0.1.0.data/data/data.csv
        built_by_uv-0.1.0.data/headers/
        built_by_uv-0.1.0.data/headers/built_by_uv.h
        built_by_uv-0.1.0.data/scripts/
        built_by_uv-0.1.0.data/scripts/whoami.sh
        built_by_uv-0.1.0.dist-info/
        built_by_uv-0.1.0.dist-info/METADATA
        built_by_uv-0.1.0.dist-info/RECORD
        built_by_uv-0.1.0.dist-info/WHEEL
        built_by_uv-0.1.0.dist-info/entry_points.txt
        built_by_uv-0.1.0.dist-info/licenses/
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT
        built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/
        built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt
        built_by_uv/
        built_by_uv/__init__.py
        built_by_uv/arithmetic/
        built_by_uv/arithmetic/__init__.py
        built_by_uv/arithmetic/circle.py
        built_by_uv/arithmetic/pi.txt
        built_by_uv/cli.py
        ");
        assert_snapshot!(format_file_list(build.wheel_list_files, src.path()), @"
        built_by_uv/__init__.py (src/built_by_uv/__init__.py)
        built_by_uv/arithmetic/__init__.py (src/built_by_uv/arithmetic/__init__.py)
        built_by_uv/arithmetic/circle.py (src/built_by_uv/arithmetic/circle.py)
        built_by_uv/arithmetic/pi.txt (src/built_by_uv/arithmetic/pi.txt)
        built_by_uv/cli.py (src/built_by_uv/cli.py)
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE (LICENSE-APACHE)
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT (LICENSE-MIT)
        built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt (third-party-licenses/PEP-401.txt)
        built_by_uv-0.1.0.data/headers/built_by_uv.h (header/built_by_uv.h)
        built_by_uv-0.1.0.data/scripts/whoami.sh (scripts/whoami.sh)
        built_by_uv-0.1.0.data/data/data.csv (assets/data.csv)
        built_by_uv-0.1.0.dist-info/WHEEL (generated)
        built_by_uv-0.1.0.dist-info/entry_points.txt (generated)
        built_by_uv-0.1.0.dist-info/METADATA (generated)
        ");

        let mut wheel = zip::ZipArchive::new(File::open(wheel_path).unwrap()).unwrap();
        let mut record = String::new();
        wheel
            .by_name("built_by_uv-0.1.0.dist-info/RECORD")
            .unwrap()
            .read_to_string(&mut record)
            .unwrap();
        assert_snapshot!(record, @"
        built_by_uv/__init__.py,sha256=AJ7XpTNWxYktP97ydb81UpnNqoebH7K4sHRakAMQKG4,44
        built_by_uv/arithmetic/__init__.py,sha256=x2agwFbJAafc9Z6TdJ0K6b6bLMApQdvRSQjP4iy7IEI,67
        built_by_uv/arithmetic/circle.py,sha256=FYZkv6KwrF9nJcwGOKigjke1dm1Fkie7qW1lWJoh3AE,287
        built_by_uv/arithmetic/pi.txt,sha256=-4HqoLoIrSKGf0JdTrM8BTTiIz8rq-MSCDL6LeF0iuU,8
        built_by_uv/cli.py,sha256=Jcm3PxSb8wTAN3dGm5vKEDQwCgoUXkoeggZeF34QyKM,44
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
        built_by_uv-0.1.0.dist-info/licenses/LICENSE-MIT,sha256=F5Z0Cpu8QWyblXwXhrSo0b9WmYXQxd1LwLjVLJZwbiI,1077
        built_by_uv-0.1.0.dist-info/licenses/third-party-licenses/PEP-401.txt,sha256=KN-KAx829G2saLjVmByc08RFFtIDWvHulqPyD0qEBZI,270
        built_by_uv-0.1.0.data/headers/built_by_uv.h,sha256=p5-HBunJ1dY-xd4dMn03PnRClmGyRosScIp8rT46kg4,144
        built_by_uv-0.1.0.data/scripts/whoami.sh,sha256=T2cmhuDFuX-dTkiSkuAmNyIzvv8AKopjnuTCcr9o-eE,20
        built_by_uv-0.1.0.data/data/data.csv,sha256=7z7u-wXu7Qr2eBZFVpBILlNUiGSngv_1vYqZHVWOU94,265
        built_by_uv-0.1.0.dist-info/WHEEL,sha256=JBpLtoa_WBz5WPGpRsAUTD4Dz6H0KkkdiKWCkfMSS1U,84
        built_by_uv-0.1.0.dist-info/entry_points.txt,sha256=-IO6yaq6x6HSl-zWH96rZmgYvfyHlH00L5WQoCpz-YI,50
        built_by_uv-0.1.0.dist-info/METADATA,sha256=m6EkVvKrGmqx43b_VR45LHD37IZxPYC0NI6Qx9_UXLE,474
        built_by_uv-0.1.0.dist-info/RECORD,,
        ");
    }

    /// Test that `license = { file = "LICENSE" }` is supported.
    #[test]
    fn license_file_pre_pep639() {
        let src = TempDir::new().unwrap();
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
            [project]
            name = "pep-pep639-license"
            version = "1.0.0"
            license = { file = "license.txt" }

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
        "#
            },
        )
        .unwrap();
        fs_err::create_dir_all(src.path().join("src").join("pep_pep639_license")).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("pep_pep639_license")
                .join("__init__.py"),
        )
        .unwrap();
        fs_err::write(
            src.path().join("license.txt"),
            "Copy carefully.\nSincerely, the authors",
        )
        .unwrap();

        // Build a wheel from a source distribution
        let output_dir = TempDir::new().unwrap();
        build_source_dist(src.path(), output_dir.path(), "0.5.15", false).unwrap();
        let sdist_tree = TempDir::new().unwrap();
        let source_dist_path = output_dir.path().join("pep_pep639_license-1.0.0.tar.gz");
        let sdist_reader = BufReader::new(File::open(&source_dist_path).unwrap());
        let mut source_dist = tar::Archive::new(GzDecoder::new(sdist_reader));
        source_dist.unpack(sdist_tree.path()).unwrap();
        {
            let _preview = uv_preview::test::with_features(&[]);
            build_wheel(
                &sdist_tree.path().join("pep_pep639_license-1.0.0"),
                output_dir.path(),
                None,
                "0.5.15",
                false,
            )
            .unwrap();
        }
        let wheel = output_dir
            .path()
            .join("pep_pep639_license-1.0.0-py3-none-any.whl");
        let mut wheel = zip::ZipArchive::new(File::open(wheel).unwrap()).unwrap();

        let mut metadata = String::new();
        wheel
            .by_name("pep_pep639_license-1.0.0.dist-info/METADATA")
            .unwrap()
            .read_to_string(&mut metadata)
            .unwrap();

        assert_snapshot!(metadata, @"
        Metadata-Version: 2.3
        Name: pep-pep639-license
        Version: 1.0.0
        License: Copy carefully.
                 Sincerely, the authors
        ");
    }

    /// Test that `build_wheel` works after the `prepare_metadata_for_build_wheel` hook.
    #[test]
    fn prepare_metadata_then_build_wheel() {
        let src = TempDir::new().unwrap();
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
            [project]
            name = "two-step-build"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
        "#
            },
        )
        .unwrap();
        fs_err::create_dir_all(src.path().join("src").join("two_step_build")).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("two_step_build")
                .join("__init__.py"),
        )
        .unwrap();

        // Prepare the metadata.
        let metadata_dir = {
            let _preview = uv_preview::test::with_features(&[]);
            TempDir::new().unwrap()
        };
        let dist_info_dir = {
            let _preview = uv_preview::test::with_features(&[]);
            metadata(src.path(), metadata_dir.path(), "0.5.15").unwrap()
        };
        let metadata_prepared =
            fs_err::read_to_string(metadata_dir.path().join(&dist_info_dir).join("METADATA"))
                .unwrap();

        // Build the wheel, using the prepared metadata directory.
        let output_dir = TempDir::new().unwrap();
        {
            let _preview = uv_preview::test::with_features(&[]);
            build_wheel(
                src.path(),
                output_dir.path(),
                Some(&metadata_dir.path().join(&dist_info_dir)),
                "0.5.15",
                false,
            )
            .unwrap();
        }
        let wheel = output_dir
            .path()
            .join("two_step_build-1.0.0-py3-none-any.whl");
        let mut wheel = zip::ZipArchive::new(File::open(wheel).unwrap()).unwrap();

        let mut metadata_wheel = String::new();
        wheel
            .by_name("two_step_build-1.0.0.dist-info/METADATA")
            .unwrap()
            .read_to_string(&mut metadata_wheel)
            .unwrap();

        assert_eq!(metadata_prepared, metadata_wheel);

        assert_snapshot!(metadata_wheel, @"
        Metadata-Version: 2.3
        Name: two-step-build
        Version: 1.0.0
        ");
    }

    /// Check that non-normalized paths for `module-root` work with the glob inclusions.
    #[test]
    fn test_glob_path_normalization() {
        let src = TempDir::new().unwrap();
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
            [project]
            name = "two-step-build"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"

            [tool.uv.build-backend]
            module-root = "./"
            "#
            },
        )
        .unwrap();

        fs_err::create_dir_all(src.path().join("two_step_build")).unwrap();
        File::create(src.path().join("two_step_build").join("__init__.py")).unwrap();

        let dist = TempDir::new().unwrap();
        let build1 = build(src.path(), dist.path(), &[]).unwrap();

        assert_snapshot!(build1.source_dist_contents.join("\n"), @"
        two_step_build-1.0.0/
        two_step_build-1.0.0/PKG-INFO
        two_step_build-1.0.0/pyproject.toml
        two_step_build-1.0.0/two_step_build
        two_step_build-1.0.0/two_step_build/__init__.py
        ");

        assert_snapshot!(build1.wheel_contents.join("\n"), @"
        two_step_build-1.0.0.dist-info/
        two_step_build-1.0.0.dist-info/METADATA
        two_step_build-1.0.0.dist-info/RECORD
        two_step_build-1.0.0.dist-info/WHEEL
        two_step_build/
        two_step_build/__init__.py
        ");

        // A path with a parent reference.
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
            [project]
            name = "two-step-build"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"

            [tool.uv.build-backend]
            module-root = "two_step_build/.././"
            "#
            },
        )
        .unwrap();

        let dist = TempDir::new().unwrap();
        let build2 = build(src.path(), dist.path(), &[]).unwrap();
        assert_eq!(build1, build2);
    }

    /// Check that upper case letters in module names work.
    #[test]
    fn test_camel_case() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "camelcase"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"

            [tool.uv.build-backend]
            module-name = "camelCase"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();

        fs_err::create_dir_all(src.path().join("src").join("camelCase")).unwrap();
        File::create(src.path().join("src").join("camelCase").join("__init__.py")).unwrap();

        let dist = TempDir::new().unwrap();
        let build1 = build(src.path(), dist.path(), &[]).unwrap();

        assert_snapshot!(build1.wheel_contents.join("\n"), @"
        camelCase/
        camelCase/__init__.py
        camelcase-1.0.0.dist-info/
        camelcase-1.0.0.dist-info/METADATA
        camelcase-1.0.0.dist-info/RECORD
        camelcase-1.0.0.dist-info/WHEEL
        ");

        // Check that an explicit wrong casing fails to build.
        fs_err::write(
            src.path().join("pyproject.toml"),
            pyproject_toml.replace("camelCase", "camel_case"),
        )
        .unwrap();
        let build_err = build(src.path(), dist.path(), &[]).unwrap_err();
        let err_message = format_err(&build_err)
            .replace(&src.path().user_display().to_string(), "[TEMP_PATH]")
            .replace('\\', "/");
        assert_snapshot!(
            err_message,
            @"Expected a Python module at: [TEMP_PATH]/src/camel_case/__init__.py"
        );
    }

    /// Test that no partial files are left in dist directory when build fails.
    #[test]
    fn no_partial_files_on_build_failure() {
        let src = TempDir::new().unwrap();

        // Create a minimal pyproject.toml without __init__.py (will fail)
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
                [project]
                name = "failing-build"
                version = "1.0.0"

                [build-system]
                requires = ["uv_build>=0.5.15,<0.6.0"]
                build-backend = "uv_build"
            "#},
        )
        .unwrap();

        let dist = TempDir::new().unwrap();

        // Source dist build should fail
        let sdist_result = build_source_dist(src.path(), dist.path(), MOCK_UV_VERSION, false);
        assert!(sdist_result.is_err());

        // Wheel build should fail
        let wheel_result = {
            let _preview = uv_preview::test::with_features(&[]);
            build_wheel(src.path(), dist.path(), None, MOCK_UV_VERSION, false)
        };
        assert!(wheel_result.is_err());

        // dist directory should be empty (no partial files)
        let dist_contents: Vec<_> = fs_err::read_dir(dist.path()).unwrap().collect();
        assert!(
            dist_contents.is_empty(),
            "Expected empty dist directory, but found: {dist_contents:?}"
        );
    }

    /// Test that pre-existing files in the dist directory are deleted before build starts.
    #[test]
    fn existing_files_deleted_on_build_failure() {
        let src = TempDir::new().unwrap();

        // Create a minimal pyproject.toml without __init__.py (will fail)
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
                [project]
                name = "failing-build"
                version = "1.0.0"

                [build-system]
                requires = ["uv_build>=0.5.15,<0.6.0"]
                build-backend = "uv_build"
            "#},
        )
        .unwrap();

        let dist = TempDir::new().unwrap();

        // Create pre-existing files in dist directory
        let sdist_path = dist.path().join("failing_build-1.0.0.tar.gz");
        let wheel_path = dist.path().join("failing_build-1.0.0-py3-none-any.whl");
        let old_content = b"old content";
        fs_err::write(&sdist_path, old_content).unwrap();
        fs_err::write(&wheel_path, old_content).unwrap();

        // Build should fail and delete existing files
        let sdist_result = build_source_dist(src.path(), dist.path(), MOCK_UV_VERSION, false);
        assert!(sdist_result.is_err());

        let wheel_result = {
            let _preview = uv_preview::test::with_features(&[]);
            build_wheel(src.path(), dist.path(), None, MOCK_UV_VERSION, false)
        };
        assert!(wheel_result.is_err());

        // Verify pre-existing files were deleted
        assert!(
            !sdist_path.exists(),
            "Pre-existing sdist should have been deleted"
        );
        assert!(
            !wheel_path.exists(),
            "Pre-existing wheel should have been deleted"
        );
    }

    /// Test that existing files are overwritten on successful build.
    #[test]
    fn existing_files_overwritten_on_success() {
        let src = TempDir::new().unwrap();

        // Create a valid project
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
                [project]
                name = "overwrite-test"
                version = "1.0.0"

                [build-system]
                requires = ["uv_build>=0.5.15,<0.6.0"]
                build-backend = "uv_build"
            "#},
        )
        .unwrap();
        fs_err::create_dir_all(src.path().join("src").join("overwrite_test")).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("overwrite_test")
                .join("__init__.py"),
        )
        .unwrap();

        let dist = TempDir::new().unwrap();

        // Create pre-existing files in dist directory with known content
        let sdist_path = dist.path().join("overwrite_test-1.0.0.tar.gz");
        let wheel_path = dist.path().join("overwrite_test-1.0.0-py3-none-any.whl");
        let old_content = b"old content";
        fs_err::write(&sdist_path, old_content).unwrap();
        fs_err::write(&wheel_path, old_content).unwrap();

        // Build should succeed and overwrite existing files
        build_source_dist(src.path(), dist.path(), MOCK_UV_VERSION, false).unwrap();
        {
            let _preview = uv_preview::test::with_features(&[]);
            build_wheel(src.path(), dist.path(), None, MOCK_UV_VERSION, false).unwrap();
        }

        // Verify files were overwritten (content should be different)
        assert_ne!(
            &fs_err::read(&sdist_path).unwrap()[..],
            &old_content[..],
            "Source dist should have been overwritten"
        );
        assert_ne!(
            &fs_err::read(&wheel_path).unwrap()[..],
            &old_content[..],
            "Wheel should have been overwritten"
        );

        // Verify the new files are valid archives
        assert!(
            !sdist_contents(&sdist_path).is_empty(),
            "sdist should be a valid archive"
        );
        assert!(
            !wheel_contents(&wheel_path).is_empty(),
            "wheel should be a valid archive"
        );
    }

    #[test]
    fn invalid_stubs_name() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "camelcase"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"

            [tool.uv.build-backend]
            module-name = "django@home-stubs"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();

        let dist = TempDir::new().unwrap();
        let build_err = build(src.path(), dist.path(), &[]).unwrap_err();
        let err_message = format_err(&build_err);
        assert_snapshot!(
            err_message,
            @"
        Invalid module name: django@home-stubs
          Caused by: Invalid character `@` at position 7 for identifier `django@home`, expected an underscore or an alphanumeric character
        "
        );
    }

    /// Stubs packages use a special name and `__init__.pyi`.
    #[test]
    fn stubs_package() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "stuffed-bird-stubs"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(src.path().join("src").join("stuffed_bird-stubs")).unwrap();
        // That's the wrong file, we're expecting a `__init__.pyi`.
        let regular_init_py = src
            .path()
            .join("src")
            .join("stuffed_bird-stubs")
            .join("__init__.py");
        File::create(&regular_init_py).unwrap();

        let dist = TempDir::new().unwrap();
        let build_err = build(src.path(), dist.path(), &[]).unwrap_err();
        let err_message = format_err(&build_err)
            .replace(&src.path().user_display().to_string(), "[TEMP_PATH]")
            .replace('\\', "/");
        assert_snapshot!(
            err_message,
            @"Expected a Python module at: [TEMP_PATH]/src/stuffed_bird-stubs/__init__.pyi"
        );

        // Create the correct file
        fs_err::remove_file(regular_init_py).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("stuffed_bird-stubs")
                .join("__init__.pyi"),
        )
        .unwrap();

        let build1 = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build1.wheel_contents.join("\n"), @"
        stuffed_bird-stubs/
        stuffed_bird-stubs/__init__.pyi
        stuffed_bird_stubs-1.0.0.dist-info/
        stuffed_bird_stubs-1.0.0.dist-info/METADATA
        stuffed_bird_stubs-1.0.0.dist-info/RECORD
        stuffed_bird_stubs-1.0.0.dist-info/WHEEL
        ");

        // Check that setting the name manually works equally.
        let pyproject_toml = indoc! {r#"
            [project]
            name = "stuffed-bird-stubs"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"

            [tool.uv.build-backend]
            module-name = "stuffed_bird-stubs"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();

        let build2 = build(src.path(), dist.path(), &[]).unwrap();
        assert_eq!(build1.wheel_contents, build2.wheel_contents);
    }

    /// A simple namespace package with a single root `__init__.py`.
    #[test]
    fn simple_namespace_package() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "simple-namespace-part"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = "simple_namespace.part"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(src.path().join("src").join("simple_namespace").join("part"))
            .unwrap();

        assert_snapshot!(
            build_err(src.path()),
            @"Expected a Python module at: [TEMP_PATH]/src/simple_namespace/part/__init__.py"
        );

        // Create the correct file
        File::create(
            src.path()
                .join("src")
                .join("simple_namespace")
                .join("part")
                .join("__init__.py"),
        )
        .unwrap();

        // For a namespace package, there must not be an `__init__.py` here.
        let bogus_init_py = src
            .path()
            .join("src")
            .join("simple_namespace")
            .join("__init__.py");
        File::create(&bogus_init_py).unwrap();
        assert_snapshot!(
            build_err(src.path()),
            @"For namespace packages, `__init__.py[i]` is not allowed in parent directory: [TEMP_PATH]/src/simple_namespace"
        );
        fs_err::remove_file(bogus_init_py).unwrap();

        let dist = TempDir::new().unwrap();
        let build1 = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build1.source_dist_contents.join("\n"), @"
        simple_namespace_part-1.0.0/
        simple_namespace_part-1.0.0/PKG-INFO
        simple_namespace_part-1.0.0/pyproject.toml
        simple_namespace_part-1.0.0/src
        simple_namespace_part-1.0.0/src/simple_namespace
        simple_namespace_part-1.0.0/src/simple_namespace/part
        simple_namespace_part-1.0.0/src/simple_namespace/part/__init__.py
        ");
        assert_snapshot!(build1.wheel_contents.join("\n"), @"
        simple_namespace/
        simple_namespace/part/
        simple_namespace/part/__init__.py
        simple_namespace_part-1.0.0.dist-info/
        simple_namespace_part-1.0.0.dist-info/METADATA
        simple_namespace_part-1.0.0.dist-info/RECORD
        simple_namespace_part-1.0.0.dist-info/WHEEL
        ");

        // Check that `namespace = true` works too.
        let pyproject_toml = indoc! {r#"
            [project]
            name = "simple-namespace-part"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = "simple_namespace.part"
            namespace = true

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();

        let build2 = build(src.path(), dist.path(), &[]).unwrap();
        assert_eq!(build1, build2);
    }

    /// A complex namespace package with a multiple root `__init__.py`.
    #[test]
    fn complex_namespace_package() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "complex-namespace"
            version = "1.0.0"

            [tool.uv.build-backend]
            namespace = true

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(
            src.path()
                .join("src")
                .join("complex_namespace")
                .join("part_a"),
        )
        .unwrap();
        File::create(
            src.path()
                .join("src")
                .join("complex_namespace")
                .join("part_a")
                .join("__init__.py"),
        )
        .unwrap();
        fs_err::create_dir_all(
            src.path()
                .join("src")
                .join("complex_namespace")
                .join("part_b"),
        )
        .unwrap();
        File::create(
            src.path()
                .join("src")
                .join("complex_namespace")
                .join("part_b")
                .join("__init__.py"),
        )
        .unwrap();

        let dist = TempDir::new().unwrap();
        let build1 = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build1.wheel_contents.join("\n"), @"
        complex_namespace-1.0.0.dist-info/
        complex_namespace-1.0.0.dist-info/METADATA
        complex_namespace-1.0.0.dist-info/RECORD
        complex_namespace-1.0.0.dist-info/WHEEL
        complex_namespace/
        complex_namespace/part_a/
        complex_namespace/part_a/__init__.py
        complex_namespace/part_b/
        complex_namespace/part_b/__init__.py
        ");

        // Check that setting the name manually works equally.
        let pyproject_toml = indoc! {r#"
            [project]
            name = "complex-namespace"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = "complex_namespace"
            namespace = true

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();

        let build2 = build(src.path(), dist.path(), &[]).unwrap();
        assert_eq!(build1, build2);
    }

    /// Stubs for a namespace package.
    #[test]
    fn stubs_namespace() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "cloud.db.schema-stubs"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = "cloud-stubs.db.schema"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(
            src.path()
                .join("src")
                .join("cloud-stubs")
                .join("db")
                .join("schema"),
        )
        .unwrap();
        File::create(
            src.path()
                .join("src")
                .join("cloud-stubs")
                .join("db")
                .join("schema")
                .join("__init__.pyi"),
        )
        .unwrap();

        let dist = TempDir::new().unwrap();
        let build = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build.wheel_contents.join("\n"), @"
        cloud-stubs/
        cloud-stubs/db/
        cloud-stubs/db/schema/
        cloud-stubs/db/schema/__init__.pyi
        cloud_db_schema_stubs-1.0.0.dist-info/
        cloud_db_schema_stubs-1.0.0.dist-info/METADATA
        cloud_db_schema_stubs-1.0.0.dist-info/RECORD
        cloud_db_schema_stubs-1.0.0.dist-info/WHEEL
        ");
    }

    /// A package with multiple modules, one a regular module and two namespace modules.
    #[test]
    fn multiple_module_names() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "simple-namespace-part"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = ["foo", "simple_namespace.part_a", "simple_namespace.part_b"]

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(src.path().join("src").join("foo")).unwrap();
        fs_err::create_dir_all(
            src.path()
                .join("src")
                .join("simple_namespace")
                .join("part_a"),
        )
        .unwrap();
        fs_err::create_dir_all(
            src.path()
                .join("src")
                .join("simple_namespace")
                .join("part_b"),
        )
        .unwrap();

        // Most of these checks exist in other tests too, but we want to ensure that they apply
        // with multiple modules too.

        // The first module is missing an `__init__.py`.
        assert_snapshot!(
            build_err(src.path()),
            @"Expected a Python module at: [TEMP_PATH]/src/foo/__init__.py"
        );

        // Create the first correct `__init__.py` file
        File::create(src.path().join("src").join("foo").join("__init__.py")).unwrap();

        // The second module, a namespace, is missing an `__init__.py`.
        assert_snapshot!(
            build_err(src.path()),
            @"Expected a Python module at: [TEMP_PATH]/src/simple_namespace/part_a/__init__.py"
        );

        // Create the other two correct `__init__.py` files
        File::create(
            src.path()
                .join("src")
                .join("simple_namespace")
                .join("part_a")
                .join("__init__.py"),
        )
        .unwrap();
        File::create(
            src.path()
                .join("src")
                .join("simple_namespace")
                .join("part_b")
                .join("__init__.py"),
        )
        .unwrap();

        // For the second module, a namespace, there must not be an `__init__.py` here.
        let bogus_init_py = src
            .path()
            .join("src")
            .join("simple_namespace")
            .join("__init__.py");
        File::create(&bogus_init_py).unwrap();
        assert_snapshot!(
            build_err(src.path()),
            @"For namespace packages, `__init__.py[i]` is not allowed in parent directory: [TEMP_PATH]/src/simple_namespace"
        );
        fs_err::remove_file(bogus_init_py).unwrap();

        let dist = TempDir::new().unwrap();
        let build = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build.source_dist_contents.join("\n"), @"
        simple_namespace_part-1.0.0/
        simple_namespace_part-1.0.0/PKG-INFO
        simple_namespace_part-1.0.0/pyproject.toml
        simple_namespace_part-1.0.0/src
        simple_namespace_part-1.0.0/src/foo
        simple_namespace_part-1.0.0/src/foo/__init__.py
        simple_namespace_part-1.0.0/src/simple_namespace
        simple_namespace_part-1.0.0/src/simple_namespace/part_a
        simple_namespace_part-1.0.0/src/simple_namespace/part_a/__init__.py
        simple_namespace_part-1.0.0/src/simple_namespace/part_b
        simple_namespace_part-1.0.0/src/simple_namespace/part_b/__init__.py
        ");
        assert_snapshot!(build.wheel_contents.join("\n"), @"
        foo/
        foo/__init__.py
        simple_namespace/
        simple_namespace/part_a/
        simple_namespace/part_a/__init__.py
        simple_namespace/part_b/
        simple_namespace/part_b/__init__.py
        simple_namespace_part-1.0.0.dist-info/
        simple_namespace_part-1.0.0.dist-info/METADATA
        simple_namespace_part-1.0.0.dist-info/RECORD
        simple_namespace_part-1.0.0.dist-info/WHEEL
        ");
    }

    /// `prune_redundant_modules` should remove modules which are already
    /// included (either directly or via their parent)
    #[test]
    fn test_prune_redundant_modules() {
        fn check(input: &[&str], expect: &[&str]) {
            let input = input.iter().map(|s| (*s).to_string()).collect();
            let expect: Vec<_> = expect.iter().map(|s| (*s).to_string()).collect();
            assert_eq!(prune_redundant_modules(input), expect);
        }

        // Basic cases
        check(&[], &[]);
        check(&["foo"], &["foo"]);
        check(&["foo", "bar"], &["bar", "foo"]);

        // Deshadowing
        check(&["foo", "foo.bar"], &["foo"]);
        check(&["foo.bar", "foo"], &["foo"]);
        check(
            &["foo.bar.a", "foo.bar.b", "foo.bar", "foo", "foo.bar.a.c"],
            &["foo"],
        );
        check(
            &["bar.one", "bar.two", "baz", "bar", "baz.one"],
            &["bar", "baz"],
        );

        // Potential false positives
        check(&["foo", "foobar"], &["foo", "foobar"]);
        check(
            &["foo", "foobar", "foo.bar", "foobar.baz"],
            &["foo", "foobar"],
        );
        check(&["foo.bar", "foo.baz"], &["foo.bar", "foo.baz"]);
        check(&["foo", "foo", "foo.bar", "foo.bar"], &["foo"]);

        // Everything
        check(
            &[
                "foo.inner",
                "foo.inner.deeper",
                "foo",
                "bar",
                "bar.sub",
                "bar.sub.deep",
                "foobar",
                "baz.baz.bar",
                "baz.baz",
                "qux",
            ],
            &["bar", "baz.baz", "foo", "foobar", "qux"],
        );
    }

    /// A package with duplicate module names.
    #[test]
    fn duplicate_module_names() {
        let src = TempDir::new().unwrap();
        let pyproject_toml = indoc! {r#"
            [project]
            name = "duplicate"
            version = "1.0.0"

            [tool.uv.build-backend]
            module-name = ["foo", "foo", "bar.baz", "bar.baz.submodule"]

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
            "#
        };
        fs_err::write(src.path().join("pyproject.toml"), pyproject_toml).unwrap();
        fs_err::create_dir_all(src.path().join("src").join("foo")).unwrap();
        File::create(src.path().join("src").join("foo").join("__init__.py")).unwrap();
        fs_err::create_dir_all(src.path().join("src").join("bar").join("baz")).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("bar")
                .join("baz")
                .join("__init__.py"),
        )
        .unwrap();

        let dist = TempDir::new().unwrap();
        let build = build(src.path(), dist.path(), &[]).unwrap();
        assert_snapshot!(build.source_dist_contents.join("\n"), @"
        duplicate-1.0.0/
        duplicate-1.0.0/PKG-INFO
        duplicate-1.0.0/pyproject.toml
        duplicate-1.0.0/src
        duplicate-1.0.0/src/bar
        duplicate-1.0.0/src/bar/baz
        duplicate-1.0.0/src/bar/baz/__init__.py
        duplicate-1.0.0/src/foo
        duplicate-1.0.0/src/foo/__init__.py
        ");
        assert_snapshot!(build.wheel_contents.join("\n"), @"
        bar/
        bar/baz/
        bar/baz/__init__.py
        duplicate-1.0.0.dist-info/
        duplicate-1.0.0.dist-info/METADATA
        duplicate-1.0.0.dist-info/RECORD
        duplicate-1.0.0.dist-info/WHEEL
        foo/
        foo/__init__.py
        ");
    }

    /// Check that JSON metadata files are present.
    #[test]
    fn metadata_json_preview() {
        let src = TempDir::new().unwrap();
        fs_err::write(
            src.path().join("pyproject.toml"),
            indoc! {r#"
            [project]
            name = "metadata-json-preview"
            version = "1.0.0"

            [build-system]
            requires = ["uv_build>=0.5.15,<0.6.0"]
            build-backend = "uv_build"
        "#
            },
        )
        .unwrap();
        fs_err::create_dir_all(src.path().join("src").join("metadata_json_preview")).unwrap();
        File::create(
            src.path()
                .join("src")
                .join("metadata_json_preview")
                .join("__init__.py"),
        )
        .unwrap();

        let dist = TempDir::new().unwrap();
        let build = build(src.path(), dist.path(), &[PreviewFeature::MetadataJson]).unwrap();

        assert_snapshot!(build.wheel_contents.join("\n"), @"
        metadata_json_preview-1.0.0.dist-info/
        metadata_json_preview-1.0.0.dist-info/METADATA
        metadata_json_preview-1.0.0.dist-info/METADATA.json
        metadata_json_preview-1.0.0.dist-info/RECORD
        metadata_json_preview-1.0.0.dist-info/WHEEL
        metadata_json_preview-1.0.0.dist-info/WHEEL.json
        metadata_json_preview/
        metadata_json_preview/__init__.py
        ");
    }
}