local-ci 0.10.0

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

use super::secret::{self, SecretBundle};
use super::store::{sha256_hex, write_atomic, ObjectStore, RelPath};
use super::*;
use crate::context::ExecContext;
use anyhow::{bail, Context, Result};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ffi::{OsStr, OsString};
use std::io::Write;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::process::Stdio;

// ---- git, as bytes --------------------------------------------------------

/// Run git with `pre` before the arguments, the environment of `ctx` plus
/// `envs`, and `stdin`; the whole of stdout, not decoded.
pub(crate) fn git_run(
    ctx: &ExecContext,
    pre: &[OsString],
    args: &[&str],
    envs: &[(&str, &OsStr)],
    stdin: Option<Vec<u8>>,
) -> Result<Vec<u8>> {
    let mut all: Vec<OsString> = pre.to_vec();
    all.extend(args.iter().map(OsString::from));
    git_run_os(ctx, None, &all, envs, stdin)
}

/// [`git_run`] with arguments that are bytes (paths) and a working directory.
pub(crate) fn git_run_os(
    ctx: &ExecContext,
    cwd: Option<&Path>,
    args: &[OsString],
    envs: &[(&str, &OsStr)],
    stdin: Option<Vec<u8>>,
) -> Result<Vec<u8>> {
    let mut c = ctx.command("git");
    c.args(args);
    if let Some(d) = cwd {
        c.current_dir(d);
    }
    for (k, v) in envs {
        c.env(k, v);
    }
    c.stdin(if stdin.is_some() {
        Stdio::piped()
    } else {
        Stdio::null()
    })
    .stdout(Stdio::piped())
    .stderr(Stdio::piped());
    let mut child = c.spawn().context("failed to run git")?;
    let writer = stdin.map(|data| {
        let mut si = child.stdin.take().unwrap();
        std::thread::spawn(move || {
            let _ = si.write_all(&data);
        })
    });
    let out = child.wait_with_output().context("failed to run git")?;
    if let Some(w) = writer {
        let _ = w.join();
    }
    if !out.status.success() {
        // `-c key=value` pairs (a filter's command line) are not worth repeating
        let mut shown: Vec<String> = vec![];
        let mut it = args.iter();
        while let Some(a) = it.next() {
            if a == "-c" {
                it.next();
            } else {
                shown.push(a.to_string_lossy().into_owned());
            }
        }
        bail!(
            "git {}: {}",
            shown.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(out.stdout)
}

/// The original repository, read only: no optional locks, so reading never
/// refreshes its index.
pub(crate) fn og(ctx: &ExecContext, root: &Path, args: &[&str]) -> Result<Vec<u8>> {
    git_run(
        ctx,
        &["-C".into(), root.into()],
        args,
        &[("GIT_OPTIONAL_LOCKS", OsStr::new("0"))],
        None,
    )
}

pub(crate) fn og_str(ctx: &ExecContext, root: &Path, args: &[&str]) -> Result<String> {
    Ok(String::from_utf8_lossy(&og(ctx, root, args)?)
        .trim()
        .to_string())
}

/// The private repository: `--git-dir`, plus `envs`.
pub(crate) fn pg(
    ctx: &ExecContext,
    git_dir: &Path,
    args: &[&str],
    envs: &[(&str, &OsStr)],
    stdin: Option<Vec<u8>>,
) -> Result<Vec<u8>> {
    git_run(
        ctx,
        &["--git-dir".into(), git_dir.into()],
        args,
        envs,
        stdin,
    )
}

fn split_z(b: &[u8]) -> Vec<&[u8]> {
    b.split(|&c| c == 0).filter(|s| !s.is_empty()).collect()
}

// ---- selection ------------------------------------------------------------

struct Globs {
    set: GlobSet,
    empty: bool,
}

impl Globs {
    fn new(patterns: &[String]) -> Result<Self> {
        let mut b = GlobSetBuilder::new();
        for p in patterns {
            b.add(Glob::new(p).with_context(|| format!("bad glob {p:?}"))?);
        }
        Ok(Globs {
            set: b.build()?,
            empty: patterns.is_empty(),
        })
    }
    /// The path, or a directory above it, matches.
    fn matches(&self, p: &RelPath) -> bool {
        if self.empty {
            return false;
        }
        let m = |r: &RelPath| self.set.is_match(Path::new(OsStr::from_bytes(&r.0)));
        m(p) || p.ancestors().iter().any(m)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Stat {
    mode: u32,
    size: u64,
    mtime: (i64, i64),
    ctime: (i64, i64),
    ino: u64,
    dev: u64,
}

impl Stat {
    fn of(m: &std::fs::Metadata) -> Stat {
        Stat {
            mode: m.mode(),
            size: m.size(),
            mtime: (m.mtime(), m.mtime_nsec()),
            ctime: (m.ctime(), m.ctime_nsec()),
            ino: m.ino(),
            dev: m.dev(),
        }
    }
}

fn lstat(root: &Path, p: &RelPath) -> Option<Stat> {
    std::fs::symlink_metadata(root.join(p.to_path()))
        .ok()
        .map(|m| Stat::of(&m))
}

/// What a capture reads, before it reads it: the state of Git and the list
/// and the stat of every file. Two equal `Meta`s around a read mean nothing
/// moved under it.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct Meta {
    head: String,
    branch: Option<String>,
    index_hash: String,
    /// Stage-0 index entries: mode, git sha, path.
    tracked: Vec<(u32, String, RelPath)>,
    untracked: Vec<RelPath>,
    /// Ignored files taken along by `include`.
    included: Vec<RelPath>,
    /// Files that match `secret_files` (declaration index, path).
    secret: Vec<(usize, RelPath)>,
    stats: BTreeMap<RelPath, Option<Stat>>,
    /// The stats of `secret`, apart from `stats`: with a `secret_root` they
    /// are files of another directory.
    secret_stats: BTreeMap<RelPath, Option<Stat>>,
}

struct Selection {
    meta: Meta,
    index_bytes: Vec<u8>,
    /// Tracked files a `secret_files` glob matches: they are commit content,
    /// so they are taken as such (declaration index, path).
    tracked_secrets: Vec<(usize, RelPath)>,
    /// With a `secret_root`: files a declaration matches that the working
    /// tree there tracks and the captured index does not. They are not in
    /// the capture at all, neither as content nor as a secret file.
    tracked_elsewhere: Vec<(usize, RelPath)>,
}

impl Meta {
    /// Why `self` and `later` differ.
    fn diff(&self, later: &Meta) -> String {
        if self.head != later.head {
            return format!("HEAD moved from {} to {}", self.head, later.head);
        }
        if self.branch != later.branch {
            return "the branch changed".into();
        }
        if self.index_hash != later.index_hash || self.tracked != later.tracked {
            return "the index changed".into();
        }
        if self.untracked != later.untracked
            || self.included != later.included
            || self.secret != later.secret
        {
            return "files were added, removed or renamed".into();
        }
        for (p, s) in &self.stats {
            if later.stats.get(p) != Some(s) {
                return format!("{} changed", p.display());
            }
        }
        for (p, s) in &self.secret_stats {
            if later.secret_stats.get(p) != Some(s) {
                return format!("{} changed", p.display());
            }
        }
        "the file list changed".into()
    }
}

/// A capture saw the input move; try again.
#[derive(Debug)]
struct Unstable(String);

impl std::fmt::Display for Unstable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl std::error::Error for Unstable {}

fn unstable(why: impl Into<String>) -> anyhow::Error {
    Unstable(why.into()).into()
}

/// Everything the first step records (spec chapter 6, step 1).
fn select_worktree(ctx: &ExecContext, root: &Path, o: &Opts) -> Result<Selection> {
    let head = og_str(ctx, root, &["rev-parse", "--verify", "HEAD^{commit}"])
        .context("the repository has no commits yet")?;
    let branch = og_str(ctx, root, &["symbolic-ref", "-q", "--short", "HEAD"])
        .ok()
        .filter(|b| !b.is_empty());
    let index_path = og_str(
        ctx,
        root,
        &["rev-parse", "--path-format=absolute", "--git-path", "index"],
    )?;
    let index_bytes = std::fs::read(&index_path).unwrap_or_default();
    let index_hash = sha256_hex(&index_bytes);

    let mut tracked = vec![];
    for rec in split_z(&og(ctx, root, &["ls-files", "-z", "-s"])?) {
        // `<mode> <sha> <stage>\t<path>`
        let tab = rec
            .iter()
            .position(|&c| c == b'\t')
            .context("unexpected ls-files output")?;
        let head_part = String::from_utf8_lossy(&rec[..tab]).into_owned();
        let mut it = head_part.split(' ');
        let mode = u32::from_str_radix(it.next().unwrap_or(""), 8)?;
        let sha = it.next().unwrap_or("").to_string();
        let stage = it.next().unwrap_or("0");
        let path = RelPath(rec[tab + 1..].to_vec());
        if stage != "0" {
            return Err(SourceError::Unmerged {
                path: path.display(),
            }
            .into());
        }
        tracked.push((mode, sha, path));
    }
    let tracked_set: BTreeSet<&RelPath> = tracked.iter().map(|t| &t.2).collect();

    let mut untracked = vec![];
    for rec in split_z(&og(
        ctx,
        root,
        &["ls-files", "-z", "-o", "--exclude-standard"],
    )?) {
        if rec.ends_with(b"/") {
            // a directory that holds a repository of its own
            let p = RelPath(rec[..rec.len() - 1].to_vec());
            if o.exclude.matches(&p) {
                continue;
            }
            return Err(SourceError::NestedRepository { path: p.display() }.into());
        }
        let p = RelPath(rec.to_vec());
        if !tracked_set.contains(&p) {
            untracked.push(p);
        }
    }

    let mut ignored = vec![];
    if !o.include.empty || !o.secrets.is_empty() {
        for rec in split_z(&og(
            ctx,
            root,
            &["ls-files", "-z", "-o", "-i", "--exclude-standard"],
        )?) {
            if !rec.ends_with(b"/") {
                ignored.push(RelPath(rec.to_vec()));
            }
        }
    }

    // git does not list FIFOs, sockets and devices at all; look for them
    // outside the ignored directories
    {
        let mut skip_dirs: Vec<RelPath> = vec![];
        for rec in split_z(&og(
            ctx,
            root,
            &[
                "ls-files",
                "-z",
                "-o",
                "-i",
                "--exclude-standard",
                "--directory",
            ],
        )?) {
            if rec.ends_with(b"/") {
                skip_dirs.push(RelPath(rec[..rec.len() - 1].to_vec()));
            }
        }
        find_special(root, &RelPath(vec![]), &skip_dirs, o)?;
    }

    // secrets: an untracked file the declaration matches, ignored or not. A
    // tracked one is part of the commit and cannot be kept apart from it.
    let mut secret = vec![];
    let mut secret_paths = BTreeSet::new();
    let mut tracked_secrets = vec![];
    let mut tracked_elsewhere = vec![];
    let secret_root = o.secret_root.as_deref().unwrap_or(root);
    if !o.secrets.is_empty() {
        for p in tracked
            .iter()
            .filter(|t| t.0 != 0o160000)
            .map(|t| &t.2)
            .filter(|p| !o.exclude.matches(p))
        {
            if let Some(i) = o.secrets.iter().position(|g| g.matches(p)) {
                tracked_secrets.push((i, p.clone()));
            }
        }
        // git lists no FIFO, socket or device, so one at a secret path
        // would pass for a file that is not there
        special_secrets(secret_root, &RelPath(vec![]), o)?;
        // a file here that a declaration matches never becomes content of
        // the source, wherever the secret files are taken from
        let own = pick_secrets(o, untracked.iter().chain(ignored.iter()));
        secret_paths = own.iter().map(|s| s.1.clone()).collect();
        secret = match &o.secret_root {
            None => own,
            Some(from) => {
                let listed = secret_candidates(ctx, from)?;
                let mut picked = pick_secrets(o, listed.iter());
                // what the captured index tracks is commit content, as above
                picked.retain(|s| {
                    let is_tracked = tracked_set.contains(&s.1);
                    if is_tracked && !tracked_secrets.contains(s) {
                        tracked_secrets.push(s.clone());
                    }
                    !is_tracked
                });
                // and what only that tree tracks is in neither place
                let there: Vec<RelPath> = split_z(&og(ctx, from, &["ls-files", "-z"])?)
                    .into_iter()
                    .map(|rec| RelPath(rec.to_vec()))
                    .filter(|p| !tracked_set.contains(p))
                    .collect();
                tracked_elsewhere = pick_secrets(o, there.iter());
                picked
            }
        };
    }
    let secret_stats: BTreeMap<RelPath, Option<Stat>> = secret
        .iter()
        .map(|s| (s.1.clone(), lstat(secret_root, &s.1)))
        .collect();

    let keep = |p: &RelPath| !o.exclude.matches(p) && !secret_paths.contains(p);
    let tracked: Vec<(u32, String, RelPath)> = tracked.into_iter().filter(|t| keep(&t.2)).collect();
    let untracked: Vec<RelPath> = untracked.into_iter().filter(|p| keep(p)).collect();
    let included: Vec<RelPath> = ignored
        .into_iter()
        .filter(|p| o.include.matches(p) && keep(p))
        .collect();

    let mut stats = BTreeMap::new();
    for p in tracked
        .iter()
        .filter(|t| t.0 != 0o160000)
        .map(|t| &t.2)
        .chain(untracked.iter())
        .chain(included.iter())
    {
        stats.insert(p.clone(), lstat(root, p));
    }
    secret.sort_by(|a, b| a.1.cmp(&b.1));
    Ok(Selection {
        meta: Meta {
            head,
            branch,
            index_hash,
            tracked,
            untracked,
            included,
            secret,
            stats,
            secret_stats,
        },
        index_bytes,
        tracked_secrets,
        tracked_elsewhere,
    })
}

/// The files among `candidates` that a `secret_files` declaration matches,
/// each with the index of the first declaration that does.
fn pick_secrets<'a>(
    o: &Opts,
    candidates: impl Iterator<Item = &'a RelPath>,
) -> Vec<(usize, RelPath)> {
    candidates
        .filter_map(|p| {
            o.secrets
                .iter()
                .position(|g| g.matches(p))
                .map(|i| (i, p.clone()))
        })
        .collect()
}

/// A FIFO, socket or device below `root` that a `secret_files` declaration
/// matches, in an ignored directory or not: an error, since it can be
/// neither read as a secret file nor passed over as if nothing were there.
/// (A repository of its own below `root` is not looked into, as in
/// [`secret_candidates`].)
fn special_secrets(root: &Path, rel: &RelPath, o: &Opts) -> Result<()> {
    let here = root.join(rel.to_path());
    let Ok(dir) = std::fs::read_dir(&here) else {
        return Ok(()); // gone or unreadable; git has said what it lists
    };
    for ent in dir {
        let ent = ent?;
        let name = ent.file_name();
        if name.as_bytes() == b".git" {
            continue;
        }
        let mut b = rel.0.clone();
        if !b.is_empty() {
            b.push(b'/');
        }
        b.extend_from_slice(name.as_bytes());
        let p = RelPath(b);
        let Ok(m) = std::fs::symlink_metadata(root.join(p.to_path())) else {
            continue; // gone; the second look notices
        };
        let t = m.file_type();
        if t.is_dir() {
            if !root.join(p.to_path()).join(".git").exists() {
                special_secrets(root, &p, o)?;
            }
        } else if !t.is_file() && !t.is_symlink() && o.secrets.iter().any(|g| g.matches(&p)) {
            return Err(SourceError::UnsupportedFileType {
                path: p.display(),
                kind: kind_of(&m).into(),
            }
            .into());
        }
    }
    Ok(())
}

/// Every file of the working tree `root` that Git does not track, ignored
/// or not: what a secret file can be. (A repository of its own below it is
/// listed as a directory and is not looked into.)
fn secret_candidates(ctx: &ExecContext, root: &Path) -> Result<Vec<RelPath>> {
    Ok(split_z(&og(ctx, root, &["ls-files", "-z", "-o"])?)
        .into_iter()
        .filter(|rec| !rec.ends_with(b"/"))
        .map(|rec| RelPath(rec.to_vec()))
        .collect())
}

/// The top of the working tree `dir` is in, for
/// [`CaptureOptions::secret_root`].
fn secret_toplevel(ctx: &ExecContext, dir: &Path) -> Result<PathBuf> {
    let top = og_str(ctx, dir, &["rev-parse", "--show-toplevel"]).with_context(|| {
        format!(
            "secret_root {} is not inside a git working tree",
            dir.display()
        )
    })?;
    Ok(std::fs::canonicalize(top)?)
}

/// A FIFO, socket or device in the working directory that is not in an
/// ignored directory, a repository of its own or `exclude`d.
fn find_special(root: &Path, rel: &RelPath, skip: &[RelPath], o: &Opts) -> Result<()> {
    let here = if rel.is_empty() {
        root.to_path_buf()
    } else {
        root.join(rel.to_path())
    };
    for ent in std::fs::read_dir(&here)? {
        let ent = ent?;
        let name = ent.file_name();
        if rel.is_empty() && name.as_bytes() == b".git" {
            continue;
        }
        let mut b = rel.0.clone();
        if !b.is_empty() {
            b.push(b'/');
        }
        b.extend_from_slice(name.as_bytes());
        let p = RelPath(b);
        let Ok(m) = std::fs::symlink_metadata(root.join(p.to_path())) else {
            continue; // gone; the second look notices
        };
        let t = m.file_type();
        if t.is_dir() {
            if skip.contains(&p) || root.join(p.to_path()).join(".git").exists() {
                continue;
            }
            find_special(root, &p, skip, o)?;
        } else if !t.is_file() && !t.is_symlink() && !o.exclude.matches(&p) {
            return Err(SourceError::UnsupportedFileType {
                path: p.display(),
                kind: kind_of(&m).into(),
            }
            .into());
        }
    }
    Ok(())
}

/// Every file below `dir`, for a directory snapshot.
fn select_directory(dir: &Path, o: &Opts, warnings: &mut Vec<String>) -> Result<Meta> {
    fn walk(
        root: &Path,
        rel: &RelPath,
        o: &Opts,
        out: &mut Vec<RelPath>,
        warnings: &mut Vec<String>,
    ) -> Result<()> {
        let here = if rel.is_empty() {
            root.to_path_buf()
        } else {
            root.join(rel.to_path())
        };
        let mut names: Vec<OsString> = std::fs::read_dir(&here)?
            .map(|e| e.map(|e| e.file_name()))
            .collect::<std::io::Result<_>>()?;
        names.sort();
        for n in names {
            let mut b = rel.0.clone();
            if !b.is_empty() {
                b.push(b'/');
            }
            b.extend_from_slice(n.as_bytes());
            let p = RelPath(b);
            if o.exclude.matches(&p) {
                continue;
            }
            let m = std::fs::symlink_metadata(root.join(p.to_path()))?;
            if n.as_bytes().eq_ignore_ascii_case(b".git") {
                // a `.git` directory is left out; anything else called that
                // could never be written into a workspace
                if m.is_dir() && n.as_bytes() == b".git" {
                    warnings.push(format!("{}: a .git directory is left out", p.display()));
                    continue;
                }
                return Err(SourceError::UnsafePath {
                    path: p.display(),
                    why: "a file or directory named .git cannot be part of a workspace".into(),
                }
                .into());
            }
            if m.is_dir() {
                walk(root, &p, o, out, warnings)?;
            } else {
                out.push(p);
            }
        }
        Ok(())
    }
    let mut files = vec![];
    walk(dir, &RelPath(vec![]), o, &mut files, warnings)?;
    // the secret files are kept apart, as in a worktree
    let secret = pick_secrets(o, files.iter());
    let secret_paths: BTreeSet<&RelPath> = secret.iter().map(|s| &s.1).collect();
    files.retain(|p| !secret_paths.contains(p));
    let stats = files.iter().map(|p| (p.clone(), lstat(dir, p))).collect();
    let secret_stats = secret
        .iter()
        .map(|s| (s.1.clone(), lstat(dir, &s.1)))
        .collect();
    Ok(Meta {
        untracked: files,
        secret,
        stats,
        secret_stats,
        ..Meta::default()
    })
}

struct Opts {
    exclude: Globs,
    include: Globs,
    secrets: Vec<Globs>,
    /// The top of the working tree the secret files are taken from, when it
    /// is not the directory that is captured.
    secret_root: Option<PathBuf>,
}

// ---- reading --------------------------------------------------------------

fn kind_of(m: &std::fs::Metadata) -> &'static str {
    let t = m.file_type();
    if t.is_fifo() {
        "FIFO"
    } else if t.is_socket() {
        "socket"
    } else if t.is_char_device() {
        "character device"
    } else if t.is_block_device() {
        "block device"
    } else {
        "special file"
    }
}

/// One file into the store: `None` when it is gone (a deletion).
fn ingest(
    store: &ObjectStore,
    root: &Path,
    p: &RelPath,
    st: &Option<Stat>,
) -> Result<Option<FileEntry>> {
    let Some(st) = st else { return Ok(None) };
    let full = root.join(p.to_path());
    let meta = match std::fs::symlink_metadata(&full) {
        Ok(m) => m,
        Err(_) => return Err(unstable(format!("{} vanished", p.display()))),
    };
    if Stat::of(&meta) != *st {
        return Err(unstable(format!("{} changed", p.display())));
    }
    let ft = meta.file_type();
    if ft.is_dir() {
        return Ok(None);
    }
    if ft.is_symlink() {
        let target = std::fs::read_link(&full)?;
        let (hash, size) = store.put_bytes(target.as_os_str().as_bytes())?;
        return Ok(Some(FileEntry {
            path: p.clone(),
            mode: 0o120000,
            size,
            hash,
        }));
    }
    if !ft.is_file() {
        return Err(SourceError::UnsupportedFileType {
            path: p.display(),
            kind: kind_of(&meta).into(),
        }
        .into());
    }
    let mut f = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
        .open(&full)?;
    let opened = f.metadata()?;
    if opened.ino() != st.ino || opened.dev() != st.dev || opened.size() != st.size {
        return Err(unstable(format!("{} was replaced", p.display())));
    }
    let (hash, size) = store.put_reader(&mut f)?;
    let after = f.metadata()?;
    if size != st.size || (after.mtime(), after.mtime_nsec()) != st.mtime {
        return Err(unstable(format!("{} changed while read", p.display())));
    }
    Ok(Some(FileEntry {
        path: p.clone(),
        mode: if st.mode & 0o111 != 0 {
            0o100755
        } else {
            0o100644
        },
        size,
        hash,
    }))
}

/// `name` in the directory `dir`, never through a symlink at `name`.
fn open_at(dir: &std::fs::File, name: &[u8], flags: libc::c_int) -> std::io::Result<std::fs::File> {
    use std::os::fd::{AsRawFd, FromRawFd};
    let name = std::ffi::CString::new(name)?;
    // SAFETY: `name` is a NUL-terminated string that outlives the call, and
    // the descriptor that comes back is owned by nothing else.
    let fd = unsafe {
        libc::openat(
            dir.as_raw_fd(),
            name.as_ptr(),
            flags | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        )
    };
    if fd < 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

/// Exactly `size` bytes of `f`, which is `p`: a file that holds more by now
/// (or less) changed while it was read. Never more than `size + 1` bytes are
/// taken, however much the file has grown.
fn read_sized(f: &mut impl std::io::Read, size: u64, p: &RelPath) -> Result<Vec<u8>> {
    let mut bytes = vec![];
    let mut limited = std::io::Read::take(f, size + 1);
    std::io::Read::read_to_end(&mut limited, &mut bytes)?;
    if bytes.len() as u64 != size {
        return Err(unstable(format!("{} changed while read", p.display())));
    }
    Ok(bytes)
}

/// One secret file of `root`: `None` when it is gone. Only a regular file
/// that is really below `root` is read: a symlink (the file itself or a
/// directory above it), a FIFO or a device is an error, never skipped and
/// never followed. The directories above it are opened one by one from
/// `root`, each without following a symlink, and the file is opened in the
/// last of them, so nothing that is swapped in on the way is gone through;
/// what was opened has to be the very file that was listed (`st`).
///
/// A file above [`MAX_SECRET_FILE_BYTES`], or one that takes `total` (the
/// bytes of the secret files read so far in this capture) above
/// [`MAX_SECRET_TOTAL_BYTES`], is [`SourceError::SecretTooLarge`], said
/// before the file is opened.
fn read_secret(
    root: &Path,
    p: &RelPath,
    st: &Option<Stat>,
    total: &mut u64,
) -> Result<Option<(u32, Vec<u8>)>> {
    let Some(st) = st else { return Ok(None) };
    super::store::check_safe(p)?;
    let mut dir = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY)
        .open(root)?;
    for a in p.ancestors() {
        let name = a.0.rsplit(|&b| b == b'/').next().unwrap();
        dir = match open_at(&dir, name, libc::O_RDONLY | libc::O_DIRECTORY) {
            Ok(d) => d,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(unstable(format!("{} vanished", p.display())))
            }
            // a symlink is ELOOP or ENOTDIR, by platform; a file is ENOTDIR
            Err(_) => {
                return Err(SourceError::UnsafePath {
                    path: p.display(),
                    why: format!("{} is not a directory (a symlink or a file)", a.display()),
                }
                .into())
            }
        };
    }
    let not_regular = || -> anyhow::Error {
        SourceError::UnsupportedFileType {
            path: p.display(),
            kind: "non-regular secret file".into(),
        }
        .into()
    };
    // by what was listed, before anything is opened: a FIFO or a device is
    // not opened at all
    // (S_IFMT and S_IFREG, whose integer type differs by platform)
    if st.mode & 0o170000 != 0o100000 {
        return Err(not_regular());
    }
    if st.size > MAX_SECRET_FILE_BYTES {
        return Err(SourceError::SecretTooLarge {
            path: p.display(),
            size: st.size,
            limit: MAX_SECRET_FILE_BYTES,
        }
        .into());
    }
    if *total + st.size > MAX_SECRET_TOTAL_BYTES {
        return Err(SourceError::SecretTooLarge {
            path: p.display(),
            size: *total + st.size,
            limit: MAX_SECRET_TOTAL_BYTES,
        }
        .into());
    }
    let name = p.0.rsplit(|&b| b == b'/').next().unwrap();
    let mut f = match open_at(&dir, name, libc::O_RDONLY | libc::O_NONBLOCK) {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(unstable(format!("{} vanished", p.display())))
        }
        // a symlink: ELOOP (EMLINK on some systems)
        Err(e) if matches!(e.raw_os_error(), Some(libc::ELOOP) | Some(libc::EMLINK)) => {
            return Err(not_regular())
        }
        Err(e) => return Err(e.into()),
    };
    // the whole stat, not only which file it is: the size that was checked
    // above is the size of what is read
    if Stat::of(&f.metadata()?) != *st {
        return Err(unstable(format!("{} changed", p.display())));
    }
    let bytes = read_sized(&mut f, st.size, p)?;
    if Stat::of(&f.metadata()?) != *st {
        return Err(unstable(format!("{} changed while read", p.display())));
    }
    *total += st.size;
    Ok(Some((0o600, bytes)))
}

