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
use anyhow::{anyhow, Context};
use async_recursion::async_recursion;
use std::os::linux::fs::MetadataExt as LinuxMetadataExt;
use tracing::instrument;
use crate::config::DryRunMode;
use crate::copy;
use crate::copy::{
check_empty_dir_cleanup, EmptyDirAction, Settings as CopySettings, Summary as CopySummary,
};
use crate::filecmp;
use crate::filter::{FilterResult, FilterSettings};
use crate::preserve;
use crate::progress;
use crate::rm;
/// Error type for link operations that preserves operation summary even on failure.
///
/// # Logging Convention
/// When logging this error, use `{:#}` or `{:?}` format to preserve the error chain:
/// ```ignore
/// tracing::error!("operation failed: {:#}", &error); // ✅ Shows full chain
/// tracing::error!("operation failed: {:?}", &error); // ✅ Shows full chain
/// ```
/// The Display implementation also shows the full chain, but workspace linting enforces `{:#}`
/// for consistency.
#[derive(Debug, thiserror::Error)]
#[error("{source:#}")]
pub struct Error {
#[source]
pub source: anyhow::Error,
pub summary: Summary,
}
impl Error {
#[must_use]
pub fn new(source: anyhow::Error, summary: Summary) -> Self {
Error { source, summary }
}
}
#[derive(Debug, Clone)]
pub struct Settings {
pub copy_settings: CopySettings,
pub update_compare: filecmp::MetadataCmpSettings,
pub update_exclusive: bool,
/// filter settings for include/exclude patterns
pub filter: Option<crate::filter::FilterSettings>,
/// dry-run mode for previewing operations
pub dry_run: Option<crate::config::DryRunMode>,
/// metadata preservation settings
pub preserve: preserve::Settings,
}
/// Reports a dry-run action for link operations
fn report_dry_run_link(src: &std::path::Path, dst: &std::path::Path, entry_type: &str) {
println!("would link {} {:?} -> {:?}", entry_type, src, dst);
}
/// Reports a skipped entry during dry-run
fn report_dry_run_skip(
path: &std::path::Path,
result: &FilterResult,
mode: DryRunMode,
entry_type: &str,
) {
match mode {
DryRunMode::Brief => { /* brief mode doesn't show skipped files */ }
DryRunMode::All => {
println!("skip {} {:?}", entry_type, path);
}
DryRunMode::Explain => match result {
FilterResult::ExcludedByDefault => {
println!(
"skip {} {:?} (no include pattern matched)",
entry_type, path
);
}
FilterResult::ExcludedByPattern(pattern) => {
println!("skip {} {:?} (excluded by '{}')", entry_type, path, pattern);
}
FilterResult::Included => { /* shouldn't happen */ }
},
}
}
/// Check if a path should be filtered out
fn should_skip_entry(
filter: &Option<FilterSettings>,
relative_path: &std::path::Path,
is_dir: bool,
) -> Option<FilterResult> {
if let Some(ref f) = filter {
let result = f.should_include(relative_path, is_dir);
match result {
FilterResult::Included => None,
_ => Some(result),
}
} else {
None
}
}
#[derive(Copy, Clone, Debug, Default)]
pub struct Summary {
pub hard_links_created: usize,
pub hard_links_unchanged: usize,
pub copy_summary: CopySummary,
}
impl std::ops::Add for Summary {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
hard_links_created: self.hard_links_created + other.hard_links_created,
hard_links_unchanged: self.hard_links_unchanged + other.hard_links_unchanged,
copy_summary: self.copy_summary + other.copy_summary,
}
}
}
impl std::fmt::Display for Summary {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{}\n\
link:\n\
-----\n\
hard-links created: {}\n\
hard links unchanged: {}\n",
&self.copy_summary, self.hard_links_created, self.hard_links_unchanged
)
}
}
fn is_hard_link(md1: &std::fs::Metadata, md2: &std::fs::Metadata) -> bool {
copy::is_file_type_same(md1, md2)
&& md2.st_dev() == md1.st_dev()
&& md2.st_ino() == md1.st_ino()
}
#[instrument(skip(prog_track, settings))]
async fn hard_link_helper(
prog_track: &'static progress::Progress,
src: &std::path::Path,
src_metadata: &std::fs::Metadata,
dst: &std::path::Path,
settings: &Settings,
) -> Result<Summary, Error> {
let mut link_summary = Summary::default();
if let Err(error) = tokio::fs::hard_link(src, dst).await {
if settings.copy_settings.overwrite && error.kind() == std::io::ErrorKind::AlreadyExists {
tracing::debug!("'dst' already exists, check if we need to update");
let dst_metadata = tokio::fs::symlink_metadata(dst)
.await
.with_context(|| format!("cannot read {dst:?} metadata"))
.map_err(|err| Error::new(err, Default::default()))?;
if is_hard_link(src_metadata, &dst_metadata) {
tracing::debug!("no change, leaving file as is");
prog_track.hard_links_unchanged.inc();
return Ok(Summary {
hard_links_unchanged: 1,
..Default::default()
});
}
tracing::info!("'dst' file type changed, removing and hard-linking");
let rm_summary = rm::rm(
prog_track,
dst,
&rm::Settings {
fail_early: settings.copy_settings.fail_early,
filter: None,
dry_run: None,
},
)
.await
.map_err(|err| {
let rm_summary = err.summary;
link_summary.copy_summary.rm_summary = rm_summary;
Error::new(err.source, link_summary)
})?;
link_summary.copy_summary.rm_summary = rm_summary;
tokio::fs::hard_link(src, dst)
.await
.with_context(|| format!("failed to hard link {:?} to {:?}", src, dst))
.map_err(|err| Error::new(err, link_summary))?;
}
}
prog_track.hard_links_created.inc();
link_summary.hard_links_created = 1;
Ok(link_summary)
}
/// Public entry point for link operations.
/// Internally delegates to link_internal with source_root tracking for proper filter matching.
#[instrument(skip(prog_track, settings))]
pub async fn link(
prog_track: &'static progress::Progress,
cwd: &std::path::Path,
src: &std::path::Path,
dst: &std::path::Path,
update: &Option<std::path::PathBuf>,
settings: &Settings,
is_fresh: bool,
) -> Result<Summary, Error> {
// check filter for top-level source (files, directories, and symlinks)
if let Some(ref filter) = settings.filter {
let src_name = src.file_name().map(std::path::Path::new);
if let Some(name) = src_name {
let src_metadata = tokio::fs::symlink_metadata(src)
.await
.with_context(|| format!("failed reading metadata from {:?}", &src))
.map_err(|err| Error::new(err, Default::default()))?;
let is_dir = src_metadata.is_dir();
let result = filter.should_include_root_item(name, is_dir);
match result {
crate::filter::FilterResult::Included => {}
result => {
if let Some(mode) = settings.dry_run {
let entry_type = if src_metadata.is_dir() {
"directory"
} else if src_metadata.file_type().is_symlink() {
"symlink"
} else {
"file"
};
report_dry_run_skip(src, &result, mode, entry_type);
}
// return summary with skipped count
let skipped_summary = if src_metadata.is_dir() {
prog_track.directories_skipped.inc();
Summary {
copy_summary: CopySummary {
directories_skipped: 1,
..Default::default()
},
..Default::default()
}
} else if src_metadata.file_type().is_symlink() {
prog_track.symlinks_skipped.inc();
Summary {
copy_summary: CopySummary {
symlinks_skipped: 1,
..Default::default()
},
..Default::default()
}
} else {
prog_track.files_skipped.inc();
Summary {
copy_summary: CopySummary {
files_skipped: 1,
..Default::default()
},
..Default::default()
}
};
return Ok(skipped_summary);
}
}
}
}
link_internal(prog_track, cwd, src, dst, src, update, settings, is_fresh).await
}
#[instrument(skip(prog_track, settings))]
#[async_recursion]
#[allow(clippy::too_many_arguments)]
async fn link_internal(
prog_track: &'static progress::Progress,
cwd: &std::path::Path,
src: &std::path::Path,
dst: &std::path::Path,
source_root: &std::path::Path,
update: &Option<std::path::PathBuf>,
settings: &Settings,
mut is_fresh: bool,
) -> Result<Summary, Error> {
let _prog_guard = prog_track.ops.guard();
tracing::debug!("reading source metadata");
let src_metadata = tokio::fs::symlink_metadata(src)
.await
.with_context(|| format!("failed reading metadata from {:?}", &src))
.map_err(|err| Error::new(err, Default::default()))?;
let update_metadata_opt = match update {
Some(update) => {
tracing::debug!("reading 'update' metadata");
let update_metadata_res = tokio::fs::symlink_metadata(update).await;
match update_metadata_res {
Ok(update_metadata) => Some(update_metadata),
Err(error) => {
if error.kind() == std::io::ErrorKind::NotFound {
if settings.update_exclusive {
// the path is missing from update, we're done
return Ok(Default::default());
}
None
} else {
return Err(Error::new(
anyhow!("failed reading metadata from {:?}", &update),
Default::default(),
));
}
}
}
}
None => None,
};
if let Some(update_metadata) = update_metadata_opt.as_ref() {
let update = update.as_ref().unwrap();
if !copy::is_file_type_same(&src_metadata, update_metadata) {
// file type changed, just copy the updated one
tracing::debug!(
"link: file type of {:?} ({:?}) and {:?} ({:?}) differs - copying from update",
src,
src_metadata.file_type(),
update,
update_metadata.file_type()
);
let copy_summary = copy::copy(
prog_track,
update,
dst,
&settings.copy_settings,
&settings.preserve,
is_fresh,
)
.await
.map_err(|err| {
let copy_summary = err.summary;
let link_summary = Summary {
copy_summary,
..Default::default()
};
Error::new(err.source, link_summary)
})?;
return Ok(Summary {
copy_summary,
..Default::default()
});
}
if update_metadata.is_file() {
// check if the file is unchanged and if so hard-link, otherwise copy from the updated one
if filecmp::metadata_equal(&settings.update_compare, &src_metadata, update_metadata) {
tracing::debug!("no change, hard link 'src'");
return hard_link_helper(prog_track, src, &src_metadata, dst, settings).await;
}
tracing::debug!(
"link: {:?} metadata has changed, copying from {:?}",
src,
update
);
let _open_file_guard = throttle::open_file_permit().await;
return Ok(Summary {
copy_summary: copy::copy_file(
prog_track,
update,
dst,
update_metadata,
&settings.copy_settings,
&settings.preserve,
is_fresh,
)
.await
.map_err(|err| {
let copy_summary = err.summary;
let link_summary = Summary {
copy_summary,
..Default::default()
};
Error::new(err.source, link_summary)
})?,
..Default::default()
});
}
if update_metadata.is_symlink() {
tracing::debug!("'update' is a symlink so just symlink that");
// use "copy" function to handle the overwrite logic
let copy_summary = copy::copy(
prog_track,
update,
dst,
&settings.copy_settings,
&settings.preserve,
is_fresh,
)
.await
.map_err(|err| {
let copy_summary = err.summary;
let link_summary = Summary {
copy_summary,
..Default::default()
};
Error::new(err.source, link_summary)
})?;
return Ok(Summary {
copy_summary,
..Default::default()
});
}
} else {
// update hasn't been specified, if this is a file just hard-link the source or symlink if it's a symlink
tracing::debug!("no 'update' specified");
if src_metadata.is_file() {
// handle dry-run mode for top-level files
if settings.dry_run.is_some() {
report_dry_run_link(src, dst, "file");
return Ok(Summary {
hard_links_created: 1,
..Default::default()
});
}
return hard_link_helper(prog_track, src, &src_metadata, dst, settings).await;
}
if src_metadata.is_symlink() {
tracing::debug!("'src' is a symlink so just symlink that");
// use "copy" function to handle the overwrite logic
let copy_summary = copy::copy(
prog_track,
src,
dst,
&settings.copy_settings,
&settings.preserve,
is_fresh,
)
.await
.map_err(|err| {
let copy_summary = err.summary;
let link_summary = Summary {
copy_summary,
..Default::default()
};
Error::new(err.source, link_summary)
})?;
return Ok(Summary {
copy_summary,
..Default::default()
});
}
}
if !src_metadata.is_dir() {
return Err(Error::new(
anyhow!(
"copy: {:?} -> {:?} failed, unsupported src file type: {:?}",
src,
dst,
src_metadata.file_type()
),
Default::default(),
));
}
assert!(update_metadata_opt.is_none() || update_metadata_opt.as_ref().unwrap().is_dir());
tracing::debug!("process contents of 'src' directory");
let mut src_entries = tokio::fs::read_dir(src)
.await
.with_context(|| format!("cannot open directory {src:?} for reading"))
.map_err(|err| Error::new(err, Default::default()))?;
// handle dry-run mode for directories at the top level
if settings.dry_run.is_some() {
report_dry_run_link(src, dst, "dir");
// still need to recurse to show contents
}
let copy_summary = if settings.dry_run.is_some() {
// skip actual directory creation in dry-run mode
CopySummary {
directories_created: 1,
..Default::default()
}
} else if let Err(error) = tokio::fs::create_dir(dst).await {
assert!(!is_fresh, "unexpected error creating directory: {:?}", &dst);
if settings.copy_settings.overwrite && error.kind() == std::io::ErrorKind::AlreadyExists {
// check if the destination is a directory - if so, leave it
//
// N.B. the permissions may prevent us from writing to it but the alternative is to open up the directory
// while we're writing to it which isn't safe
let dst_metadata = tokio::fs::metadata(dst)
.await
.with_context(|| format!("failed reading metadata from {:?}", &dst))
.map_err(|err| Error::new(err, Default::default()))?;
if dst_metadata.is_dir() {
tracing::debug!("'dst' is a directory, leaving it as is");
CopySummary {
directories_unchanged: 1,
..Default::default()
}
} else {
tracing::info!("'dst' is not a directory, removing and creating a new one");
let mut copy_summary = CopySummary::default();
let rm_summary = rm::rm(
prog_track,
dst,
&rm::Settings {
fail_early: settings.copy_settings.fail_early,
filter: None,
dry_run: None,
},
)
.await
.map_err(|err| {
let rm_summary = err.summary;
copy_summary.rm_summary = rm_summary;
Error::new(
err.source,
Summary {
copy_summary,
..Default::default()
},
)
})?;
tokio::fs::create_dir(dst)
.await
.with_context(|| format!("cannot create directory {dst:?}"))
.map_err(|err| {
copy_summary.rm_summary = rm_summary;
Error::new(
err,
Summary {
copy_summary,
..Default::default()
},
)
})?;
// anything copied into dst may assume they don't need to check for conflicts
is_fresh = true;
CopySummary {
rm_summary,
directories_created: 1,
..Default::default()
}
}
} else {
return Err(error)
.with_context(|| format!("cannot create directory {dst:?}"))
.map_err(|err| Error::new(err, Default::default()))?;
}
} else {
// new directory created, anything copied into dst may assume they don't need to check for conflicts
is_fresh = true;
CopySummary {
directories_created: 1,
..Default::default()
}
};
// track whether we created this directory (vs it already existing)
// this is used later to decide if we should clean up an empty directory
let we_created_this_dir = copy_summary.directories_created == 1;
let mut link_summary = Summary {
copy_summary,
..Default::default()
};
let mut join_set = tokio::task::JoinSet::new();
let errors = crate::error_collector::ErrorCollector::default();
// create a set of all the files we already processed
let mut processed_files = std::collections::HashSet::new();
// iterate through src entries and recursively call "link" on each one
while let Some(src_entry) = src_entries
.next_entry()
.await
.with_context(|| format!("failed traversing directory {:?}", &src))
.map_err(|err| Error::new(err, link_summary))?
{
// it's better to await the token here so that we throttle the syscalls generated by the
// DirEntry call. the ops-throttle will never cause a deadlock (unlike max-open-files limit)
// so it's safe to do here.
throttle::get_ops_token().await;
let cwd_path = cwd.to_owned();
let entry_path = src_entry.path();
let entry_name = entry_path.file_name().unwrap();
// check entry type for filter matching and dry-run reporting
let entry_file_type = src_entry.file_type().await.ok();
let entry_is_dir = entry_file_type.map(|ft| ft.is_dir()).unwrap_or(false);
let entry_is_symlink = entry_file_type.map(|ft| ft.is_symlink()).unwrap_or(false);
// compute relative path from source_root for filter matching
let relative_path = entry_path.strip_prefix(source_root).unwrap_or(&entry_path);
// apply filter if configured
if let Some(skip_result) = should_skip_entry(&settings.filter, relative_path, entry_is_dir)
{
if let Some(mode) = settings.dry_run {
let entry_type = if entry_is_dir {
"dir"
} else if entry_is_symlink {
"symlink"
} else {
"file"
};
report_dry_run_skip(&entry_path, &skip_result, mode, entry_type);
}
tracing::debug!("skipping {:?} due to filter", &entry_path);
// increment skipped counters
if entry_is_dir {
link_summary.copy_summary.directories_skipped += 1;
prog_track.directories_skipped.inc();
} else if entry_is_symlink {
link_summary.copy_summary.symlinks_skipped += 1;
prog_track.symlinks_skipped.inc();
} else {
link_summary.copy_summary.files_skipped += 1;
prog_track.files_skipped.inc();
}
continue;
}
processed_files.insert(entry_name.to_owned());
let dst_path = dst.join(entry_name);
let update_path = update.as_ref().map(|s| s.join(entry_name));
// handle dry-run mode for link operations
if let Some(_mode) = settings.dry_run {
let entry_type = if entry_is_dir {
"dir"
} else if entry_is_symlink {
"symlink"
} else {
"file"
};
report_dry_run_link(&entry_path, &dst_path, entry_type);
// for directories in dry-run, still need to recurse to show all entries
if entry_is_dir {
let settings = settings.clone();
let source_root = source_root.to_owned();
let do_link = || async move {
link_internal(
prog_track,
&cwd_path,
&entry_path,
&dst_path,
&source_root,
&update_path,
&settings,
true,
)
.await
};
join_set.spawn(do_link());
} else if entry_is_symlink {
// for symlinks in dry-run, count as symlink (in copy_summary)
link_summary.copy_summary.symlinks_created += 1;
} else {
// for files in dry-run, count the "would be created" hard link
link_summary.hard_links_created += 1;
}
continue;
}
let settings = settings.clone();
let source_root = source_root.to_owned();
let do_link = || async move {
link_internal(
prog_track,
&cwd_path,
&entry_path,
&dst_path,
&source_root,
&update_path,
&settings,
is_fresh,
)
.await
};
join_set.spawn(do_link());
}
// unfortunately ReadDir is opening file-descriptors and there's not a good way to limit this,
// one thing we CAN do however is to drop it as soon as we're done with it
drop(src_entries);
// only process update if the path was provided and the directory is present
if update_metadata_opt.is_some() {
let update = update.as_ref().unwrap();
tracing::debug!("process contents of 'update' directory");
let mut update_entries = tokio::fs::read_dir(update)
.await
.with_context(|| format!("cannot open directory {:?} for reading", &update))
.map_err(|err| Error::new(err, link_summary))?;
// iterate through update entries and for each one that's not present in src call "copy"
while let Some(update_entry) = update_entries
.next_entry()
.await
.with_context(|| format!("failed traversing directory {:?}", &update))
.map_err(|err| Error::new(err, link_summary))?
{
let entry_path = update_entry.path();
let entry_name = entry_path.file_name().unwrap();
if processed_files.contains(entry_name) {
// we already must have considered this file, skip it
continue;
}
tracing::debug!("found a new entry in the 'update' directory");
let dst_path = dst.join(entry_name);
let update_path = update.join(entry_name);
let settings = settings.clone();
let do_copy = || async move {
let copy_summary = copy::copy(
prog_track,
&update_path,
&dst_path,
&settings.copy_settings,
&settings.preserve,
is_fresh,
)
.await
.map_err(|err| {
link_summary.copy_summary = link_summary.copy_summary + err.summary;
Error::new(err.source, link_summary)
})?;
Ok(Summary {
copy_summary,
..Default::default()
})
};
join_set.spawn(do_copy());
}
// unfortunately ReadDir is opening file-descriptors and there's not a good way to limit this,
// one thing we CAN do however is to drop it as soon as we're done with it
drop(update_entries);
}
while let Some(res) = join_set.join_next().await {
match res {
Ok(result) => match result {
Ok(summary) => link_summary = link_summary + summary,
Err(error) => {
tracing::error!(
"link: {:?} {:?} -> {:?} failed with: {:#}",
src,
update,
dst,
&error
);
link_summary = link_summary + error.summary;
if settings.copy_settings.fail_early {
return Err(Error::new(error.source, link_summary));
}
errors.push(error.source);
}
},
Err(error) => {
if settings.copy_settings.fail_early {
return Err(Error::new(error.into(), link_summary));
}
errors.push(error.into());
}
}
}
// when filtering is active and we created this directory, check if anything was actually
// linked/copied into it. if nothing was linked, we may need to clean up the empty directory.
let this_dir_count = usize::from(we_created_this_dir);
let child_dirs_created = link_summary
.copy_summary
.directories_created
.saturating_sub(this_dir_count);
let anything_linked = link_summary.hard_links_created > 0
|| link_summary.copy_summary.files_copied > 0
|| link_summary.copy_summary.symlinks_created > 0
|| child_dirs_created > 0;
let relative_path = src.strip_prefix(source_root).unwrap_or(src);
let is_root = src == source_root;
match check_empty_dir_cleanup(
settings.filter.as_ref(),
we_created_this_dir,
anything_linked,
relative_path,
is_root,
settings.dry_run.is_some(),
) {
EmptyDirAction::Keep => { /* proceed with metadata application */ }
EmptyDirAction::DryRunSkip => {
tracing::debug!(
"dry-run: directory {:?} would not be created (nothing to link inside)",
&dst
);
link_summary.copy_summary.directories_created = 0;
return Ok(link_summary);
}
EmptyDirAction::Remove => {
tracing::debug!(
"directory {:?} has nothing to link inside, removing empty directory",
&dst
);
match tokio::fs::remove_dir(dst).await {
Ok(()) => {
link_summary.copy_summary.directories_created = 0;
return Ok(link_summary);
}
Err(err) => {
// removal failed (not empty, permission error, etc.) — keep directory
tracing::debug!(
"failed to remove empty directory {:?}: {:#}, keeping",
&dst,
&err
);
// fall through to apply metadata
}
}
}
}
// apply directory metadata regardless of whether all children linked successfully.
// the directory itself was created earlier in this function (we would have returned
// early if create_dir failed), so we should preserve the source metadata.
// skip metadata setting in dry-run mode since directory wasn't actually created
tracing::debug!("set 'dst' directory metadata");
let metadata_result = if settings.dry_run.is_some() {
Ok(()) // skip metadata setting in dry-run mode
} else {
let preserve_metadata = if let Some(update_metadata) = update_metadata_opt.as_ref() {
update_metadata
} else {
&src_metadata
};
preserve::set_dir_metadata(&settings.preserve, preserve_metadata, dst).await
};
if errors.has_errors() {
// child failures take precedence - log metadata error if it also failed
if let Err(metadata_err) = metadata_result {
tracing::error!(
"link: {:?} {:?} -> {:?} failed to set directory metadata: {:#}",
src,
update,
dst,
&metadata_err
);
}
// unwrap is safe: has_errors() guarantees into_error() returns Some
return Err(Error::new(errors.into_error().unwrap(), link_summary));
}
// no child failures, so metadata error is the primary error
metadata_result.map_err(|err| Error::new(err, link_summary))?;
Ok(link_summary)
}
#[cfg(test)]
mod link_tests {
use crate::testutils;
use std::os::unix::fs::PermissionsExt;
use tracing_test::traced_test;
use super::*;
static PROGRESS: std::sync::LazyLock<progress::Progress> =
std::sync::LazyLock::new(progress::Progress::new);
fn common_settings(dereference: bool, overwrite: bool) -> Settings {
Settings {
copy_settings: CopySettings {
dereference,
fail_early: false,
overwrite,
overwrite_compare: filecmp::MetadataCmpSettings {
size: true,
mtime: true,
..Default::default()
},
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: filecmp::MetadataCmpSettings {
size: true,
mtime: true,
..Default::default()
},
update_exclusive: false,
filter: None,
dry_run: None,
preserve: preserve::preserve_all(),
}
}
#[tokio::test]
#[traced_test]
async fn test_basic_link() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("bar"),
&None,
&common_settings(false, false),
false,
)
.await?;
assert_eq!(summary.hard_links_created, 5);
assert_eq!(summary.copy_summary.files_copied, 0);
assert_eq!(summary.copy_summary.symlinks_created, 2);
assert_eq!(summary.copy_summary.directories_created, 3);
testutils::check_dirs_identical(
&test_path.join("foo"),
&test_path.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_basic_link_update() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("bar"),
&Some(test_path.join("foo")),
&common_settings(false, false),
false,
)
.await?;
assert_eq!(summary.hard_links_created, 5);
assert_eq!(summary.copy_summary.files_copied, 0);
assert_eq!(summary.copy_summary.symlinks_created, 2);
assert_eq!(summary.copy_summary.directories_created, 3);
testutils::check_dirs_identical(
&test_path.join("foo"),
&test_path.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_basic_link_empty_src() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
tokio::fs::create_dir(tmp_dir.join("baz")).await?;
let test_path = tmp_dir.as_path();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("baz"), // empty source
&test_path.join("bar"),
&Some(test_path.join("foo")),
&common_settings(false, false),
false,
)
.await?;
assert_eq!(summary.hard_links_created, 0);
assert_eq!(summary.copy_summary.files_copied, 5);
assert_eq!(summary.copy_summary.symlinks_created, 2);
assert_eq!(summary.copy_summary.directories_created, 3);
testutils::check_dirs_identical(
&test_path.join("foo"),
&test_path.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_destination_permission_error_includes_root_cause(
) -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let readonly_parent = test_path.join("readonly_dest");
tokio::fs::create_dir(&readonly_parent).await?;
tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
.await?;
let mut settings = common_settings(false, false);
settings.copy_settings.fail_early = true;
let result = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&readonly_parent.join("bar"),
&None,
&settings,
false,
)
.await;
// restore permissions to allow temporary directory cleanup
tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
.await?;
assert!(result.is_err(), "link into read-only parent should fail");
let err = result.unwrap_err();
let err_msg = format!("{:#}", err.source);
assert!(
err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
"Error message must include permission denied text. Got: {}",
err_msg
);
Ok(())
}
pub async fn setup_update_dir(tmp_dir: &std::path::Path) -> Result<(), anyhow::Error> {
// update
// |- 0.txt
// |- bar
// |- 1.txt
// |- 2.txt -> ../0.txt
let foo_path = tmp_dir.join("update");
tokio::fs::create_dir(&foo_path).await.unwrap();
tokio::fs::write(foo_path.join("0.txt"), "0-new")
.await
.unwrap();
let bar_path = foo_path.join("bar");
tokio::fs::create_dir(&bar_path).await.unwrap();
tokio::fs::write(bar_path.join("1.txt"), "1-new")
.await
.unwrap();
tokio::fs::symlink("../1.txt", bar_path.join("2.txt"))
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_update() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
setup_update_dir(&tmp_dir).await?;
let test_path = tmp_dir.as_path();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("bar"),
&Some(test_path.join("update")),
&common_settings(false, false),
false,
)
.await?;
assert_eq!(summary.hard_links_created, 2);
assert_eq!(summary.copy_summary.files_copied, 2);
assert_eq!(summary.copy_summary.symlinks_created, 3);
assert_eq!(summary.copy_summary.directories_created, 3);
// compare subset of src and dst
testutils::check_dirs_identical(
&test_path.join("foo").join("baz"),
&test_path.join("bar").join("baz"),
testutils::FileEqualityCheck::HardLink,
)
.await?;
// compare update and dst
testutils::check_dirs_identical(
&test_path.join("update"),
&test_path.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_update_exclusive() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
setup_update_dir(&tmp_dir).await?;
let test_path = tmp_dir.as_path();
let mut settings = common_settings(false, false);
settings.update_exclusive = true;
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("bar"),
&Some(test_path.join("update")),
&settings,
false,
)
.await?;
// we should end up with same directory as the update
// |- 0.txt
// |- bar
// |- 1.txt
// |- 2.txt -> ../0.txt
assert_eq!(summary.hard_links_created, 0);
assert_eq!(summary.copy_summary.files_copied, 2);
assert_eq!(summary.copy_summary.symlinks_created, 1);
assert_eq!(summary.copy_summary.directories_created, 2);
// compare update and dst
testutils::check_dirs_identical(
&test_path.join("update"),
&test_path.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
async fn setup_test_dir_and_link() -> Result<std::path::PathBuf, anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("bar"),
&None,
&common_settings(false, false),
false,
)
.await?;
assert_eq!(summary.hard_links_created, 5);
assert_eq!(summary.copy_summary.symlinks_created, 2);
assert_eq!(summary.copy_summary.directories_created, 3);
Ok(tmp_dir)
}
#[tokio::test]
#[traced_test]
async fn test_link_overwrite_basic() -> Result<(), anyhow::Error> {
let tmp_dir = setup_test_dir_and_link().await?;
let output_path = &tmp_dir.join("bar");
{
// bar
// |- 0.txt
// |- bar <---------------------------------------- REMOVE
// |- 1.txt <----------------------------------- REMOVE
// |- 2.txt <----------------------------------- REMOVE
// |- 3.txt <----------------------------------- REMOVE
// |- baz
// |- 4.txt
// |- 5.txt -> ../bar/2.txt <-------------------- REMOVE
// |- 6.txt -> (absolute path) .../foo/bar/3.txt
let summary = rm::rm(
&PROGRESS,
&output_path.join("bar"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&output_path.join("baz").join("5.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?;
assert_eq!(summary.files_removed, 3);
assert_eq!(summary.symlinks_removed, 1);
assert_eq!(summary.directories_removed, 1);
}
let summary = link(
&PROGRESS,
&tmp_dir,
&tmp_dir.join("foo"),
output_path,
&None,
&common_settings(false, true), // overwrite!
false,
)
.await?;
assert_eq!(summary.hard_links_created, 3);
assert_eq!(summary.copy_summary.symlinks_created, 1);
assert_eq!(summary.copy_summary.directories_created, 1);
testutils::check_dirs_identical(
&tmp_dir.join("foo"),
output_path,
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_update_overwrite_basic() -> Result<(), anyhow::Error> {
let tmp_dir = setup_test_dir_and_link().await?;
let output_path = &tmp_dir.join("bar");
{
// bar
// |- 0.txt
// |- bar <---------------------------------------- REMOVE
// |- 1.txt <----------------------------------- REMOVE
// |- 2.txt <----------------------------------- REMOVE
// |- 3.txt <----------------------------------- REMOVE
// |- baz
// |- 4.txt
// |- 5.txt -> ../bar/2.txt <-------------------- REMOVE
// |- 6.txt -> (absolute path) .../foo/bar/3.txt
let summary = rm::rm(
&PROGRESS,
&output_path.join("bar"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&output_path.join("baz").join("5.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?;
assert_eq!(summary.files_removed, 3);
assert_eq!(summary.symlinks_removed, 1);
assert_eq!(summary.directories_removed, 1);
}
setup_update_dir(&tmp_dir).await?;
// update
// |- 0.txt
// |- bar
// |- 1.txt
// |- 2.txt -> ../0.txt
let summary = link(
&PROGRESS,
&tmp_dir,
&tmp_dir.join("foo"),
output_path,
&Some(tmp_dir.join("update")),
&common_settings(false, true), // overwrite!
false,
)
.await?;
assert_eq!(summary.hard_links_created, 1); // 3.txt
assert_eq!(summary.copy_summary.files_copied, 2); // 0.txt, 1.txt
assert_eq!(summary.copy_summary.symlinks_created, 2); // 2.txt, 5.txt
assert_eq!(summary.copy_summary.directories_created, 1);
// compare subset of src and dst
testutils::check_dirs_identical(
&tmp_dir.join("foo").join("baz"),
&tmp_dir.join("bar").join("baz"),
testutils::FileEqualityCheck::HardLink,
)
.await?;
// compare update and dst
testutils::check_dirs_identical(
&tmp_dir.join("update"),
&tmp_dir.join("bar"),
testutils::FileEqualityCheck::Timestamp,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_overwrite_hardlink_file() -> Result<(), anyhow::Error> {
let tmp_dir = setup_test_dir_and_link().await?;
let output_path = &tmp_dir.join("bar");
{
// bar
// |- 0.txt
// |- bar
// |- 1.txt <----------------------------------- REPLACE W/ FILE
// |- 2.txt <----------------------------------- REPLACE W/ SYMLINK
// |- 3.txt <----------------------------------- REPLACE W/ DIRECTORY
// |- baz <-------------------------------------- REPLACE W/ FILE
// |- ...
let bar_path = output_path.join("bar");
let summary = rm::rm(
&PROGRESS,
&bar_path.join("1.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&bar_path.join("2.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&bar_path.join("3.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&output_path.join("baz"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?;
assert_eq!(summary.files_removed, 4);
assert_eq!(summary.symlinks_removed, 2);
assert_eq!(summary.directories_removed, 1);
// REPLACE with a file, a symlink, a directory and a file
tokio::fs::write(bar_path.join("1.txt"), "1-new")
.await
.unwrap();
tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
.await
.unwrap();
tokio::fs::create_dir(&bar_path.join("3.txt"))
.await
.unwrap();
tokio::fs::write(&output_path.join("baz"), "baz")
.await
.unwrap();
}
let summary = link(
&PROGRESS,
&tmp_dir,
&tmp_dir.join("foo"),
output_path,
&None,
&common_settings(false, true), // overwrite!
false,
)
.await?;
assert_eq!(summary.hard_links_created, 4);
assert_eq!(summary.copy_summary.files_copied, 0);
assert_eq!(summary.copy_summary.symlinks_created, 2);
assert_eq!(summary.copy_summary.directories_created, 1);
testutils::check_dirs_identical(
&tmp_dir.join("foo"),
&tmp_dir.join("bar"),
testutils::FileEqualityCheck::HardLink,
)
.await?;
Ok(())
}
#[tokio::test]
#[traced_test]
async fn test_link_overwrite_error() -> Result<(), anyhow::Error> {
let tmp_dir = setup_test_dir_and_link().await?;
let output_path = &tmp_dir.join("bar");
{
// bar
// |- 0.txt
// |- bar
// |- 1.txt <----------------------------------- REPLACE W/ FILE
// |- 2.txt <----------------------------------- REPLACE W/ SYMLINK
// |- 3.txt <----------------------------------- REPLACE W/ DIRECTORY
// |- baz <-------------------------------------- REPLACE W/ FILE
// |- ...
let bar_path = output_path.join("bar");
let summary = rm::rm(
&PROGRESS,
&bar_path.join("1.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&bar_path.join("2.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&bar_path.join("3.txt"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?
+ rm::rm(
&PROGRESS,
&output_path.join("baz"),
&rm::Settings {
fail_early: false,
filter: None,
dry_run: None,
},
)
.await?;
assert_eq!(summary.files_removed, 4);
assert_eq!(summary.symlinks_removed, 2);
assert_eq!(summary.directories_removed, 1);
// REPLACE with a file, a symlink, a directory and a file
tokio::fs::write(bar_path.join("1.txt"), "1-new")
.await
.unwrap();
tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
.await
.unwrap();
tokio::fs::create_dir(&bar_path.join("3.txt"))
.await
.unwrap();
tokio::fs::write(&output_path.join("baz"), "baz")
.await
.unwrap();
}
let source_path = &tmp_dir.join("foo");
// unreadable
tokio::fs::set_permissions(
&source_path.join("baz"),
std::fs::Permissions::from_mode(0o000),
)
.await?;
// bar
// |- ...
// |- baz <- NON READABLE
match link(
&PROGRESS,
&tmp_dir,
&tmp_dir.join("foo"),
output_path,
&None,
&common_settings(false, true), // overwrite!
false,
)
.await
{
Ok(_) => panic!("Expected the link to error!"),
Err(error) => {
tracing::info!("{}", &error);
assert_eq!(error.summary.hard_links_created, 3);
assert_eq!(error.summary.copy_summary.files_copied, 0);
assert_eq!(error.summary.copy_summary.symlinks_created, 0);
assert_eq!(error.summary.copy_summary.directories_created, 0);
assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 1);
assert_eq!(error.summary.copy_summary.rm_summary.directories_removed, 1);
assert_eq!(error.summary.copy_summary.rm_summary.symlinks_removed, 1);
}
}
Ok(())
}
/// Verify that directory metadata is applied even when child link operations fail.
/// This is a regression test for a bug where directory permissions were not preserved
/// when linking with fail_early=false and some children failed to link.
#[tokio::test]
#[traced_test]
async fn test_link_directory_metadata_applied_on_child_error() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::create_temp_dir().await?;
let test_path = tmp_dir.as_path();
// create source directory with specific permissions
let src_dir = test_path.join("src");
tokio::fs::create_dir(&src_dir).await?;
tokio::fs::set_permissions(&src_dir, std::fs::Permissions::from_mode(0o750)).await?;
// create a readable file (will be linked successfully)
tokio::fs::write(src_dir.join("readable.txt"), "content").await?;
// create a subdirectory with a file, then make the subdirectory unreadable
// this will cause the recursive walk to fail when trying to read subdirectory contents
let unreadable_subdir = src_dir.join("unreadable_subdir");
tokio::fs::create_dir(&unreadable_subdir).await?;
tokio::fs::write(unreadable_subdir.join("hidden.txt"), "secret").await?;
tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o000))
.await?;
let dst_dir = test_path.join("dst");
// link with fail_early=false
let result = link(
&PROGRESS,
test_path,
&src_dir,
&dst_dir,
&None,
&common_settings(false, false),
false,
)
.await;
// restore permissions so cleanup can succeed
tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o755))
.await?;
// verify the operation returned an error (unreadable subdirectory should fail)
assert!(
result.is_err(),
"link should fail due to unreadable subdirectory"
);
let error = result.unwrap_err();
// verify the readable file was linked successfully
assert_eq!(error.summary.hard_links_created, 1);
// verify the destination directory exists and has the correct permissions
let dst_metadata = tokio::fs::metadata(&dst_dir).await?;
assert!(dst_metadata.is_dir());
let actual_mode = dst_metadata.permissions().mode() & 0o7777;
assert_eq!(
actual_mode, 0o750,
"directory should have preserved source permissions (0o750), got {:o}",
actual_mode
);
Ok(())
}
mod filter_tests {
use super::*;
use crate::filter::FilterSettings;
/// Test that path-based patterns (with /) work correctly with nested paths.
#[tokio::test]
#[traced_test]
async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
// create filter that should only link files in bar/ directory
let mut filter = FilterSettings::new();
filter.add_include("bar/*.txt").unwrap();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("dst"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// should only link files matching bar/*.txt pattern (bar/1.txt, bar/2.txt, bar/3.txt)
assert_eq!(
summary.hard_links_created, 3,
"should link 3 files matching bar/*.txt"
);
// verify the right files were linked
assert!(
test_path.join("dst/bar/1.txt").exists(),
"bar/1.txt should be linked"
);
assert!(
test_path.join("dst/bar/2.txt").exists(),
"bar/2.txt should be linked"
);
assert!(
test_path.join("dst/bar/3.txt").exists(),
"bar/3.txt should be linked"
);
// verify files outside the pattern don't exist
assert!(
!test_path.join("dst/0.txt").exists(),
"0.txt should not be linked"
);
Ok(())
}
/// Test that filters are applied to top-level file arguments.
#[tokio::test]
#[traced_test]
async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
// create filter that excludes .txt files
let mut filter = FilterSettings::new();
filter.add_exclude("*.txt").unwrap();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo/0.txt"), // single file source
&test_path.join("dst/0.txt"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// the file should NOT be linked because it matches the exclude pattern
assert_eq!(
summary.hard_links_created, 0,
"file matching exclude pattern should not be linked"
);
assert!(
!test_path.join("dst/0.txt").exists(),
"excluded file should not exist at destination"
);
Ok(())
}
/// Test that filters apply to root directories with simple exclude patterns.
#[tokio::test]
#[traced_test]
async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create a directory that should be excluded
tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
// create filter that excludes *_dir/ directories
let mut filter = FilterSettings::new();
filter.add_exclude("*_dir/").unwrap();
let result = link(
&PROGRESS,
&test_path,
&test_path.join("excluded_dir"),
&test_path.join("dst"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// directory should NOT be linked because it matches exclude pattern
assert_eq!(
result.copy_summary.directories_created, 0,
"root directory matching exclude should not be created"
);
assert!(
!test_path.join("dst").exists(),
"excluded root directory should not exist at destination"
);
Ok(())
}
/// Test that filters apply to root symlinks with simple exclude patterns.
#[tokio::test]
#[traced_test]
async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create a target file and a symlink to it
tokio::fs::write(test_path.join("target.txt"), "content").await?;
tokio::fs::symlink(
test_path.join("target.txt"),
test_path.join("excluded_link"),
)
.await?;
// create filter that excludes *_link
let mut filter = FilterSettings::new();
filter.add_exclude("*_link").unwrap();
let result = link(
&PROGRESS,
&test_path,
&test_path.join("excluded_link"),
&test_path.join("dst"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// symlink should NOT be copied because it matches exclude pattern
assert_eq!(
result.copy_summary.symlinks_created, 0,
"root symlink matching exclude should not be created"
);
assert!(
!test_path.join("dst").exists(),
"excluded root symlink should not exist at destination"
);
Ok(())
}
/// Test combined include and exclude patterns (exclude takes precedence).
#[tokio::test]
#[traced_test]
async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
// test structure from setup_test_dir:
// foo/
// 0.txt
// bar/ (1.txt, 2.txt, 3.txt)
// baz/ (4.txt, 5.txt symlink, 6.txt symlink)
// include all .txt files in bar/, but exclude 2.txt specifically
let mut filter = FilterSettings::new();
filter.add_include("bar/*.txt").unwrap();
filter.add_exclude("bar/2.txt").unwrap();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("dst"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// should link: bar/1.txt, bar/3.txt = 2 hard links
// should skip: bar/2.txt (excluded by pattern), 0.txt (excluded by default - no match) = 2 files
assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
assert_eq!(
summary.copy_summary.files_skipped, 2,
"should skip 2 files (bar/2.txt excluded, 0.txt no match)"
);
// verify
assert!(
test_path.join("dst/bar/1.txt").exists(),
"bar/1.txt should be linked"
);
assert!(
!test_path.join("dst/bar/2.txt").exists(),
"bar/2.txt should be excluded"
);
assert!(
test_path.join("dst/bar/3.txt").exists(),
"bar/3.txt should be linked"
);
Ok(())
}
/// Test that skipped counts accurately reflect what was filtered.
#[tokio::test]
#[traced_test]
async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
// test structure from setup_test_dir:
// foo/
// 0.txt
// bar/ (1.txt, 2.txt, 3.txt)
// baz/ (4.txt, 5.txt symlink, 6.txt symlink)
// exclude bar/ directory entirely
let mut filter = FilterSettings::new();
filter.add_exclude("bar/").unwrap();
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&test_path.join("dst"),
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// linked: 0.txt (1 hard link), baz/4.txt (1 hard link)
// symlinks copied: 5.txt, 6.txt
// skipped: bar directory (1 dir)
assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
assert_eq!(
summary.copy_summary.symlinks_created, 2,
"should copy 2 symlinks"
);
assert_eq!(
summary.copy_summary.directories_skipped, 1,
"should skip 1 directory (bar)"
);
// bar should not exist in dst
assert!(
!test_path.join("dst/bar").exists(),
"bar directory should not be linked"
);
Ok(())
}
/// Test that empty directories are not created when they were only traversed to look
/// for matches (regression test for bug where --include='foo' would create empty dir baz).
#[tokio::test]
#[traced_test]
async fn test_empty_dir_not_created_when_only_traversed() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create structure:
// src/
// foo (file)
// bar (file)
// baz/ (empty directory)
let src_path = test_path.join("src");
tokio::fs::create_dir(&src_path).await?;
tokio::fs::write(src_path.join("foo"), "content").await?;
tokio::fs::write(src_path.join("bar"), "content").await?;
tokio::fs::create_dir(src_path.join("baz")).await?;
// include only 'foo' file
let mut filter = FilterSettings::new();
filter.add_include("foo").unwrap();
let summary = link(
&PROGRESS,
&test_path,
&src_path,
&test_path.join("dst"),
&None,
&Settings {
copy_settings: copy::Settings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// only 'foo' should be linked
assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
assert_eq!(
summary.copy_summary.directories_created, 1,
"should create only root directory (not empty 'baz')"
);
// verify foo was linked
assert!(
test_path.join("dst").join("foo").exists(),
"foo should be linked"
);
// verify bar was not linked (not matching include pattern)
assert!(
!test_path.join("dst").join("bar").exists(),
"bar should not be linked"
);
// verify empty baz directory was NOT created
assert!(
!test_path.join("dst").join("baz").exists(),
"empty baz directory should NOT be created"
);
Ok(())
}
/// Test that directories with only non-matching content are not created at destination.
/// This is different from empty directories - the source dir has content but none matches.
#[tokio::test]
#[traced_test]
async fn test_dir_with_nonmatching_content_not_created() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create structure:
// src/
// foo (file)
// baz/
// qux (file - doesn't match 'foo')
// quux (file - doesn't match 'foo')
let src_path = test_path.join("src");
tokio::fs::create_dir(&src_path).await?;
tokio::fs::write(src_path.join("foo"), "content").await?;
tokio::fs::create_dir(src_path.join("baz")).await?;
tokio::fs::write(src_path.join("baz").join("qux"), "content").await?;
tokio::fs::write(src_path.join("baz").join("quux"), "content").await?;
// include only 'foo' file
let mut filter = FilterSettings::new();
filter.add_include("foo").unwrap();
let summary = link(
&PROGRESS,
&test_path,
&src_path,
&test_path.join("dst"),
&None,
&Settings {
copy_settings: copy::Settings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// only 'foo' should be linked
assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
assert_eq!(
summary.copy_summary.files_skipped, 2,
"should skip 2 files (qux and quux)"
);
assert_eq!(
summary.copy_summary.directories_created, 1,
"should create only root directory (not 'baz' with non-matching content)"
);
// verify foo was linked
assert!(
test_path.join("dst").join("foo").exists(),
"foo should be linked"
);
// verify baz directory was NOT created (even though source baz has content)
assert!(
!test_path.join("dst").join("baz").exists(),
"baz directory should NOT be created (no matching content inside)"
);
Ok(())
}
/// Test that empty directories are not reported as created in dry-run mode
/// when they were only traversed.
#[tokio::test]
#[traced_test]
async fn test_dry_run_empty_dir_not_reported_as_created() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create structure:
// src/
// foo (file)
// bar (file)
// baz/ (empty directory)
let src_path = test_path.join("src");
tokio::fs::create_dir(&src_path).await?;
tokio::fs::write(src_path.join("foo"), "content").await?;
tokio::fs::write(src_path.join("bar"), "content").await?;
tokio::fs::create_dir(src_path.join("baz")).await?;
// include only 'foo' file
let mut filter = FilterSettings::new();
filter.add_include("foo").unwrap();
let summary = link(
&PROGRESS,
&test_path,
&src_path,
&test_path.join("dst"),
&None,
&Settings {
copy_settings: copy::Settings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: Some(crate::config::DryRunMode::Explain),
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// only 'foo' should be reported as would-be-linked
assert_eq!(
summary.hard_links_created, 1,
"should report only 'foo' would be linked"
);
assert_eq!(
summary.copy_summary.directories_created, 1,
"should report only root directory would be created (not empty 'baz')"
);
// verify nothing was actually created (dry-run mode)
assert!(
!test_path.join("dst").exists(),
"dst should not exist in dry-run"
);
Ok(())
}
/// Test that existing directories are NOT removed when using --overwrite,
/// even if nothing is linked into them due to filters.
#[tokio::test]
#[traced_test]
async fn test_existing_dir_not_removed_with_overwrite() -> Result<(), anyhow::Error> {
let test_path = testutils::create_temp_dir().await?;
// create source structure:
// src/
// foo (file)
// bar (file)
// baz/ (empty directory)
let src_path = test_path.join("src");
tokio::fs::create_dir(&src_path).await?;
tokio::fs::write(src_path.join("foo"), "content").await?;
tokio::fs::write(src_path.join("bar"), "content").await?;
tokio::fs::create_dir(src_path.join("baz")).await?;
// create destination with baz directory already existing
let dst_path = test_path.join("dst");
tokio::fs::create_dir(&dst_path).await?;
tokio::fs::create_dir(dst_path.join("baz")).await?;
// add a marker file inside dst/baz to verify we don't touch it
tokio::fs::write(dst_path.join("baz").join("marker.txt"), "existing").await?;
// include only 'foo' file - baz should not match
let mut filter = FilterSettings::new();
filter.add_include("foo").unwrap();
let summary = link(
&PROGRESS,
&test_path,
&src_path,
&dst_path,
&None,
&Settings {
copy_settings: copy::Settings {
dereference: false,
fail_early: false,
overwrite: true, // enable overwrite mode
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: Some(filter),
dry_run: None,
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// foo should be linked
assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
// dst and baz should be unchanged (both already existed)
assert_eq!(
summary.copy_summary.directories_unchanged, 2,
"root dst and baz directories should be unchanged"
);
assert_eq!(
summary.copy_summary.directories_created, 0,
"should not create any directories"
);
// verify foo was linked
assert!(dst_path.join("foo").exists(), "foo should be linked");
// verify bar was NOT linked
assert!(!dst_path.join("bar").exists(), "bar should not be linked");
// verify existing baz directory still exists with its content
assert!(
dst_path.join("baz").exists(),
"existing baz directory should still exist"
);
assert!(
dst_path.join("baz").join("marker.txt").exists(),
"existing content in baz should still exist"
);
Ok(())
}
}
mod dry_run_tests {
use super::*;
/// Test that dry-run mode for files doesn't create hard links.
#[tokio::test]
#[traced_test]
async fn test_dry_run_file_does_not_create_link() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let src_file = test_path.join("foo/0.txt");
let dst_file = test_path.join("dst_link.txt");
// verify destination doesn't exist
assert!(
!dst_file.exists(),
"destination should not exist before dry-run"
);
let summary = link(
&PROGRESS,
test_path,
&src_file,
&dst_file,
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: None,
dry_run: Some(crate::config::DryRunMode::Brief),
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// verify destination still doesn't exist
assert!(!dst_file.exists(), "dry-run should not create hard link");
// verify summary reports what would be created
assert_eq!(
summary.hard_links_created, 1,
"dry-run should report 1 hard link that would be created"
);
Ok(())
}
/// Test that dry-run mode for directories doesn't create the destination directory.
#[tokio::test]
#[traced_test]
async fn test_dry_run_directory_does_not_create_destination() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
let dst_path = test_path.join("nonexistent_dst");
// verify destination doesn't exist
assert!(
!dst_path.exists(),
"destination should not exist before dry-run"
);
let summary = link(
&PROGRESS,
test_path,
&test_path.join("foo"),
&dst_path,
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: None,
dry_run: Some(crate::config::DryRunMode::Brief),
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// verify destination still doesn't exist
assert!(
!dst_path.exists(),
"dry-run should not create destination directory"
);
// verify summary reports what would be created
assert!(
summary.hard_links_created > 0,
"dry-run should report hard links that would be created"
);
Ok(())
}
/// Test that dry-run mode correctly reports symlinks (not as hard links).
#[tokio::test]
#[traced_test]
async fn test_dry_run_symlinks_counted_correctly() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::setup_test_dir().await?;
let test_path = tmp_dir.as_path();
// baz contains: 4.txt (file), 5.txt (symlink), 6.txt (symlink)
let src_path = test_path.join("foo/baz");
let dst_path = test_path.join("dst_baz");
// verify destination doesn't exist
assert!(
!dst_path.exists(),
"destination should not exist before dry-run"
);
let summary = link(
&PROGRESS,
test_path,
&src_path,
&dst_path,
&None,
&Settings {
copy_settings: CopySettings {
dereference: false,
fail_early: false,
overwrite: false,
overwrite_compare: Default::default(),
overwrite_filter: None,
ignore_existing: false,
chunk_size: 0,
remote_copy_buffer_size: 0,
filter: None,
dry_run: None,
},
update_compare: Default::default(),
update_exclusive: false,
filter: None,
dry_run: Some(crate::config::DryRunMode::Brief),
preserve: preserve::preserve_all(),
},
false,
)
.await?;
// verify destination still doesn't exist
assert!(!dst_path.exists(), "dry-run should not create destination");
// baz contains 1 regular file (4.txt) and 2 symlinks (5.txt, 6.txt)
assert_eq!(
summary.hard_links_created, 1,
"dry-run should report 1 hard link (for 4.txt)"
);
assert_eq!(
summary.copy_summary.symlinks_created, 2,
"dry-run should report 2 symlinks (5.txt and 6.txt)"
);
Ok(())
}
}
/// Verify that fail-early preserves the summary from the failing subtree.
///
/// Regression test: the fail-early return path in the join loop must
/// accumulate error.summary from the failing child into the parent's
/// link_summary. Without this, directories_created from the child subtree
/// would be lost.
#[tokio::test]
#[traced_test]
async fn test_fail_early_preserves_summary_from_failing_subtree() -> Result<(), anyhow::Error> {
let tmp_dir = testutils::create_temp_dir().await?;
let test_path = tmp_dir.as_path();
// src/sub/ has a file and an unreadable subdirectory:
// src/sub/good.txt <-- links successfully
// src/sub/unreadable_dir/ <-- mode 000, can't be traversed
// src/sub/unreadable_dir/f.txt
let src_dir = test_path.join("src");
let sub_dir = src_dir.join("sub");
let bad_dir = sub_dir.join("unreadable_dir");
tokio::fs::create_dir_all(&bad_dir).await?;
tokio::fs::write(sub_dir.join("good.txt"), "content").await?;
tokio::fs::write(bad_dir.join("f.txt"), "data").await?;
tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o000)).await?;
let dst_dir = test_path.join("dst");
let result = link(
&PROGRESS,
test_path,
&src_dir,
&dst_dir,
&None,
&Settings {
copy_settings: CopySettings {
fail_early: true,
..common_settings(false, false).copy_settings
},
..common_settings(false, false)
},
false,
)
.await;
// restore permissions for cleanup
tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o755)).await?;
let error = result.expect_err("link should fail due to unreadable directory");
// sub/'s link_internal created dst/sub/ (directories_created=1) before
// its join loop encountered the unreadable_dir error. that directory
// creation must be reflected in the error summary propagated up to the
// top-level caller.
assert!(
error.summary.copy_summary.directories_created >= 2,
"fail-early summary should include directories from the failing subtree, \
got directories_created={} (expected >= 2: dst/ and dst/sub/)",
error.summary.copy_summary.directories_created
);
Ok(())
}
}