ostrya 0.14.0

Pure-Rust async reimplementation of the ostree repository library
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
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
//! The directory primitives: the open and the create of a directory, the temp
//! directories, the listing, the removal of a tree, and the directory sync.
//!
//! Each open of a path below a [`RepoDir`] is one `openat2` with
//! `RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS`. The kernel refuses a symlink at each
//! component with `ELOOP`. Each primitive refuses a `..`, `.`, or empty
//! component, and an absolute path, before the call. The opens of a tree
//! removal also use `RESOLVE_NO_XDEV`, so the removal does not go into a
//! mount.
//!
//! A primitive that changes the names in a directory takes `fsync`. With
//! `fsync`, it syncs the directory that it changed with `fsync` before it
//! returns. A caller that changes the names in many directories keeps their
//! paths, and syncs each one at the end with [`RepoDir::sync_dir`].

use std::ffi::{CStr, OsStr};
use std::io;
use std::mem::MaybeUninit;
use std::ops::ControlFlow;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::sync::Arc;

use ostrya_core::RepoMode;
use rustix::fs::{AtFlags, FileType, Mode, OFlags, RawDir, ResolveFlags, StatxFlags};
use rustix::io::Errno;

use super::{DirPath, Entry, FsError, Reason, RepoContext, RepoDir, RepoLayout};

/// The flags of each directory open.
pub(super) const DIR_OPEN: OFlags = OFlags::RDONLY
    .union(OFlags::DIRECTORY)
    .union(OFlags::CLOEXEC);

/// The resolve flags of each open below a handle.
pub(super) const BENEATH: ResolveFlags = ResolveFlags::BENEATH.union(ResolveFlags::NO_SYMLINKS);

/// The resolve flags of each open of a tree removal. They are the flags of
/// [`BENEATH`] with `RESOLVE_NO_XDEV`, so the open of a mount point gives
/// `EXDEV`.
const BENEATH_SAME_MOUNT: ResolveFlags = BENEATH.union(ResolveFlags::NO_XDEV);

/// The size of the `getdents` buffer of a listing or a tree removal.
const LIST_BUF_LEN: usize = 32 * 1024;

/// The size of the stack buffer that joins the path of a nested handle. A
/// longer path costs one more allocation.
const JOIN_BUF_LEN: usize = 512;

/// The character set of the random suffix of a temp name (the alphabet of
/// `mkdtemp`).
const SUFFIX_ALPHABET: &[u8; 62] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

/// The length of the random suffix of a temp name.
pub(super) const SUFFIX_LEN: usize = 6;

/// The maximum number of names that the create of a temp directory, a temp
/// file, or a temp symlink tries.
pub(super) const TEMP_ATTEMPTS: u32 = 128;

/// The device and the inode of a directory.
type Identity = (u64, u64);

/// A directory on the path of a tree removal, from the top of the tree down
/// to the directory that the removal reads.
struct Level {
    /// The name of the directory in its parent.
    name: Vec<u8>,
    /// The device and inode of the directory. The removal reads them when it
    /// descends below the directory, and compares them when it goes up again.
    id: Option<Identity>,
    /// The names of the subdirectories that the removal did not remove yet.
    subdirs: Vec<Vec<u8>>,
}

/// The failure of the read of one directory in a tree removal: the errno, and
/// the name of the entry that failed, or `None` for the directory itself.
type ClearError = (Errno, Option<Vec<u8>>);

impl RepoDir {
    /// Opens the repository root at `path` relative to `base`, and returns a
    /// handle of kind [`RepoLayout::Root`] with no repository mode.
    ///
    /// The open is one `openat`. It follows a symlink at each component of
    /// `path`, because the caller names the root. An absolute `path` ignores
    /// `base`.
    ///
    /// `ENOENT` gives [`FsError::Absent`] and `ENOTDIR` gives
    /// [`Reason::NotDirectory`], each with `path` as the caller gives it. Each
    /// other errno gives [`FsError::Io`].
    pub(crate) fn open_root(base: impl AsFd, path: &Path) -> Result<RepoDir, FsError> {
        let fd = rustix::fs::openat(base, path, DIR_OPEN, Mode::empty())
            .map_err(|e| root_error(e, path))?;
        Ok(RepoDir::from_root_fd(fd))
    }

    /// Creates the repository root at `path` relative to `base` if it does
    /// not exist, opens it, and returns a handle of kind [`RepoLayout::Root`]
    /// with the repository mode `mode`.
    ///
    /// The `mkdirat` requests the directory mode of the root kind. In a
    /// `bare-user-shared` repository it requests the shared mode with no
    /// special bits, and an `fchmod` forces the shared mode when the function
    /// created the directory. If the `fchmod` fails, the function removes the
    /// directory that it created. An existing directory keeps its mode. The
    /// open and its errors are those of [`open_root`](RepoDir::open_root).
    ///
    /// With `fsync`, the function syncs the parent directory of a root that
    /// it created. It opens the parent with one `openat` of `..` relative to
    /// the new root, so the sync reaches the directory that holds the new
    /// entry, also when `path` passes through a symlink. An existing root
    /// syncs nothing. An error of the open or of the sync gives
    /// [`FsError::Io`], and the new root stays.
    pub(crate) fn create_root(
        base: impl AsFd,
        path: &Path,
        mode: RepoMode,
        fsync: bool,
    ) -> Result<RepoDir, FsError> {
        let base = base.as_fd();
        let (request, force) = dir_modes(
            Some(mode),
            RepoLayout::Root,
            RepoLayout::Root.rules().dir_mode,
        );
        let created = match rustix::fs::mkdirat(base, path, Mode::from_raw_mode(request)) {
            Ok(()) => true,
            Err(Errno::EXIST) => false,
            Err(e) => return Err(root_error(e, path)),
        };
        let root = RepoDir::open_root(base, path)?.with_repo_mode(mode);
        if let Some(force) = force.filter(|_| created) {
            force_new_dir_mode(base, path, root.as_fd(), force).map_err(io_error)?;
        }
        if created && fsync {
            let parent =
                rustix::fs::openat(&root, "..", DIR_OPEN, Mode::empty()).map_err(io_error)?;
            fsync_dir(parent.as_fd()).map_err(io_error)?;
        }
        Ok(root)
    }

    /// Opens the directory of the layout kind `kind` on the root handle, and
    /// returns a handle of that kind.
    ///
    /// The open is one `openat2` of the path of the kind. `kind` must be a kind
    /// with a fixed path, so not [`RepoLayout::Root`] and not
    /// [`RepoLayout::Staging`]. A call on a handle other than the root, or
    /// with such a kind, is a defect of the caller: it fails a debug assertion,
    /// and gives an `InvalidInput` error in a release build.
    pub(crate) fn open_layout(&self, kind: RepoLayout) -> Result<RepoDir, FsError> {
        let path = self.layout_path(kind)?;
        let fd = open_beneath(self.as_fd(), path).map_err(|e| FsError::at(e, path.to_owned()))?;
        Ok(self.handle(fd, kind, DirPath::Fixed(path)))
    }

    /// Opens the directory at `path` below this handle, and returns a handle
    /// of the same kind.
    ///
    /// `path` is relative to this directory. The open is one `openat2`. A
    /// symlink at a component gives [`Reason::Symlink`], a file at a
    /// component gives [`Reason::NotDirectory`], and a `..`, `.`, or empty
    /// component or an absolute path gives [`Reason::Escape`]. The path of an
    /// error is the full `path`, relative to the repository root.
    ///
    /// A call on the root handle is a defect of the caller, because the root
    /// has no kind for the directories below it. Use
    /// [`open_layout`](RepoDir::open_layout) there.
    pub(crate) fn open_dir(&self, path: &str) -> Result<RepoDir, FsError> {
        require(
            (self.kind != RepoLayout::Root).then_some(()),
            "open_dir needs a handle other than the root",
        )?;
        self.check_path(path)?;
        let fd =
            open_beneath(self.as_fd(), path).map_err(|e| FsError::at(e, self.err_path(path)))?;
        Ok(self.nested(fd, path))
    }

    /// Makes the directory of the layout kind `kind` and its initial children
    /// if they do not exist, and returns a handle of that kind. The call is on
    /// the root handle, and `kind` is a kind with a fixed path.
    ///
    /// The directory of the kind gets the directory mode of the kind, and each
    /// child in `init_children` gets the same mode. The function makes each
    /// child that is missing, also when the directory of the kind exists. One
    /// `statx` with no follow checks each child that exists: a symlink gives
    /// [`Reason::Symlink`], and an entry that is not a directory gives
    /// [`Reason::NotDirectory`].
    ///
    /// The rules of [`ensure_dir`](RepoDir::ensure_dir) for the shared mode
    /// apply to each new directory. With `fsync`, the function syncs the root
    /// when it makes the directory of the kind, and syncs the directory of the
    /// kind one time when it makes one or more children.
    pub(crate) fn ensure_layout(&self, kind: RepoLayout, fsync: bool) -> Result<RepoDir, FsError> {
        let path = self.layout_path(kind)?;
        let rules = kind.rules();
        let (request, force) = dir_modes(self.ctx.mode, kind, rules.dir_mode);
        let (fd, _) = ensure_component(self.as_fd(), path, request, force, fsync)
            .map_err(|e| FsError::at(e, path.to_owned()))?;
        let dir = self.handle(fd, kind, DirPath::Fixed(path));
        let mut made = false;
        for child in rules.init_children {
            made |= ensure_child(dir.as_fd(), child, request, force)
                .map_err(|e| FsError::at(e, dir.err_path(child)))?;
        }
        if made && fsync {
            fsync_dir(dir.as_fd()).map_err(io_error)?;
        }
        Ok(dir)
    }

    /// Makes the directory at `path` below this handle and each missing
    /// directory on the way, and returns a handle of the same kind.
    ///
    /// Each new directory gets the mode below the kind (`below_mode`). A call
    /// on a kind with no mode below is a defect of the caller.
    ///
    /// The function first opens the full path with one `openat2`. If a
    /// component is missing, it goes through the components. It opens each
    /// component before the first missing one. It makes the first missing
    /// component, each component below it, and the last component with
    /// `mkdirat`, and then opens each one. An entry that another process
    /// makes at the same time is used as it is. The path rules and the errors
    /// are those of [`open_dir`](RepoDir::open_dir). A file at a component,
    /// also at the last one, gives [`Reason::NotDirectory`]. An error in the
    /// walk gives the path up to the component that failed.
    ///
    /// In a `bare-user-shared` repository the `mkdirat` requests the shared
    /// mode of the kind with no special bits, and an `fchmod` forces the
    /// shared mode on each new directory. If the `fchmod` fails, the function
    /// removes that directory. An existing directory keeps its mode. Outside
    /// that mode, the umask reduces the mode of each new directory.
    ///
    /// With `fsync`, the function syncs the parent of each new directory at
    /// once. It syncs no other directory, so an existing path syncs nothing.
    pub(crate) fn ensure_dir(&self, path: &str, fsync: bool) -> Result<RepoDir, FsError> {
        let below = require(
            self.kind.rules().below_mode,
            "ensure_dir needs a kind with a mode below it",
        )?;
        self.check_path(path)?;
        match open_beneath(self.as_fd(), path) {
            Ok(fd) => return Ok(self.nested(fd, path)),
            Err(Errno::NOENT) => {}
            Err(e) => return Err(FsError::at(e, self.err_path(path))),
        }
        #[cfg(test)]
        run_hook(super::HookPoint::Walk, path.as_bytes());
        let (request, force) = dir_modes(self.ctx.mode, self.kind, below);
        let mut parent: Option<OwnedFd> = None;
        let mut made = false;
        let mut end = 0;
        let mut components = path.split('/').peekable();
        while let Some(component) = components.next() {
            end += component.len();
            let at = parent.as_ref().map_or(self.as_fd(), AsFd::as_fd);
            // The open before the first missing component found that a
            // component is missing. Below a new directory, and at the last
            // component, `mkdirat` comes first.
            let result = if made || components.peek().is_none() {
                make_component(at, component, request, force, fsync)
            } else {
                ensure_component(at, component, request, force, fsync)
            };
            let (fd, created) = result.map_err(|e| FsError::at(e, self.err_path(&path[..end])))?;
            made |= created;
            parent = Some(fd);
            end += 1;
        }
        let Some(fd) = parent else {
            unreachable!("a checked path has a component");
        };
        Ok(self.nested(fd, path))
    }

