fm84 0.27.0

A synthwave dual-pane TUI file manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
use crate::app::Item;
use crate::constants::COPY_CHUNK;
use crate::options::{Options, SortKey};
use crate::utils::format_size;
use std::env;
use std::ffi::OsString;
use std::fs::{self, File, create_dir, read_dir, remove_dir, remove_file, rename};
use std::io::{self, Error, ErrorKind, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

/// Permission bits as `ls -l` writes them. The mode comes from the metadata the
/// listing already holds, so this costs no extra syscall.
#[cfg(unix)]
fn format_attributes(metadata: &fs::Metadata, is_dir: bool, is_symlink: bool) -> String {
    use std::os::unix::fs::PermissionsExt;

    let mode = metadata.permissions().mode();
    let kind = if is_symlink {
        'l'
    } else if is_dir {
        'd'
    } else {
        '-'
    };

    // Each triplet's execute slot doubles as the setuid/setgid/sticky flag,
    // which would otherwise be invisible.
    let triplet = |shift: u32, special: u32, on: char| {
        let bits = mode >> shift;
        let execute = bits & 0o1 != 0;
        [
            if bits & 0o4 != 0 { 'r' } else { '-' },
            if bits & 0o2 != 0 { 'w' } else { '-' },
            match (mode & special != 0, execute) {
                (true, true) => on,
                (true, false) => on.to_ascii_uppercase(),
                (false, true) => 'x',
                (false, false) => '-',
            },
        ]
    };

    let mut text = String::with_capacity(10);
    text.push(kind);
    text.extend(triplet(6, 0o4000, 's'));
    text.extend(triplet(3, 0o2000, 's'));
    text.extend(triplet(0, 0o1000, 't'));
    text
}

#[cfg(windows)]
fn format_attributes(metadata: &fs::Metadata, _is_dir: bool, is_symlink: bool) -> String {
    use std::os::windows::fs::MetadataExt;

    const READONLY: u32 = 0x0000_0001;
    const HIDDEN: u32 = 0x0000_0002;
    const SYSTEM: u32 = 0x0000_0004;
    const DIRECTORY: u32 = 0x0000_0010;
    const ARCHIVE: u32 = 0x0000_0020;

    let flags = metadata.file_attributes();
    let flag = |bit: u32, on: char| if flags & bit != 0 { on } else { '-' };
    let kind = if is_symlink { 'l' } else { flag(DIRECTORY, 'd') };

    [kind, flag(ARCHIVE, 'a'), flag(READONLY, 'r'), flag(HIDDEN, 'h'), flag(SYSTEM, 's')].iter().collect()
}

#[cfg(not(any(unix, windows)))]
fn format_attributes(_metadata: &fs::Metadata, _is_dir: bool, _is_symlink: bool) -> String {
    String::new()
}

/// Hidden the way the platform means it: a leading dot, or on Windows the
/// hidden attribute, which is what Explorer goes by.
#[cfg(windows)]
pub fn is_hidden(_name: &str, metadata: Option<&fs::Metadata>) -> bool {
    use std::os::windows::fs::MetadataExt;
    const HIDDEN: u32 = 0x0000_0002;
    metadata.is_some_and(|metadata| metadata.file_attributes() & HIDDEN != 0)
}

#[cfg(not(windows))]
pub fn is_hidden(name: &str, _metadata: Option<&fs::Metadata>) -> bool {
    name.starts_with('.')
}

pub fn load_directory_rows(path: &Path, options: &Options) -> Result<Vec<Item>, Error> {
    let entries: Vec<_> = read_dir(path)?.filter_map(|entry| entry.ok()).collect();

    let has_parent = path.parent().is_some();
    let mut children = Vec::with_capacity(entries.len() + usize::from(has_parent));

    // Don't add ".." on root folder.
    if has_parent {
        children.push(Item {
            name_os: OsString::from(".."),
            name_full: "..".to_string(),
            name: "..".to_string(),
            extension: String::new(),
            is_dir: true,
            size: String::new(),
            size_bytes: 0,
            modified_at: None,
            attributes: String::new(),
        });
    }

    // One metadata() call per entry (one stat syscall), two for a symlink
    for entry in &entries {
        let entry_path = entry.path();
        // file_type() comes from readdir's d_type - no syscall on Linux.
        let is_symlink = entry.file_type().map(|file_type| file_type.is_symlink()).unwrap_or(false);
        // DirEntry::metadata() describes the link itself, which would list a link
        // to a directory as a file: sorted among the files, sized in bytes and
        // impossible to enter. Follow it, and fall back to the link when the
        // target is missing so a broken link still lists as an ordinary entry.
        let metadata = if is_symlink { fs::metadata(&entry_path).or_else(|_| entry.metadata()).ok() } else { entry.metadata().ok() };
        let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
        let name_os = entry.file_name();
        let name_full = name_os.to_string_lossy().into_owned();
        if !options.show_hidden && is_hidden(&name_full, metadata.as_ref()) {
            continue;
        }
        // Lossy like the name above, and for the same reason: a name that is
        // not valid UTF-8 still has to be shown as something. to_str() gave
        // None for those, which left the column blank.
        let name = if is_dir { name_full.clone() } else { entry_path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() };
        let extension = if is_dir { String::new() } else { entry_path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default() };
        let size_bytes = if is_dir { 0 } else { metadata.as_ref().map(|m| m.len()).unwrap_or(0) };
        let size = if is_dir { "<DIR>".to_string() } else { format_size(size_bytes) };
        // Written out when drawn, in whichever format F11 names - and a
        // relative date has to be, or it would go stale between reloads.
        let modified_at = metadata.as_ref().and_then(|m| m.modified().ok());

        let attributes = metadata.as_ref().map(|metadata| format_attributes(metadata, is_dir, is_symlink)).unwrap_or_default();

        children.push(Item {
            name_os,
            name_full,
            name,
            extension,
            is_dir,
            size,
            size_bytes,
            modified_at,
            attributes,
        });
    }

    // Sort items on already-computed fields (no stat syscalls during sort)
    let sort_start = usize::from(has_parent);
    children[sort_start..].sort_by(|a, b| compare_rows(a, b, options));

    Ok(children)
}

/// Directories before files whichever way the rest runs, unless F11 mixes
/// them in, then the chosen key, with the name settling ties so equal sizes or
/// dates still list steadily.
fn compare_rows(a: &Item, b: &Item, options: &Options) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    if options.dirs_first {
        match (a.is_dir, b.is_dir) {
            (true, false) => return Ordering::Less,
            (false, true) => return Ordering::Greater,
            _ => {}
        }
    }

    let text = |a: &str, b: &str| if options.case_sensitive { a.cmp(b) } else { a.to_lowercase().cmp(&b.to_lowercase()) };
    let name = || text(&a.name_full, &b.name_full);
    let order = match options.sort_key {
        SortKey::Name => name(),
        SortKey::Extension => text(&a.extension, &b.extension).then_with(name),
        SortKey::Size => a.size_bytes.cmp(&b.size_bytes).then_with(name),
        SortKey::Modified => a.modified_at.cmp(&b.modified_at).then_with(name),
    };
    if options.sort_descending { order.reverse() } else { order }
}

/// What kind of place a mount is, so the UI can pick an icon for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MountKind {
    Home,
    Disk,
    /// Detected on Linux and Windows; other platforms have no cheap way to tell.
    #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
    Removable,
    Network,
    #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
    Optical,
}

/// Somewhere a panel can jump to: a filesystem mount, or home.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mount {
    pub path: PathBuf,
    pub label: String,
    pub kind: MountKind,
}

/// Home, listed first after root because it is where people actually go.
fn home_mount() -> Option<Mount> {
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(Mount {
        path: PathBuf::from(home),
        label: "~".to_string(),
        kind: MountKind::Home,
    })
}

/// Mount points worth offering, root first, then home, then the rest by path.
#[cfg(target_os = "linux")]
pub fn list_mounts() -> Vec<Mount> {
    let mut mounts = vec![Mount {
        path: PathBuf::from("/"),
        label: "/".to_string(),
        kind: MountKind::Disk,
    }];
    mounts.extend(home_mount());
    if let Ok(table) = fs::read_to_string("/proc/mounts") {
        mounts.extend(parse_proc_mounts(&table));
    }
    mounts
}

/// Pick the interesting lines out of /proc/mounts. Filesystem type alone is not
/// enough to tell machinery from media: what separates them is being backed by
/// a real device, or being a fuse mount somewhere the user chose.
#[cfg(target_os = "linux")]
fn parse_proc_mounts(table: &str) -> Vec<Mount> {
    let mut found: Vec<Mount> = Vec::new();

    for line in table.lines() {
        let mut fields = line.split_whitespace();
        let (Some(source), Some(target), Some(fstype)) = (fields.next(), fields.next(), fields.next()) else {
            continue;
        };
        // /proc/mounts escapes spaces and tabs as octal.
        let target = target.replace("\\040", " ").replace("\\011", "\t");

        // Root is listed separately. The rest of these trees are machinery:
        // credentials, portals and gvfs under /run, and fusectl under /sys,
        // which a filesystem-type check alone would let through.
        const MACHINERY: [&str; 4] = ["/run", "/sys", "/proc", "/dev"];
        // One branch of /run is not machinery: udisks2 mounts removable media
        // under /run/media, which is where a stick plugged into a desktop
        // actually turns up. The trailing slash keeps it to that directory
        // rather than anything merely starting with the name.
        const REMOVABLE_MEDIA: &str = "/run/media/";
        let machinery = MACHINERY.iter().any(|prefix| target.starts_with(prefix)) && !target.starts_with(REMOVABLE_MEDIA);
        if target == "/" || machinery {
            continue;
        }

        let is_device = source.starts_with("/dev/");
        let is_fuse = fstype.starts_with("fuse");
        if !is_device && !is_fuse {
            continue;
        }

        let path = PathBuf::from(&target);
        if found.iter().any(|mount| mount.path == path) {
            continue;
        }
        let label = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_else(|| target.clone());
        found.push(Mount {
            path,
            label,
            kind: classify_mount(source, fstype, is_fuse),
        });
    }

    found.sort_by(|a, b| a.path.cmp(&b.path));
    found
}

/// Optical media announce themselves by filesystem type; removable media by a
/// flag the kernel exposes for the block device underneath.
#[cfg(target_os = "linux")]
fn classify_mount(source: &str, fstype: &str, is_fuse: bool) -> MountKind {
    if matches!(fstype, "iso9660" | "udf") {
        return MountKind::Optical;
    }
    if is_fuse {
        return MountKind::Network;
    }
    if is_removable(source) {
        return MountKind::Removable;
    }
    MountKind::Disk
}

#[cfg(target_os = "linux")]
fn is_removable(source: &str) -> bool {
    let Some(device) = source.strip_prefix("/dev/") else {
        return false;
    };
    // A whole device has its own /sys/block entry; a partition has to be
    // reduced to the device it sits on.
    for candidate in [device, base_device(device)] {
        if let Ok(flag) = fs::read_to_string(format!("/sys/block/{candidate}/removable")) {
            return flag.trim() == "1";
        }
    }
    false
}

/// The whole-disk name behind a partition. NVMe and SD cards separate the
/// partition number with a 'p'; everything else just appends it.
#[cfg(target_os = "linux")]
fn base_device(name: &str) -> &str {
    if let Some(index) = name.rfind('p') {
        let (head, tail) = name.split_at(index);
        let digits = &tail[1..];
        if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) && head.bytes().last().is_some_and(|byte| byte.is_ascii_digit()) {
            return head;
        }
    }
    name.trim_end_matches(|c: char| c.is_ascii_digit())
}

#[cfg(all(test, target_os = "linux"))]
mod mount_tests {
    use super::{MountKind, parse_proc_mounts};

    /// Verbatim lines from a real /proc/mounts, machinery and media mixed.
    const TABLE: &str = "\
devtmpfs /dev devtmpfs rw,nosuid 0 0
run /run tmpfs rw,nosuid 0 0
/dev/nvme0n1p4 / ext4 rw,relatime 0 0
tmpfs /dev/shm tmpfs rw,nosuid 0 0
/dev/nvme0n1p3 /tmp ext4 rw,relatime 0 0
/dev/nvme0n1p5 /mnt/laserbeak ext4 rw,relatime 0 0
/dev/sda1 /mnt/grimlock ext4 rw,relatime 0 0
/dev/nvme0n1p2 /boot vfat rw,relatime 0 0
none /run/credentials/getty@tty1.service tmpfs ro 0 0
tmpfs /run/user/1000 tmpfs rw,nosuid 0 0
pcloud: /mnt/pcloud fuse.rclone rw,nosuid 0 0
portal /run/user/1000/doc fuse.portal rw,nosuid 0 0
gvfsd-fuse /run/user/1000/gvfs fuse.gvfsd-fuse rw,nosuid 0 0
fusectl /sys/fs/fuse/connections fusectl rw,nosuid 0 0
/dev/sdb1 /media/My\\040Backup ext4 rw,relatime 0 0
/dev/sr0 /run/media/colt/AUDIO iso9660 ro,nosuid 0 0
/dev/sdb1 /run/media/colt/ravage ntfs3 rw,nosuid 0 0
/dev/sdc1 /media/stick vfat rw,nosuid 0 0";