// ---- LFS ------------------------------------------------------------------

const LFS_VERSION: &str = "version https://git-lfs.github.com/spec/v1";

fn lfs_pointer_text(oid: &str, size: u64) -> String {
    format!("{LFS_VERSION}\noid sha256:{oid}\nsize {size}\n")
}

fn parse_lfs_pointer(b: &[u8]) -> Option<(String, u64)> {
    let t = std::str::from_utf8(b).ok()?;
    let mut lines = t.lines();
    if lines.next()? != LFS_VERSION {
        return None;
    }
    let mut oid = None;
    let mut size = None;
    for l in lines {
        if let Some(h) = l.strip_prefix("oid sha256:") {
            oid = Some(h.to_string());
        } else if let Some(s) = l.strip_prefix("size ") {
            size = s.parse().ok();
        }
    }
    let oid = oid?;
    (oid.len() == 64 && oid.bytes().all(|c| c.is_ascii_hexdigit())).then_some(())?;
    Some((oid, size?))
}

/// For every entry whose `filter` attribute is `lfs`, put the payload in the
/// place of a pointer, and note it. A pointer without a payload is an error.
fn resolve_lfs(
    ctx: &ExecContext,
    store: &ObjectStore,
    root: &Path,
    entries: &mut [FileEntry],
) -> Result<Vec<LfsRef>> {
    let regular: Vec<usize> = (0..entries.len())
        .filter(|&i| entries[i].mode != 0o120000)
        .collect();
    if regular.is_empty() {
        return Ok(vec![]);
    }
    let mut input = vec![];
    for &i in &regular {
        input.extend_from_slice(&entries[i].path.0);
        input.push(0);
    }
    let out = git_run(
        ctx,
        &["-C".into(), root.into()],
        &["check-attr", "-z", "--stdin", "filter"],
        &[("GIT_OPTIONAL_LOCKS", OsStr::new("0"))],
        Some(input),
    )?;
    let fields: Vec<&[u8]> = out.split(|&c| c == 0).collect();
    let mut lfs_paths = BTreeSet::new();
    for rec in fields.chunks(3) {
        if rec.len() == 3 && rec[2] == b"lfs" {
            lfs_paths.insert(RelPath(rec[0].to_vec()));
        }
    }
    if lfs_paths.is_empty() {
        return Ok(vec![]);
    }
    let common = og_str(
        ctx,
        root,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )?;
    let lfs_dir = Path::new(&common).join("lfs/objects");
    let mut refs = vec![];
    for e in entries.iter_mut() {
        if !lfs_paths.contains(&e.path) {
            continue;
        }
        if e.size <= 1024 {
            if let Some((oid, size)) = parse_lfs_pointer(&store.read(&e.hash)?) {
                let payload = lfs_dir.join(&oid[..2]).join(&oid[2..4]).join(&oid);
                let missing = || SourceError::LfsPayloadMissing {
                    path: e.path.display(),
                    oid: oid.clone(),
                };
                let mut f = std::fs::File::open(&payload).map_err(|_| missing())?;
                let (hash, n) = store.put_reader(&mut f)?;
                if hash != oid || n != size {
                    return Err(SourceError::Corrupt {
                        what: format!("LFS object {oid} does not match its pointer"),
                    }
                    .into());
                }
                refs.push(LfsRef {
                    path: e.path.clone(),
                    oid: oid.clone(),
                    size,
                    pointer_hash: sha256_hex(lfs_pointer_text(&oid, size).as_bytes()),
                });
                e.hash = hash;
                e.size = n;
                continue;
            }
        }
        // already the payload (the smudge filter ran)
        refs.push(LfsRef {
            path: e.path.clone(),
            oid: e.hash.clone(),
            size: e.size,
            pointer_hash: sha256_hex(lfs_pointer_text(&e.hash, e.size).as_bytes()),
        });
    }
    Ok(refs)
}