    /// Returns a handle of `tmp/`. The first call for a context makes `tmp/`
    /// and its initial children as [`ensure_layout`](RepoDir::ensure_layout)
    /// does, with `fsync`, and keeps the descriptor in the context. Each later
    /// call, from each handle of the context, gives a handle on the same
    /// descriptor and syncs nothing.
    pub(crate) fn tmp_dir(&self, fsync: bool) -> Result<RepoDir, FsError> {
        let fd = match self.ctx.tmp.get() {
            Some(fd) => Arc::clone(fd),
            None => {
                let root = RepoDir {
                    fd: Arc::clone(&self.ctx.root),
                    kind: RepoLayout::Root,
                    ctx: Arc::clone(&self.ctx),
                    path: DirPath::Fixed(""),
                };
                let tmp = root.ensure_layout(RepoLayout::Tmp, fsync)?;
                // A concurrent call can set the descriptor first. Its
                // descriptor is then the descriptor of the context.
                Arc::clone(self.ctx.tmp.get_or_init(|| tmp.fd))
            }
        };
        Ok(self.handle_on(fd, RepoLayout::Tmp, DirPath::Fixed("tmp")))
    }

    /// Makes a new directory with a unique name in this `tmp/` handle, and
    /// gives its name, a handle of kind [`RepoLayout::Staging`] on it, and the
    /// claim of the name.
    ///
    /// The name is `prefix` and a random suffix of six characters from
    /// `[A-Za-z0-9]`. Before the `mkdirat` of each name, the function calls
    /// `claim` with the name. `None` makes the function draw a new name. A
    /// name that exists also makes it draw a new name, and the claim of that
    /// name drops. The function tries 128 names at most, and then gives an
    /// `AlreadyExists` error.
    ///
    /// The `mkdirat` requests the directory mode of the staging kind. In a
    /// `bare-user-shared` repository it requests the shared mode with no
    /// special bits, and an `fchmod` forces the shared mode. If a step after
    /// the `mkdirat` fails, the function removes the new directory, then drops
    /// the claim, and gives the error of the step.
    ///
    /// The function syncs no directory. The sync of the file system at the
    /// commit of a transaction covers the content of a staging directory, and
    /// a staging directory that a crash loses does no harm.
    ///
    /// A call on a handle other than `tmp/` is a defect of the caller.
    pub(crate) fn make_temp_dir<G>(
        &self,
        prefix: &str,
        mut claim: impl FnMut(&str) -> Option<G>,
    ) -> Result<(String, RepoDir, G), FsError> {
        require(
            (self.kind == RepoLayout::Tmp).then_some(()),
            "make_temp_dir needs the tmp/ handle",
        )?;
        if prefix.contains('/') {
            return Err(FsError::Invalid {
                path: self.err_path(prefix),
                reason: Reason::Escape,
            });
        }
        let (request, force) = dir_modes(
            self.ctx.mode,
            RepoLayout::Staging,
            RepoLayout::Staging.rules().dir_mode,
        );
        let pid = std::process::id();
        for _ in 0..TEMP_ATTEMPTS {
            let mut name = String::with_capacity(prefix.len() + SUFFIX_LEN);
            name.push_str(prefix);
            push_random_suffix(&mut name, pid);
            let Some(guard) = claim(&name) else {
                continue;
            };
            match mkdir_temp(self.as_fd(), &name, request) {
                Ok(()) => {}
                Err(Errno::EXIST) => continue,
                Err(e) => return Err(FsError::at(e, self.err_path(&name))),
            }
            match open_temp_dir(self.as_fd(), &name, force) {
                Ok(fd) => {
                    let dir = self.handle(fd, RepoLayout::Staging, self.child_path(&name));
                    return Ok((name, dir, guard));
                }
                Err(e) => {
                    let _ = rustix::fs::unlinkat(self, name.as_str(), AtFlags::REMOVEDIR);
                    return Err(FsError::at(e, self.err_path(&name)));
                }
            }
        }
        Err(FsError::Io(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "could not allocate a unique temp directory",
        )))
    }

    /// Calls `visit` with the name and the type of each entry of the
    /// directory, with no `.` and no `..`, until `visit` gives
    /// [`ControlFlow::Break`].
    ///
    /// The function opens `.` of the directory again, so it needs search
    /// permission on the directory. A listing of a clone of the handle thus
    /// does not share the read position. It uses one `getdents` buffer of
    /// 32 KiB, and makes no allocation for each entry. A name stays as bytes,
    /// also a name that is not UTF-8. The type comes from `getdents`. For an
    /// entry of unknown type, one `statx` with no follow gives the type, and
    /// an entry that is gone at that `statx` is left out. A directory that is
    /// removed after its open gives no more entries.
    pub(crate) fn for_each_entry(
        &self,
        visit: impl FnMut(&CStr, FileType) -> ControlFlow<()>,
    ) -> Result<(), FsError> {
        reopen_and_visit(self.as_fd(), visit).map_err(|e| FsError::at(e, self.err_path("")))
    }

    /// Returns the entries of the directory, with no `.` and no `..`.
    ///
    /// The rules of [`for_each_entry`](RepoDir::for_each_entry) apply. The
    /// listing thus needs search permission on the directory.
    pub(crate) fn list(&self) -> Result<Vec<Entry>, FsError> {
        let mut entries = Vec::new();
        self.for_each_entry(|name, file_type| push_entry(&mut entries, name, file_type))?;
        Ok(entries)
    }

    /// Removes the directory `name` of this directory and each entry below
    /// it. It gives `true` if the directory existed.
    ///
    /// `name` is one component. A `..`, `.`, empty, or multi-component name
    /// gives [`Reason::Escape`]. A symlink at `name` gives
    /// [`Reason::Symlink`], and a file at `name` gives
    /// [`Reason::NotDirectory`]. Each of them stays. An absent `name` gives
    /// `false`.
    ///
    /// The removal follows no symlink. It reads each directory with one
    /// `getdents` buffer for all levels, unlinks each entry that is not a
    /// directory at once, and keeps the names of the subdirectories alone. It
    /// unlinks a symlink as a link, so the target stays. It removes a
    /// subdirectory that has no subdirectory of its own from the parent that
    /// it holds. It descends into each other subdirectory, and holds two
    /// directory descriptors of its own at most. It goes up with an open of
    /// `..`, and compares the device and inode of that directory with the
    /// parent that it left. A difference means that a directory moved during
    /// the removal: the removal stops with an error, and does not follow the
    /// directory. An entry that is gone before the removal gets to it is
    /// skipped.
    ///
    /// Each open of the removal uses `RESOLVE_NO_XDEV`, so the removal does
    /// not go into a mount. A mount on the directory `name` or on a directory
    /// below it gives [`Reason::Escape`] with the path of the mount point.
    /// The removal then stops. The mount point and its content stay. The
    /// entries that the removal did not get to yet also stay. The removal
    /// reads each directory before it descends, so the entries of the parent
    /// of the mount point that are not directories are already gone.
    ///
    /// With `fsync`, the function syncs this directory after it removes the
    /// directory `name`. It syncs nothing after an error.
    pub(crate) fn remove_tree(&self, name: &OsStr, fsync: bool) -> Result<bool, FsError> {
        let bytes = name.as_bytes();
        let err_path = || self.err_path(&String::from_utf8_lossy(bytes));
        if !is_component(bytes) {
            return Err(FsError::Invalid {
                path: err_path(),
                reason: Reason::Escape,
            });
        }
        let top = match open_same_mount(self.as_fd(), name) {
            Ok(fd) => fd,
            Err(Errno::NOENT) => return Ok(false),
            Err(e) => return Err(FsError::at(e, err_path())),
        };
        self.clear_tree(bytes, top)?;
        unlink_entry(self.as_fd(), name, AtFlags::REMOVEDIR)
            .map_err(|e| FsError::at(e, err_path()))?;
        if fsync {
            fsync_dir(self.as_fd()).map_err(io_error)?;
        }
        Ok(true)
    }

    /// Removes each entry below the directory `name`, open at `top`. The
    /// directory `name` stays.
    fn clear_tree(&self, name: &[u8], top: OwnedFd) -> Result<(), FsError> {
        let mut buf: Box<[MaybeUninit<u8>]> = Box::new_uninit_slice(LIST_BUF_LEN);
        let mut levels = vec![Level {
            name: name.to_vec(),
            id: None,
            subdirs: Vec::new(),
        }];
        clear_level(top.as_fd(), &mut buf, &mut levels[0].subdirs)
            .map_err(|e| self.clear_error(&levels, None, e))?;
        // The descriptor of the last level.
        let mut level_fd = top;

        loop {
            let Some(level) = levels.last_mut() else {
                unreachable!("a level is in hand within the loop");
            };
            let Some(child) = level.subdirs.pop() else {
                // The level is clear. Go up, and remove it.
                let Some(cleared) = levels.pop() else {
                    unreachable!("a level is in hand within the loop");
                };
                let Some(parent) = levels.last() else {
                    return Ok(());
                };
                // `..` is never a symlink. The device and inode check below
                // guards the open.
                let up = rustix::fs::openat(level_fd.as_fd(), c"..", DIR_OPEN, Mode::empty())
                    .map_err(|e| {
                        FsError::at(e, self.tree_path(&levels, &[cleared.name.as_slice()]))
                    })?;
                if Some(identity(up.as_fd())?) != parent.id {
                    return Err(FsError::Io(io::Error::other(
                        "a directory moved during the removal",
                    )));
                }
                level_fd = up;
                unlink_entry(
                    level_fd.as_fd(),
                    cleared.name.as_slice(),
                    AtFlags::REMOVEDIR,
                )
                .map_err(|e| FsError::at(e, self.tree_path(&levels, &[cleared.name.as_slice()])))?;
                continue;
            };
            let child_fd = match open_same_mount(level_fd.as_fd(), child.as_slice()) {
                Ok(fd) => fd,
                Err(Errno::NOENT) => continue,
                Err(e) => {
                    return Err(FsError::at(e, self.tree_path(&levels, &[child.as_slice()])));
                }
            };
            let mut subdirs = Vec::new();
            clear_level(child_fd.as_fd(), &mut buf, &mut subdirs)
                .map_err(|e| self.clear_error(&levels, Some(child.as_slice()), e))?;
            #[cfg(test)]
            run_hook(super::HookPoint::Descend, &child);
            if subdirs.is_empty() {
                drop(child_fd);
                unlink_entry(level_fd.as_fd(), child.as_slice(), AtFlags::REMOVEDIR)
                    .map_err(|e| FsError::at(e, self.tree_path(&levels, &[child.as_slice()])))?;
                continue;
            }
            // The removal descends, and drops the descriptor of this level.
            // The way up again compares the device and inode of `..` with this
            // level.
            if let Some(level) = levels.last_mut()
                && level.id.is_none()
            {
                level.id = Some(identity(level_fd.as_fd())?);
            }
            level_fd = child_fd;
            levels.push(Level {
                name: child,
                id: None,
                subdirs,
            });
        }
    }

    /// Syncs the directory at `path` below this handle with `fsync`.
    ///
    /// The open is one `openat2`. The path rules and the errors of the open
    /// are those of [`open_dir`](RepoDir::open_dir). An error of the `fsync`
    /// gives [`FsError::Io`]. The call is also correct on the root handle.
    pub(crate) fn sync_dir(&self, path: &str) -> Result<(), FsError> {
        self.check_path(path)?;
        let fd =
            open_beneath(self.as_fd(), path).map_err(|e| FsError::at(e, self.err_path(path)))?;
        fsync_dir(fd.as_fd()).map_err(io_error)
    }

    /// Syncs the directory of this handle with `fsync`. The call opens
    /// nothing. An error of the `fsync` gives [`FsError::Io`].
    pub(crate) fn sync(&self) -> Result<(), FsError> {
        fsync_dir(self.as_fd()).map_err(io_error)
    }

    /// Syncs the file system that holds the directory, with `syncfs`.
    pub(crate) fn syncfs(&self) -> Result<(), FsError> {
        rustix::fs::syncfs(self).map_err(io_error)
    }

    /// Returns the fixed path of `kind`, after the check that this is the root
    /// handle and that `kind` has a fixed path.
    fn layout_path(&self, kind: RepoLayout) -> Result<&'static str, FsError> {
        require(
            kind.rules().path.filter(|_| self.kind == RepoLayout::Root),
            "a layout kind opens on the root handle and has a fixed path",
        )
    }

    /// Refuses a `path` that is empty or absolute, or that has a `..`, `.`,
    /// or empty component, with [`Reason::Escape`].
    pub(super) fn check_path(&self, path: &str) -> Result<(), FsError> {
        if path.split('/').all(|c| is_component(c.as_bytes())) {
            return Ok(());
        }
        Err(FsError::Invalid {
            path: self.err_path(path),
            reason: Reason::Escape,
        })
    }

    /// Returns a handle of the kind `kind` on `fd`, in the context of this
    /// handle.
    fn handle(&self, fd: OwnedFd, kind: RepoLayout, path: DirPath) -> RepoDir {
        self.handle_on(Arc::new(fd), kind, path)
    }

    /// Returns a handle of the kind `kind` on the shared descriptor `fd`, in
    /// the context of this handle.
    fn handle_on(&self, fd: Arc<OwnedFd>, kind: RepoLayout, path: DirPath) -> RepoDir {
        RepoDir {
            fd,
            kind,
            ctx: Arc::clone(&self.ctx),
            path,
        }
    }

    /// Returns a handle of the same kind on `fd`, the directory at `path`
    /// below this handle.
    fn nested(&self, fd: OwnedFd, path: &str) -> RepoDir {
        self.handle(fd, self.kind, self.child_path(path))
    }

    /// Returns the path of the directory `rel` below this handle. The path
    /// costs one allocation, or two for a joined path longer than 512 bytes.
    fn child_path(&self, rel: &str) -> DirPath {
        match &self.path {
            DirPath::Fixed(base) => DirPath::Nested {
                base,
                rel: Arc::from(rel),
            },
            DirPath::Nested { base, rel: head } => DirPath::Nested {
                base,
                rel: join_arc(head, rel),
            },
        }
    }

    /// Returns the path of an error at `rel`, relative to this directory, as
    /// a path relative to the repository root. An empty `rel` gives the path
    /// of this directory. The root itself shows as `.`.
    pub(crate) fn err_path(&self, rel: &str) -> String {
        let (base, mid) = match &self.path {
            DirPath::Fixed(base) => (*base, ""),
            DirPath::Nested { base, rel } => (*base, &**rel),
        };
        let parts = [base, mid, rel];
        let mut path = String::with_capacity(parts.iter().map(|p| p.len() + 1).sum());
        for part in parts.into_iter().filter(|p| !p.is_empty()) {
            if !path.is_empty() {
                path.push('/');
            }
            path.push_str(part);
        }
        if path.is_empty() {
            path.push('.');
        }
        path
    }

    /// Returns the path of an error at the names `tail` below the last level
    /// of `levels`. The first level is a directory of this handle.
    fn tree_path(&self, levels: &[Level], tail: &[&[u8]]) -> String {
        let mut rel = String::new();
        for name in levels
            .iter()
            .map(|level| level.name.as_slice())
            .chain(tail.iter().copied())
        {
            if !rel.is_empty() {
                rel.push('/');
            }
            rel.push_str(&String::from_utf8_lossy(name));
        }
        self.err_path(&rel)
    }

    /// Returns the error of the read of a directory in a tree removal. The
    /// directory is `child` of the last level of `levels`, or the last level
    /// itself for `None`.
    fn clear_error(
        &self,
        levels: &[Level],
        child: Option<&[u8]>,
        (errno, entry): ClearError,
    ) -> FsError {
        let tail: Vec<&[u8]> = child.into_iter().chain(entry.as_deref()).collect();
        FsError::at(errno, self.tree_path(levels, &tail))
    }
}