    #[test]
    fn keeps_media_and_drops_machinery() {
        let mounts = parse_proc_mounts(TABLE);
        let paths: Vec<String> = mounts.iter().map(|m| m.path.display().to_string()).collect();

        assert_eq!(
            paths,
            ["/boot", "/media/My Backup", "/media/stick", "/mnt/grimlock", "/mnt/laserbeak", "/mnt/pcloud", "/run/media/colt/AUDIO", "/run/media/colt/ravage", "/tmp",],
            "should keep device-backed and user fuse mounts, sorted"
        );

        // The rest of /run is still machinery: the portal and gvfs are fuse
        // mounts, which the check below this would otherwise wave through.
        assert!(!paths.iter().any(|path| path.starts_with("/run/user")));

        // Root is added by the caller, not here.
        assert!(!paths.iter().any(|p| p == "/"));
        // fusectl matches a bare "fuse" prefix but is machinery, not media.
        assert!(!paths.iter().any(|p| p.starts_with("/sys")));
        // A fuse mount the user chose is network-ish; a partition is a disk.
        let pcloud = mounts.iter().find(|m| m.label == "pcloud").unwrap();
        assert_eq!(pcloud.kind, MountKind::Network);
        let boot = mounts.iter().find(|m| m.label == "boot").unwrap();
        assert_eq!(boot.kind, MountKind::Disk);
        // Octal escapes are decoded for display.
        assert!(mounts.iter().any(|m| m.label == "My Backup"));
    }

    #[test]
    fn optical_filesystems_are_recognised() {
        assert_eq!(super::classify_mount("/dev/sr0", "iso9660", false), MountKind::Optical);
        assert_eq!(super::classify_mount("/dev/sr0", "udf", false), MountKind::Optical);
        assert_eq!(super::classify_mount("pcloud:", "fuse.rclone", true), MountKind::Network);
    }

    #[test]
    fn partitions_reduce_to_their_whole_device() {
        assert_eq!(super::base_device("sda1"), "sda");
        assert_eq!(super::base_device("sda"), "sda");
        assert_eq!(super::base_device("nvme0n1p5"), "nvme0n1");
        assert_eq!(super::base_device("mmcblk0p1"), "mmcblk0");
        // 'p' only splits when a digit precedes it, so sdp1 is not sd.
        assert_eq!(super::base_device("sdp1"), "sdp");
    }
}

/// Every mounted volume on macOS shows up under /Volumes.
#[cfg(target_vendor = "apple")]
pub fn list_mounts() -> Vec<Mount> {
    let mut mounts = vec![Mount {
        path: PathBuf::from("/"),
        label: "/".to_string(),
        kind: MountKind::Disk,
    }];
    mounts.extend(home_mount());

    let Ok(entries) = read_dir("/Volumes") else {
        return mounts;
    };
    let mut found: Vec<Mount> = entries
        .flatten()
        .map(|entry| Mount {
            label: entry.file_name().to_string_lossy().into_owned(),
            path: entry.path(),
            kind: MountKind::Disk,
        })
        .collect();

    found.sort_by(|a, b| a.path.cmp(&b.path));
    mounts.extend(found);
    mounts
}

#[cfg(windows)]
pub fn list_mounts() -> Vec<Mount> {
    // Declared here rather than pulling in windows-sys, as elsewhere.
    unsafe extern "system" {
        fn GetLogicalDrives() -> u32;
        fn GetDriveTypeW(root: *const u16) -> u32;
    }
    const DRIVE_REMOVABLE: u32 = 2;
    const DRIVE_FIXED: u32 = 3;
    const DRIVE_REMOTE: u32 = 4;
    const DRIVE_CDROM: u32 = 5;

    // SAFETY: no arguments, and the bitmask is just read back.
    let mask = unsafe { GetLogicalDrives() };
    let mut mounts = Vec::new();
    mounts.extend(home_mount());

    for letter in 0..26u32 {
        if mask & (1 << letter) == 0 {
            continue;
        }
        let root = format!("{}:\\", (b'A' + letter as u8) as char);
        let wide: Vec<u16> = root.encode_utf16().chain(std::iter::once(0)).collect();
        // SAFETY: wide is NUL-terminated and outlives the call.
        let kind = match unsafe { GetDriveTypeW(wide.as_ptr()) } {
            DRIVE_REMOVABLE => MountKind::Removable,
            DRIVE_REMOTE => MountKind::Network,
            DRIVE_CDROM => MountKind::Optical,
            DRIVE_FIXED => MountKind::Disk,
            _ => continue,
        };
        mounts.push(Mount {
            path: PathBuf::from(&root),
            label: root[..2].to_string(),
            kind,
        });
    }
    mounts
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple", windows)))]
pub fn list_mounts() -> Vec<Mount> {
    home_mount().into_iter().collect()
}

/// Walk up from `path` until a directory that still exists is found. A panel's
/// directory can be removed underneath it - and so can several of its parents,
/// if something deleted a whole tree - so this climbs until it lands somewhere
/// listable. None only if even the root is unreachable.
pub fn nearest_existing_dir(path: &Path) -> Option<PathBuf> {
    let mut candidate = Some(path);
    while let Some(dir) = candidate {
        if dir.is_dir() {
            return Some(dir.to_path_buf());
        }
        candidate = dir.parent();
    }
    None
}

/// Bytes used and total for the filesystem holding `path`, as `df` counts them.
/// None when the platform call fails, so a dead network mount shows nothing
/// rather than an error.
#[cfg(all(unix, not(target_vendor = "apple")))]
pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let c_path = CString::new(path.as_os_str().as_bytes()).ok()?;
    // SAFETY: c_path is a valid NUL-terminated string and stats is only read
    // back after statvfs reports success.
    let stats = unsafe {
        let mut stats = std::mem::zeroed::<libc::statvfs>();
        if libc::statvfs(c_path.as_ptr(), &mut stats) != 0 {
            return None;
        }
        stats
    };

    let block = stats.f_frsize as u64;
    let total = (stats.f_blocks as u64).checked_mul(block)?;
    let free = (stats.f_bfree as u64).checked_mul(block)?;
    Some((total.saturating_sub(free), total))
}

/// Apple platforms declare statvfs block counts as a 32-bit fsblkcnt_t, so it
/// truncates past about 16 TiB. Their native statfs carries the counts as u64.
#[cfg(target_vendor = "apple")]
pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let c_path = CString::new(path.as_os_str().as_bytes()).ok()?;
    // SAFETY: c_path is a valid NUL-terminated string and stats is only read
    // back after statfs reports success.
    let stats = unsafe {
        let mut stats = std::mem::zeroed::<libc::statfs>();
        if libc::statfs(c_path.as_ptr(), &mut stats) != 0 {
            return None;
        }
        stats
    };

    let block = stats.f_bsize as u64;
    let total = stats.f_blocks.checked_mul(block)?;
    let free = stats.f_bfree.checked_mul(block)?;
    Some((total.saturating_sub(free), total))
}

#[cfg(windows)]
pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {
    use std::os::windows::ffi::OsStrExt;

    // Declared here rather than pulling in windows-sys for one call.
    unsafe extern "system" {
        fn GetDiskFreeSpaceExW(directory: *const u16, free_to_caller: *mut u64, total: *mut u64, total_free: *mut u64) -> i32;
    }

    let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
    let (mut free_to_caller, mut total, mut total_free) = (0u64, 0u64, 0u64);
    // SAFETY: wide is NUL-terminated and the three outputs are only read back
    // after the call reports success.
    let ok = unsafe { GetDiskFreeSpaceExW(wide.as_ptr(), &mut free_to_caller, &mut total, &mut total_free) != 0 };
    if !ok {
        return None;
    }
    Some((total.saturating_sub(total_free), total))
}

#[cfg(not(any(unix, windows)))]
pub fn disk_usage(_path: &Path) -> Option<(u64, u64)> {
    None
}

pub fn get_current_dir() -> Result<PathBuf, Error> {
    env::current_dir()
}

pub fn rename_path(original_path: PathBuf, new_path: PathBuf) -> Result<(), Error> {
    rename(original_path, new_path)?;
    Ok(())
}

/// Entries a delete will remove, for the progress bar to count against. A
/// directory counts itself as well as everything inside it, which is what the
/// walk below removes. Anything unreadable counts as nothing rather than
/// failing the job, since this is only ever a denominator.
pub fn count_entries(items: &[(PathBuf, bool)]) -> u64 {
    fn walk(path: &Path) -> u64 {
        let Ok(entries) = read_dir(path) else {
            return 1;
        };
        1 + entries
            .flatten()
            .map(|entry| match entry.file_type() {
                Ok(file_type) if file_type.is_dir() => walk(&entry.path()),
                _ => 1,
            })
            .sum::<u64>()
    }

    items
        .iter()
        .map(|(path, is_dir)| {
            let link = fs::symlink_metadata(path).map(|meta| meta.file_type().is_symlink()).unwrap_or(false);
            if *is_dir && !link { walk(path) } else { 1 }
        })
        .sum()
}

/// Remove a file, or a directory and everything in it, reporting each entry as
/// it goes and stopping when the report says to.
///
/// Walked rather than handed to remove_dir_all, which has nowhere to report
/// from and no way to be interrupted: a large tree on a slow disk would hold
/// the whole app still. A cancelled delete leaves whatever it had not reached.
pub fn delete_path(path: PathBuf, is_dir: bool, report: Report<'_>) -> Result<Transfer, Error> {
    // A symlink is removed as a link, never followed - including one pointing at
    // a directory, which reaches here with is_dir set because the panel treats it
    // as one. Walking into one would delete what it points at.
    let is_symlink = path.symlink_metadata().map(|metadata| metadata.file_type().is_symlink()).unwrap_or(false);

    let outcome = if is_dir && !is_symlink { delete_dir_recursive(&path, report)? } else { remove_one(&path, false, report)? };
    Ok(outcome.into())
}

/// Move a file or a directory to the system's trash, from where it can be put
/// back. Counted as one, however much is in it: on one filesystem it is a
/// rename and over at once, with nothing to count inside.
///
/// What the trash will not take - a read-only disk, one with nowhere to keep
/// a trash - is asked about like any other failure, with deleting it for good
/// as one more answer.
pub fn trash_path(path: PathBuf, is_dir: bool, report: Report<'_>) -> Result<Transfer, Error> {
    if !report.step(Step::Starting(&path)) {
        return Ok(Transfer::Cancelled);
    }
    loop {
        let error = match trash::delete(&path) {
            Ok(()) => break,
            Err(error) => trash_error(error),
        };
        match report.failed(&path, &error) {
            Reply::Retry => {}
            Reply::Skip => break,
            Reply::Abort => return Err(error),
            Reply::Delete => {
                // Its entries are not what this job counts, so they pass by
                // without adding to it; the one below counts the item.
                let mut uncounted = Uncounted(&mut *report);
                if delete_path(path, is_dir, &mut uncounted)? == Transfer::Cancelled {
                    return Ok(Transfer::Cancelled);
                }
                break;
            }
        }
    }
    Ok(if report.step(Step::Advanced(1)) { Transfer::Done } else { Transfer::Cancelled })
}

/// The trash crate's errors print with a prefix and a Debug dump. What
/// matters to someone looking at the popup is what went wrong.
fn trash_error(error: trash::Error) -> Error {
    match error {
        // The freedesktop trash fails with the filesystem's own error, which
        // already says it plainly. Only that build of the crate has it.
        #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))]
        trash::Error::FileSystem { source, .. } => source,
        trash::Error::TargetedRoot => Error::other("A root directory cannot go to the trash"),
        trash::Error::CouldNotAccess { target } => Error::other(format!("Cannot reach {target}")),
        trash::Error::Os { description, .. } | trash::Error::Unknown { description } => Error::other(description),
        other => Error::other(format!("Cannot move to the trash: {other:?}")),
    }
}

/// Passes a report on with every amount taken out, so a walk inside another
/// job's step counts as nothing of its own - but still stops when it is told.
struct Uncounted<'a, 'b>(&'a mut (dyn Progress + 'b));

impl Progress for Uncounted<'_, '_> {
    fn step(&mut self, step: Step<'_>) -> bool {
        match step {
            Step::Advanced(_) => self.0.step(Step::Advanced(0)),
            starting => self.0.step(starting),
        }
    }

    fn failed(&mut self, path: &Path, error: &Error) -> Reply {
        self.0.failed(path, error)
    }

    fn exists(&mut self, source: &Path, dest: &Path) -> Clash {
        self.0.exists(source, dest)
    }
}