// ---- the manifest ---------------------------------------------------------

pub(crate) fn tree_digest(entries: &[FileEntry]) -> String {
    let mut s = String::new();
    for e in entries {
        s.push_str(&format!(
            "{:o} {} {} {}\n",
            e.mode,
            store::hex(&e.path.0),
            e.size,
            e.hash
        ));
    }
    format!("sha256:{}", sha256_hex(s.as_bytes()))
}

fn digest_of(m: &SourceManifest) -> String {
    let mut blank = m.clone();
    blank.source_id = String::new();
    blank.manifest_digest = String::new();
    let v: Value = serde_json::to_value(&blank).expect("a manifest is JSON");
    sha256_hex(crate::frozen::canonical_json(&v).as_bytes())
}

/// `m` with its `manifest_digest` and `source_id` worked out from its content.
pub fn seal_manifest(mut m: SourceManifest) -> SourceManifest {
    let d = digest_of(&m);
    m.source_id = format!("src-{}", &d[..32]);
    m.manifest_digest = format!("sha256:{d}");
    m
}

pub(crate) fn check_digest(m: &SourceManifest) -> Result<()> {
    if m.schema_version != SCHEMA_VERSION {
        bail!(
            "source manifest schema version {} is not supported (this is {SCHEMA_VERSION})",
            m.schema_version
        );
    }
    let d = digest_of(m);
    if m.manifest_digest != format!("sha256:{d}") || m.source_id != format!("src-{}", &d[..32]) {
        return Err(SourceError::Corrupt {
            what: format!("manifest {} does not match its digest", m.source_id),
        }
        .into());
    }
    Ok(())
}