impl RepoContext {
    /// Returns `true` if the repository mode is `bare-user-shared`.
    pub(super) fn is_shared(&self) -> bool {
        self.mode == Some(RepoMode::BareUserShared)
    }
}

/// Calls `visit` with the name and the type of each entry of the directory
/// open at `dir`, with no `.` and no `..`. The rules of
/// [`RepoDir::for_each_entry`] apply.
///
/// The function lists a directory that is not a handle of a repository, for
/// example a directory that a config names. It opens `.` of `dir` again, so
/// it needs search permission on the directory, and the read position of
/// `dir` does not change. Each error gives [`FsError::Io`].
pub(crate) fn for_each_entry_fd(
    dir: BorrowedFd<'_>,
    visit: impl FnMut(&CStr, FileType) -> ControlFlow<()>,
) -> Result<(), FsError> {
    reopen_and_visit(dir, visit).map_err(io_error)
}

/// Returns the entries of the directory open at `dir`, with no `.` and no
/// `..`. The rules of [`for_each_entry_fd`] apply. The listing thus needs
/// search permission on the directory.
pub(crate) fn list_fd(dir: BorrowedFd<'_>) -> Result<Vec<Entry>, FsError> {
    let mut entries = Vec::new();
    for_each_entry_fd(dir, |name, file_type| {
        push_entry(&mut entries, name, file_type)
    })?;
    Ok(entries)
}

/// Adds the entry `name` of type `file_type` to `entries`, and continues the
/// listing.
fn push_entry(entries: &mut Vec<Entry>, name: &CStr, file_type: FileType) -> ControlFlow<()> {
    entries.push(Entry {
        name: name.to_bytes().to_vec(),
        file_type,
    });
    ControlFlow::Continue(())
}

/// Opens `.` of `dir`, and calls `visit` with each entry of it.
fn reopen_and_visit(
    dir: BorrowedFd<'_>,
    mut visit: impl FnMut(&CStr, FileType) -> ControlFlow<()>,
) -> Result<(), Errno> {
    let fd = rustix::fs::openat(dir, c".", DIR_OPEN, Mode::empty())?;
    let mut buf: Box<[MaybeUninit<u8>]> = Box::new_uninit_slice(LIST_BUF_LEN);
    read_entries(fd.as_fd(), &mut buf, |name, file_type| {
        Ok(visit(name, file_type))
    })
}

/// Reads the directory open at `dir` from its read position, with `buf` as the
/// `getdents` buffer, and calls `visit` with the name and the type of each
/// entry until `visit` gives [`ControlFlow::Break`] or an error.
///
/// The function skips `.` and `..`. [`entry_type`] gives the type, and the
/// function skips an entry that is gone at its `statx`. `ENOENT` from
/// `getdents` means that the directory was removed after its open, and ends
/// the read.
fn read_entries(
    dir: BorrowedFd<'_>,
    buf: &mut [MaybeUninit<u8>],
    mut visit: impl FnMut(&CStr, FileType) -> Result<ControlFlow<()>, Errno>,
) -> Result<(), Errno> {
    #[cfg(test)]
    let unknown_type = super::FAULTS.with(|faults| faults.borrow().unknown_type);
    #[cfg(test)]
    run_hook(super::HookPoint::Getdents, b"");
    let mut raw = RawDir::new(dir, buf);
    while let Some(entry) = raw.next() {
        let entry = match entry {
            Ok(entry) => entry,
            Err(Errno::NOENT) => break,
            Err(e) => return Err(e),
        };
        let name = entry.file_name();
        if matches!(name.to_bytes(), b"." | b"..") {
            continue;
        }
        let d_type = entry.file_type();
        #[cfg(test)]
        let d_type = if unknown_type {
            FileType::Unknown
        } else {
            d_type
        };
        #[cfg(test)]
        run_hook(super::HookPoint::Entry, name.to_bytes());
        let Some(file_type) = entry_type(dir, name, d_type)? else {
            continue;
        };
        if visit(name, file_type)?.is_break() {
            break;
        }
    }
    Ok(())
}

/// Reads the directory open at `dir` in a tree removal. The function unlinks
/// each entry that is not a directory, and adds the name of each
/// subdirectory to `subdirs`.
///
/// An `unlinkat` with no flag removes a symlink itself, and never follows
/// it. An entry that is gone at its unlink is skipped.
fn clear_level(
    dir: BorrowedFd<'_>,
    buf: &mut [MaybeUninit<u8>],
    subdirs: &mut Vec<Vec<u8>>,
) -> Result<(), ClearError> {
    let mut failed = None;
    read_entries(dir, buf, |name, file_type| {
        if file_type == FileType::Directory {
            subdirs.push(name.to_bytes().to_vec());
        } else if let Err(e) = unlink_entry(dir, name, AtFlags::empty()) {
            failed = Some(name.to_bytes().to_vec());
            return Err(e);
        }
        Ok(ControlFlow::Continue(()))
    })
    .map_err(|e| (e, failed.take()))
}