/// Remove one entry, announcing it first so the popup can name it, and counting
/// it once it is dealt with - removed, or skipped when it would not go.
fn remove_one(path: &Path, is_dir: bool, report: Report<'_>) -> Result<Outcome, Error> {
    if !report.step(Step::Starting(path)) {
        return Ok(Outcome::Cancelled);
    }
    let removed = attempt(path, report, |_| if is_dir { remove_dir(path) } else { remove_entry(path) })?;
    report.step(Step::Advanced(1));
    Ok(if removed.is_some() { Outcome::Done } else { Outcome::Skipped })
}

/// Remove anything that is not a directory, links included. Windows keeps a
/// link to a directory - a directory symlink or a junction - as a directory,
/// which remove_file refuses; remove_dir takes the link away, and never what
/// it points at.
#[cfg(windows)]
fn remove_entry(path: &Path) -> Result<(), Error> {
    use std::os::windows::fs::FileTypeExt;
    if path.symlink_metadata().is_ok_and(|metadata| metadata.file_type().is_symlink_dir()) {
        remove_dir(path)
    } else {
        remove_file(path)
    }
}

/// Elsewhere every link is a file to unlink, whatever it points at.
#[cfg(not(windows))]
fn remove_entry(path: &Path) -> Result<(), Error> {
    remove_file(path)
}

fn delete_dir_recursive(path: &Path, report: Report<'_>) -> Result<Outcome, Error> {
    let Some(entries) = attempt(path, report, |_| read_dir(path))? else {
        return Ok(Outcome::Skipped);
    };
    let mut skipped = false;
    for entry in entries {
        let Some((entry, file_type)) = next_entry(path, entry, report)? else {
            skipped = true;
            continue;
        };
        let entry_path = entry.path();

        // file_type() describes the entry itself, so a link to a directory is a
        // link here and is unlinked rather than followed into.
        let outcome = if file_type.is_dir() { delete_dir_recursive(&entry_path, &mut *report)? } else { remove_one(&entry_path, false, &mut *report)? };
        match outcome {
            Outcome::Cancelled => return Ok(Outcome::Cancelled),
            Outcome::Skipped => skipped = true,
            Outcome::Done => {}
        }
    }

    // Something inside was left where it was, so the directory has to stay
    // too. Trying would only ask about it again, as "Directory not empty".
    if skipped {
        return Ok(Outcome::Skipped);
    }
    // The directory itself, now that it is empty.
    remove_one(path, true, report)
}

/// True for an ordinary file, following a symlink to one. Pipes, sockets and
/// devices are not, and nothing should open them to read: opening a named pipe
/// waits for a writer that may never come, and a device like /dev/zero reports
/// a size of nothing and then never ends.
pub fn is_regular_file(path: &Path) -> bool {
    fs::metadata(path).is_ok_and(|metadata| metadata.is_file())
}

fn not_regular(path: &Path) -> Error {
    Error::new(ErrorKind::InvalidInput, format!("Not a regular file: {}", path.display()))
}

/// True for a name that stays in the directory it is given in: one plain
/// component, so not "." or "..", and no separator - "../x" or "sub/x" would
/// rename or create somewhere else entirely.
pub fn is_plain_name(name: &str) -> bool {
    let mut components = Path::new(name).components();
    matches!(
        (components.next(), components.next()),
        (Some(std::path::Component::Normal(only)), None) if only == name
    )
}

/// True when two paths in the same directory name one entry: on a
/// case-insensitive filesystem, "readme" and "README" do. Links are not
/// followed - a symlink to a file is an entry of its own, and renaming the
/// file over it would destroy it.
#[cfg(unix)]
pub fn is_same_entry(a: &Path, b: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    match (a.symlink_metadata(), b.symlink_metadata()) {
        (Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(),
        _ => false,
    }
}

/// Windows has no stable file identity in std, but its directories are
/// case-insensitive, so within one of them a name differing only in case is
/// the same entry.
#[cfg(windows)]
pub fn is_same_entry(a: &Path, b: &Path) -> bool {
    let name = |path: &Path| path.file_name().map(|name| name.to_string_lossy().to_lowercase());
    a.parent() == b.parent() && name(a).is_some() && name(a) == name(b) && path_exists(a)
}

#[cfg(not(any(unix, windows)))]
pub fn is_same_entry(a: &Path, b: &Path) -> bool {
    a == b
}

/// True if anything occupies this path, including a dangling symlink - which
/// Path::exists() reports as absent because it follows the link.
pub fn path_exists(path: &Path) -> bool {
    path.symlink_metadata().is_ok()
}

/// Create an empty file, refusing if anything is already there - create_new
/// fails rather than truncating, matching how create_dir refuses.
pub fn create_file(path: PathBuf) -> Result<(), Error> {
    std::fs::OpenOptions::new().write(true).create_new(true).open(path)?;
    Ok(())
}

pub fn create_directory(path: PathBuf) -> Result<(), Error> {
    create_dir(path)?;
    Ok(())
}

/// What a running transfer reports as it goes.
pub enum Step<'a> {
    /// Starting this file. Bytes reported after it belong to it.
    Starting(&'a Path),
    /// Another `amount` of the current entry is done. Bytes for a copy, and
    /// entries removed for a delete, which is what each counts its total in.
    Advanced(u64),
}

/// How a transfer ended. Cancelled leaves everything already finished where it
/// is; only the one file that was in flight is cleaned up.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Transfer {
    Done,
    Cancelled,
}

/// How one entry went, inside a walk. Skipped tells the directory around it
/// that something in it was left where it was: a delete then keeps the
/// directory, and a move keeps the source directory.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Outcome {
    Done,
    Skipped,
    Cancelled,
}

/// A walk with entries skipped still finished: what was skipped was answered
/// for, one at a time, as it came up.
impl From<Outcome> for Transfer {
    fn from(outcome: Outcome) -> Self {
        match outcome {
            Outcome::Cancelled => Transfer::Cancelled,
            Outcome::Done | Outcome::Skipped => Transfer::Done,
        }
    }
}

/// What to do about an entry that could not be dealt with.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Reply {
    /// Try the same thing again - after freeing some space, say, or
    /// remounting a drive.
    Retry,
    /// Leave this entry where it is and go on with the rest.
    Skip,
    /// Stop the whole job, passing the error up.
    Abort,
    /// Delete it for good instead. Offered only when moving to the trash,
    /// for what the trash will not take; anywhere else it is a Skip.
    Delete,
}

/// Follows a running transfer.
pub trait Progress {
    /// Takes progress and answers whether to carry on. Returning false stops
    /// the transfer at the next chunk or file, whichever comes first.
    fn step(&mut self, step: Step<'_>) -> bool;

    /// `path` could not be copied, moved or removed, for `error`. Asked once
    /// for each failure. Left alone, the first one ends the job.
    fn failed(&mut self, _path: &Path, _error: &Error) -> Reply {
        Reply::Abort
    }

    /// `dest` is already there - a file or a link - and `source` is about to
    /// be written over it. Asked once for each; a directory onto a directory
    /// is never asked about, but merged, its files asked about one at a time.
    /// Left alone, what is there is replaced: a caller with nobody to ask has
    /// already said it may be.
    fn exists(&mut self, _source: &Path, _dest: &Path) -> Clash {
        Clash::Replace
    }
}

/// The answer to a name already taken.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Clash {
    /// Write over what is there.
    Replace,
    /// Leave what is there, and the source where it was.
    Keep,
    /// Stop the whole job.
    Abort,
}

/// A closure is a Progress that never answers for a failure, which is all a
/// caller wants when it has nobody to ask.
impl<F: FnMut(Step<'_>) -> bool> Progress for F {
    fn step(&mut self, step: Step<'_>) -> bool {
        self(step)
    }
}

pub type Report<'a> = &'a mut dyn Progress;

/// Do `op` for `path`, and when it fails ask what next: try it again, leave
/// this entry where it is (None), or give up with the error.
fn attempt<T>(path: &Path, report: Report<'_>, mut op: impl FnMut(Report<'_>) -> Result<T, Error>) -> Result<Option<T>, Error> {
    loop {
        match op(&mut *report) {
            Ok(value) => return Ok(Some(value)),
            Err(error) => match report.failed(path, &error) {
                Reply::Retry => {}
                Reply::Skip | Reply::Delete => return Ok(None),
                Reply::Abort => return Err(error),
            },
        }
    }
}

/// The next entry of a listing and what kind it is, or None when reading it
/// failed and the answer was to go on past it. Retry is taken as Skip here:
/// the listing has moved on, and there is no asking it for the same entry.
fn next_entry(dir: &Path, entry: Result<fs::DirEntry, Error>, report: Report<'_>) -> Result<Option<(fs::DirEntry, fs::FileType)>, Error> {
    match entry.and_then(|entry| entry.file_type().map(|file_type| (entry, file_type))) {
        Ok(pair) => Ok(Some(pair)),
        Err(error) => match report.failed(dir, &error) {
            Reply::Abort => Err(error),
            Reply::Retry | Reply::Skip | Reply::Delete => Ok(None),
        },
    }
}

/// Move by renaming, which only works within one filesystem. True if it did;
/// the caller copies instead when it did not. Kept separate from move_path so
/// a caller can get the instant moves out of the way before measuring the rest.
pub fn rename_in_place(source: &Path, dest: &Path) -> bool {
    rename(source, dest).is_ok()
}

/// Bytes a transfer will move, for the progress bar to count against. A
/// directory is walked; anything unreadable counts as nothing rather than
/// failing the job, since this is only ever a denominator.
pub fn measure(items: &[(PathBuf, PathBuf, bool)]) -> u64 {
    items
        .iter()
        .map(|(source, _, is_dir)| {
            // A symlink is recreated, not followed, so it carries no bytes.
            if fs::symlink_metadata(source).map(|meta| meta.file_type().is_symlink()).unwrap_or(false) {
                0
            } else if *is_dir {
                calculate_dir_size(source).unwrap_or(0)
            } else {
                fs::metadata(source).map(|meta| meta.len()).unwrap_or(0)
            }
        })
        .sum()
}

/// True when copying `source` to `dest` would descend into what it is writing:
/// a directory copied to somewhere inside itself. copy_dir_recursive creates
/// the destination before it reads the source, so it then finds it, copies it,
/// finds it again, and carries on until the path outgrows PATH_MAX - around a
/// thousand levels, re-copying every file at each one.
///
/// Paths are resolved first, so a destination reaching the source through a
/// symlink counts. A symlink source does not: it is recreated as a link rather
/// than walked, so it cannot recurse.
pub fn copies_into_itself(source: &Path, dest: &Path) -> bool {
    if fs::symlink_metadata(source).map(|meta| meta.file_type().is_symlink()).unwrap_or(false) || !source.is_dir() {
        return false;
    }

    let resolve = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    let source = resolve(source);
    // The destination does not exist yet, so its parent is what can be resolved.
    let dest = match (dest.parent(), dest.file_name()) {
        (Some(parent), Some(name)) => resolve(parent).join(name),
        _ => resolve(dest),
    };
    // Component-wise, so "/x/subfoo" is not inside "/x/sub".
    dest.starts_with(&source)
}

pub fn copy_path(source: PathBuf, dest: PathBuf, is_dir: bool, report: Report<'_>) -> Result<Transfer, Error> {
    // Refused here as well as before the transfer starts, so no caller can
    // reach the runaway however it assembles its paths.
    if copies_into_itself(&source, &dest) {
        return Err(Error::new(ErrorKind::InvalidInput, format!("Cannot copy \"{}\" into itself", source.display())));
    }

    // A symlink is copied as the link itself, never as its target, matching
    // cp -r. is_dir can't decide this: it comes from DirEntry::metadata(),
    // which doesn't follow links, so a link to a directory arrives false here
    // and would otherwise be handed to copy_file_content.
    let Some(metadata) = attempt(&source, report, |_| fs::symlink_metadata(&source))? else {
        return Ok(Transfer::Done);
    };
    let outcome = if metadata.file_type().is_symlink() {
        settle_clash(&source, &dest, report).map_or_else(|| copy_link(&source, &dest, report), Ok)?
    } else if is_dir {
        copy_dir_recursive(&source, &dest, report)?
    } else {
        settle_clash(&source, &dest, report).map_or_else(|| copy_file(&source, &dest, report), Ok)?
    };
    Ok(outcome.into())
}

/// When `dest` is already there and is not a directory - a file or a link -
/// ask whether `source` may be written over it. None to go ahead; otherwise
/// how the entry came out without it: left where it was, or the job stopped.
/// A directory in the way is not asked about here: a directory is merged
/// into it, and a file onto it fails, which is asked about as a failure.
fn settle_clash(source: &Path, dest: &Path, report: Report<'_>) -> Option<Outcome> {
    let existing = dest.symlink_metadata().ok()?;
    if existing.is_dir() {
        return None;
    }
    match report.exists(source, dest) {
        Clash::Replace => None,
        Clash::Keep => {
            // Counted as dealt with, so the bar still reaches the end.
            let bytes = source.symlink_metadata().map_or(0, |metadata| if metadata.is_file() { metadata.len() } else { 0 });
            let carry_on = report.step(Step::Starting(source)) && report.step(Step::Advanced(bytes));
            Some(if carry_on { Outcome::Skipped } else { Outcome::Cancelled })
        }
        Clash::Abort => Some(Outcome::Cancelled),
    }
}