// ---- the private repository ----------------------------------------------

/// The store key of the private repository of a repository: its id and where
/// its common Git directory is on this host.
pub(crate) fn private_key(repository_id: &str, common_dir: &str) -> String {
    sha256_hex(format!("{repository_id}\0{common_dir}").as_bytes())[..16].to_string()
}

/// The bare repository that holds the synthetic commits of one repository.
///
/// It owns its objects: [`import_history`] copies in the history a capture
/// needs, so a rewrite or a `git gc` in the original does not break an export
/// later. The original's `info/attributes` is copied here, because
/// `.gitattributes` files are read from the working tree but this one does
/// not have it.
fn private_repo(
    ctx: &ExecContext,
    store: &ObjectStore,
    root: &Path,
    repository_id: &str,
) -> Result<PathBuf> {
    let common = og_str(
        ctx,
        root,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )?;
    let dir = store.git_dir(&private_key(repository_id, &common));
    if !dir.join("HEAD").is_file() {
        let out = ctx
            .command("git")
            .args(["init", "--bare", "-q"])
            .arg(&dir)
            .output()
            .context("failed to run git")?;
        if !out.status.success() {
            bail!("git init: {}", String::from_utf8_lossy(&out.stderr).trim());
        }
    }
    let dest = dir.join("info/attributes");
    match std::fs::read(Path::new(&common).join("info/attributes")) {
        Ok(b) => write_atomic(&dest, &b, 0o644)?,
        Err(_) => {
            let _ = std::fs::remove_file(&dest);
        }
    }
    Ok(dir)
}

/// The history of `head` (so the merge base and the unpushed commits too),
/// fetched from the original into the private repository. Reads the original,
/// writes only the private one.
/// A shallow clone has no history to copy, and only SHA-1 object names fit
/// the manifest: both are refused before anything is written.
fn check_supported(ctx: &ExecContext, root: &Path) -> Result<()> {
    let shallow = og_str(ctx, root, &["rev-parse", "--is-shallow-repository"]).unwrap_or_default();
    if shallow == "true" {
        return Err(SourceError::ShallowClone.into());
    }
    let format = og_str(ctx, root, &["rev-parse", "--show-object-format"]).unwrap_or_default();
    if !format.is_empty() && format != "sha1" {
        return Err(SourceError::UnsupportedObjectFormat { format }.into());
    }
    Ok(())
}

fn import_history(ctx: &ExecContext, git_dir: &Path, root: &Path, head: &str) -> Result<()> {
    let r = format!("refs/local-ci/heads/{head}");
    if pg(
        ctx,
        git_dir,
        &["rev-parse", "--verify", "-q", &r],
        &[],
        None,
    )
    .is_ok()
    {
        return Ok(());
    }
    let args: Vec<OsString> = vec![
        "--git-dir".into(),
        git_dir.into(),
        "-c".into(),
        "uploadpack.allowAnySHA1InWant=true".into(),
        "fetch".into(),
        "-q".into(),
        "--no-tags".into(),
        "--no-write-fetch-head".into(),
        root.into(),
        format!("+{head}:{r}").into(),
    ];
    git_run_os(
        ctx,
        None,
        &args,
        &[("GIT_OPTIONAL_LOCKS", OsStr::new("0"))],
        None,
    )
    .context("cannot copy the history of HEAD into the source store")?;
    // a fetch that warns and exits 0 leaves no ref behind
    pg(
        ctx,
        git_dir,
        &["rev-parse", "--verify", "-q", &format!("{r}^{{commit}}")],
        &[],
        None,
    )
    .with_context(|| format!("the history of {head} did not arrive in the source store"))?;
    Ok(())
}

fn repository_id(ctx: &ExecContext, root: &Path) -> Result<String> {
    if let Some(slug) = crate::git::repo_slug(ctx, root) {
        return Ok(format!("github:{slug}"));
    }
    let roots = og_str(ctx, root, &["rev-list", "--max-parents=0", "HEAD"])?;
    let first = roots.lines().min().context("no root commit")?;
    Ok(format!("root:{first}"))
}