/// Returns the type of the entry `name` of `dir`, with the type `d_type` from
/// `getdents`.
///
/// A known `d_type` is the type, with no syscall. For
/// [`FileType::Unknown`], one `statx` with no follow gives the type. `None`
/// means that the entry is gone.
fn entry_type(
    dir: BorrowedFd<'_>,
    name: &CStr,
    d_type: FileType,
) -> Result<Option<FileType>, Errno> {
    if d_type != FileType::Unknown {
        return Ok(Some(d_type));
    }
    match rustix::fs::statx(dir, name, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE) {
        Ok(stx) => Ok(Some(FileType::from_raw_mode(u32::from(stx.stx_mode)))),
        Err(Errno::NOENT) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Opens the directory `path` below `dir` with one `openat2`. The open
/// refuses a symlink at each component, and a path that leaves `dir`.
pub(super) fn open_beneath<P: rustix::path::Arg>(
    dir: BorrowedFd<'_>,
    path: P,
) -> Result<OwnedFd, Errno> {
    rustix::fs::openat2(dir, path, DIR_OPEN, Mode::empty(), BENEATH)
}

/// Opens the directory `path` below `dir` with one `openat2`, as
/// [`open_beneath`] does. The open also refuses a mount point at each
/// component with `EXDEV`.
fn open_same_mount<P: rustix::path::Arg>(dir: BorrowedFd<'_>, path: P) -> Result<OwnedFd, Errno> {
    rustix::fs::openat2(dir, path, DIR_OPEN, Mode::empty(), BENEATH_SAME_MOUNT)
}

/// Opens the directory `name` of `parent`, and makes it if it is missing. It
/// gives the descriptor and `true` if the function made the directory.
///
/// The function makes a missing directory as [`make_component`] does.
fn ensure_component(
    parent: BorrowedFd<'_>,
    name: &str,
    request: u32,
    force: Option<u32>,
    fsync: bool,
) -> Result<(OwnedFd, bool), Errno> {
    match open_beneath(parent, name) {
        Ok(fd) => Ok((fd, false)),
        Err(Errno::NOENT) => make_component(parent, name, request, force, fsync),
        Err(e) => Err(e),
    }
}

/// Makes the directory `name` of `parent` with the mode `request`, and opens
/// it. It gives the descriptor and `true` if the function made the
/// directory.
///
/// A directory that exists, also one that another process makes at the same
/// time, is used as it is. On a new directory, an `fchmod` sets the mode
/// `force`, and the function removes the directory if the `fchmod` fails.
/// With `fsync`, the function then syncs `parent`.
fn make_component(
    parent: BorrowedFd<'_>,
    name: &str,
    request: u32,
    force: Option<u32>,
    fsync: bool,
) -> Result<(OwnedFd, bool), Errno> {
    let created = match rustix::fs::mkdirat(parent, name, Mode::from_raw_mode(request)) {
        Ok(()) => true,
        Err(Errno::EXIST) => false,
        Err(e) => return Err(e),
    };
    let fd = open_beneath(parent, name)?;
    if created {
        if let Some(force) = force {
            force_new_dir_mode(parent, name, fd.as_fd(), force)?;
        }
        if fsync {
            fsync_dir(parent)?;
        }
    }
    Ok((fd, created))
}

/// Makes the initial child `name` of `parent` with the mode `request` if it is
/// missing. It gives `true` if the function made the directory.
///
/// One `statx` with no follow checks an existing child. The function opens
/// the child only to force the mode `force` on a directory that it made. If
/// the `fchmod` fails, the function removes the directory.
fn ensure_child(
    parent: BorrowedFd<'_>,
    name: &str,
    request: u32,
    force: Option<u32>,
) -> Result<bool, Errno> {
    match check_dir_entry(parent, name) {
        Ok(()) => return Ok(false),
        Err(Errno::NOENT) => {}
        Err(e) => return Err(e),
    }
    match rustix::fs::mkdirat(parent, name, Mode::from_raw_mode(request)) {
        Ok(()) => {}
        Err(Errno::EXIST) => return check_dir_entry(parent, name).map(|()| false),
        Err(e) => return Err(e),
    }
    if let Some(force) = force {
        let fd = open_beneath(parent, name)?;
        force_new_dir_mode(parent, name, fd.as_fd(), force)?;
    }
    Ok(true)
}

/// Checks the entry `name` of `parent` with one `statx` with no follow. A
/// directory gives `Ok`, a symlink gives `ELOOP`, and each other type gives
/// `ENOTDIR`.
fn check_dir_entry(parent: BorrowedFd<'_>, name: &str) -> Result<(), Errno> {
    let stx = rustix::fs::statx(parent, name, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE)?;
    match FileType::from_raw_mode(u32::from(stx.stx_mode)) {
        FileType::Directory => Ok(()),
        FileType::Symlink => Err(Errno::LOOP),
        _ => Err(Errno::NOTDIR),
    }
}

/// Forces the mode `force` on the new directory `name` of `parent`, open at
/// `fd`. If the `fchmod` fails, the function removes the directory, and gives
/// the error of the `fchmod`.
pub(super) fn force_new_dir_mode<P: rustix::path::Arg + Copy>(
    parent: BorrowedFd<'_>,
    name: P,
    fd: BorrowedFd<'_>,
    force: u32,
) -> Result<(), Errno> {
    fchmod_new(fd, force).inspect_err(|_| {
        let _ = rustix::fs::unlinkat(parent, name, AtFlags::REMOVEDIR);
    })
}

/// Sets the mode `force` on the new directory or the new file open at `fd`
/// with `fchmod`.
pub(super) fn fchmod_new(fd: BorrowedFd<'_>, force: u32) -> Result<(), Errno> {
    #[cfg(test)]
    fault_after_mkdir(super::FaultStep::Fchmod)?;
    rustix::fs::fchmod(fd, Mode::from_raw_mode(force))
}

/// Syncs the directory open at `fd` with `fsync`.
pub(super) fn fsync_dir(fd: BorrowedFd<'_>) -> Result<(), Errno> {
    #[cfg(test)]
    record_sync(fd);
    rustix::fs::fsync(fd)
}

/// Returns the mode that a `mkdirat` of a directory of `kind` requests, and
/// the mode that an `fchmod` forces after the create.
///
/// In a `bare-user-shared` repository the request is the shared mode of the
/// kind with no special bits, and the forced mode is the shared mode. In each
/// other mode, and with no mode, the request is `plain` and nothing is
/// forced.
fn dir_modes(mode: Option<RepoMode>, kind: RepoLayout, plain: u32) -> (u32, Option<u32>) {
    if mode == Some(RepoMode::BareUserShared) {
        let shared = kind.rules().shared_dir_mode;
        (shared & 0o777, Some(shared))
    } else {
        (plain, None)
    }
}

/// Makes the temp directory `name` of `tmp`.
fn mkdir_temp(tmp: BorrowedFd<'_>, name: &str, request: u32) -> Result<(), Errno> {
    #[cfg(test)]
    if super::FAULTS.with(|faults| faults.borrow().force_eexist) {
        return Err(Errno::EXIST);
    }
    rustix::fs::mkdirat(tmp, name, Mode::from_raw_mode(request))
}

/// Opens the new temp directory `name` of `tmp`, and forces the mode `force`
/// on it.
fn open_temp_dir(tmp: BorrowedFd<'_>, name: &str, force: Option<u32>) -> Result<OwnedFd, Errno> {
    #[cfg(test)]
    fault_after_mkdir(super::FaultStep::Open)?;
    let fd = open_beneath(tmp, name)?;
    if let Some(force) = force {
        fchmod_new(fd.as_fd(), force)?;
    }
    Ok(fd)
}

/// Gives the errno of a test fault at `step`.
#[cfg(test)]
pub(super) fn fault_after_mkdir(step: super::FaultStep) -> Result<(), Errno> {
    match super::FAULTS.with(|faults| faults.borrow().fail_after_mkdir) {
        Some((at, errno)) if at == step => Err(errno),
        _ => Ok(()),
    }
}

/// Runs the test hook at `point`, if the thread has one, with `name`.
#[cfg(test)]
pub(super) fn run_hook(point: super::HookPoint, name: &[u8]) {
    let taken = super::FAULTS.with(|faults| {
        let mut faults = faults.borrow_mut();
        let at = faults.hooks.iter().position(|(p, _)| *p == point)?;
        Some(faults.hooks.swap_remove(at))
    });
    if let Some((point, mut hook)) = taken {
        hook(name);
        super::FAULTS.with(|faults| faults.borrow_mut().hooks.push((point, hook)));
    }
}

/// Records the device and inode of the directory open at `fd`, if the test
/// records the syncs of its thread.
#[cfg(test)]
fn record_sync(fd: BorrowedFd<'_>) {
    super::FAULTS.with(|faults| {
        if let Some(synced) = faults.borrow_mut().synced.as_mut() {
            synced.push(identity(fd).expect("the identity of a synced directory"));
        }
    });
}

/// Appends a six-character `[A-Za-z0-9]` suffix to the temp name `name`, from
/// a seed of the time, the process id `pid`, and a counter of the process.
/// The temp name is the name of a temp directory, a temp file, or a temp
/// symlink.
///
/// The name must be unique on the host only. A collision causes a new attempt.
pub(super) fn push_random_suffix(name: &mut String, pid: u32) {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    let mut state = nanos ^ (u64::from(pid) << 32) ^ counter.wrapping_mul(0x9E37_79B9_7F4A_7C15);
    for _ in 0..SUFFIX_LEN {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        name.push(SUFFIX_ALPHABET[(state % 62) as usize] as char);
    }
}

/// Unlinks `name` of `dir` with `flags`. An entry that is already gone is a
/// success.
fn unlink_entry<P: rustix::path::Arg>(
    dir: BorrowedFd<'_>,
    name: P,
    flags: AtFlags,
) -> Result<(), Errno> {
    match rustix::fs::unlinkat(dir, name, flags) {
        Ok(()) | Err(Errno::NOENT) => Ok(()),
        Err(e) => Err(e),
    }
}

/// Returns `true` if `name` is one path component: not empty, not `.`, not
/// `..`, and with no `/`.
pub(super) fn is_component(name: &[u8]) -> bool {
    !matches!(name, b"" | b"." | b"..") && !name.contains(&b'/')
}

/// Returns `head/tail` with one allocation when the joined path fits in a
/// stack buffer of 512 bytes.
fn join_arc(head: &str, tail: &str) -> Arc<str> {
    let len = head.len() + 1 + tail.len();
    let mut buf = [0u8; JOIN_BUF_LEN];
    if let Some(out) = buf.get_mut(..len) {
        let (left, right) = out.split_at_mut(head.len());
        left.copy_from_slice(head.as_bytes());
        right[0] = b'/';
        right[1..].copy_from_slice(tail.as_bytes());
        // The join of two strings is UTF-8, so the check always passes.
        if let Ok(joined) = std::str::from_utf8(out) {
            return Arc::from(joined);
        }
    }
    Arc::from(format!("{head}/{tail}"))
}

/// Returns the device and inode of the directory open at `fd`, from one
/// `statx`.
fn identity(fd: BorrowedFd<'_>) -> Result<Identity, FsError> {
    let stx = rustix::fs::statx(fd, c"", AtFlags::EMPTY_PATH, StatxFlags::INO).map_err(io_error)?;
    Ok((
        rustix::fs::makedev(stx.stx_dev_major, stx.stx_dev_minor),
        stx.stx_ino,
    ))
}

/// Maps the error of the open or the create of the root, or of a path that a
/// caller or a config names, at `path`. The path of the error is `path` as
/// the caller gives it.
pub(super) fn root_error(errno: Errno, path: &Path) -> FsError {
    match errno {
        Errno::NOENT => FsError::Absent {
            path: path.display().to_string(),
        },
        Errno::NOTDIR => FsError::Invalid {
            path: path.display().to_string(),
            reason: Reason::NotDirectory,
        },
        other => io_error(other),
    }
}

/// Returns an errno as [`FsError::Io`].
pub(super) fn io_error(errno: Errno) -> FsError {
    FsError::Io(errno.into())
}

/// Gives the value of `value`, which a correct caller always supplies.
///
/// `None` is a defect of the caller, and `what` states the rule. It fails a
/// debug assertion, and gives an `InvalidInput` error in a release build.
pub(super) fn require<T>(value: Option<T>, what: &'static str) -> Result<T, FsError> {
    debug_assert!(value.is_some(), "{what}");
    value.ok_or_else(|| FsError::Io(io::Error::new(io::ErrorKind::InvalidInput, what)))
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::{PermissionsExt, symlink};
    use std::path::PathBuf;
    use std::rc::Rc;

    use super::super::{
        FaultStep, HookPoint, TestDir, id_of, invalid, io_err, is_symlink, mode_of, names_with,
        record_syncs, reference_mode, root, set_faults, set_hook, take_synced,
    };
    use super::*;

    fn set_mode(path: &Path, mode: u32) {
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
    }

    /// A claim of a temp directory name. Its drop records whether the
    /// directory existed at that time.
    #[derive(Debug)]
    struct Claim {
        path: PathBuf,
        existed_at_drop: Rc<Cell<Option<bool>>>,
    }

    impl Drop for Claim {
        fn drop(&mut self) {
            self.existed_at_drop.set(Some(self.path.exists()));
        }
    }

    #[test]
    fn open_layout_gives_symlink_for_a_symlinked_kind() {
        for dangling in [false, true] {
            let dir = TestDir::new("layout-link");
            std::fs::create_dir(dir.path().join("real")).unwrap();
            let target = if dangling { "nowhere" } else { "real" };
            symlink(target, dir.path().join("objects")).unwrap();
            let repo = root(&dir);
            let (path, reason) = invalid(repo.open_layout(RepoLayout::Objects));
            assert_eq!(path, "objects");
            assert!(matches!(reason, Reason::Symlink), "{reason:?}");
            let _reset = record_syncs();
            let (path, reason) = invalid(repo.ensure_layout(RepoLayout::Objects, true));
            assert_eq!(path, "objects");
            assert!(matches!(reason, Reason::Symlink), "{reason:?}");
            assert!(take_synced().is_empty());
            assert!(is_symlink(&dir.path().join("objects")));
        }
    }

    #[test]
    fn a_symlink_at_each_component_gives_symlink_with_the_full_path() {
        let components = ["a", "b", "c"];
        for at in 0..components.len() {
            for dangling in [false, true] {
                let dir = TestDir::new("component-link");
                let objects = dir.path().join("objects");
                std::fs::create_dir(&objects).unwrap();
                let mut path = objects.clone();
                for component in &components[..at] {
                    path.push(component);
                    std::fs::create_dir(&path).unwrap();
                }
                path.push(components[at]);
                // A real target holds the rest of the path, so a follow of
                // the link would succeed.
                let mut real = dir.path().join("real");
                std::fs::create_dir(&real).unwrap();
                for component in &components[at + 1..] {
                    real.push(component);
                    std::fs::create_dir(&real).unwrap();
                }
                let target = if dangling {
                    PathBuf::from("nowhere")
                } else {
                    dir.path().join("real")
                };
                symlink(&target, &path).unwrap();

                let objects_dir = root(&dir).open_layout(RepoLayout::Objects).unwrap();
                let case = format!("link at {at}, dangling {dangling}");
                let (err_path, reason) = invalid(objects_dir.open_dir("a/b/c"));
                assert_eq!(err_path, "objects/a/b/c", "{case}");
                assert!(matches!(reason, Reason::Symlink), "{case}: {reason:?}");
                let _reset = record_syncs();
                let (err_path, reason) = invalid(objects_dir.ensure_dir("a/b/c", true));
                assert_eq!(err_path, "objects/a/b/c", "{case}");
                assert!(matches!(reason, Reason::Symlink), "{case}: {reason:?}");
                assert!(take_synced().is_empty(), "{case}");
                let (err_path, reason) = invalid(objects_dir.sync_dir("a/b/c"));
                assert_eq!(err_path, "objects/a/b/c", "{case}");
                assert!(matches!(reason, Reason::Symlink), "{case}: {reason:?}");
                assert!(take_synced().is_empty(), "{case}");
                assert!(is_symlink(&path), "{case}");
            }
        }
    }

    #[test]
    fn a_dot_dot_an_absolute_path_or_an_empty_component_gives_escape() {
        let dir = TestDir::new("escape");
        std::fs::create_dir_all(dir.path().join("objects/a")).unwrap();
        let repo = root(&dir);
        let objects = repo.open_layout(RepoLayout::Objects).unwrap();
        let cases = [
            "..",
            "../x",
            "../objects",
            "a/../b",
            "a/..",
            "/etc",
            "/",
            "",
            "a//b",
            "./a",
            "a/.",
            "a/",
        ];
        let _reset = record_syncs();
        for path in cases {
            let (err_path, reason) = invalid(objects.open_dir(path));
            assert_eq!(err_path, objects.err_path(path), "{path}");
            assert!(matches!(reason, Reason::Escape), "{path}: {reason:?}");
            let (_, reason) = invalid(objects.ensure_dir(path, true));
            assert!(matches!(reason, Reason::Escape), "{path}: {reason:?}");
            let (err_path, reason) = invalid(objects.sync_dir(path));
            assert_eq!(err_path, objects.err_path(path), "{path}");
            assert!(matches!(reason, Reason::Escape), "{path}: {reason:?}");
            let (_, reason) = invalid(repo.sync_dir(path));
            assert!(matches!(reason, Reason::Escape), "{path}: {reason:?}");
        }
        assert!(take_synced().is_empty());
        assert_eq!(objects.err_path("../x"), "objects/../x");
        assert!(!dir.path().join("objects/b").exists());
        assert!(!dir.path().join("x").exists());
    }

    #[test]
    fn a_file_at_a_component_before_the_last_gives_not_directory() {
        let dir = TestDir::new("not-dir");
        std::fs::create_dir_all(dir.path().join("objects/a")).unwrap();
        std::fs::write(dir.path().join("objects/a/file"), b"x").unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        let (path, reason) = invalid(objects.open_dir("a/file/c"));
        assert_eq!(path, "objects/a/file/c");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        let _reset = record_syncs();
        let (path, reason) = invalid(objects.ensure_dir("a/file/c", true));
        assert_eq!(path, "objects/a/file/c");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        let (path, reason) = invalid(objects.sync_dir("a/file/c"));
        assert_eq!(path, "objects/a/file/c");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        assert!(take_synced().is_empty());
        assert_eq!(
            std::fs::read(dir.path().join("objects/a/file")).unwrap(),
            b"x"
        );
    }

    #[test]
    fn ensure_dir_at_a_file_gives_not_directory_and_at_a_directory_gives_it() {
        let dir = TestDir::new("ensure-existing");
        let a = dir.path().join("objects/a");
        std::fs::create_dir_all(a.join("d")).unwrap();
        set_mode(&a.join("d"), 0o700);
        std::fs::write(a.join("f"), b"x").unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        let _reset = record_syncs();

        let (path, reason) = invalid(objects.ensure_dir("a/f", true));
        assert_eq!(path, "objects/a/f");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        assert!(a.join("f").is_file());

        let d = objects.ensure_dir("a/d", true).unwrap();
        assert_eq!(identity(d.as_fd()).unwrap(), id_of(&a.join("d")));
        assert_eq!(d.kind(), RepoLayout::Objects);
        assert_eq!(d.err_path(""), "objects/a/d");
        assert!(take_synced().is_empty());
        assert_eq!(mode_of(&a.join("d")), 0o700);
    }

    #[test]
    fn ensure_dir_in_bare_user_shared_forces_the_shared_mode_on_new_directories_alone() {
        let dir = TestDir::new("ensure-shared");
        let heads = dir.path().join("refs/heads");
        std::fs::create_dir_all(&heads).unwrap();
        set_mode(&heads, 0o700);
        let repo = root(&dir).with_repo_mode(RepoMode::BareUserShared);
        let refs = repo.open_layout(RepoLayout::Refs).unwrap();
        let _reset = record_syncs();

        let y = refs.ensure_dir("heads/x/y", true).unwrap();
        assert_eq!(y.err_path(""), "refs/heads/x/y");
        assert_eq!(identity(y.as_fd()).unwrap(), id_of(&heads.join("x/y")));
        assert_eq!(mode_of(&heads), 0o700);
        assert_eq!(mode_of(&heads.join("x")), 0o2770);
        assert_eq!(mode_of(&heads.join("x/y")), 0o2770);
        assert_eq!(take_synced(), [id_of(&heads), id_of(&heads.join("x"))]);

        // An existing path syncs nothing.
        refs.ensure_dir("heads/x/y", true).unwrap();
        assert!(take_synced().is_empty());
    }

    #[test]
    fn ensure_dir_in_bare_user_requests_the_mode_below_the_kind() {
        let dir = TestDir::new("ensure-plain");
        let heads = dir.path().join("refs/heads");
        std::fs::create_dir_all(&heads).unwrap();
        let repo = root(&dir).with_repo_mode(RepoMode::BareUser);
        let refs = repo.open_layout(RepoLayout::Refs).unwrap();
        let _reset = record_syncs();

        refs.ensure_dir("heads/x/y", true).unwrap();
        assert_eq!(mode_of(&heads.join("x")), reference_mode(&heads, 0o777));
        let x = heads.join("x");
        assert_eq!(mode_of(&x.join("y")), reference_mode(&x, 0o777));
        assert_eq!(take_synced(), [id_of(&heads), id_of(&x)]);

        // With no `fsync`, a new path syncs nothing.
        refs.ensure_dir("heads/x/z/w", false).unwrap();
        assert!(x.join("z/w").is_dir());
        refs.ensure_dir("heads/v", false).unwrap();
        assert!(heads.join("v").is_dir());
        assert!(take_synced().is_empty());
    }

    #[test]
    fn ensure_dir_removes_a_new_directory_when_its_fchmod_fails() {
        let dir = TestDir::new("ensure-fchmod");
        let heads = dir.path().join("refs/heads");
        std::fs::create_dir_all(&heads).unwrap();
        let repo = root(&dir).with_repo_mode(RepoMode::BareUserShared);
        let refs = repo.open_layout(RepoLayout::Refs).unwrap();
        let _reset = set_faults(|f| f.fail_after_mkdir = Some((FaultStep::Fchmod, Errno::IO)));
        let _record = record_syncs();

        let err = io_err(refs.ensure_dir("heads/x/y", true));
        assert_eq!(err.raw_os_error(), Some(Errno::IO.raw_os_error()));
        assert!(!heads.join("x").exists());
        assert!(take_synced().is_empty());
    }

    #[test]
    fn ensure_dir_reports_an_error_of_the_walk_at_the_component_that_failed() {
        // Each case plants an entry after the first open of the full path,
        // so the walk meets it. The path names the component that failed.
        type Plant = fn(&Path);
        let symlink_to_real: Plant = |at| symlink("real", at).unwrap();
        let dangling: Plant = |at| symlink("nowhere", at).unwrap();
        let file: Plant = |at| std::fs::write(at, b"x").unwrap();
        let cases: [(&str, Plant, Reason); 6] = [
            // A component before the last: the walk opens it first.
            ("a/b", symlink_to_real, Reason::Symlink),
            ("a/b", dangling, Reason::Symlink),
            ("a/b", file, Reason::NotDirectory),
            // The last component: `mkdirat` gives `EEXIST`, and the open
            // gives the error.
            ("a", symlink_to_real, Reason::Symlink),
            ("a", dangling, Reason::Symlink),
            ("a", file, Reason::NotDirectory),
        ];
        for (path, plant, reason) in cases {
            let dir = TestDir::new("ensure-walk");
            let objects_path = dir.path().join("objects");
            std::fs::create_dir_all(objects_path.join("real")).unwrap();
            let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
            let at = objects_path.join("a");
            let planted = at.clone();
            let _reset = set_hook(HookPoint::Walk, move |_| plant(&planted));
            let _record = record_syncs();
            let (err_path, got) = invalid(objects.ensure_dir(path, true));
            let case = format!("{path} {reason:?}");
            assert_eq!(err_path, "objects/a", "{case}");
            assert_eq!(got.to_string(), reason.to_string(), "{case}");
            assert!(take_synced().is_empty(), "{case}");
            assert!(!objects_path.join("nowhere").exists(), "{case}");
            assert!(!objects_path.join("real/b").exists(), "{case}");
        }
    }

    #[test]
    fn ensure_layout_makes_the_kind_and_its_children() {
        for mode in [None, Some(RepoMode::BareUserShared)] {
            let dir = TestDir::new("ensure-layout");
            let mut repo = root(&dir);
            if let Some(mode) = mode {
                repo = repo.with_repo_mode(mode);
            }
            let _reset = record_syncs();
            let refs = repo.ensure_layout(RepoLayout::Refs, true).unwrap();
            assert_eq!(refs.kind(), RepoLayout::Refs);
            assert_eq!(refs.err_path(""), "refs");
            let path = dir.path().join("refs");
            assert_eq!(identity(refs.as_fd()).unwrap(), id_of(&path));
            let (kind_mode, child_mode) = match mode {
                Some(_) => (0o2770, 0o2770),
                None => (
                    reference_mode(dir.path(), 0o775),
                    reference_mode(&path, 0o775),
                ),
            };
            assert_eq!(mode_of(&path), kind_mode, "{mode:?}");
            for child in ["heads", "remotes", "mirrors"] {
                assert_eq!(mode_of(&path.join(child)), child_mode, "{child} {mode:?}");
            }
            assert_eq!(take_synced(), [id_of(dir.path()), id_of(&path)]);

            // A missing child is made also when the kind exists.
            std::fs::remove_dir(path.join("mirrors")).unwrap();
            repo.ensure_layout(RepoLayout::Refs, true).unwrap();
            assert_eq!(mode_of(&path.join("mirrors")), child_mode);
            assert_eq!(take_synced(), [id_of(&path)]);

            repo.ensure_layout(RepoLayout::Refs, true).unwrap();
            assert!(take_synced().is_empty());

            // With no `fsync`, a new child syncs nothing.
            std::fs::remove_dir(path.join("heads")).unwrap();
            repo.ensure_layout(RepoLayout::Refs, false).unwrap();
            assert!(path.join("heads").is_dir());
            assert!(take_synced().is_empty());
        }
    }

    #[test]
    fn ensure_layout_refuses_a_child_that_is_a_symlink_or_a_file() {
        let dir = TestDir::new("ensure-layout-child");
        let refs = dir.path().join("refs");
        std::fs::create_dir_all(refs.join("real")).unwrap();
        symlink("real", refs.join("heads")).unwrap();
        let repo = root(&dir);
        let (path, reason) = invalid(repo.ensure_layout(RepoLayout::Refs, true));
        assert_eq!(path, "refs/heads");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
        assert!(is_symlink(&refs.join("heads")));

        std::fs::remove_file(refs.join("heads")).unwrap();
        std::fs::write(refs.join("remotes"), b"x").unwrap();
        let (path, reason) = invalid(repo.ensure_layout(RepoLayout::Refs, true));
        assert_eq!(path, "refs/remotes");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        assert!(refs.join("remotes").is_file());
    }

    #[test]
    fn ensure_layout_removes_a_new_directory_when_its_fchmod_fails() {
        let dir = TestDir::new("layout-fchmod");
        let repo = root(&dir).with_repo_mode(RepoMode::BareUserShared);
        let _reset = set_faults(|f| f.fail_after_mkdir = Some((FaultStep::Fchmod, Errno::IO)));
        let _record = record_syncs();

        // The directory of the kind.
        let err = io_err(repo.ensure_layout(RepoLayout::Refs, true));
        assert_eq!(err.raw_os_error(), Some(Errno::IO.raw_os_error()));
        assert!(!dir.path().join("refs").exists());

        // An initial child.
        std::fs::create_dir(dir.path().join("refs")).unwrap();
        let err = io_err(repo.ensure_layout(RepoLayout::Refs, true));
        assert_eq!(err.raw_os_error(), Some(Errno::IO.raw_os_error()));
        assert_eq!(
            names_with(&dir.path().join("refs"), ""),
            Vec::<String>::new()
        );
        assert!(take_synced().is_empty());
    }

    #[test]
    fn sync_dir_syncs_the_directory_at_the_path() {
        let dir = TestDir::new("sync-dir");
        let ab = dir.path().join("objects/ab");
        std::fs::create_dir_all(&ab).unwrap();
        let repo = root(&dir);
        let objects = repo.open_layout(RepoLayout::Objects).unwrap();
        let _reset = record_syncs();
        objects.sync_dir("ab").unwrap();
        repo.sync_dir("objects/ab").unwrap();
        repo.sync_dir("objects").unwrap();
        assert_eq!(
            take_synced(),
            [id_of(&ab), id_of(&ab), id_of(&dir.path().join("objects"))]
        );
        match objects.sync_dir("cd") {
            Err(FsError::Absent { path }) => assert_eq!(path, "objects/cd"),
            other => panic!("{other:?}"),
        }
        assert!(take_synced().is_empty());
    }

    #[test]
    fn sync_syncs_the_directory_of_the_handle() {
        let dir = TestDir::new("sync-self");
        std::fs::create_dir(dir.path().join("objects")).unwrap();
        let repo = root(&dir);
        let objects = repo.open_layout(RepoLayout::Objects).unwrap();
        let _reset = record_syncs();
        repo.sync().unwrap();
        objects.sync().unwrap();
        assert_eq!(
            take_synced(),
            [id_of(dir.path()), id_of(&dir.path().join("objects"))]
        );
    }

    #[test]
    fn make_temp_dir_gives_a_staging_handle_with_a_unique_name() {
        for mode in [None, Some(RepoMode::BareUserShared)] {
            let dir = TestDir::new("temp-dir");
            let mut repo = root(&dir);
            if let Some(mode) = mode {
                repo = repo.with_repo_mode(mode);
            }
            let tmp = repo.tmp_dir(false).unwrap();
            let _reset = record_syncs();
            let (name, staging, ()) = tmp.make_temp_dir("staging-", |_| Some(())).unwrap();
            assert!(take_synced().is_empty());
            let suffix = name.strip_prefix("staging-").unwrap();
            assert_eq!(suffix.len(), SUFFIX_LEN, "{name}");
            assert!(
                suffix.bytes().all(|b| SUFFIX_ALPHABET.contains(&b)),
                "{name}"
            );
            assert_eq!(staging.kind(), RepoLayout::Staging);
            assert_eq!(staging.err_path(""), format!("tmp/{name}"));
            let tmp_path = dir.path().join("tmp");
            let path = tmp_path.join(&name);
            assert_eq!(identity(staging.as_fd()).unwrap(), id_of(&path));
            let expected = match mode {
                Some(_) => 0o2770,
                None => reference_mode(&tmp_path, 0o775),
            };
            assert_eq!(mode_of(&path), expected, "{mode:?}");
        }
    }

    #[test]
    fn make_temp_dir_removes_the_new_directory_when_a_later_step_fails() {
        let cases = [
            (None, FaultStep::Open),
            (Some(RepoMode::BareUserShared), FaultStep::Open),
            (Some(RepoMode::BareUserShared), FaultStep::Fchmod),
        ];
        for (mode, step) in cases {
            let dir = TestDir::new("temp-fault");
            let mut repo = root(&dir);
            if let Some(mode) = mode {
                repo = repo.with_repo_mode(mode);
            }
            let tmp = repo.tmp_dir(false).unwrap();
            let _reset = set_faults(|f| f.fail_after_mkdir = Some((step, Errno::IO)));
            let existed_at_drop = Rc::new(Cell::new(None));
            let tmp_path = dir.path().join("tmp");
            let result = tmp.make_temp_dir("pfx-", |name| {
                Some(Claim {
                    path: tmp_path.join(name),
                    existed_at_drop: Rc::clone(&existed_at_drop),
                })
            });
            let err = io_err(result);
            assert_eq!(
                err.raw_os_error(),
                Some(Errno::IO.raw_os_error()),
                "{step:?}"
            );
            assert_eq!(existed_at_drop.get(), Some(false), "{step:?}");
            assert!(names_with(&tmp_path, "pfx-").is_empty(), "{step:?}");
        }
    }

    #[test]
    fn make_temp_dir_gives_already_exists_after_128_names() {
        let dir = TestDir::new("temp-exhaust");
        let tmp = root(&dir).tmp_dir(false).unwrap();
        let _reset = set_faults(|f| f.force_eexist = true);
        let claims = Cell::new(0);
        let drops = Rc::new(Cell::new(None));
        let result = tmp.make_temp_dir("pfx-", |name| {
            claims.set(claims.get() + 1);
            Some(Claim {
                path: dir.path().join("tmp").join(name),
                existed_at_drop: Rc::clone(&drops),
            })
        });
        let err = io_err(result);
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(
            err.to_string(),
            "could not allocate a unique temp directory"
        );
        assert_eq!(claims.get(), TEMP_ATTEMPTS);
        assert_eq!(drops.get(), Some(false));
        assert!(names_with(&dir.path().join("tmp"), "pfx-").is_empty());
    }

    #[test]
    fn make_temp_dir_draws_a_new_name_when_the_claim_refuses() {
        let dir = TestDir::new("temp-claim");
        let tmp = root(&dir).tmp_dir(false).unwrap();
        let names = RefCell::new(Vec::new());
        let (name, _, guard) = tmp
            .make_temp_dir("pfx-", |name| {
                let mut names = names.borrow_mut();
                names.push(name.to_owned());
                (names.len() == 4).then_some(7u8)
            })
            .unwrap();
        let names = names.into_inner();
        assert_eq!(guard, 7);
        assert_eq!(names.len(), 4);
        assert_eq!(name, names[3]);
        let mut distinct = names.clone();
        distinct.sort();
        distinct.dedup();
        assert_eq!(distinct.len(), 4, "{names:?}");
        assert_eq!(names_with(&dir.path().join("tmp"), "pfx-"), [name]);
    }

    /// Makes one entry of each type, and a name that is not UTF-8.
    fn make_entries(dir: &TestDir) -> Vec<(Vec<u8>, FileType)> {
        std::fs::write(dir.path().join("file"), b"x").unwrap();
        std::fs::create_dir(dir.path().join("dir")).unwrap();
        symlink("dir", dir.path().join("link")).unwrap();
        rustix::fs::mknodat(
            dir.fd(),
            "fifo",
            FileType::Fifo,
            Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();
        rustix::fs::mknodat(
            dir.fd(),
            "sock",
            FileType::Socket,
            Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();
        let raw = OsStr::from_bytes(b"\xff\xfe");
        std::fs::write(dir.path().join(raw), b"y").unwrap();
        let mut expected = vec![
            (b"file".to_vec(), FileType::RegularFile),
            (b"dir".to_vec(), FileType::Directory),
            (b"link".to_vec(), FileType::Symlink),
            (b"fifo".to_vec(), FileType::Fifo),
            (b"sock".to_vec(), FileType::Socket),
            (b"\xff\xfe".to_vec(), FileType::RegularFile),
        ];
        expected.sort_by(|a, b| a.0.cmp(&b.0));
        expected
    }

    fn sorted(entries: Vec<Entry>) -> Vec<(Vec<u8>, FileType)> {
        let mut entries: Vec<_> = entries.into_iter().map(|e| (e.name, e.file_type)).collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        entries
    }

    #[test]
    fn list_skips_dot_entries_keeps_raw_names_and_types_each_entry() {
        let dir = TestDir::new("list");
        let expected = make_entries(&dir);
        let repo = root(&dir);
        assert_eq!(sorted(repo.list().unwrap()), expected);
        assert_eq!(sorted(repo.list().unwrap()), expected);
        let clone = repo.clone();
        assert_eq!(sorted(clone.list().unwrap()), expected);
        assert_eq!(sorted(repo.list().unwrap()), expected);
        assert_eq!(sorted(list_fd(dir.fd()).unwrap()), expected);
        assert_eq!(sorted(list_fd(dir.fd()).unwrap()), expected);
    }

    #[test]
    fn list_reads_a_directory_larger_than_one_buffer() {
        let dir = TestDir::new("list-large");
        let mut expected = Vec::new();
        for n in 0..1000 {
            let name = format!("{n:04}-{}", "x".repeat(100));
            std::fs::write(dir.path().join(&name), b"").unwrap();
            expected.push((name.into_bytes(), FileType::RegularFile));
        }
        expected.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(sorted(root(&dir).list().unwrap()), expected);
    }

    #[test]
    fn list_types_unknown_entries_and_leaves_out_an_entry_gone_at_its_statx() {
        let dir = TestDir::new("list-unknown");
        let expected = make_entries(&dir);
        let gone = dir.path().join("gone");
        std::fs::write(&gone, b"x").unwrap();
        let _reset = set_faults(|f| f.unknown_type = true);
        // `getdents` reads each entry of the small directory with its first
        // call, so the entry is in the buffer when the hook removes it.
        let _hook = set_hook(HookPoint::Entry, move |_| {
            let _ = std::fs::remove_file(&gone);
        });
        assert_eq!(sorted(root(&dir).list().unwrap()), expected);
        std::fs::write(dir.path().join("gone"), b"x").unwrap();
        assert_eq!(sorted(list_fd(dir.fd()).unwrap()), expected);
    }

    #[test]
    fn list_of_a_directory_removed_after_its_open_is_empty() {
        let dir = TestDir::new("list-removed");
        let ab = dir.path().join("objects/ab");
        std::fs::create_dir_all(&ab).unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        let handle = objects.open_dir("ab").unwrap();

        // `getdents` of a removed directory gives `ENOENT`.
        let removed = ab.clone();
        let _reset = set_hook(HookPoint::Getdents, move |_| {
            let _ = std::fs::remove_dir(&removed);
        });
        let mut buf: Box<[MaybeUninit<u8>]> = Box::new_uninit_slice(LIST_BUF_LEN);
        std::fs::remove_dir(&ab).unwrap();
        let mut raw = RawDir::new(handle.as_fd(), &mut buf);
        assert!(matches!(raw.next(), Some(Err(Errno::NOENT))));

        std::fs::create_dir(&ab).unwrap();
        let handle = objects.open_dir("ab").unwrap();
        assert!(handle.list().unwrap().is_empty());
        assert!(!ab.exists());
        std::fs::create_dir(&ab).unwrap();
        let fd = rustix::fs::open(&ab, DIR_OPEN, Mode::empty()).unwrap();
        assert!(list_fd(fd.as_fd()).unwrap().is_empty());
        assert!(!ab.exists());
    }

    #[test]
    fn for_each_entry_stops_when_the_visitor_breaks() {
        let dir = TestDir::new("visit-stop");
        for n in 0..5 {
            std::fs::write(dir.path().join(format!("f{n}")), b"").unwrap();
        }
        let repo = root(&dir);
        let mut seen = Vec::new();
        repo.for_each_entry(|name, file_type| {
            assert_eq!(file_type, FileType::RegularFile);
            seen.push(name.to_bytes().to_vec());
            if seen.len() == 2 {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        })
        .unwrap();
        assert_eq!(seen.len(), 2);

        let mut count = 0;
        for_each_entry_fd(dir.fd(), |_, _| {
            count += 1;
            ControlFlow::Break(())
        })
        .unwrap();
        assert_eq!(count, 1);

        let mut count = 0;
        repo.for_each_entry(|_, _| {
            count += 1;
            ControlFlow::Continue(())
        })
        .unwrap();
        assert_eq!(count, 5);
    }

    #[test]
    fn entry_type_types_an_unknown_entry_with_statx() {
        let dir = TestDir::new("entry-type");
        make_entries(&dir);
        let cases = [
            (c"file", FileType::RegularFile),
            (c"dir", FileType::Directory),
            (c"link", FileType::Symlink),
            (c"fifo", FileType::Fifo),
            (c"sock", FileType::Socket),
        ];
        for (name, file_type) in cases {
            assert_eq!(
                entry_type(dir.fd(), name, FileType::Unknown).unwrap(),
                Some(file_type),
                "{name:?}"
            );
        }
        assert_eq!(
            entry_type(dir.fd(), c"gone", FileType::Unknown).unwrap(),
            None
        );
        // A known type costs no syscall, so a gone entry keeps it.
        assert_eq!(
            entry_type(dir.fd(), c"gone", FileType::RegularFile).unwrap(),
            Some(FileType::RegularFile)
        );
    }

    #[test]
    fn remove_tree_unlinks_symlinks_and_keeps_their_targets() {
        for unknown_type in [false, true] {
            let dir = TestDir::new("remove-tree");
            let victim = dir.path().join("victim");
            std::fs::create_dir_all(victim.join("a/b/c")).unwrap();
            std::fs::create_dir(victim.join("empty")).unwrap();
            std::fs::write(victim.join("a/b/file"), b"x").unwrap();
            std::fs::write(victim.join("a/b/c/file"), b"x").unwrap();
            std::fs::write(victim.join("a").join(OsStr::from_bytes(b"\xff")), b"x").unwrap();
            let outside = dir.path().join("outside");
            std::fs::create_dir(&outside).unwrap();
            std::fs::write(outside.join("kept"), b"x").unwrap();
            symlink(&outside, victim.join("link")).unwrap();
            symlink(&outside, victim.join("a/b/c/dlink")).unwrap();
            symlink(outside.join("kept"), victim.join("a/flink")).unwrap();
            // A directory with no search permission and no entries goes too.
            std::fs::create_dir(victim.join("a/closed")).unwrap();
            set_mode(&victim.join("a/closed"), 0o400);

            let _reset = set_faults(|f| f.unknown_type = unknown_type);
            let _record = record_syncs();
            let repo = root(&dir);
            assert!(repo.remove_tree(OsStr::new("victim"), true).unwrap());
            assert!(!victim.exists(), "{unknown_type}");
            assert!(outside.join("kept").is_file(), "{unknown_type}");
            assert_eq!(take_synced(), [id_of(dir.path())], "{unknown_type}");
        }
    }

    #[test]
    fn remove_tree_with_no_fsync_syncs_nothing() {
        let dir = TestDir::new("remove-no-sync");
        std::fs::create_dir_all(dir.path().join("victim/a")).unwrap();
        let _record = record_syncs();
        assert!(root(&dir).remove_tree(OsStr::new("victim"), false).unwrap());
        assert!(!dir.path().join("victim").exists());
        assert!(take_synced().is_empty());
    }

    #[test]
    fn remove_tree_of_an_absent_name_gives_false() {
        let dir = TestDir::new("remove-absent");
        let _record = record_syncs();
        assert!(!root(&dir).remove_tree(OsStr::new("gone"), true).unwrap());
        assert!(take_synced().is_empty());
    }

    #[test]
    fn remove_tree_refuses_a_file_a_symlink_and_a_bad_name() {
        let dir = TestDir::new("remove-refuse");
        std::fs::create_dir(dir.path().join("objects")).unwrap();
        std::fs::write(dir.path().join("objects/file"), b"x").unwrap();
        std::fs::create_dir(dir.path().join("objects/target")).unwrap();
        symlink("target", dir.path().join("objects/link")).unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        let _record = record_syncs();

        let (path, reason) = invalid(objects.remove_tree(OsStr::new("file"), true));
        assert_eq!(path, "objects/file");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        let (path, reason) = invalid(objects.remove_tree(OsStr::new("link"), true));
        assert_eq!(path, "objects/link");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
        for name in ["", ".", "..", "target/x", "/target"] {
            let (_, reason) = invalid(objects.remove_tree(OsStr::new(name), true));
            assert!(matches!(reason, Reason::Escape), "{name}: {reason:?}");
        }
        assert!(take_synced().is_empty());
        assert!(dir.path().join("objects/file").is_file());
        assert!(is_symlink(&dir.path().join("objects/link")));
        assert!(dir.path().join("objects/target").is_dir());
    }

    #[test]
    fn remove_tree_stops_when_a_directory_moves() {
        let dir = TestDir::new("remove-moved");
        let victim = dir.path().join("victim");
        std::fs::create_dir_all(victim.join("a/b")).unwrap();
        std::fs::write(victim.join("a/b/file"), b"x").unwrap();
        let elsewhere = dir.path().join("elsewhere");
        let (from, to) = (victim.join("a"), elsewhere.clone());
        let _reset = set_hook(HookPoint::Descend, move |name| {
            if name == b"a" {
                std::fs::rename(&from, &to).unwrap();
                std::fs::write(to.join("planted"), b"p").unwrap();
            }
        });
        let _record = record_syncs();

        let err = io_err(root(&dir).remove_tree(OsStr::new("victim"), true));
        assert_eq!(err.to_string(), "a directory moved during the removal");
        assert!(take_synced().is_empty());
        assert!(victim.is_dir());
        assert!(elsewhere.is_dir());
        assert_eq!(std::fs::read(elsewhere.join("planted")).unwrap(), b"p");
    }

    /// The variable that holds the base directory of
    /// `remove_tree_stops_at_a_mount_point_and_keeps_it` in its child
    /// process.
    const MOUNT_BASE_VAR: &str = "OSTRYA_TEST_REMOVE_TREE_MOUNT_BASE";

    /// Mounts a tmpfs at `below/mnt` and at `top` of a base directory, and
    /// runs the removal in a child process in a new user and mount
    /// namespace. The test skips when the child cannot make the namespace or
    /// the mounts.
    #[test]
    fn remove_tree_stops_at_a_mount_point_and_keeps_it() {
        if let Some(base) = std::env::var_os(MOUNT_BASE_VAR) {
            let base = PathBuf::from(base);
            std::fs::write(base.join("below/mnt/inside"), b"x").unwrap();
            std::fs::write(base.join("top/inside"), b"x").unwrap();
            let repo = RepoDir::open_root(rustix::fs::CWD, &base).unwrap();

            let (path, reason) = invalid(repo.remove_tree(OsStr::new("below"), false));
            assert_eq!(path, "below/mnt");
            assert!(matches!(reason, Reason::Escape), "{reason:?}");
            assert!(base.join("below/mnt/inside").is_file());
            assert!(!base.join("below/file").exists());

            let (path, reason) = invalid(repo.remove_tree(OsStr::new("top"), false));
            assert_eq!(path, "top");
            assert!(matches!(reason, Reason::Escape), "{reason:?}");
            assert!(base.join("top/inside").is_file());
            std::fs::write(base.join("ran"), b"").unwrap();
            return;
        }

        let dir = TestDir::new("remove-mount");
        std::fs::create_dir_all(dir.path().join("below/mnt")).unwrap();
        std::fs::write(dir.path().join("below/file"), b"x").unwrap();
        std::fs::create_dir(dir.path().join("top")).unwrap();
        let module = module_path!().split_once("::").unwrap().1;
        let name = format!("{module}::remove_tree_stops_at_a_mount_point_and_keeps_it");
        let script = "mount -t tmpfs tmpfs \"$1/below/mnt\" && \
                      mount -t tmpfs tmpfs \"$1/top\" || exit 77; \
                      exec \"$2\" --exact \"$3\" --test-threads=1";
        let output = std::process::Command::new("unshare")
            .args(["--user", "--map-root-user", "--mount", "--", "sh", "-c"])
            .arg(script)
            .arg("sh")
            .arg(dir.path())
            .arg(std::env::current_exe().unwrap())
            .arg(&name)
            .env(MOUNT_BASE_VAR, dir.path())
            .output();
        let output = match output {
            Ok(output) => output,
            Err(e) => {
                eprintln!("skipped: unshare does not run: {e}");
                return;
            }
        };
        let log = || {
            format!(
                "{}{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            )
        };
        match output.status.code() {
            Some(0) => {}
            // libtest exits with 101 when a test fails.
            Some(101) | None => panic!("the child test failed: {}\n{}", output.status, log()),
            Some(_) => {
                eprintln!(
                    "skipped: no user and mount namespace with a tmpfs:\n{}",
                    log()
                );
                return;
            }
        }
        assert!(dir.path().join("ran").is_file(), "the child ran no test");
        assert!(dir.path().join("below/mnt").is_dir());
        assert!(dir.path().join("top").is_dir());
    }

    #[test]
    fn open_root_follows_a_symlink_and_maps_its_errors() {
        let dir = TestDir::new("open-root");
        std::fs::create_dir(dir.path().join("repo")).unwrap();
        symlink("repo", dir.path().join("link")).unwrap();
        std::fs::write(dir.path().join("file"), b"x").unwrap();

        let repo = RepoDir::open_root(dir.fd(), Path::new("link")).unwrap();
        assert_eq!(repo.kind(), RepoLayout::Root);
        assert_eq!(repo.repo_mode(), None);
        assert_eq!(
            identity(repo.as_fd()).unwrap(),
            id_of(&dir.path().join("repo"))
        );
        let repo = RepoDir::open_root(dir.fd(), &dir.path().join("repo")).unwrap();
        assert_eq!(
            identity(repo.as_fd()).unwrap(),
            id_of(&dir.path().join("repo"))
        );

        match RepoDir::open_root(dir.fd(), Path::new("missing/repo")) {
            Err(FsError::Absent { path }) => assert_eq!(path, "missing/repo"),
            other => panic!("{other:?}"),
        }
        let (path, reason) = invalid(RepoDir::open_root(dir.fd(), Path::new("file")));
        assert_eq!(path, "file");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
    }

    #[test]
    fn create_root_makes_the_root_with_its_mode() {
        let dir = TestDir::new("create-root");
        let repo =
            RepoDir::create_root(dir.fd(), Path::new("plain"), RepoMode::BareUser, false).unwrap();
        assert_eq!(repo.kind(), RepoLayout::Root);
        assert_eq!(repo.repo_mode(), Some(RepoMode::BareUser));
        assert_eq!(
            mode_of(&dir.path().join("plain")),
            reference_mode(dir.path(), 0o775)
        );

        let repo = RepoDir::create_root(
            dir.fd(),
            Path::new("shared"),
            RepoMode::BareUserShared,
            true,
        )
        .unwrap();
        assert_eq!(repo.repo_mode(), Some(RepoMode::BareUserShared));
        assert_eq!(mode_of(&dir.path().join("shared")), 0o2770);

        // An existing root keeps its mode.
        std::fs::create_dir(dir.path().join("old")).unwrap();
        set_mode(&dir.path().join("old"), 0o700);
        let repo = RepoDir::create_root(dir.fd(), Path::new("old"), RepoMode::BareUserShared, true)
            .unwrap();
        assert_eq!(
            identity(repo.as_fd()).unwrap(),
            id_of(&dir.path().join("old"))
        );
        assert_eq!(mode_of(&dir.path().join("old")), 0o700);

        match RepoDir::create_root(dir.fd(), Path::new("missing/repo"), RepoMode::Archive, true) {
            Err(FsError::Absent { path }) => assert_eq!(path, "missing/repo"),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn create_root_removes_the_new_root_when_its_fchmod_fails() {
        let dir = TestDir::new("create-root-fchmod");
        let _reset = set_faults(|f| f.fail_after_mkdir = Some((FaultStep::Fchmod, Errno::IO)));
        let err = io_err(RepoDir::create_root(
            dir.fd(),
            Path::new("shared"),
            RepoMode::BareUserShared,
            true,
        ));
        assert_eq!(err.raw_os_error(), Some(Errno::IO.raw_os_error()));
        assert!(!dir.path().join("shared").exists());
    }

    #[test]
    fn create_root_with_fsync_syncs_the_parent_of_a_new_root_alone() {
        let dir = TestDir::new("create-root-sync");
        std::fs::create_dir(dir.path().join("real")).unwrap();
        symlink("real", dir.path().join("link")).unwrap();
        let _reset = record_syncs();

        RepoDir::create_root(dir.fd(), Path::new("plain"), RepoMode::BareUser, true).unwrap();
        assert_eq!(take_synced(), [id_of(dir.path())]);
        RepoDir::create_root(dir.fd(), Path::new("link/repo"), RepoMode::Archive, true).unwrap();
        assert_eq!(take_synced(), [id_of(&dir.path().join("real"))]);

        // An existing root syncs nothing, and no fsync syncs nothing.
        RepoDir::create_root(dir.fd(), Path::new("plain"), RepoMode::BareUser, true).unwrap();
        RepoDir::create_root(dir.fd(), Path::new("quiet"), RepoMode::BareUser, false).unwrap();
        assert!(take_synced().is_empty());
        assert!(dir.path().join("quiet").is_dir());
    }

    #[test]
    fn a_nested_handle_keeps_its_kind_and_gives_the_full_path_in_an_error() {
        let dir = TestDir::new("nested");
        std::fs::create_dir_all(dir.path().join("objects/ab")).unwrap();
        let repo = root(&dir);
        assert_eq!(repo.err_path(""), ".");
        let objects = repo.open_layout(RepoLayout::Objects).unwrap();
        assert_eq!(objects.err_path(""), "objects");
        let ab = objects.open_dir("ab").unwrap();
        assert_eq!(ab.kind(), RepoLayout::Objects);
        assert_eq!(ab.err_path(""), "objects/ab");
        match ab.open_dir("cd") {
            Err(FsError::Absent { path }) => assert_eq!(path, "objects/ab/cd"),
            other => panic!("{other:?}"),
        }
        let _record = record_syncs();
        let ef = ab.ensure_dir("cd/ef", true).unwrap();
        assert_eq!(ef.kind(), RepoLayout::Objects);
        assert_eq!(ef.err_path(""), "objects/ab/cd/ef");
        assert_eq!(ef.err_path("gh"), "objects/ab/cd/ef/gh");
        assert_eq!(
            take_synced(),
            [
                id_of(&dir.path().join("objects/ab")),
                id_of(&dir.path().join("objects/ab/cd"))
            ]
        );
        assert_eq!(
            identity(ef.as_fd()).unwrap(),
            id_of(&dir.path().join("objects/ab/cd/ef"))
        );
    }

    #[test]
    fn a_nested_handle_keeps_a_long_path() {
        let dir = TestDir::new("nested-long");
        let names = ["a".repeat(250), "b".repeat(250), "c".repeat(250)];
        let mut path = dir.path().join("objects");
        for name in &names {
            path.push(name);
        }
        std::fs::create_dir_all(&path).unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        let a = objects.open_dir(&names[0]).unwrap();
        let ab = a.open_dir(&names[1]).unwrap();
        let abc = ab.open_dir(&names[2]).unwrap();
        assert_eq!(
            ab.err_path(""),
            format!("objects/{}/{}", names[0], names[1])
        );
        assert_eq!(
            abc.err_path("d"),
            format!("objects/{}/{}/{}/d", names[0], names[1], names[2])
        );
        assert_eq!(identity(abc.as_fd()).unwrap(), id_of(&path));
        assert_eq!(&*join_arc("x", "y"), "x/y");
    }

    #[test]
    fn syncfs_syncs_the_file_system_of_a_handle() {
        let dir = TestDir::new("syncfs");
        root(&dir).syncfs().unwrap();
    }

    #[test]
    fn tmp_dir_makes_tmp_once_for_each_context() {
        let dir = TestDir::new("tmp-once");
        std::fs::create_dir(dir.path().join("objects")).unwrap();
        let repo = root(&dir);
        let _record = record_syncs();
        let tmp = repo.tmp_dir(true).unwrap();
        assert_eq!(tmp.kind(), RepoLayout::Tmp);
        assert_eq!(tmp.err_path(""), "tmp");
        assert!(dir.path().join("tmp/cache").is_dir());
        assert_eq!(
            take_synced(),
            [id_of(dir.path()), id_of(&dir.path().join("tmp"))]
        );

        let again = repo.tmp_dir(true).unwrap();
        assert!(Arc::ptr_eq(&tmp.fd, &again.fd));
        let objects = repo.open_layout(RepoLayout::Objects).unwrap();
        let from_objects = objects.tmp_dir(true).unwrap();
        assert!(Arc::ptr_eq(&tmp.fd, &from_objects.fd));
        assert!(take_synced().is_empty());
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "open_dir needs a handle other than the root")]
    fn open_dir_on_the_root_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-open-dir");
        std::fs::create_dir(dir.path().join("objects")).unwrap();
        let _ = root(&dir).open_dir("objects");
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "a layout kind opens on the root handle and has a fixed path")]
    fn open_layout_of_staging_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-layout");
        let _ = root(&dir).open_layout(RepoLayout::Staging);
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "ensure_dir needs a kind with a mode below it")]
    fn ensure_dir_on_a_kind_with_no_mode_below_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-ensure");
        std::fs::create_dir(dir.path().join("state")).unwrap();
        let state = root(&dir).open_layout(RepoLayout::State).unwrap();
        let _ = state.ensure_dir("x", false);
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "make_temp_dir needs the tmp/ handle")]
    fn make_temp_dir_on_another_handle_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-temp");
        let _ = root(&dir).make_temp_dir("pfx-", |_| Some(()));
    }
}