/// Recreate a link, asking about it if that fails.
fn copy_link(source: &Path, dest: &Path, report: Report<'_>) -> Result<Outcome, Error> {
    let copied = attempt(source, report, |_| {
        clear_for_link(dest)?;
        copy_symlink(source, dest)
    })?;
    Ok(if copied.is_some() { Outcome::Done } else { Outcome::Skipped })
}

/// Copy a file, asking about it if that fails. A retry starts the file over:
/// copy_file_content has cleared away what it wrote before failing.
fn copy_file(source: &Path, dest: &Path, report: Report<'_>) -> Result<Outcome, Error> {
    Ok(match attempt(source, report, |report| copy_file_content(source, dest, report))? {
        Some(Transfer::Done) => Outcome::Done,
        Some(Transfer::Cancelled) => Outcome::Cancelled,
        None => Outcome::Skipped,
    })
}

/// Recreate a symlink at the destination, pointing where the original pointed.
#[cfg(unix)]
fn copy_symlink(source: &Path, dest: &Path) -> Result<(), Error> {
    std::os::unix::fs::symlink(fs::read_link(source)?, dest)
}

#[cfg(windows)]
fn copy_symlink(source: &Path, dest: &Path) -> Result<(), Error> {
    let target = fs::read_link(source)?;
    // Windows picks the call by link kind, and creating one needs Developer
    // Mode or elevation - the error surfaces to the user either way.
    if source.is_dir() { std::os::windows::fs::symlink_dir(target, dest) } else { std::os::windows::fs::symlink_file(target, dest) }
}

/// Copy a file's content, then its times and permissions - so a script or a
/// program stays executable, and a move across filesystems leaves the file
/// dated as it was. Setting them is allowed to fail: on a filesystem with no
/// Unix permissions (ext4 to exFAT, say) it would, with EPERM, and the copy
/// itself is still good.
///
/// The copy runs in COPY_CHUNK pieces so there is somewhere to report progress
/// from and somewhere to notice a cancel. Each piece is still an io::copy, over
/// a reader limited to the chunk rather than a buffer of our own, which is what
/// keeps the platform's fast path - copy_file_range on Linux.
fn copy_file_content(source: &Path, dest: &Path, report: Report<'_>) -> Result<Transfer, Error> {
    // Links are recreated before this is reached, so what arrives here is the
    // entry itself. A pipe or a device would block the worker in open() or
    // read forever, out of reach of Esc. cp -R recreates them instead of
    // reading them; short of doing that, refusing is what is safe.
    let metadata = fs::symlink_metadata(source)?;
    if !metadata.is_file() {
        return Err(not_regular(source));
    }
    if !report.step(Step::Starting(source)) {
        return Ok(Transfer::Cancelled);
    }

    let mut src_file = File::open(source)?;
    // The bytes go to a temporary beside the destination, and a rename puts
    // them in place once they are all there. Only an overwrite, or a directory
    // merged into another, finds something already at the destination; that
    // file is somebody's, and writing straight over it would destroy it the
    // moment the copy began. Where nothing is there, a file written under its
    // own name would still be half a file whenever the copy stopped short of
    // the end - fm84 quit partway, or killed - and would pass for a whole one.
    // A temporary that is left behind is plainly not one.
    let replacing = dest.symlink_metadata().is_ok();
    let (temp, mut dst_file) = temp_beside(dest)?;
    // What a failure or a cancel partway leaves: nothing, of ours.
    let discard = |dst_file: File| {
        drop(dst_file);
        let _ = remove_file(&temp);
    };
    loop {
        let copied = match io::copy(&mut (&mut src_file).take(COPY_CHUNK), &mut dst_file) {
            Ok(copied) => copied,
            Err(e) => {
                // A read or write that failed partway - a full disk, a device
                // gone. What was at the destination, if anything, is untouched.
                discard(dst_file);
                return Err(e);
            }
        };
        if copied == 0 {
            keep_times(&dst_file, &metadata);
            drop(dst_file);
            let _ = fs::set_permissions(&temp, metadata.permissions());
            // The one moment the destination changes, and it changes all at
            // once: anything reading it sees the old bytes or the new ones.
            let placed = if replacing {
                clear_link(dest).and_then(|()| rename(&temp, dest))
            } else if path_exists(dest) {
                // Taken while the copy ran, and nobody said it could be
                // replaced. A rename would replace it without a word.
                Err(Error::new(ErrorKind::AlreadyExists, format!("Destination already exists: {}", dest.display())))
            } else {
                rename(&temp, dest)
            };
            if let Err(e) = placed {
                let _ = remove_file(&temp);
                return Err(e);
            }
            return Ok(Transfer::Done);
        }
        if !report.step(Step::Advanced(copied)) {
            // Half a file that will never be finished.
            discard(dst_file);
            return Ok(Transfer::Cancelled);
        }
    }
}

/// Give a copy the access and modification times of what it was copied
/// from, as cp -p and file managers do. Allowed to fail, like the permissions:
/// some filesystems keep no such times, or will not take them from us.
fn keep_times(dest: &File, metadata: &fs::Metadata) {
    let mut times = fs::FileTimes::new();
    if let Ok(modified) = metadata.modified() {
        times = times.set_modified(modified);
    }
    if let Ok(accessed) = metadata.accessed() {
        times = times.set_accessed(accessed);
    }
    let _ = dest.set_times(times);
}

/// keep_times for a directory, once everything is inside it - each file
/// copied in moves its modification time on. Opening a directory to set them
/// fails on Windows, which only costs the times.
fn keep_dir_times(dest: &Path, metadata: &fs::Metadata) {
    if let Ok(dir) = File::open(dest) {
        keep_times(&dir, metadata);
    }
}

fn copy_dir_recursive(source: &Path, dest: &Path, report: Report<'_>) -> Result<Outcome, Error> {
    if attempt(dest, report, |_| fs::create_dir_all(dest))?.is_none() {
        return Ok(Outcome::Skipped);
    }
    let Some(entries) = attempt(source, report, |_| read_dir(source))? else {
        return Ok(Outcome::Skipped);
    };

    let mut skipped = false;
    for entry in entries {
        let Some((entry, file_type)) = next_entry(source, entry, report)? else {
            skipped = true;
            continue;
        };
        let entry_path = entry.path();
        let dest_path = dest.join(entry.file_name());

        // file_type() describes the entry itself; is_dir() would follow the
        // link, copying the target's contents - and a link pointing at an
        // ancestor recurses until the path outgrows PATH_MAX. cp -r recreates
        // the link, so do the same.
        let outcome = if file_type.is_dir() {
            copy_dir_recursive(&entry_path, &dest_path, &mut *report)?
        } else if let Some(outcome) = settle_clash(&entry_path, &dest_path, &mut *report) {
            outcome
        } else if file_type.is_symlink() {
            copy_link(&entry_path, &dest_path, &mut *report)?
        } else {
            copy_file(&entry_path, &dest_path, &mut *report)?
        };
        match outcome {
            Outcome::Cancelled => return Ok(Outcome::Cancelled),
            Outcome::Skipped => skipped = true,
            Outcome::Done => {}
        }
    }

    // Last, once everything is inside: a read-only directory given its mode
    // first would refuse the files being copied into it. Allowed to fail, as
    // for files.
    if let Ok(metadata) = fs::metadata(source) {
        keep_dir_times(dest, &metadata);
        let _ = fs::set_permissions(dest, metadata.permissions());
    }
    Ok(if skipped { Outcome::Skipped } else { Outcome::Done })
}

/// Move `source` to `dest`. Where something is already at `dest`, it goes
/// by way of move_across: a file in the way is asked about, and a directory
/// moved onto a directory is merged into it - a rename cannot replace a
/// directory that holds anything, so that goes entry by entry.
pub fn move_path(source: PathBuf, dest: PathBuf, report: Report<'_>) -> Result<Transfer, Error> {
    if path_exists(&dest) {
        return Ok(move_across(&source, &dest, report)?.into());
    }

    // Try rename first (fast, same filesystem)
    let renamed = attempt(&source, report, |_| match rename(&source, &dest) {
        Ok(()) => Ok(true),
        Err(e) if is_cross_device(&e) => Ok(false),
        Err(e) => Err(e),
    })?;
    match renamed {
        Some(true) | None => Ok(Transfer::Done),
        Some(false) => Ok(move_across(&source, &dest, report)?.into()),
    }
}

/// Move what one rename could not: across filesystems, or into a directory
/// already there. Entry by entry, each source removed only once its copy is
/// whole - so a skip, a cancel or an error partway leaves every entry either
/// moved or where it was, and never gone from both. A directory with anything
/// skipped inside stays behind, holding what was not moved.
fn move_across(source: &Path, dest: &Path, report: Report<'_>) -> Result<Outcome, Error> {
    let Some(metadata) = attempt(source, report, |_| fs::symlink_metadata(source))? else {
        return Ok(Outcome::Skipped);
    };
    // Another name for the very same file - a hard link to it. It is there
    // already, so what is left of the move is to take away the name it had,
    // as mv does. A rename between the two would report success and do
    // nothing, leaving the source where it was and its directory refusing to
    // go as not empty. Nothing would be written over, so nothing is asked.
    if !metadata.is_dir() && is_same_entry(source, dest) {
        let bytes = if metadata.is_file() { metadata.len() } else { 0 };
        if !report.step(Step::Starting(source)) || !report.step(Step::Advanced(bytes)) {
            return Ok(Outcome::Cancelled);
        }
        let removed = attempt(source, report, |_| remove_file(source))?;
        return Ok(if removed.is_some() { Outcome::Done } else { Outcome::Skipped });
    }

    // Asked first, since the rename below would replace it without a word.
    if !metadata.is_dir()
        && let Some(outcome) = settle_clash(source, dest, report)
    {
        return Ok(outcome);
    }

    // Within one filesystem - merging into a directory already there - a
    // rename does it at once: a file replaces the one in the way, and a
    // directory goes whole when nothing is in its way. Across filesystems it
    // fails at once, and costs nothing to try.
    if rename(source, dest).is_ok() {
        if !metadata.is_dir() {
            let bytes = if metadata.file_type().is_symlink() { 0 } else { metadata.len() };
            if !report.step(Step::Starting(source)) || !report.step(Step::Advanced(bytes)) {
                return Ok(Outcome::Cancelled);
            }
        }
        return Ok(Outcome::Done);
    }

    if !metadata.is_dir() {
        let copied = if metadata.file_type().is_symlink() { copy_link(source, dest, report)? } else { copy_file(source, dest, report)? };
        if copied != Outcome::Done {
            return Ok(copied);
        }
        let removed = attempt(source, report, |_| remove_file(source))?;
        return Ok(if removed.is_some() { Outcome::Done } else { Outcome::Skipped });
    }

    if attempt(dest, report, |_| fs::create_dir_all(dest))?.is_none() {
        return Ok(Outcome::Skipped);
    }
    let Some(entries) = attempt(source, report, |_| read_dir(source))? else {
        return Ok(Outcome::Skipped);
    };
    let mut skipped = false;
    for entry in entries {
        let Some((entry, _)) = next_entry(source, entry, report)? else {
            skipped = true;
            continue;
        };
        match move_across(&entry.path(), &dest.join(entry.file_name()), &mut *report)? {
            Outcome::Cancelled => return Ok(Outcome::Cancelled),
            Outcome::Skipped => skipped = true,
            Outcome::Done => {}
        }
    }
    if skipped {
        return Ok(Outcome::Skipped);
    }

    keep_dir_times(dest, &metadata);
    let _ = fs::set_permissions(dest, metadata.permissions());
    let removed = attempt(source, report, |_| remove_dir(source))?;
    Ok(if removed.is_some() { Outcome::Done } else { Outcome::Skipped })
}

/// A directory itself, not a link to one.
fn is_real_dir(path: &Path) -> bool {
    path.symlink_metadata().is_ok_and(|metadata| metadata.is_dir())
}

/// Where each source goes when copied or moved to `destination`, read the
/// way cp and mv read it. Into a directory that is there, or one named with a
/// separator on the end (`names_dir`), each goes under its own name. Anything
/// else is the new path of the one source being copied - several cannot all
/// take one name - and the directory it would go in has to be there.
pub fn transfer_targets(sources: &[(PathBuf, bool)], destination: &Path, names_dir: bool) -> Result<Vec<(PathBuf, PathBuf, bool)>, String> {
    if destination.is_dir() {
        return Ok(sources.iter().map(|(source, is_dir)| (source.clone(), destination.join(source.file_name().unwrap_or_default()), *is_dir)).collect());
    }
    if names_dir {
        return Err(format!("No such directory: {}", destination.display()));
    }
    let [(source, is_dir)] = sources else {
        return Err(format!("{} items need a directory to go into, and {} is not one", sources.len(), destination.display()));
    };
    match destination.parent() {
        Some(parent) if parent.is_dir() => Ok(vec![(source.clone(), destination.to_path_buf(), *is_dir)]),
        Some(parent) => Err(format!("No such directory: {}", parent.display())),
        None => Err(format!("Cannot copy to {}", destination.display())),
    }
}