/// Blobs for the store objects `hashes` in the private repository; returns
/// the git id of each.
fn write_blobs(
    ctx: &ExecContext,
    store: &ObjectStore,
    git_dir: &Path,
    hashes: &[&str],
) -> Result<HashMap<String, String>> {
    if hashes.is_empty() {
        return Ok(HashMap::new());
    }
    let marks = store::tmp_name(&store.tmp_dir(), "marks");
    let mut child = ctx
        .command("git")
        .arg("--git-dir")
        .arg(git_dir)
        .args(["fast-import", "--quiet", "--done"])
        .arg(format!("--export-marks={}", marks.display()))
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .context("failed to run git fast-import")?;
    let mut si = child.stdin.take().unwrap();
    let paths: Vec<PathBuf> = hashes.iter().map(|h| store.object_path(h)).collect();
    let writer = std::thread::spawn(move || -> std::io::Result<()> {
        for (i, p) in paths.iter().enumerate() {
            let size = std::fs::metadata(p)?.len();
            write!(si, "blob\nmark :{}\ndata {size}\n", i + 1)?;
            let mut f = std::fs::File::open(p)?;
            std::io::copy(&mut f, &mut si)?;
            si.write_all(b"\n")?;
        }
        si.write_all(b"done\n")
    });
    let out = child.wait_with_output()?;
    writer
        .join()
        .map_err(|_| anyhow::anyhow!("fast-import writer panicked"))??;
    if !out.status.success() {
        bail!(
            "git fast-import: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let text = std::fs::read_to_string(&marks)?;
    let _ = std::fs::remove_file(&marks);
    let mut shas = HashMap::new();
    for line in text.lines() {
        let (m, sha) = line.split_once(' ').context("bad marks file")?;
        let i: usize = m.trim_start_matches(':').parse()?;
        shas.insert(hashes[i - 1].to_string(), sha.to_string());
    }
    Ok(shas)
}

/// The global attributes file the original's Git reads: `core.attributesFile`,
/// else the default one under `$XDG_CONFIG_HOME` / `~/.config`, when it exists.
pub(crate) fn global_attributes_path(ctx: &ExecContext, root: &Path) -> Option<PathBuf> {
    let configured = og_str(
        ctx,
        root,
        &["config", "--type=path", "--get", "core.attributesfile"],
    )
    .ok()
    .filter(|s| !s.is_empty());
    let p = match configured {
        Some(c) => PathBuf::from(c),
        None => {
            let base = match ctx.var("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
                Some(x) => PathBuf::from(x),
                None => PathBuf::from(ctx.home()?).join(".config"),
            };
            base.join("git/attributes")
        }
    };
    p.is_file().then_some(p)
}

/// `-c key=value` arguments for the settings of the original that decide how
/// content becomes a blob: filters and line-ending conversion. They are passed
/// on the command line, so the original's config is read and never written.
fn filter_config(ctx: &ExecContext, root: &Path) -> Vec<OsString> {
    let out = og(
        ctx,
        root,
        &[
            "config",
            "-z",
            "--get-regexp",
            r"^(filter\..*|core\.(autocrlf|eol|safecrlf|whitespace))$",
        ],
    )
    .unwrap_or_default();
    let mut args = vec![];
    for rec in out.split(|&c| c == 0).filter(|r| !r.is_empty()) {
        let kv = match rec.iter().position(|&c| c == b'\n') {
            Some(i) => [&rec[..i], b"=", &rec[i + 1..]].concat(),
            None => rec.to_vec(),
        };
        args.push(OsString::from("-c"));
        args.push(OsString::from_vec(kv));
    }
    if let Some(p) = global_attributes_path(ctx, root) {
        args.push(OsString::from("-c"));
        let mut kv = b"core.attributesfile=".to_vec();
        kv.extend_from_slice(p.as_os_str().as_bytes());
        args.push(OsString::from_vec(kv));
    }
    args
}

/// A scratch directory holding the `.gitattributes` files of the capture, as
/// captured: attributes are read from here and not from the original's
/// working tree, which may have moved since.
struct AttrTree {
    dir: PathBuf,
}

impl AttrTree {
    fn new(store: &ObjectStore, entries: &[FileEntry]) -> Result<Self> {
        let dir = store::tmp_name(&store.tmp_dir(), "attrs");
        std::fs::create_dir_all(&dir)?;
        let tree = AttrTree { dir };
        for e in entries {
            let name = &e.path.0;
            let is_attrs = name.ends_with(b".gitattributes")
                && (name.len() == 14 || name[name.len() - 15] == b'/');
            if !is_attrs || e.mode == 0o120000 {
                continue;
            }
            let target = tree.dir.join(e.path.to_path());
            if let Some(parent) = target.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&target, store.read(&e.hash)?)?;
        }
        Ok(tree)
    }
}

impl Drop for AttrTree {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// The value of each of `names` for each of `paths`, by the attributes of the
/// capture: `(path, attribute, value)`.
fn check_attr(
    ctx: &ExecContext,
    git_dir: &Path,
    attrs: &AttrTree,
    cfg: &[OsString],
    names: &[&str],
    paths: &[&RelPath],
) -> Result<Vec<(RelPath, String, String)>> {
    if paths.is_empty() {
        return Ok(vec![]);
    }
    let mut input = vec![];
    for p in paths {
        input.extend_from_slice(&p.0);
        input.push(0);
    }
    let mut args: Vec<OsString> = vec![
        "--git-dir".into(),
        git_dir.into(),
        "--work-tree".into(),
        attrs.dir.clone().into(),
    ];
    args.extend(cfg.iter().cloned());
    args.extend(["check-attr", "-z", "--stdin"].map(OsString::from));
    args.extend(names.iter().map(OsString::from));
    let out = git_run_os(ctx, Some(&attrs.dir), &args, &[], Some(input))?;
    let fields: Vec<&[u8]> = out.split(|&c| c == 0).collect();
    Ok(fields
        .chunks(3)
        .filter(|r| r.len() == 3)
        .map(|r| {
            (
                RelPath(r[0].to_vec()),
                String::from_utf8_lossy(r[1]).into_owned(),
                String::from_utf8_lossy(r[2]).into_owned(),
            )
        })
        .collect())
}

/// The attribute rules that are not in the tree: the global attributes file,
/// then `info/attributes` of the repository at `git_dir`.
pub(crate) fn attribute_rules(ctx: &ExecContext, root: &Path, git_dir: &Path) -> Vec<u8> {
    let mut rules = vec![];
    if let Some(g) = global_attributes_path(ctx, root) {
        rules.extend(std::fs::read(g).unwrap_or_default());
    }
    if let Ok(info) = std::fs::read(git_dir.join("info/attributes")) {
        if !rules.is_empty() && !rules.ends_with(b"\n") {
            rules.push(b'\n');
        }
        rules.extend(info);
    }
    rules
}

/// The settings that made the blobs, for a worker to repeat.
fn canonical_config(
    ctx: &ExecContext,
    root: &Path,
    git_dir: &Path,
    cfg: &[OsString],
    attrs: &AttrTree,
    entries: &[FileEntry],
) -> Result<CanonicalConfig> {
    let get = |k: &str| {
        og_str(ctx, root, &["config", "--get", k])
            .ok()
            .filter(|v| !v.is_empty())
    };
    let rules = attribute_rules(ctx, root, git_dir);
    let paths: Vec<&RelPath> = entries.iter().map(|e| &e.path).collect();
    let used: BTreeSet<String> = check_attr(ctx, git_dir, attrs, cfg, &["filter"], &paths)?
        .into_iter()
        .map(|(_, _, v)| v)
        .filter(|v| !matches!(v.as_str(), "unspecified" | "unset" | "set"))
        .collect();
    let mut defs: BTreeMap<String, FilterDef> = BTreeMap::new();
    if !used.is_empty() {
        let out = og(
            ctx,
            root,
            &["config", "-z", "--get-regexp", r"^filter\..*\.[^.]+$"],
        )
        .unwrap_or_default();
        for rec in out.split(|&c| c == 0).filter(|r| !r.is_empty()) {
            let text = String::from_utf8_lossy(rec).into_owned();
            let (key, val) = text.split_once('\n').unwrap_or((text.as_str(), ""));
            let Some((name, var)) = key.strip_prefix("filter.").and_then(|k| k.rsplit_once('.'))
            else {
                continue;
            };
            if !used.contains(name) {
                continue;
            }
            let d = defs.entry(name.to_string()).or_insert_with(|| FilterDef {
                name: name.to_string(),
                clean: None,
                smudge: None,
                process: None,
                required: None,
            });
            let v = Some(val.to_string());
            match var {
                "clean" => d.clean = v,
                "smudge" => d.smudge = v,
                "process" => d.process = v,
                "required" => d.required = v,
                _ => {}
            }
        }
    }
    Ok(CanonicalConfig {
        autocrlf: get("core.autocrlf"),
        eol: get("core.eol"),
        safecrlf: get("core.safecrlf"),
        attributes: store::hex(&rules),
        filters: defs.into_values().collect(),
    })
}

/// Hash `content` as Git would when adding the file `path` of the original:
/// attributes from the capture (the `.gitattributes` files it holds, the
/// original's `info/attributes` in the private repository), filters and line
/// endings from the original's config. The blob goes to the private
/// repository.
fn hash_filtered(
    ctx: &ExecContext,
    git_dir: &Path,
    attrs: &AttrTree,
    cfg: &[OsString],
    path: &RelPath,
    content: Vec<u8>,
) -> Result<String> {
    let mut args: Vec<OsString> = vec![
        "--git-dir".into(),
        git_dir.into(),
        "--work-tree".into(),
        attrs.dir.clone().into(),
    ];
    args.extend(cfg.iter().cloned());
    args.extend(["hash-object", "-w", "--stdin"].map(OsString::from));
    args.push(OsString::from_vec(
        [b"--path=".as_slice(), &path.0].concat(),
    ));
    let out = git_run_os(ctx, Some(&attrs.dir), &args, &[], Some(content))
        .with_context(|| format!("cannot hash {}", path.display()))?;
    Ok(String::from_utf8_lossy(&out).trim().to_string())
}

/// Hash bytes as they are (no path, so no filter).
fn hash_plain(ctx: &ExecContext, git_dir: &Path, content: Vec<u8>) -> Result<String> {
    let out = pg(
        ctx,
        git_dir,
        &["hash-object", "-w", "--stdin"],
        &[],
        Some(content),
    )?;
    Ok(String::from_utf8_lossy(&out).trim().to_string())
}

/// Paths (of `paths`) that no attribute and no setting touches on their way
/// into Git: their blob is their bytes.
fn untouched_paths(
    ctx: &ExecContext,
    root: &Path,
    git_dir: &Path,
    attrs: &AttrTree,
    cfg: &[OsString],
    paths: &[&RelPath],
) -> Result<BTreeSet<RelPath>> {
    let autocrlf = og_str(ctx, root, &["config", "--get", "core.autocrlf"]).unwrap_or_default();
    if !(autocrlf.is_empty() || autocrlf == "false") || paths.is_empty() {
        return Ok(BTreeSet::new());
    }
    let found = check_attr(
        ctx,
        git_dir,
        attrs,
        cfg,
        &[
            "text",
            "eol",
            "filter",
            "ident",
            "working-tree-encoding",
            "crlf",
        ],
        paths,
    )?;
    let touched: BTreeSet<RelPath> = found
        .into_iter()
        .filter(|(_, _, v)| v != "unspecified")
        .map(|(p, _, _)| p)
        .collect();
    Ok(paths
        .iter()
        .filter(|p| !touched.contains(**p))
        .map(|p| (*p).clone())
        .collect())
}

/// Make sure the blobs `shas` of the original are in the private repository
/// (staged content that was never committed is only in the original).
fn copy_blobs(ctx: &ExecContext, root: &Path, git_dir: &Path, shas: &[&str]) -> Result<()> {
    if shas.is_empty() {
        return Ok(());
    }
    let input: Vec<u8> = shas
        .iter()
        .flat_map(|s| format!("{s}\n").into_bytes())
        .collect();
    let out = pg(
        ctx,
        git_dir,
        &["cat-file", "--batch-check"],
        &[],
        Some(input),
    )?;
    for line in String::from_utf8_lossy(&out).lines() {
        let Some(sha) = line.strip_suffix(" missing") else {
            continue;
        };
        let content = og(ctx, root, &["cat-file", "blob", sha])?;
        let got = hash_plain(ctx, git_dir, content)?;
        if got != sha {
            bail!("blob {sha} was copied as {got}");
        }
    }
    Ok(())
}

/// The Git blob of every entry, in the private repository.
///
/// A blob is what Git itself would store, not the bytes of the file: the
/// content as it is in the original's index when the file is unchanged, the
/// result of the original's `.gitattributes` and filters (`hash-object
/// --path`) when it is not, the pointer for an LFS file, and the link value
/// for a symlink. Reading the commit therefore gives what Git gives:
/// a clean repository has the tree of `HEAD`.
#[allow(clippy::too_many_arguments)]
fn blob_ids(
    ctx: &ExecContext,
    store: &ObjectStore,
    root: &Path,
    git_dir: &Path,
    entries: &[FileEntry],
    tracked: &[(u32, String, RelPath)],
    lfs: &[LfsRef],
    attrs: &AttrTree,
    cfg: &[OsString],
) -> Result<Vec<String>> {
    let lfs_by: HashMap<&RelPath, &LfsRef> = lfs.iter().map(|l| (&l.path, l)).collect();
    let index: HashMap<&RelPath, &str> = tracked
        .iter()
        .filter(|t| t.0 == 0o100644 || t.0 == 0o100755)
        .map(|t| (&t.2, t.1.as_str()))
        .collect();
    let mut changed: BTreeSet<RelPath> =
        split_z(&og(ctx, root, &["diff-files", "--name-only", "-z"])?)
            .into_iter()
            .map(|p| RelPath(p.to_vec()))
            .collect();
    // skip-worktree and assume-unchanged paths are never compared against the
    // index, so a working file that differs from it is not reported: hash them
    let listing = og(ctx, root, &["ls-files", "-v", "-z"])?;
    for rec in split_z(&listing) {
        if rec.len() > 2 && (rec[0] == b'S' || rec[0].is_ascii_lowercase()) {
            changed.insert(RelPath(rec[2..].to_vec()));
        }
    }

    let mut shas: Vec<Option<String>> = vec![None; entries.len()];
    let mut from_index: Vec<String> = vec![];
    let mut need_attrs = vec![];
    for (i, e) in entries.iter().enumerate() {
        if e.mode == 0o120000 || lfs_by.contains_key(&e.path) {
            continue;
        }
        match index.get(&e.path) {
            Some(sha) if !changed.contains(&e.path) => {
                shas[i] = Some((*sha).to_string());
                from_index.push((*sha).to_string());
            }
            _ => need_attrs.push(i),
        }
    }
    let untouched = untouched_paths(
        ctx,
        root,
        git_dir,
        attrs,
        cfg,
        &need_attrs
            .iter()
            .map(|&i| &entries[i].path)
            .collect::<Vec<_>>(),
    )?;

    // bytes that go in as they are: symlinks and files nothing touches
    let mut raw: Vec<&str> = vec![];
    for (i, e) in entries.iter().enumerate() {
        if shas[i].is_none() && (e.mode == 0o120000 || untouched.contains(&e.path)) {
            raw.push(&e.hash);
        }
    }
    raw.sort();
    raw.dedup();
    let raw_ids = write_blobs(ctx, store, git_dir, &raw)?;

    for (i, e) in entries.iter().enumerate() {
        if shas[i].is_some() {
            continue;
        }
        shas[i] = Some(if e.mode == 0o120000 {
            raw_ids[&e.hash].clone()
        } else if let Some(l) = lfs_by.get(&e.path) {
            hash_plain(ctx, git_dir, lfs_pointer_text(&l.oid, l.size).into_bytes())?
        } else if untouched.contains(&e.path) {
            raw_ids[&e.hash].clone()
        } else {
            hash_filtered(ctx, git_dir, attrs, cfg, &e.path, store.read(&e.hash)?)?
        });
    }
    let from_index: Vec<&str> = from_index.iter().map(String::as_str).collect();
    copy_blobs(ctx, root, git_dir, &from_index)?;
    Ok(shas.into_iter().map(|s| s.unwrap()).collect())
}

/// The tree of `entries` (with the blobs `shas`) and `gitlinks` in the
/// private repository.
fn build_tree(
    ctx: &ExecContext,
    store: &ObjectStore,
    git_dir: &Path,
    entries: &[FileEntry],
    shas: &[String],
    gitlinks: &[(RelPath, String)],
) -> Result<String> {
    let mut input = vec![];
    for (e, sha) in entries.iter().zip(shas) {
        input.extend_from_slice(format!("{:o} {sha}\t", e.mode).as_bytes());
        input.extend_from_slice(&e.path.0);
        input.push(0);
    }
    for (p, sha) in gitlinks {
        input.extend_from_slice(format!("160000 {sha}\t").as_bytes());
        input.extend_from_slice(&p.0);
        input.push(0);
    }
    let idx = store::tmp_name(&store.tmp_dir(), "index");
    let res = (|| -> Result<String> {
        let env = [("GIT_INDEX_FILE", idx.as_os_str())];
        pg(
            ctx,
            git_dir,
            &["update-index", "-z", "--index-info"],
            &env,
            Some(input),
        )?;
        let out = pg(ctx, git_dir, &["write-tree"], &env, None)?;
        Ok(String::from_utf8_lossy(&out).trim().to_string())
    })();
    let _ = std::fs::remove_file(&idx);
    res
}

/// The tree of the index, taken from a copy of it. The blobs that are staged
/// and not committed exist only in the original: they are copied here first.
fn index_tree(
    ctx: &ExecContext,
    store: &ObjectStore,
    root: &Path,
    git_dir: &Path,
    bytes: &[u8],
) -> Result<String> {
    let idx = store::tmp_name(&store.tmp_dir(), "index");
    std::fs::write(&idx, bytes)?;
    let res = (|| -> Result<String> {
        let env = [("GIT_INDEX_FILE", idx.as_os_str())];
        let listing = pg(ctx, git_dir, &["ls-files", "-z", "-s"], &env, None)?;
        let mut shas = vec![];
        for rec in split_z(&listing) {
            let text = String::from_utf8_lossy(rec);
            let mut it = text.split(' ');
            let (mode, sha) = (it.next().unwrap_or(""), it.next().unwrap_or(""));
            if mode != "160000" && !sha.is_empty() {
                shas.push(sha.to_string());
            }
        }
        shas.sort();
        shas.dedup();
        let shas: Vec<&str> = shas.iter().map(String::as_str).collect();
        copy_blobs(ctx, root, git_dir, &shas)?;
        let out = pg(ctx, git_dir, &["write-tree"], &env, None)?;
        Ok(String::from_utf8_lossy(&out).trim().to_string())
    })();
    let _ = std::fs::remove_file(&idx);
    res
}

fn synthetic_commit(ctx: &ExecContext, git_dir: &Path, tree: &str, parent: &str) -> Result<String> {
    fixed_commit(ctx, git_dir, tree, Some(parent), "local-ci source snapshot")
}

/// A commit with no parent that holds the index tree, so that a bundle can
/// carry the tree (a bundle holds commits, not bare trees). The same tree is
/// the same commit.
pub(super) fn index_commit(ctx: &ExecContext, git_dir: &Path, tree: &str) -> Result<String> {
    fixed_commit(ctx, git_dir, tree, None, "local-ci index snapshot")
}

fn fixed_commit(
    ctx: &ExecContext,
    git_dir: &Path,
    tree: &str,
    parent: Option<&str>,
    message: &str,
) -> Result<String> {
    // fixed author and dates: the same content is the same commit
    let who = OsStr::new("local-ci");
    let mail = OsStr::new("local-ci@localhost");
    let date = OsStr::new("1000000000 +0000");
    let env = [
        ("GIT_AUTHOR_NAME", who),
        ("GIT_AUTHOR_EMAIL", mail),
        ("GIT_AUTHOR_DATE", date),
        ("GIT_COMMITTER_NAME", who),
        ("GIT_COMMITTER_EMAIL", mail),
        ("GIT_COMMITTER_DATE", date),
    ];
    let mut args = vec!["commit-tree", tree];
    if let Some(p) = parent {
        args.extend(["-p", p]);
    }
    args.extend(["-m", message]);
    let out = pg(ctx, git_dir, &args, &env, None)?;
    Ok(String::from_utf8_lossy(&out).trim().to_string())
}

// ---- capture --------------------------------------------------------------

fn build_opts(o: &CaptureOptions) -> Result<Opts> {
    Ok(Opts {
        exclude: Globs::new(&o.exclude)?,
        include: Globs::new(&o.include)?,
        secrets: o
            .secret_files
            .iter()
            .map(|s| Globs::new(std::slice::from_ref(&s.glob)))
            .collect::<Result<_>>()?,
        secret_root: None,
    })
}

/// What has to hold before a capture with `secret_files` starts.
fn check_secret_opts(opts: &CaptureOptions) -> Result<()> {
    if opts.secret_files.is_empty() {
        return Ok(());
    }
    if opts.secret_key.len() < MIN_SECRET_KEY {
        return Err(SourceError::SecretKeyTooShort {
            len: opts.secret_key.len(),
        }
        .into());
    }
    if let Some(path) = &opts.secret_bundle {
        // said before anything is read; the write itself checks again
        secret::check_new_path(path)?;
    }
    Ok(())
}

fn store_of(ctx: &ExecContext, o: &CaptureOptions) -> Result<ObjectStore> {
    ObjectStore::open(
        o.store
            .clone()
            .unwrap_or_else(|| ctx.cache_dir().join("sources")),
    )
}

struct Read {
    entries: Vec<FileEntry>,
    secrets: Vec<(usize, RelPath, u32, Vec<u8>)>,
}

fn read_all(
    store: &ObjectStore,
    root: &Path,
    secret_root: &Path,
    meta: &Meta,
    gitlink_paths: &BTreeSet<&RelPath>,
) -> Result<Read> {
    let mut entries = vec![];
    let paths = meta
        .tracked
        .iter()
        .filter(|t| t.0 != 0o160000 && !gitlink_paths.contains(&t.2))
        .map(|t| &t.2)
        .chain(meta.untracked.iter())
        .chain(meta.included.iter());
    for p in paths {
        if let Some(e) = ingest(store, root, p, &meta.stats[p])? {
            entries.push(e);
        }
    }
    entries.sort_by(|a, b| a.path.cmp(&b.path));
    let mut secrets = vec![];
    // of this attempt: the next one starts from nothing
    let mut secret_bytes = 0u64;
    for (i, p) in &meta.secret {
        let st = &meta.secret_stats[p];
        if let Some((mode, bytes)) = read_secret(secret_root, p, st, &mut secret_bytes)? {
            secrets.push((*i, p.clone(), mode, bytes));
        }
    }
    Ok(Read { entries, secrets })
}

/// Capture the working directory of the repository containing `repo_dir`
/// (spec chapter 6). Never writes the repository.
pub fn capture_source(
    ctx: &ExecContext,
    repo_dir: &Path,
    opts: &CaptureOptions,
) -> Result<SourceSnapshot> {
    check_secret_opts(opts)?;
    capture_worktree(ctx, repo_dir, opts, &store_of(ctx, opts)?).map(|(snap, _)| snap)
}

/// The directories of a capture and what they looked like when it read them:
/// the repository itself, then every submodule below it.
type Seen = Vec<(PathBuf, Meta)>;

fn capture_worktree(
    ctx: &ExecContext,
    repo_dir: &Path,
    opts: &CaptureOptions,
    store: &ObjectStore,
) -> Result<(SourceSnapshot, Seen)> {
    let top = og_str(ctx, repo_dir, &["rev-parse", "--show-toplevel"])
        .context("not inside a git repository")?;
    let root = std::fs::canonicalize(top)?;
    let cwd = std::fs::canonicalize(repo_dir)?;
    let cwd_relative = RelPath::new(cwd.strip_prefix(&root).unwrap_or(Path::new("")));
    let mut o = build_opts(opts)?;
    if let (Some(dir), false) = (&opts.secret_root, o.secrets.is_empty()) {
        o.secret_root = Some(secret_toplevel(ctx, dir)?);
    }
    check_supported(ctx, &root)?;
    let repo_id = repository_id(ctx, &root)?;
    let git_dir = private_repo(ctx, store, &root, &repo_id)?;

    let mut last = String::new();
    let attempts = opts.max_attempts.max(1);
    for attempt in 1..=attempts {
        match one_pass(ctx, &root, opts, &o, store, attempt) {
            Ok(p) => {
                let mut seen = vec![(root.clone(), p.sel.meta.clone())];
                seen.extend(p.seen.iter().cloned());
                let snap = finish(ctx, store, &root, &git_dir, opts, repo_id, cwd_relative, p)?;
                return Ok((snap, seen));
            }
            Err(e) => match e.downcast_ref::<Unstable>() {
                Some(u) => last = u.0.clone(),
                None => return Err(e),
            },
        }
    }
    Err(SourceError::Busy { attempts, last }.into())
}

struct Stable {
    sel: Selection,
    read: Read,
    lfs: Vec<LfsRef>,
    submodules: Vec<(SubmoduleRef, String)>,
    /// The submodules below, as they were read.
    seen: Seen,
}

/// Read everything once, then look again: `Err(Unstable)` when it moved.
fn one_pass(
    ctx: &ExecContext,
    root: &Path,
    opts: &CaptureOptions,
    o: &Opts,
    store: &ObjectStore,
    attempt: u32,
) -> Result<Stable> {
    let sel = select_worktree(ctx, root, o)?;
    // initialized submodules are captured whole, each with its own retries
    let mut submodules = vec![];
    let mut seen: Seen = vec![];
    let mut gitlink_paths = BTreeSet::new();
    for (mode, sha, path) in sel.meta.tracked.iter().filter(|t| t.0 == 0o160000) {
        gitlink_paths.insert(path);
        let sub = root.join(path.to_path());
        if sub.join(".git").exists() {
            let inner = CaptureOptions {
                store: Some(store.root().to_path_buf()),
                max_attempts: opts.max_attempts,
                ..CaptureOptions::default()
            };
            let (snap, sub_seen) = capture_worktree(ctx, &sub, &inner, store)
                .with_context(|| format!("submodule {}", path.display()))?;
            seen.extend(sub_seen);
            let m = &snap.manifest;
            let head_tree = og_str(ctx, &sub, &["rev-parse", "HEAD^{tree}"]).unwrap_or_default();
            let dirty = m.original_head.as_deref() != Some(sha.as_str())
                || m.worktree_tree.as_deref() != Some(head_tree.as_str());
            let _ = mode;
            let gitlink = if dirty {
                m.execution_commit.clone().unwrap_or_else(|| sha.clone())
            } else {
                sha.clone()
            };
            submodules.push((
                SubmoduleRef {
                    path: path.clone(),
                    revision: sha.clone(),
                    source_id: Some(m.source_id.clone()),
                    dirty,
                },
                gitlink,
            ));
        } else {
            submodules.push((
                SubmoduleRef {
                    path: path.clone(),
                    revision: sha.clone(),
                    source_id: None,
                    dirty: false,
                },
                sha.clone(),
            ));
        }
    }
    let secret_root = o.secret_root.as_deref().unwrap_or(root);
    let mut read = read_all(store, root, secret_root, &sel.meta, &gitlink_paths)?;
    let lfs = resolve_lfs(ctx, store, root, &mut read.entries)?;
    opts.call(Stage::AfterRead(attempt))?;
    let again = select_worktree(ctx, root, o)?;
    if again.meta != sel.meta {
        return Err(unstable(sel.meta.diff(&again.meta)));
    }
    // the stats of what was read are the stats now
    for p in sel.meta.stats.keys() {
        if lstat(root, p) != sel.meta.stats[p] {
            return Err(unstable(format!("{} changed", p.display())));
        }
    }
    for (p, st) in &sel.meta.secret_stats {
        if lstat(secret_root, p) != *st {
            return Err(unstable(format!("{} changed", p.display())));
        }
    }
    // and a submodule is as it was when its own capture settled: its HEAD,
    // index and every file in it
    let plain = build_opts(&CaptureOptions::default())?;
    for (dir, was) in &seen {
        let now = select_worktree(ctx, dir, &plain)?;
        if &now.meta != was {
            return Err(unstable(format!(
                "submodule {}: {}",
                dir.strip_prefix(root).unwrap_or(dir).display(),
                was.diff(&now.meta)
            )));
        }
    }
    Ok(Stable {
        sel,
        read,
        lfs,
        submodules,
        seen,
    })
}

#[allow(clippy::too_many_arguments)]
fn finish(
    ctx: &ExecContext,
    store: &ObjectStore,
    root: &Path,
    git_dir: &Path,
    opts: &CaptureOptions,
    repo_id: String,
    cwd_relative: RelPath,
    p: Stable,
) -> Result<SourceSnapshot> {
    let mut warnings = vec![];
    let head = p.sel.meta.head.clone();
    let gitlinks: Vec<(RelPath, String)> = p
        .submodules
        .iter()
        .map(|(s, g)| (s.path.clone(), g.clone()))
        .collect();
    import_history(ctx, git_dir, root, &head)?;
    let cfg = filter_config(ctx, root);
    let attrs = AttrTree::new(store, &p.read.entries)?;
    let shas = blob_ids(
        ctx,
        store,
        root,
        git_dir,
        &p.read.entries,
        &p.sel.meta.tracked,
        &p.lfs,
        &attrs,
        &cfg,
    )?;
    let canonical = canonical_config(ctx, root, git_dir, &cfg, &attrs, &p.read.entries)?;
    let worktree_tree = build_tree(ctx, store, git_dir, &p.read.entries, &shas, &gitlinks)?;
    let commit = synthetic_commit(ctx, git_dir, &worktree_tree, &head)?;
    let itree = index_tree(ctx, store, root, git_dir, &p.sel.index_bytes)?;

    let base = opts
        .base
        .clone()
        .or_else(|| crate::git::default_base(ctx, root).ok());
    let merge_base = base.as_deref().and_then(|b| {
        og_str(ctx, root, &["merge-base", b, "HEAD"])
            .ok()
            .filter(|s| !s.is_empty())
    });

    let (secret_files, bundle_files) = secret_entries(
        opts,
        p.read.secrets,
        &p.sel.tracked_secrets,
        &p.sel.tracked_elsewhere,
        &mut warnings,
    )?;

    let entries = p.read.entries;
    let mut submodules: Vec<SubmoduleRef> = p.submodules.into_iter().map(|s| s.0).collect();
    submodules.sort_by(|a, b| a.path.cmp(&b.path));
    let mut lfs = p.lfs;
    lfs.sort_by(|a, b| a.path.cmp(&b.path));
    let m = seal_manifest(SourceManifest {
        schema_version: SCHEMA_VERSION,
        source_id: String::new(),
        manifest_digest: String::new(),
        repository_id: Some(repo_id),
        source_kind: SourceKind::Worktree,
        original_head: Some(head),
        index_tree: Some(itree),
        worktree_tree: Some(worktree_tree),
        execution_commit: Some(commit.clone()),
        base,
        merge_base,
        branch: p.sel.meta.branch.clone(),
        cwd_relative,
        object_manifest: ObjectManifest {
            tree_digest: tree_digest(&entries),
            entries,
            git_tips: vec![commit.clone()],
        },
        submodules,
        lfs,
        canonical,
        secret_files,
    });
    pg(
        ctx,
        git_dir,
        &[
            "update-ref",
            &format!("refs/local-ci/snapshots/{}", m.source_id),
            &commit,
        ],
        &[],
        None,
    )?;
    // The index tree is kept by a ref of its own too (a commit around it), so
    // that a prune of the store does not take what was staged and an export
    // can carry it.
    if let Some(tree) = &m.index_tree {
        let ic = index_commit(ctx, git_dir, tree)?;
        pg(
            ctx,
            git_dir,
            &[
                "update-ref",
                &format!("refs/local-ci/index/{}", m.source_id),
                &ic,
            ],
            &[],
            None,
        )?;
    }
    let secrets = publish(store, opts, &m, bundle_files)?;
    Ok(SourceSnapshot {
        manifest: m,
        secrets,
        warnings,
    })
}

type BundleFile = (RelPath, u32, Vec<u8>);

/// The manifest entries and the bundle content of the secret files that were
/// read. A declaration that matched nothing fails the capture when it is
/// `required` and is a warning otherwise. `elsewhere` are the files that
/// only the working tree of a `secret_root` tracks: they are in neither
/// place, which the warning says instead of "matches no file".
fn secret_entries(
    opts: &CaptureOptions,
    read: Vec<(usize, RelPath, u32, Vec<u8>)>,
    tracked: &[(usize, RelPath)],
    elsewhere: &[(usize, RelPath)],
    warnings: &mut Vec<String>,
) -> Result<(Vec<SecretEntry>, Vec<BundleFile>)> {
    for (_, path) in tracked {
        warnings.push(format!(
            "{} is tracked, so it is commit content and not a secret file",
            path.display()
        ));
    }
    for (_, path) in elsewhere {
        warnings.push(format!(
            "{} is tracked in the working tree of secret_root but not in the captured commit, so it is neither content of the source nor a secret file",
            path.display()
        ));
    }
    for (i, spec) in opts.secret_files.iter().enumerate() {
        if read.iter().all(|s| s.0 != i) && tracked.iter().all(|s| s.0 != i) {
            if spec.required {
                return Err(SourceError::RequiredSecretMissing {
                    glob: spec.glob.clone(),
                }
                .into());
            }
            if elsewhere.iter().all(|s| s.0 != i) {
                warnings.push(format!("secret_files {:?} matches no file", spec.glob));
            }
        }
    }
    let mut secret_files = vec![];
    let mut bundle_files = vec![];
    for (_, path, mode, bytes) in read {
        secret_files.push(SecretEntry {
            hmac: secret::secret_digest(&opts.secret_key, &path, &bytes),
            path: path.clone(),
        });
        bundle_files.push((path, mode, bytes));
    }
    secret_files.sort_by(|a, b| a.path.cmp(&b.path));
    Ok((secret_files, bundle_files))
}

/// The last step of a capture: the secret bundle, then the manifest. A
/// bundle at a path the caller chose is taken away again when the manifest
/// is not published after all, so nothing of a capture that failed stays
/// there (and the same path can be used for the next try).
fn publish(
    store: &ObjectStore,
    opts: &CaptureOptions,
    m: &SourceManifest,
    bundle_files: Vec<BundleFile>,
) -> Result<Option<PathBuf>> {
    let secrets = if bundle_files.is_empty() {
        None
    } else {
        let bundle = SecretBundle::new(bundle_files);
        Some(match &opts.secret_bundle {
            Some(path) => {
                bundle.save_new(path)?;
                path.clone()
            }
            None => {
                let path = store.secrets_path(&m.source_id);
                bundle.save(&path)?;
                path
            }
        })
    };
    let published = opts
        .call(Stage::BeforePublish)
        .and_then(|()| store.publish_manifest(m));
    if let Err(e) = published {
        if let (Some(written), true) = (&secrets, opts.secret_bundle.is_some()) {
            let _ = std::fs::remove_file(written);
        }
        return Err(e);
    }
    Ok(secrets)
}

/// Capture a directory that is not a repository: the same manifest, without
/// Git.
pub fn capture_directory(
    ctx: &ExecContext,
    dir: &Path,
    opts: &CaptureOptions,
) -> Result<SourceSnapshot> {
    check_secret_opts(opts)?;
    if opts.secret_root.is_some() && !opts.secret_files.is_empty() {
        bail!("secret_root is for the capture of a repository; a directory capture takes its secret files from the directory itself");
    }
    let store = store_of(ctx, opts)?;
    let root = std::fs::canonicalize(dir)?;
    let o = build_opts(opts)?;
    let mut warnings = vec![];
    let attempts = opts.max_attempts.max(1);
    let mut last = String::new();
    for attempt in 1..=attempts {
        let attempt_res = (|| -> Result<(Meta, Read, Vec<LfsRef>)> {
            let meta = select_directory(&root, &o, &mut warnings)?;
            let read = read_all(&store, &root, &root, &meta, &BTreeSet::new())?;
            opts.call(Stage::AfterRead(attempt))?;
            let mut again_warnings = vec![];
            let again = select_directory(&root, &o, &mut again_warnings)?;
            if again != meta {
                return Err(unstable(meta.diff(&again)));
            }
            Ok((meta, read, vec![]))
        })();
        match attempt_res {
            Ok((_meta, read, lfs)) => {
                let entries = read.entries;
                let (secret_files, bundle_files) =
                    secret_entries(opts, read.secrets, &[], &[], &mut warnings)?;
                let m = seal_manifest(SourceManifest {
                    schema_version: SCHEMA_VERSION,
                    source_id: String::new(),
                    manifest_digest: String::new(),
                    repository_id: None,
                    source_kind: SourceKind::Directory,
                    original_head: None,
                    index_tree: None,
                    worktree_tree: None,
                    execution_commit: None,
                    base: None,
                    merge_base: None,
                    branch: None,
                    cwd_relative: RelPath(vec![]),
                    object_manifest: ObjectManifest {
                        tree_digest: tree_digest(&entries),
                        entries,
                        git_tips: vec![],
                    },
                    submodules: vec![],
                    lfs,
                    canonical: CanonicalConfig::default(),
                    secret_files,
                });
                let secrets = publish(&store, opts, &m, bundle_files)?;
                warnings.sort();
                warnings.dedup();
                return Ok(SourceSnapshot {
                    manifest: m,
                    secrets,
                    warnings,
                });
            }
            Err(e) => match e.downcast_ref::<Unstable>() {
                Some(u) => last = u.0.clone(),
                None => return Err(e),
            },
        }
    }
    Err(SourceError::Busy { attempts, last }.into())
}

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

    fn err_of(root: &Path, p: &str) -> SourceError {
        let p = RelPath::new(p);
        // the stat as a selection that followed the path would have taken it
        let st = std::fs::metadata(root.join(p.to_path()))
            .ok()
            .map(|m| Stat::of(&m));
        let e = read_secret(root, &p, &st, &mut 0).unwrap_err();
        e.downcast_ref::<SourceError>()
            .unwrap_or_else(|| panic!("{e:#}"))
            .clone()
    }

    #[test]
    fn a_regular_file_below_the_root_is_read() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("conf/deep")).unwrap();
        std::fs::write(root.join("conf/deep/a.key"), "k1\n").unwrap();
        let p = RelPath::new("conf/deep/a.key");
        let got = read_secret(root, &p, &lstat(root, &p), &mut 0).unwrap();
        assert_eq!(got, Some((0o600, b"k1\n".to_vec())));
        // gone when it was listed: nothing, and `required` decides
        assert_eq!(
            read_secret(root, &RelPath::new("conf/none"), &None, &mut 0).unwrap(),
            None
        );
    }

    #[test]
    fn a_directory_above_the_file_that_is_a_symlink_is_not_gone_through() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("root");
        let outside = tmp.path().join("outside");
        std::fs::create_dir_all(outside.join("deep")).unwrap();
        std::fs::create_dir_all(root.join("real")).unwrap();
        std::fs::write(outside.join("a.key"), "out\n").unwrap();
        std::fs::write(outside.join("deep/b.key"), "out\n").unwrap();
        std::os::unix::fs::symlink(&outside, root.join("conf")).unwrap();
        std::os::unix::fs::symlink(outside.join("deep"), root.join("real/deep")).unwrap();
        assert_eq!(
            err_of(&root, "conf/a.key"),
            SourceError::UnsafePath {
                path: "conf/a.key".into(),
                why: "conf is not a directory (a symlink or a file)".into()
            }
        );
        // not only the first component
        assert_eq!(
            err_of(&root, "real/deep/b.key"),
            SourceError::UnsafePath {
                path: "real/deep/b.key".into(),
                why: "real/deep is not a directory (a symlink or a file)".into()
            }
        );
    }

    #[test]
    fn a_path_that_leaves_the_root_or_is_not_a_file_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("root");
        std::fs::create_dir_all(root.join("d")).unwrap();
        std::fs::write(tmp.path().join("up.key"), "out\n").unwrap();
        std::os::unix::fs::symlink("../up.key", root.join("l.key")).unwrap();
        assert!(matches!(
            err_of(&root, "../up.key"),
            SourceError::UnsafePath { .. }
        ));
        assert_eq!(
            err_of(&root, "l.key"),
            SourceError::UnsupportedFileType {
                path: "l.key".into(),
                kind: "non-regular secret file".into()
            }
        );
        assert!(matches!(
            err_of(&root, "d"),
            SourceError::UnsupportedFileType { .. }
        ));
    }

    #[test]
    fn a_file_that_is_not_the_one_that_was_listed_is_a_change() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("a.key"), "one\n").unwrap();
        let p = RelPath::new("a.key");
        let st = lstat(root, &p);
        std::fs::write(root.join("b.key"), "two\n").unwrap();
        std::fs::rename(root.join("b.key"), root.join("a.key")).unwrap();
        let e = read_secret(root, &p, &st, &mut 0).unwrap_err();
        assert!(e.downcast_ref::<Unstable>().is_some(), "{e:#}");
    }

    fn sized(root: &Path, name: &str, len: u64) -> RelPath {
        let f = std::fs::File::create(root.join(name)).unwrap();
        f.set_len(len).unwrap();
        RelPath::new(name)
    }

    #[test]
    fn a_file_above_the_limit_is_refused_and_one_at_the_limit_is_read() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let at = sized(root, "at.key", MAX_SECRET_FILE_BYTES);
        let over = sized(root, "over.key", MAX_SECRET_FILE_BYTES + 1);
        let mut total = 0;
        let got = read_secret(root, &at, &lstat(root, &at), &mut total).unwrap();
        assert_eq!(got.unwrap().1.len() as u64, MAX_SECRET_FILE_BYTES);
        assert_eq!(total, MAX_SECRET_FILE_BYTES);
        let e = read_secret(root, &over, &lstat(root, &over), &mut total).unwrap_err();
        assert_eq!(
            e.downcast_ref::<SourceError>(),
            Some(&SourceError::SecretTooLarge {
                path: "over.key".into(),
                size: MAX_SECRET_FILE_BYTES + 1,
                limit: MAX_SECRET_FILE_BYTES
            })
        );
        // nothing of it was counted
        assert_eq!(total, MAX_SECRET_FILE_BYTES);
    }

    #[test]
    fn the_files_of_one_capture_are_refused_when_they_pass_the_total() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let big = sized(root, "big.key", MAX_SECRET_FILE_BYTES);
        let one = sized(root, "one.key", 1);
        let st = lstat(root, &big);
        let mut total = 0;
        for _ in 0..MAX_SECRET_TOTAL_BYTES / MAX_SECRET_FILE_BYTES {
            read_secret(root, &big, &st, &mut total).unwrap().unwrap();
        }
        // exactly the limit is still fine; one byte more is not
        assert_eq!(total, MAX_SECRET_TOTAL_BYTES);
        let e = read_secret(root, &one, &lstat(root, &one), &mut total).unwrap_err();
        assert_eq!(
            e.downcast_ref::<SourceError>(),
            Some(&SourceError::SecretTooLarge {
                path: "one.key".into(),
                size: MAX_SECRET_TOTAL_BYTES + 1,
                limit: MAX_SECRET_TOTAL_BYTES
            })
        );
        assert_eq!(total, MAX_SECRET_TOTAL_BYTES);
    }

    #[test]
    fn a_file_that_grew_after_it_was_listed_is_a_change_and_is_not_read_whole() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("a.key"), "one\n").unwrap();
        let p = RelPath::new("a.key");
        let st = lstat(root, &p);
        // appended in place: the same file, more bytes
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(root.join("a.key"))
            .unwrap();
        f.write_all(&vec![b'x'; 4 * MAX_SECRET_FILE_BYTES as usize])
            .unwrap();
        drop(f);
        let mut total = 0;
        let e = read_secret(root, &p, &st, &mut total).unwrap_err();
        assert!(e.downcast_ref::<Unstable>().is_some(), "{e:#}");
        assert_eq!(total, 0);
    }

    /// A reader that counts what is asked of it.
    struct Endless(u64);
    impl std::io::Read for Endless {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            self.0 += buf.len() as u64;
            buf.fill(7);
            Ok(buf.len())
        }
    }

    #[test]
    fn a_file_that_grows_while_it_is_read_is_cut_one_byte_past_its_size() {
        let p = RelPath::new("a.key");
        // it grows without end: one byte past the size is all that is taken
        let mut grows = Endless(0);
        let e = read_sized(&mut grows, 10, &p).unwrap_err();
        assert_eq!(
            e.downcast_ref::<Unstable>().map(|u| u.0.as_str()),
            Some("a.key changed while read")
        );
        assert_eq!(grows.0, 11);
        // shorter than listed is a change too
        let e = read_sized(&mut &b"12345"[..], 10, &p).unwrap_err();
        assert!(e.downcast_ref::<Unstable>().is_some(), "{e:#}");
        assert_eq!(read_sized(&mut &b"12345"[..], 5, &p).unwrap(), b"12345");
        assert_eq!(read_sized(&mut &b""[..], 0, &p).unwrap(), b"");
    }

    #[test]
    fn a_directory_that_is_swapped_for_a_symlink_after_the_listing_is_not_gone_through() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("root");
        let outside = tmp.path().join("outside");
        std::fs::create_dir_all(root.join("conf")).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        std::fs::write(root.join("conf/a.key"), "in\n").unwrap();
        std::fs::write(outside.join("a.key"), "out\n").unwrap();
        let p = RelPath::new("conf/a.key");
        let st = lstat(&root, &p);
        std::fs::rename(root.join("conf"), root.join("was")).unwrap();
        std::os::unix::fs::symlink(&outside, root.join("conf")).unwrap();
        let e = read_secret(&root, &p, &st, &mut 0).unwrap_err();
        assert!(
            matches!(
                e.downcast_ref::<SourceError>(),
                Some(SourceError::UnsafePath { .. })
            ),
            "{e:#}"
        );
        // a FIFO is refused by what was listed, without being opened
        let fifo = std::ffi::CString::new(root.join("was/p.key").as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
        let p = RelPath::new("was/p.key");
        let e = read_secret(&root, &p, &lstat(&root, &p), &mut 0).unwrap_err();
        assert!(
            matches!(
                e.downcast_ref::<SourceError>(),
                Some(SourceError::UnsupportedFileType { .. })
            ),
            "{e:#}"
        );
    }
}