/// What a copy or move would write over, checked for every item before any
/// is started - bailing out partway would leave some done and the rest not.
/// Returns the destinations already taken, for the caller to ask about or
/// refuse. What no answer could make safe is an error instead: an item onto
/// itself, which overwriting would empty before reading; a directory into
/// itself, which never ends; and a file and a directory in each other's
/// place, where replacing would throw away a whole tree.
pub fn check_destinations(items: &[(PathBuf, PathBuf, bool)]) -> Result<Vec<PathBuf>, String> {
    let mut taken = Vec::new();
    for (source, dest, _) in items {
        if !path_exists(dest) {
            continue;
        }
        if is_same_entry(source, dest) {
            return Err(format!("\"{}\" is already there", source.display()));
        }
        match (is_real_dir(source), is_real_dir(dest)) {
            (false, true) => return Err(format!("Cannot replace directory {} with a file", dest.display())),
            (true, false) => return Err(format!("Cannot replace file {} with a directory", dest.display())),
            _ => {}
        }
        taken.push(dest.clone());
    }
    // A destination inside the source would be copied into itself, filling the
    // disk.
    if let Some((source, _, _)) = items.iter().find(|(source, dest, _)| copies_into_itself(source, dest)) {
        return Err(format!("Cannot copy \"{}\" into itself", source.display()));
    }
    Ok(taken)
}

/// Save `content` over the file at `path` so that a failure partway - a full
/// disk, a device gone, fm84 killed - leaves the file as it was rather than
/// truncated. Written straight over, the file is emptied the moment the write
/// begins. Instead the bytes go to a temporary beside it, which is flushed to
/// disk and then renamed into place, so the file is whole either way.
///
/// A rename puts a new file where the old one was, which is not always the
/// same thing as changing it. Where the difference would show, the file is
/// written in place as before:
/// - it has other hard links, which would go on holding the old content;
/// - its owner cannot be kept, as when editing someone else's file that the
///   group may write to;
/// - its directory cannot be added to, though the file itself can be written.
pub fn save_file(path: &Path, content: &[u8]) -> Result<(), Error> {
    // Through a link to the file it names: renaming over the link would put a
    // regular file in its place and leave what it points at unedited.
    let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let in_place = || fs::write(&target, content);

    let Ok(metadata) = fs::metadata(&target) else {
        // Gone since it was opened, so there is nothing to keep safe.
        return in_place();
    };
    if !metadata.is_file() {
        return Err(not_regular(&target));
    }
    // Asked of the file itself, since a rename needs only the directory: a
    // read-only file would otherwise be replaced without a word. Opened
    // without truncating, so asking changes nothing.
    File::options().write(true).open(&target)?;
    if has_other_links(&metadata) {
        return in_place();
    }

    let (temp, mut file) = match temp_beside(&target) {
        Ok(pair) => pair,
        Err(e) if e.kind() == ErrorKind::PermissionDenied => return in_place(),
        Err(e) => return Err(e),
    };
    if keep_owner(&file, &metadata).is_err() {
        drop(file);
        let _ = remove_file(&temp);
        return in_place();
    }
    // After the owner, which can clear the setuid and setgid bits.
    let written = file.write_all(content).and_then(|()| file.set_permissions(metadata.permissions())).and_then(|()| file.sync_all());
    drop(file);
    if let Err(e) = written.and_then(|()| rename(&temp, &target)) {
        let _ = remove_file(&temp);
        return Err(e);
    }
    Ok(())
}

#[cfg(unix)]
fn has_other_links(metadata: &fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt;
    metadata.nlink() > 1
}

#[cfg(not(unix))]
fn has_other_links(_metadata: &fs::Metadata) -> bool {
    false
}

/// Give the temporary the owner and group of the file it will replace. Only
/// root may give a file away, but anyone may set what is already theirs, so
/// this fails exactly when the rename would change who owns the file.
#[cfg(unix)]
fn keep_owner(file: &File, metadata: &fs::Metadata) -> Result<(), Error> {
    use std::os::unix::fs::MetadataExt;
    std::os::unix::fs::fchown(file, Some(metadata.uid()), Some(metadata.gid()))
}

#[cfg(not(unix))]
fn keep_owner(_file: &File, _metadata: &fs::Metadata) -> Result<(), Error> {
    Ok(())
}

/// A file to write into beside `dest`, renamed over it once it is whole.
/// Same directory, so the rename that finishes the copy is atomic and cannot
/// half-replace anything; a temporary elsewhere would have to be copied back
/// across, which is the thing being avoided.
///
/// Named after the file, shortened: the prefix and suffix would otherwise
/// carry a name already near the filesystem's limit past it, and every copy
/// goes through one of these now.
fn temp_beside(dest: &Path) -> Result<(PathBuf, File), Error> {
    let name: String = dest.file_name().unwrap_or_default().to_string_lossy().chars().take(64).collect();
    for attempt in 0..1000u32 {
        let candidate = dest.with_file_name(format!(".{name}.fm84-{}-{attempt}", std::process::id()));
        match File::options().write(true).create_new(true).open(&candidate) {
            Ok(file) => return Ok((candidate, file)),
            // Something of ours from a run that was killed partway. Step past it.
            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }
    Err(Error::new(ErrorKind::AlreadyExists, format!("Cannot make room beside {}", dest.display())))
}

/// Clear a link out of the way of a file about to be written at `dest`, so the
/// write replaces the link instead of following it into whatever it points
/// at. Anything else stays for the write to deal with.
fn clear_link(dest: &Path) -> Result<(), Error> {
    match dest.symlink_metadata() {
        // A link to a directory is removed as a directory on Windows.
        Ok(metadata) if metadata.file_type().is_symlink() => remove_file(dest).or_else(|_| remove_dir(dest)),
        _ => Ok(()),
    }
}

/// Make room at `dest` for a link about to be recreated there: a file or a
/// link in the way goes. A directory does not - no link replaces a tree.
fn clear_for_link(dest: &Path) -> Result<(), Error> {
    match dest.symlink_metadata() {
        Ok(metadata) if metadata.is_dir() => Err(Error::new(ErrorKind::AlreadyExists, format!("Cannot replace directory {} with a link", dest.display()))),
        Ok(_) => clear_link(dest).and_then(|()| if path_exists(dest) { remove_file(dest) } else { Ok(()) }),
        Err(_) => Ok(()),
    }
}

/// True for the error a rename gives across filesystems: EXDEV on Unix,
/// ERROR_NOT_SAME_DEVICE on Windows. By kind rather than number - the two are
/// 18 and 17, and 17 on Unix is EEXIST, which is no reason to copy anything.
fn is_cross_device(error: &Error) -> bool {
    error.kind() == ErrorKind::CrossesDevices
}

pub fn calculate_dir_size(path: &Path) -> Result<u64, Error> {
    walk_dir_size(path, &AtomicBool::new(false), &mut |_| {}).map(Option::unwrap_or_default)
}

/// Bytes in the files under `path`, links not followed. `found` is told each
/// file's size as it is reached, so a long walk can show how far it has got,
/// and `cancel` stops it between entries, which gives None.
///
/// Only `path` itself has to be readable. Anything inside that is not - a
/// directory locked to its owner, a file gone mid-walk - counts as nothing,
/// the way du carries on past what it cannot read rather than giving up.
pub fn walk_dir_size(path: &Path, cancel: &AtomicBool, found: &mut dyn FnMut(u64)) -> Result<Option<u64>, Error> {
    let mut total = 0u64;
    for entry in read_dir(path)? {
        if cancel.load(Ordering::Relaxed) {
            return Ok(None);
        }
        let Ok(entry) = entry else { continue };
        // file_type() uses readdir's d_type on Linux - no extra stat syscall
        let Ok(file_type) = entry.file_type() else { continue };
        if file_type.is_dir() {
            match walk_dir_size(&entry.path(), cancel, found) {
                Ok(Some(size)) => total += size,
                Ok(None) => return Ok(None),
                Err(_) => {}
            }
        } else if let Ok(metadata) = entry.metadata() {
            total += metadata.len();
            found(metadata.len());
        }
    }
    Ok(Some(total))
}

#[cfg(test)]
mod live_mount_probe {
    #[test]
    #[ignore = "machine-specific; run with --ignored to eyeball this host's mounts"]
    fn show() {
        for mount in super::list_mounts() {
            println!("  {:<24} {:<14} {:?}", mount.path.display(), mount.label, mount.kind);
        }
    }
}

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

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("fm84-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn a_save_replaces_the_content_and_leaves_nothing_beside_it() {
        let dir = scratch("save");
        let file = dir.join("notes.txt");
        fs::write(&file, "old and longer than the new").unwrap();

        save_file(&file, b"new").unwrap();
        assert_eq!(fs::read_to_string(&file).unwrap(), "new");
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "a temporary was left behind");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_save_keeps_the_mode_and_writes_through_a_link() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("save-link");
        let file = dir.join("run.sh");
        fs::write(&file, "echo old").unwrap();
        fs::set_permissions(&file, fs::Permissions::from_mode(0o750)).unwrap();
        std::os::unix::fs::symlink(&file, dir.join("link.sh")).unwrap();

        save_file(&dir.join("link.sh"), b"echo new").unwrap();
        assert!(fs::symlink_metadata(dir.join("link.sh")).unwrap().file_type().is_symlink());
        assert_eq!(fs::read_to_string(&file).unwrap(), "echo new");
        assert_eq!(fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o750);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_save_keeps_a_hard_link_joined() {
        let dir = scratch("save-hardlink");
        let file = dir.join("a.txt");
        fs::write(&file, "old").unwrap();
        fs::hard_link(&file, dir.join("b.txt")).unwrap();

        save_file(&file, b"new").unwrap();
        assert_eq!(fs::read_to_string(dir.join("b.txt")).unwrap(), "new");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_read_only_file_is_not_replaced() {
        let dir = scratch("save-readonly");
        let file = dir.join("locked.txt");
        fs::write(&file, "old").unwrap();
        let mut permissions = fs::metadata(&file).unwrap().permissions();
        permissions.set_readonly(true);
        fs::set_permissions(&file, permissions.clone()).unwrap();

        // Root may write anything, so there is nothing to refuse.
        if File::options().write(true).open(&file).is_err() {
            assert!(save_file(&file, b"new").is_err());
            assert_eq!(fs::read_to_string(&file).unwrap(), "old");
        }
        #[allow(clippy::permissions_set_readonly_false)]
        permissions.set_readonly(false);
        fs::set_permissions(&file, permissions).unwrap();
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_size_walk_counts_what_it_can_and_stops_when_asked() {
        let dir = scratch("walk-size");
        fs::write(dir.join("a.bin"), vec![0u8; 1000]).unwrap();
        fs::create_dir(dir.join("sub")).unwrap();
        fs::write(dir.join("sub").join("b.bin"), vec![0u8; 2500]).unwrap();

        let mut reported = Vec::new();
        let size = walk_dir_size(&dir, &AtomicBool::new(false), &mut |bytes| reported.push(bytes)).unwrap();
        assert_eq!(size, Some(3500));
        reported.sort();
        assert_eq!(reported, [1000, 2500]);

        // Cancelled before it starts, it finds nothing and says so.
        assert_eq!(walk_dir_size(&dir, &AtomicBool::new(true), &mut |_| {}).unwrap(), None);
        // The directory itself has to be there; a vanished one is an error.
        assert!(walk_dir_size(&dir.join("gone"), &AtomicBool::new(false), &mut |_| {}).is_err());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn measure_adds_up_files_and_walks_directories() {
        let dir = scratch("measure");
        fs::write(dir.join("a.bin"), vec![0u8; 1000]).unwrap();
        fs::create_dir(dir.join("sub")).unwrap();
        fs::write(dir.join("sub").join("b.bin"), vec![0u8; 2500]).unwrap();

        let items = vec![(dir.join("a.bin"), dir.join("copy-a.bin"), false), (dir.join("sub"), dir.join("copy-sub"), true)];
        assert_eq!(measure(&items), 3500);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_copy_reports_every_file_and_every_byte() {
        let dir = scratch("report");
        let source = dir.join("src");
        fs::create_dir(&source).unwrap();
        // One file longer than a chunk, so the inner loop reports several times.
        fs::write(source.join("big.bin"), vec![7u8; COPY_CHUNK as usize * 2 + 13]).unwrap();
        fs::write(source.join("small.bin"), vec![7u8; 10]).unwrap();
        let dest = dir.join("dst");

        let mut started = Vec::new();
        let mut bytes = 0u64;
        {
            let mut report = |step: Step<'_>| {
                match step {
                    Step::Starting(path) => started.push(path.file_name().unwrap().to_string_lossy().into_owned()),
                    Step::Advanced(n) => bytes += n,
                }
                true
            };
            assert_eq!(copy_path(source.clone(), dest.clone(), true, &mut report).unwrap(), Transfer::Done);
        }

        started.sort();
        assert_eq!(started, ["big.bin", "small.bin"]);
        // What the bar counts has to reach what the counting pass promised.
        assert_eq!(bytes, measure(&[(source, dest, true)]));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_cancelled_overwrite_leaves_the_old_file_alone() {
        let dir = scratch("overwrite-cancel").canonicalize().unwrap();
        let source = dir.join("new.bin");
        let dest = dir.join("old.bin");
        fs::write(&source, vec![7u8; COPY_CHUNK as usize * 3]).unwrap();
        fs::write(&dest, b"the file that was already here").unwrap();

        // Stop after the first chunk, the way Esc does partway through.
        let mut chunks = 0;
        {
            let mut report = |step: Step<'_>| {
                if let Step::Advanced(_) = step {
                    chunks += 1;
                }
                chunks < 1
            };
            assert_eq!(copy_path(source, dest.clone(), false, &mut report).unwrap(), Transfer::Cancelled);
        }

        // Untouched: not truncated, not removed, still the original bytes.
        assert_eq!(fs::read(&dest).unwrap(), b"the file that was already here");
        // And nothing of ours left lying beside it.
        let strays: Vec<_> = fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).filter(|n| n.to_string_lossy().contains("fm84-")).collect();
        assert!(strays.is_empty(), "left behind {strays:?}");

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn an_overwrite_that_finishes_replaces_the_file() {
        let dir = scratch("overwrite-done").canonicalize().unwrap();
        let source = dir.join("new.bin");
        let dest = dir.join("old.bin");
        fs::write(&source, b"replacement").unwrap();
        fs::write(&dest, b"the file that was already here").unwrap();

        let mut report = |_: Step<'_>| true;
        assert_eq!(copy_path(source, dest.clone(), false, &mut report).unwrap(), Transfer::Done);
        assert_eq!(fs::read(&dest).unwrap(), b"replacement");
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 2, "a temporary was left behind");

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn cancelling_clears_the_half_written_file() {
        let dir = scratch("cancel");
        let source = dir.join("big.bin");
        let dest = dir.join("copy.bin");
        fs::write(&source, vec![7u8; COPY_CHUNK as usize * 3]).unwrap();

        // Stop after the first chunk, the way Esc does partway through.
        let mut chunks = 0;
        {
            let mut report = |step: Step<'_>| {
                if let Step::Advanced(_) = step {
                    chunks += 1;
                }
                chunks < 1
            };
            assert_eq!(copy_path(source, dest.clone(), false, &mut report).unwrap(), Transfer::Cancelled);
        }
        // A fragment left behind would sit there looking like a finished copy.
        assert!(!dest.exists());
        // Nor is the temporary it was written into.
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "a temporary was left behind");
        fs::remove_dir_all(&dir).unwrap();
    }

    /// Until the last byte is in, a new copy is not under its own name: fm84
    /// quit or killed partway would otherwise leave half a file passing for
    /// a whole one.
    #[test]
    fn a_copy_under_way_is_not_under_its_own_name() {
        let dir = scratch("copy-temp");
        let source = dir.join("big.bin");
        let dest = dir.join("copy.bin");
        fs::write(&source, vec![7u8; COPY_CHUNK as usize * 2]).unwrap();

        let mut seen_early = None;
        {
            let mut report = |step: Step<'_>| {
                if let Step::Advanced(_) = step {
                    seen_early.get_or_insert(dest.exists());
                }
                true
            };
            assert_eq!(copy_path(source.clone(), dest.clone(), false, &mut report).unwrap(), Transfer::Done);
        }
        assert_eq!(seen_early, Some(false));
        assert_eq!(fs::read(&dest).unwrap(), fs::read(&source).unwrap());
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 2, "a temporary was left behind");
        fs::remove_dir_all(&dir).unwrap();
    }

    /// A copy keeps the times of what it came from, files and directories
    /// alike. A move across filesystems copies through the same code.
    #[test]
    fn a_copy_keeps_its_times() {
        let dir = scratch("copy-times");
        let source = dir.join("src");
        fs::create_dir_all(source.join("sub")).unwrap();
        fs::write(source.join("sub").join("old.txt"), "old").unwrap();
        let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000);
        let times = fs::FileTimes::new().set_modified(then).set_accessed(then);
        File::options().write(true).open(source.join("sub").join("old.txt")).unwrap().set_times(times).unwrap();
        for directory in [source.join("sub"), source.clone()] {
            if let Ok(handle) = File::open(&directory) {
                let _ = handle.set_times(times);
            }
        }

        let mut report = |_: Step<'_>| true;
        let copied = dir.join("copied");
        assert_eq!(copy_path(source.clone(), copied.clone(), true, &mut report).unwrap(), Transfer::Done);
        let modified = |path: &Path| fs::metadata(path).unwrap().modified().unwrap();
        assert_eq!(modified(&copied.join("sub").join("old.txt")), then);
        // Directories only where the platform lets them be opened to set it.
        if modified(&source.join("sub")) == then {
            assert_eq!(modified(&copied.join("sub")), then);
            assert_eq!(modified(&copied), then);
        }
        fs::remove_dir_all(&dir).unwrap();
    }

    /// A named pipe with no writer: anything that opens it to read blocks, so a
    /// test that reaches one hangs rather than fails.
    #[cfg(unix)]
    fn fifo(path: &Path) {
        use std::os::unix::ffi::OsStrExt;
        let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);
    }

    /// Answers every file in the way the same way, and remembers which.
    struct Clashing {
        answer: Clash,
        asked: Vec<(PathBuf, PathBuf)>,
    }

    impl Clashing {
        fn new(answer: Clash) -> Self {
            Clashing { answer, asked: Vec::new() }
        }
    }

    impl Progress for Clashing {
        fn step(&mut self, _step: Step<'_>) -> bool {
            true
        }

        fn exists(&mut self, source: &Path, dest: &Path) -> Clash {
            self.asked.push((source.to_path_buf(), dest.to_path_buf()));
            self.answer
        }
    }

    /// Answers every failure the same way, and remembers what it was asked about.
    struct Answering {
        reply: Reply,
        asked: Vec<PathBuf>,
    }

    impl Answering {
        fn new(reply: Reply) -> Self {
            Answering { reply, asked: Vec::new() }
        }
    }

    impl Progress for Answering {
        fn step(&mut self, _step: Step<'_>) -> bool {
            true
        }

        fn failed(&mut self, path: &Path, _error: &Error) -> Reply {
            self.asked.push(path.to_path_buf());
            self.reply
        }
    }

    /// The trash is found through XDG_DATA_HOME, so pointed at a scratch
    /// directory the test trashes nothing of anyone's. Set for a child run of
    /// this same test rather than with set_var: the variable belongs to the
    /// whole process, where every other test is running at the same time.
    #[cfg(target_os = "linux")]
    #[test]
    fn trashing_moves_it_away_and_what_will_not_go_can_be_deleted() {
        const ROOT: &str = "FM84_TRASH_TEST_ROOT";
        let Some(root) = std::env::var_os(ROOT).map(PathBuf::from) else {
            let root = std::env::temp_dir().join(format!("fm84-trash-{}", std::process::id()));
            let _ = fs::remove_dir_all(&root);
            fs::create_dir_all(&root).unwrap();
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args(["--exact", "fs_ops::transfer_tests::trashing_moves_it_away_and_what_will_not_go_can_be_deleted", "--nocapture"])
                .env(ROOT, &root)
                .env("XDG_DATA_HOME", root.join("data"))
                .output()
                .unwrap();
            let _ = fs::remove_dir_all(&root);
            let said = String::from_utf8_lossy(&output.stdout);
            assert!(output.status.success() && said.contains("1 passed"), "the child run failed:\n{said}");
            return;
        };
        let data = root.join("data");

        // A file and a directory with something in it go, and are in the trash.
        let file = root.join("note.txt");
        fs::write(&file, "kept").unwrap();
        let dir = root.join("folder");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("inside.txt"), "").unwrap();
        let mut answering = Answering::new(Reply::Abort);
        assert_eq!(trash_path(file.clone(), false, &mut answering).unwrap(), Transfer::Done);
        assert_eq!(trash_path(dir.clone(), true, &mut answering).unwrap(), Transfer::Done);
        assert!(!file.exists() && !dir.exists());
        assert_eq!(fs::read_to_string(data.join("Trash/files/note.txt")).unwrap(), "kept");
        assert!(data.join("Trash/files/folder/inside.txt").exists());
        assert!(data.join("Trash/info/note.txt.trashinfo").exists());
        assert!(answering.asked.is_empty());

        // A trash that cannot be made takes nothing. Its directory is a file
        // now, where it was one to make before.
        fs::remove_dir_all(&data).unwrap();
        fs::write(&data, "").unwrap();
        let other = root.join("other");
        fs::create_dir_all(&other).unwrap();
        fs::write(other.join("inside.txt"), "").unwrap();

        // Skipped, it stays; asked to delete instead, it goes for good.
        let mut skipping = Answering::new(Reply::Skip);
        assert_eq!(trash_path(other.clone(), true, &mut skipping).unwrap(), Transfer::Done);
        assert!(other.exists());
        assert_eq!(skipping.asked, std::slice::from_ref(&other));
        let mut deleting = Answering::new(Reply::Delete);
        assert_eq!(trash_path(other.clone(), true, &mut deleting).unwrap(), Transfer::Done);
        assert!(!other.exists());
    }

    /// The delete inside a trash job counts nothing of its own: the item it
    /// stands for is counted once, by the trash.
    #[test]
    fn a_delete_inside_another_step_counts_nothing() {
        let dir = std::env::temp_dir().join(format!("fm84-uncounted-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("sub")).unwrap();
        fs::write(dir.join("sub").join("a"), "").unwrap();

        let mut counted = 0;
        let mut started = 0;
        let mut report = |step: Step<'_>| {
            match step {
                Step::Advanced(amount) => counted += amount,
                Step::Starting(_) => started += 1,
            }
            true
        };
        let mut uncounted = Uncounted(&mut report);
        assert_eq!(delete_path(dir.clone(), true, &mut uncounted).unwrap(), Transfer::Done);
        assert!(!dir.exists());
        assert_eq!(counted, 0);
        // Still named as it goes, so the popup shows what is being deleted.
        assert_eq!(started, 3);
    }

    /// A directory nothing can be added to or removed from. None when running
    /// as root, which the permissions do not stop.
    #[cfg(unix)]
    fn locked(dir: &Path) -> Option<()> {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(dir, fs::Permissions::from_mode(0o555)).unwrap();
        if File::create(dir.join(".probe")).is_ok() {
            let _ = remove_file(dir.join(".probe"));
            unlock(dir);
            return None;
        }
        Some(())
    }

    #[cfg(unix)]
    fn unlock(dir: &Path) {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(dir, fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_skipped_pipe_leaves_the_rest_of_the_copy_whole() {
        let dir = scratch("skip-pipe");
        let tree = dir.join("tree");
        fs::create_dir_all(tree.join("sub")).unwrap();
        fs::write(tree.join("a.txt"), "a").unwrap();
        fifo(&tree.join("pipe"));
        fs::write(tree.join("sub").join("b.txt"), "b").unwrap();

        let mut progress = Answering::new(Reply::Skip);
        let dest = dir.join("copy");
        assert_eq!(copy_path(tree.clone(), dest.clone(), true, &mut progress).unwrap(), Transfer::Done);
        assert_eq!(progress.asked, [tree.join("pipe")]);
        assert_eq!(fs::read_to_string(dest.join("a.txt")).unwrap(), "a");
        assert_eq!(fs::read_to_string(dest.join("sub").join("b.txt")).unwrap(), "b");
        assert!(!path_exists(&dest.join("pipe")));

        // Abort ends it with the error, as a failure always did before.
        let mut progress = Answering::new(Reply::Abort);
        assert!(copy_path(tree, dir.join("aborted"), true, &mut progress).is_err());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_skipped_delete_keeps_only_what_holds_it() {
        let dir = scratch("skip-delete");
        let tree = dir.join("tree");
        fs::create_dir_all(tree.join("locked")).unwrap();
        fs::create_dir_all(tree.join("open")).unwrap();
        fs::write(tree.join("locked").join("stuck.txt"), "").unwrap();
        fs::write(tree.join("open").join("free.txt"), "").unwrap();
        fs::write(tree.join("top.txt"), "").unwrap();
        if locked(&tree.join("locked")).is_none() {
            return fs::remove_dir_all(&dir).unwrap();
        }

        let mut progress = Answering::new(Reply::Skip);
        assert_eq!(delete_path(tree.clone(), true, &mut progress).unwrap(), Transfer::Done);
        // Asked about the one file, and not again about the directories that
        // cannot go because it is still in them.
        assert_eq!(progress.asked, [tree.join("locked").join("stuck.txt")]);
        assert!(path_exists(&tree.join("locked").join("stuck.txt")));
        assert!(!path_exists(&tree.join("open")));
        assert!(!path_exists(&tree.join("top.txt")));

        unlock(&tree.join("locked"));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_retry_tries_the_same_entry_again() {
        struct UnlockThenRetry(PathBuf, u32);
        impl Progress for UnlockThenRetry {
            fn step(&mut self, _step: Step<'_>) -> bool {
                true
            }
            fn failed(&mut self, _path: &Path, _error: &Error) -> Reply {
                // What the user would do between seeing the error and pressing R.
                unlock(&self.0);
                self.1 += 1;
                Reply::Retry
            }
        }

        let dir = scratch("retry");
        fs::create_dir(dir.join("locked")).unwrap();
        fs::write(dir.join("locked").join("file"), "").unwrap();
        if locked(&dir.join("locked")).is_none() {
            return fs::remove_dir_all(&dir).unwrap();
        }

        let mut progress = UnlockThenRetry(dir.join("locked"), 0);
        assert_eq!(delete_path(dir.join("locked"), true, &mut progress).unwrap(), Transfer::Done);
        assert_eq!(progress.1, 1);
        assert!(!path_exists(&dir.join("locked")));
        fs::remove_dir_all(&dir).unwrap();
    }

    /// A move merging into a directory goes entry by entry, and one it cannot
    /// take from its source stays there, copied but not removed, rather than
    /// gone from both.
    #[cfg(unix)]
    #[test]
    fn a_skipped_move_leaves_the_source_of_what_it_skipped() {
        let dir = scratch("skip-move");
        let source = dir.join("a");
        fs::create_dir_all(source.join("locked")).unwrap();
        fs::write(source.join("locked").join("stuck.txt"), "stuck").unwrap();
        fs::write(source.join("free.txt"), "free").unwrap();
        let dest = dir.join("b");
        fs::create_dir_all(dest.join("locked")).unwrap();
        fs::write(dest.join("locked").join("other.txt"), "").unwrap();
        if locked(&source.join("locked")).is_none() {
            return fs::remove_dir_all(&dir).unwrap();
        }

        let mut progress = Answering::new(Reply::Skip);
        assert_eq!(move_path(source.clone(), dest.clone(), &mut progress).unwrap(), Transfer::Done);
        assert_eq!(progress.asked, [source.join("locked").join("stuck.txt")]);
        assert_eq!(fs::read_to_string(dest.join("free.txt")).unwrap(), "free");
        assert!(!path_exists(&source.join("free.txt")));
        assert_eq!(fs::read_to_string(source.join("locked").join("stuck.txt")).unwrap(), "stuck");
        assert_eq!(fs::read_to_string(dest.join("locked").join("stuck.txt")).unwrap(), "stuck");

        unlock(&source.join("locked"));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn special_files_are_never_opened() {
        let dir = scratch("fifo");
        let pipe = dir.join("pipe");
        fifo(&pipe);

        assert!(!is_regular_file(&pipe));
        assert!(!is_regular_file(Path::new("/dev/zero")));
        assert!(!is_regular_file(&dir));
        fs::write(dir.join("plain"), "x").unwrap();
        assert!(is_regular_file(&dir.join("plain")));

        assert!(matches!(crate::viewer::load_preview(&pipe, 1024, 10), crate::viewer::Preview::Lines(lines) if lines == ["Not a regular file"]));
        assert!(crate::viewer::load_file_content(&pipe, None).is_err());
        assert!(crate::viewer::load_file_content(Path::new("/dev/zero"), None).is_err());

        // Alone, and inside a directory being copied.
        let mut report = |_: Step<'_>| true;
        assert!(copy_path(pipe.clone(), dir.join("pipe-copy"), false, &mut report).is_err());
        let tree = dir.join("tree");
        fs::create_dir(&tree).unwrap();
        fifo(&tree.join("pipe"));
        assert!(copy_path(tree, dir.join("tree-copy"), true, &mut report).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_failed_copy_leaves_no_fragment() {
        // A regular file that opens, then fails the first read: offset 0 of a
        // process's memory is never mapped.
        let source = Path::new("/proc/self/mem");
        let dir = scratch("failed");
        let dest = dir.join("mem-copy");
        let mut report = |_: Step<'_>| true;
        assert!(copy_path(source.to_path_buf(), dest.clone(), false, &mut report).is_err());
        assert!(!path_exists(&dest));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_plain_name_stays_where_it_is_put() {
        for name in ["notes.txt", ".hidden", "with space", "ünïcode", "a.b.c"] {
            assert!(is_plain_name(name), "{name}");
        }
        for name in ["", ".", "..", "../x", "sub/x", "x/", "/x", "./x"] {
            assert!(!is_plain_name(name), "{name}");
        }
        #[cfg(windows)]
        for name in ["sub\\x", "C:x", "C:"] {
            assert!(!is_plain_name(name), "{name}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn an_entry_is_itself_and_nothing_else() {
        let dir = scratch("same");
        fs::write(dir.join("a"), "a").unwrap();
        fs::write(dir.join("b"), "b").unwrap();
        std::os::unix::fs::symlink(dir.join("a"), dir.join("link")).unwrap();

        assert!(is_same_entry(&dir.join("a"), &dir.join("a")));
        assert!(!is_same_entry(&dir.join("a"), &dir.join("b")));
        // A link to a is an entry of its own; renaming a over it must be refused.
        assert!(!is_same_entry(&dir.join("a"), &dir.join("link")));
        assert!(!is_same_entry(&dir.join("a"), &dir.join("missing")));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn only_a_cross_device_rename_falls_back_to_copying() {
        assert!(is_cross_device(&Error::from_raw_os_error(libc::EXDEV)));
        // 17, which the fallback used to take for Windows' cross-device error.
        assert!(!is_cross_device(&Error::from_raw_os_error(libc::EEXIST)));
        assert!(!is_cross_device(&Error::from_raw_os_error(libc::ENOTEMPTY)));
        assert!(!is_cross_device(&Error::from_raw_os_error(libc::EACCES)));
    }

    #[cfg(unix)]
    #[test]
    fn a_copy_keeps_its_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o7777;
        let set = |path: &Path, mode: u32| fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();

        let dir = scratch("modes");
        let source = dir.join("src");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("script"), "#!/bin/sh\n").unwrap();
        set(&source.join("script"), 0o755);
        fs::write(source.join("secret"), "x").unwrap();
        set(&source.join("secret"), 0o600);
        // Read-only, so its files have to be copied in before it gets its mode.
        set(&source, 0o555);

        let dest = dir.join("dst");
        let mut report = |_: Step<'_>| true;
        assert_eq!(copy_path(source.clone(), dest.clone(), true, &mut report).unwrap(), Transfer::Done);
        assert_eq!(mode(&dest.join("script")), 0o755);
        assert_eq!(mode(&dest.join("secret")), 0o600);
        assert_eq!(mode(&dest), 0o555);

        set(&source, 0o755);
        set(&dest, 0o755);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn refusing_the_first_file_copies_nothing() {
        let dir = scratch("refuse");
        let source = dir.join("src");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("a.bin"), vec![1u8; 10]).unwrap();
        let dest = dir.join("dst");

        let mut report = |_: Step<'_>| false;
        assert_eq!(copy_path(source, dest.clone(), true, &mut report).unwrap(), Transfer::Cancelled);
        assert!(!dest.join("a.bin").exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_directory_will_not_be_copied_into_itself() {
        let dir = scratch("into-itself").canonicalize().unwrap();
        let source = dir.join("sub");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("f.bin"), vec![1u8; 32]).unwrap();

        // Straight into itself, and deeper inside itself.
        assert!(copies_into_itself(&source, &source.join("sub")));
        assert!(copies_into_itself(&source, &source.join("a").join("b")));

        // Ordinary copies must still go through.
        assert!(!copies_into_itself(&source, &dir.join("elsewhere")));
        assert!(!copies_into_itself(&source, &dir.join("sub2")));
        // Sharing a name prefix is not being inside: "/x/subfoo" is not in "/x/sub".
        assert!(!copies_into_itself(&source, &dir.join("subfoo").join("sub")));
        // A file has nothing to recurse into.
        assert!(!copies_into_itself(&source.join("f.bin"), &source.join("f.bin").join("x")));

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    #[cfg(unix)]
    fn a_link_into_the_source_is_caught_and_a_link_source_is_not() {
        let dir = scratch("into-itself-links").canonicalize().unwrap();
        let source = dir.join("sub");
        fs::create_dir(&source).unwrap();

        // A destination that reaches the source through a link is still inside.
        let link = dir.join("link");
        std::os::unix::fs::symlink(&source, &link).unwrap();
        assert!(copies_into_itself(&source, &link.join("copy")));

        // A link is recreated rather than walked, so it cannot recurse and is
        // not refused - even pointing at the directory it is copied into.
        assert!(!copies_into_itself(&link, &source.join("copy")));

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn the_runaway_copy_is_refused_before_anything_is_written() {
        let dir = scratch("runaway").canonicalize().unwrap();
        let source = dir.join("sub");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("f.bin"), vec![9u8; 64]).unwrap();

        let mut report = |_: Step<'_>| true;
        let error = copy_path(source.clone(), source.join("sub"), true, &mut report).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
        assert!(error.to_string().contains("into itself"), "{error}");
        // Nothing started, so nothing was left behind.
        assert!(!source.join("sub").exists());
        assert_eq!(fs::read_dir(&source).unwrap().count(), 1);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_delete_counts_and_removes_every_entry() {
        let dir = scratch("delete").canonicalize().unwrap();
        let tree = dir.join("tree");
        fs::create_dir(&tree).unwrap();
        fs::write(tree.join("a.bin"), b"a").unwrap();
        fs::create_dir(tree.join("inner")).unwrap();
        fs::write(tree.join("inner").join("b.bin"), b"b").unwrap();

        // tree, a.bin, inner, b.bin. Counted before the delete, since counting
        // walks the live filesystem and there is nothing left to walk after.
        let total = count_entries(&[(tree.clone(), true)]);
        assert_eq!(total, 4);

        let mut removed = 0u64;
        let mut named = Vec::new();
        {
            let mut report = |step: Step<'_>| {
                match step {
                    Step::Starting(path) => named.push(path.file_name().unwrap().to_string_lossy().into_owned()),
                    Step::Advanced(n) => removed += n,
                }
                true
            };
            assert_eq!(delete_path(tree.clone(), true, &mut report).unwrap(), Transfer::Done);
        }

        assert!(!tree.exists());
        // What the bar counts has to reach what the counting pass promised.
        assert_eq!(removed, total);
        named.sort();
        assert_eq!(named, ["a.bin", "b.bin", "inner", "tree"]);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn cancelling_a_delete_leaves_the_rest_alone() {
        let dir = scratch("delete-cancel").canonicalize().unwrap();
        let tree = dir.join("tree");
        fs::create_dir(&tree).unwrap();
        for index in 0..8 {
            fs::write(tree.join(format!("f{index}.bin")), b"x").unwrap();
        }

        // Stop after the first entry, the way Esc does partway through.
        let mut removed = 0;
        {
            let mut report = |step: Step<'_>| {
                if let Step::Advanced(_) = step {
                    removed += 1;
                }
                removed < 1
            };
            assert_eq!(delete_path(tree.clone(), true, &mut report).unwrap(), Transfer::Cancelled);
        }

        // The tree is still there, minus what had already gone.
        assert!(tree.exists());
        assert_eq!(fs::read_dir(&tree).unwrap().count(), 7);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    #[cfg(unix)]
    fn deleting_a_link_to_a_directory_spares_what_it_points_at() {
        let dir = scratch("delete-link").canonicalize().unwrap();
        let target = dir.join("target");
        fs::create_dir(&target).unwrap();
        fs::write(target.join("keep.bin"), b"keep").unwrap();

        // The panel reports a link to a directory as a directory, so the delete
        // arrives with is_dir set and must still only unlink it.
        let link = dir.join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        assert_eq!(count_entries(&[(link.clone(), true)]), 1);

        let mut report = |_: Step<'_>| true;
        assert_eq!(delete_path(link.clone(), true, &mut report).unwrap(), Transfer::Done);

        assert!(!link.exists());
        assert!(target.join("keep.bin").exists(), "the link's target was followed");

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_destination_is_read_as_cp_reads_it() {
        let dir = scratch("targets");
        fs::create_dir(dir.join("into")).unwrap();
        let one = vec![(dir.join("a.txt"), false)];
        let two = vec![(dir.join("a.txt"), false), (dir.join("sub"), true)];

        // A directory that is there takes each under its own name, whether or
        // not it was typed with a separator after it.
        for names_dir in [false, true] {
            assert_eq!(
                transfer_targets(&two, &dir.join("into"), names_dir).unwrap(),
                [(dir.join("a.txt"), dir.join("into").join("a.txt"), false), (dir.join("sub"), dir.join("into").join("sub"), true)]
            );
        }
        // Anything else is a new name, for one source only.
        assert_eq!(transfer_targets(&one, &dir.join("b.txt"), false).unwrap(), [(dir.join("a.txt"), dir.join("b.txt"), false)]);
        assert!(transfer_targets(&two, &dir.join("b.txt"), false).unwrap_err().contains("2 items need a directory"));
        // In a directory that has to be there, and a separator means one.
        assert!(transfer_targets(&one, &dir.join("missing").join("b.txt"), false).unwrap_err().starts_with("No such directory"));
        assert!(transfer_targets(&one, &dir.join("missing"), true).unwrap_err().starts_with("No such directory"));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn destinations_are_checked_before_anything_is_written() {
        let dir = scratch("check");
        let (from, to) = (dir.join("from"), dir.join("to"));
        fs::create_dir_all(from.join("tree")).unwrap();
        fs::create_dir_all(to.join("tree")).unwrap();
        for name in ["same", "new", "file-vs-dir"] {
            fs::write(from.join(name), name).unwrap();
        }
        fs::write(to.join("same"), "old").unwrap();
        fs::create_dir(to.join("file-vs-dir")).unwrap();
        let item = |name: &str| (from.join(name), to.join(name), from.join(name).is_dir());

        // Nothing in the way, and something in the way: the latter is reported.
        assert_eq!(check_destinations(&[item("new")]).unwrap(), Vec::<PathBuf>::new());
        assert_eq!(check_destinations(&[item("new"), item("same"), item("tree")]).unwrap(), [to.join("same"), to.join("tree")]);
        // What overwriting could never make right.
        assert!(check_destinations(&[item("file-vs-dir")]).unwrap_err().contains("Cannot replace directory"));
        assert!(check_destinations(&[(to.join("tree"), from.join("same"), true)]).unwrap_err().contains("Cannot replace file"));
        assert!(check_destinations(&[(from.join("same"), from.join("same"), false)]).unwrap_err().contains("already there"));
        assert!(check_destinations(&[(from.clone(), from.join("inside"), true)]).unwrap_err().contains("into itself"));
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_move_onto_a_directory_merges_into_it() {
        let dir = scratch("merge");
        let (source, dest) = (dir.join("src"), dir.join("dst"));
        fs::create_dir_all(source.join("sub")).unwrap();
        fs::write(source.join("clash"), "new").unwrap();
        fs::write(source.join("sub").join("only-in-source"), "s").unwrap();
        fs::create_dir_all(dest.join("sub")).unwrap();
        fs::write(dest.join("clash"), "old").unwrap();
        fs::write(dest.join("only-in-dest"), "d").unwrap();

        // Skipped: the rest merges, and the file in the way stays as it was -
        // as does the one that would have replaced it, with its directory.
        let mut keeping = Clashing::new(Clash::Keep);
        assert_eq!(move_path(source.clone(), dest.clone(), &mut keeping).unwrap(), Transfer::Done);
        assert_eq!(keeping.asked, [(source.join("clash"), dest.join("clash"))]);
        assert_eq!(fs::read_to_string(dest.join("clash")).unwrap(), "old");
        assert_eq!(fs::read_to_string(source.join("clash")).unwrap(), "new");
        assert!(dest.join("sub").join("only-in-source").exists());

        // Written over, which is what a caller with nobody to ask gets.
        let mut report = |_: Step<'_>| true;
        assert_eq!(move_path(source.clone(), dest.clone(), &mut report).unwrap(), Transfer::Done);
        assert!(!source.exists());
        assert_eq!(fs::read_to_string(dest.join("clash")).unwrap(), "new");
        assert_eq!(fs::read_to_string(dest.join("only-in-dest")).unwrap(), "d");
        assert_eq!(fs::read_to_string(dest.join("sub").join("only-in-source")).unwrap(), "s");
        fs::remove_dir_all(&dir).unwrap();
    }

    /// Merging within one filesystem renames each entry into place rather
    /// than copying it and deleting the source. A copy would be a new file
    /// with a new inode; a rename keeps the one it had, and takes no time
    /// however large the file.
    #[cfg(unix)]
    #[test]
    fn a_merge_on_one_filesystem_renames_rather_than_copies() {
        use std::os::unix::fs::MetadataExt;
        let inode = |path: &Path| fs::symlink_metadata(path).unwrap().ino();

        let dir = scratch("merge-rename");
        let (source, dest) = (dir.join("src"), dir.join("dst"));
        fs::create_dir_all(source.join("shared")).unwrap();
        fs::create_dir_all(source.join("fresh")).unwrap();
        fs::write(source.join("shared").join("big.bin"), vec![0u8; 4096]).unwrap();
        fs::write(source.join("fresh").join("inner.txt"), "i").unwrap();
        fs::write(source.join("clash"), "new").unwrap();
        fs::create_dir_all(dest.join("shared")).unwrap();
        fs::write(dest.join("shared").join("keep.txt"), "k").unwrap();
        fs::write(dest.join("clash"), "old").unwrap();

        let before = [inode(&source.join("shared").join("big.bin")), inode(&source.join("fresh")), inode(&source.join("clash"))];
        let mut report = |_: Step<'_>| true;
        assert_eq!(move_path(source.clone(), dest.clone(), &mut report).unwrap(), Transfer::Done);

        // A file inside a directory both sides have, a directory only the
        // source has (moved whole), and a file replacing one in the way.
        let after = [inode(&dest.join("shared").join("big.bin")), inode(&dest.join("fresh")), inode(&dest.join("clash"))];
        assert_eq!(before, after);
        assert_eq!(fs::read_to_string(dest.join("clash")).unwrap(), "new");
        assert_eq!(fs::read_to_string(dest.join("shared").join("keep.txt")).unwrap(), "k");
        assert!(!source.exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    /// Merged into a directory holding another name for the same file - a
    /// hard link - the move takes the source's name away and is done, rather
    /// than leaving it and failing on its directory as not empty.
    #[cfg(unix)]
    #[test]
    fn a_move_onto_its_own_hard_link_takes_the_old_name_away() {
        let dir = scratch("move-hardlink");
        let (source, dest) = (dir.join("src"), dir.join("dst"));
        fs::create_dir_all(&source).unwrap();
        fs::create_dir_all(&dest).unwrap();
        fs::write(source.join("shared"), "one file, two names").unwrap();
        fs::hard_link(source.join("shared"), dest.join("shared")).unwrap();
        fs::write(source.join("other"), "o").unwrap();

        // Not asked about: nothing would be written over.
        let mut asking = Clashing::new(Clash::Keep);
        assert_eq!(move_path(source.clone(), dest.clone(), &mut asking).unwrap(), Transfer::Done);
        assert!(asking.asked.is_empty(), "{:?}", asking.asked);
        assert!(!source.exists(), "the source directory is gone, emptied");
        assert_eq!(fs::read_to_string(dest.join("shared")).unwrap(), "one file, two names");
        assert_eq!(fs::read_to_string(dest.join("other")).unwrap(), "o");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_move_onto_a_file_replaces_it() {
        let dir = scratch("replace");
        fs::write(dir.join("a"), "new").unwrap();
        fs::write(dir.join("b"), "old").unwrap();
        let mut report = |_: Step<'_>| true;
        assert_eq!(move_path(dir.join("a"), dir.join("b"), &mut report).unwrap(), Transfer::Done);
        assert_eq!(fs::read_to_string(dir.join("b")).unwrap(), "new");
        assert!(!dir.join("a").exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn overwriting_replaces_a_link_rather_than_writing_through_it() {
        let dir = scratch("through");
        fs::write(dir.join("precious"), "keep me").unwrap();
        fs::write(dir.join("new"), "new").unwrap();
        std::os::unix::fs::symlink(dir.join("precious"), dir.join("link")).unwrap();

        let mut report = |_: Step<'_>| true;
        copy_path(dir.join("new"), dir.join("link"), false, &mut report).unwrap();
        assert_eq!(fs::read_to_string(dir.join("precious")).unwrap(), "keep me");
        assert!(!dir.join("link").symlink_metadata().unwrap().file_type().is_symlink());
        assert_eq!(fs::read_to_string(dir.join("link")).unwrap(), "new");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn overwriting_a_read_only_file_replaces_it() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("readonly");
        fs::write(dir.join("new"), "new").unwrap();
        fs::write(dir.join("locked"), "old").unwrap();
        fs::set_permissions(dir.join("locked"), fs::Permissions::from_mode(0o444)).unwrap();

        let mut report = |_: Step<'_>| true;
        copy_path(dir.join("new"), dir.join("locked"), false, &mut report).unwrap();
        assert_eq!(fs::read_to_string(dir.join("locked")).unwrap(), "new");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_rename_within_one_filesystem_moves_no_bytes() {
        let dir = scratch("rename");
        let source = dir.join("a.bin");
        let dest = dir.join("b.bin");
        fs::write(&source, vec![3u8; 4096]).unwrap();

        assert!(rename_in_place(&source, &dest));
        assert!(!source.exists() && dest.exists());
        // Across filesystems it has to say so rather than pretend.
        assert!(!rename_in_place(&dest, Path::new("/proc/fm84-cannot-go-here")));
        fs::remove_dir_all(&dir).unwrap();
    }
}

/// The parts of an entry the columns have no room for: its exact size, the
/// second on its timestamp, who owns it, and where it points if it is a link.
pub struct Description {
    pub size_bytes: Option<u64>,
    pub modified: Option<std::time::SystemTime>,
    pub owner: String,
    pub attributes: String,
    /// Where a symlink points. Listed but never shown until now, and it is the
    /// one thing about a link worth knowing.
    pub link: Option<String>,
}

/// Look one entry up. Costs a stat, a readlink for a link, and the owner's
/// name - which is why it is done when the cursor moves rather than on the way
/// to drawing a frame, and on a thread of its own, where a dead mount holds
/// up nothing.
pub fn describe(path: &Path, is_dir: bool) -> Option<Description> {
    let metadata = fs::symlink_metadata(path).ok()?;
    let is_symlink = metadata.file_type().is_symlink();
    // A link's own size is the length of the path it holds, which tells nobody
    // anything; follow it for the figure. A broken one has no figure at all,
    // and saying 31 bytes would be worse than saying nothing.
    let followed = if is_symlink { fs::metadata(path).ok() } else { None };
    let size_bytes = if is_symlink { followed.as_ref().map(|target| target.len()) } else { (!is_dir).then_some(metadata.len()) };

    Some(Description {
        size_bytes,
        modified: metadata.modified().ok(),
        owner: owner_of(&metadata),
        // The link's own bits, as ls -l writes them, not the target's.
        attributes: format_attributes(&metadata, is_dir, is_symlink),
        link: is_symlink.then(|| fs::read_link(path).ok()).flatten().map(|target| target.display().to_string()),
    })
}

/// Who owns it, by name where the system can say and by number where it cannot.
#[cfg(unix)]
fn owner_of(metadata: &fs::Metadata) -> String {
    use std::os::unix::fs::MetadataExt;
    let (uid, gid) = (metadata.uid(), metadata.gid());

    let user = lookup_name(|entry: &mut libc::passwd, buffer, length, found| unsafe { libc::getpwuid_r(uid, entry, buffer, length, found) }, |entry| entry.pw_name);
    let group = lookup_name(|entry: &mut libc::group, buffer, length, found| unsafe { libc::getgrgid_r(gid, entry, buffer, length, found) }, |entry| entry.gr_name);

    format!("{}:{}", user.unwrap_or_else(|| uid.to_string()), group.unwrap_or_else(|| gid.to_string()))
}

/// A user or group name, looked up with the _r calls, which write into a
/// buffer of ours. The plain getpwuid and getgrgid hand back storage shared by
/// the whole process, which is only safe while one thread ever asks - and the
/// detail lines are gathered on a thread of their own now. The buffer grows
/// for an entry too long for it, as a directory service's can be.
#[cfg(unix)]
fn lookup_name<E>(call: impl Fn(&mut E, *mut libc::c_char, libc::size_t, *mut *mut E) -> libc::c_int, name: impl Fn(&E) -> *const libc::c_char) -> Option<String> {
    let mut buffer: Vec<libc::c_char> = vec![0; 1024];
    loop {
        // SAFETY: an all-zero passwd or group is a valid value of the type -
        // null pointers and zero ids - and is only read once the call has
        // filled it in and said so by setting `found`.
        let mut entry: E = unsafe { std::mem::zeroed() };
        let mut found: *mut E = std::ptr::null_mut();
        let status = call(&mut entry, buffer.as_mut_ptr(), buffer.len(), &mut found);
        if status == libc::ERANGE && buffer.len() < 1 << 20 {
            buffer.resize(buffer.len() * 2, 0);
            continue;
        }
        if status != 0 || found.is_null() {
            return None;
        }
        let pointer = name(&entry);
        // SAFETY: the name points into `buffer`, which is alive and holds a
        // NUL-terminated string the call wrote there.
        return (!pointer.is_null()).then(|| unsafe { std::ffi::CStr::from_ptr(pointer) }.to_string_lossy().into_owned());
    }
}

#[cfg(not(unix))]
fn owner_of(_metadata: &fs::Metadata) -> String {
    String::new()
}