sley-worktree 0.3.0

Native-Rust Git worktree operations for the sley engine: checkout, status, and index/tree reconciliation.
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
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
//! checkout/restore/reset materialization: branch/detached/path checkout, tree materialization, and the symlink-safe blob writer.
//!
//! Split out of `lib.rs` in the wave-47 mechanical refactor: a pure code move
//! (no function body changed); all items are re-exported from `lib.rs`.
use super::*;
use crate::attributes::*;
use crate::filter::*;
use crate::index::*;
use crate::index_io::*;
use crate::status::*;
use crate::types_admin::*;

pub fn deleted_index_entries(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
) -> Result<Vec<IndexEntry>> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Ok(Vec::new());
    }
    let index = Index::parse(&fs::read(index_path)?, format)?;
    let mut deleted = Vec::new();
    for entry in index.entries {
        if !worktree_path(worktree_root, entry.path.as_bytes())?.exists()
            && !index_entry_skip_worktree(&entry)
        {
            deleted.push(entry);
        }
    }
    Ok(deleted)
}

pub fn modified_index_entries(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
) -> Result<Vec<IndexEntry>> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Ok(Vec::new());
    }
    let mut index = Index::parse(&fs::read(&index_path)?, format)?;
    if index.entries.iter().any(IndexEntry::is_sparse_dir) {
        let db = FileObjectDatabase::from_git_dir(git_dir, format);
        expand_sparse_index(&mut index, &db, format)?;
    }
    // Reuse the same racy-git stat shortcut here: build the cache from the index
    // we just parsed (no second parse) so the worktree walk can skip re-hashing
    // unchanged files. A cached oid is only trusted on a non-racy stat match, so
    // genuinely modified files still fall through to a hash and are reported.
    let stat_cache = IndexStatCache::from_index(&index, &index_path);
    let mut modified = Vec::new();
    for entry in index.entries {
        let worktree_entry = worktree_entry_for_git_path(
            worktree_root,
            git_dir,
            format,
            entry.path.as_bytes(),
            &entry.oid,
            entry.mode,
            Some(&stat_cache),
        )?;
        let Some(worktree_entry) = worktree_entry else {
            if !index_entry_skip_worktree(&entry) {
                modified.push(entry);
            }
            continue;
        };
        if worktree_entry.mode != entry.mode || worktree_entry.oid != entry.oid {
            modified.push(entry);
        }
    }
    Ok(modified)
}

pub fn checkout_branch(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    branch: &str,
    committer: Vec<u8>,
) -> Result<CheckoutResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let branch_ref = branch_ref_name(branch)?;
    let refs = FileRefStore::new(git_dir, format);
    let target = match sley_refs::resolve_ref_peeled(&refs, &branch_ref)? {
        Some(oid) => oid,
        None => {
            checkout_switch_head_symbolic(&refs, branch_ref, committer, branch, None, None)?;
            return Ok(CheckoutResult {
                branch: branch.into(),
                oid: ObjectId::null(format),
                files: 0,
            });
        }
    };
    let current_head = resolve_head_commit_oid(git_dir, format)?;
    let files = if current_head == Some(target) {
        0
    } else {
        checkout_commit_to_index_and_worktree(worktree_root, git_dir, format, &target)?
    };
    checkout_switch_head_symbolic(
        &refs,
        branch_ref,
        committer,
        branch,
        Some(target),
        Some(target),
    )?;
    Ok(CheckoutResult {
        branch: branch.into(),
        oid: target,
        files,
    })
}

pub fn checkout_detached(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    target: &ObjectId,
    committer: Vec<u8>,
    message: Vec<u8>,
) -> Result<CheckoutResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let files = checkout_commit_to_index_and_worktree(worktree_root, git_dir, format, target)?;
    let refs = FileRefStore::new(git_dir, format);
    let zero = ObjectId::null(format);
    let mut tx = refs.transaction();
    tx.update(RefUpdate {
        name: "HEAD".into(),
        expected: None,
        new: RefTarget::Direct(*target),
        reflog: Some(ReflogEntry {
            old_oid: zero,
            new_oid: *target,
            committer,
            message,
        }),
    });
    tx.commit()?;
    Ok(CheckoutResult {
        branch: target.to_string(),
        oid: *target,
        files,
    })
}

/// Like [`checkout_branch`], but runs the smudge-side content filters
/// (`core.autocrlf`/`text`/`eol` EOL conversion and `filter.<name>.smudge`
/// drivers) on each blob as it is written to the worktree. `config` is the
/// repository config used to resolve the filters.
pub fn checkout_branch_filtered(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    branch: &str,
    committer: Vec<u8>,
    config: &GitConfig,
) -> Result<CheckoutResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let branch_ref = branch_ref_name(branch)?;
    let refs = FileRefStore::new(git_dir, format);
    let target = match sley_refs::resolve_ref_peeled(&refs, &branch_ref)? {
        Some(oid) => oid,
        None => {
            checkout_switch_head_symbolic(&refs, branch_ref, committer, branch, None, None)?;
            return Ok(CheckoutResult {
                branch: branch.into(),
                oid: ObjectId::null(format),
                files: 0,
            });
        }
    };
    let current_head = resolve_head_commit_oid(git_dir, format)?;
    let files = if current_head == Some(target) {
        0
    } else {
        checkout_commit_to_index_and_worktree_filtered(
            worktree_root,
            git_dir,
            format,
            &target,
            Some(config),
            Some(vec![
                ("ref".to_string(), branch_ref.clone()),
                ("treeish".to_string(), target.to_hex()),
            ]),
        )?
    };
    checkout_switch_head_symbolic(
        &refs,
        branch_ref,
        committer,
        branch,
        Some(target),
        Some(target),
    )?;
    Ok(CheckoutResult {
        branch: branch.into(),
        oid: target,
        files,
    })
}

/// Like [`checkout_detached`], but runs the smudge-side content filters (see
/// [`checkout_branch_filtered`]).
pub fn checkout_detached_filtered(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    target: &ObjectId,
    committer: Vec<u8>,
    message: Vec<u8>,
    config: &GitConfig,
) -> Result<CheckoutResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let files = checkout_commit_to_index_and_worktree_filtered(
        worktree_root,
        git_dir,
        format,
        target,
        Some(config),
        Some(vec![("treeish".to_string(), target.to_hex())]),
    )?;
    let refs = FileRefStore::new(git_dir, format);
    let zero = ObjectId::null(format);
    let mut tx = refs.transaction();
    tx.update(RefUpdate {
        name: "HEAD".into(),
        expected: None,
        new: RefTarget::Direct(*target),
        reflog: Some(ReflogEntry {
            old_oid: zero,
            new_oid: *target,
            committer,
            message,
        }),
    });
    tx.commit()?;
    Ok(CheckoutResult {
        branch: target.to_string(),
        oid: *target,
        files,
    })
}

pub(crate) fn checkout_commit_to_index_and_worktree(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    target: &ObjectId,
) -> Result<usize> {
    checkout_commit_to_index_and_worktree_filtered(
        worktree_root,
        git_dir,
        format,
        target,
        None,
        None,
    )
}

/// Like [`checkout_commit_to_index_and_worktree`] but optionally runs the
/// smudge-side content filters (see [`apply_smudge_filter`]) on each blob before
/// it is written to the worktree. Attribute lookups use the `.gitattributes`
/// recorded in the *target tree* so the rules of the checked-out commit apply.
pub(crate) fn checkout_commit_to_index_and_worktree_filtered(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    target: &ObjectId,
    smudge_config: Option<&GitConfig>,
    process_metadata: Option<Vec<(String, String)>>,
) -> Result<usize> {
    if let Some((sparse, mode)) = active_sparse_checkout(git_dir)? {
        return checkout_commit_to_index_and_worktree_sparse(
            worktree_root,
            git_dir,
            format,
            target,
            Some((&sparse, mode)),
            smudge_config,
            process_metadata,
        );
    }
    let _process_filter_metadata = set_process_filter_metadata(process_metadata);
    let mut dirty = false;
    if smudge_config.is_some() {
        dirty = !modified_index_entries(worktree_root, git_dir, format)?.is_empty();
    } else {
        stream_short_status(worktree_root, git_dir, format, |entry| {
            if !status_row_is_untracked_or_ignored(entry) {
                dirty = true;
                return Ok(StreamControl::Stop);
            }
            Ok(StreamControl::Continue)
        })?;
    }
    if dirty {
        return Err(GitError::Transaction(
            "checkout requires a clean working tree".into(),
        ));
    }
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let commit = read_commit(&db, format, target)?;
    let mut target_entries = BTreeMap::new();
    collect_tree_entries(&db, format, &commit.tree, &mut target_entries)?;
    refuse_if_current_working_directory_becomes_file(worktree_root, &target_entries)?;

    let attributes = smudge_config
        .map(|_| build_tree_attribute_matcher(worktree_root, &db, format, &commit.tree))
        .transpose()?;

    for path in read_index_entries(git_dir, format)?.keys() {
        if !target_entries.contains_key(path) {
            remove_worktree_file(worktree_root, path)?;
        }
    }

    let mut index_entries = Vec::new();
    for (path, entry) in &target_entries {
        // Single type-by-mode materializer: gitlinks become a directory (mkdir,
        // no blob read), symlinks (mode 120000) a real symlink to the raw blob
        // bytes, and regular files the smudge-filtered content. Inlining the blob
        // write here previously dropped the symlink arm and wrote the link target
        // as a regular file — the whole symlink-checkout class.
        index_entries.push(materialize_tree_entry_with_optional_smudge(
            &db,
            format,
            worktree_root,
            path,
            entry,
            smudge_config,
            attributes.as_ref(),
        )?);
    }
    index_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let extensions = preserved_index_extensions(git_dir, format)?;
    fs::write(
        repository_index_path(git_dir),
        Index {
            version: 2,
            entries: index_entries,
            extensions,
            checksum: None,
        }
        .write(format)?,
    )?;
    Ok(target_entries.len())
}

/// Build an [`AttributeMatcher`] from the `.gitattributes` files contained in a
/// tree, plus the repo-level (`core.attributesFile`, `.git/info/attributes`)
/// sources, mirroring [`standard_attributes_for_path_from_tree`].
pub(crate) fn build_tree_attribute_matcher(
    worktree_root: &Path,
    db: &FileObjectDatabase,
    format: ObjectFormat,
    tree_oid: &ObjectId,
) -> Result<AttributeMatcher> {
    let mut matcher = AttributeMatcher::default();
    let git_dir = worktree_root.join(".git");
    matcher.configure_case_sensitivity(&git_dir);
    if !matcher.read_configured_attributes(worktree_root, &git_dir) {
        matcher.read_default_global_attributes();
    }
    collect_attribute_patterns_from_tree(db, format, tree_oid, Vec::new(), &mut matcher)?;
    read_attribute_patterns(
        worktree_root.join(".git").join("info").join("attributes"),
        &mut matcher,
        &[],
        b".git/info/attributes",
        false,
    );
    Ok(matcher)
}

pub(crate) fn materialize_tree_entry_with_optional_smudge(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    worktree_root: &Path,
    path: &[u8],
    entry: &TrackedEntry,
    smudge_config: Option<&GitConfig>,
    attributes: Option<&AttributeMatcher>,
) -> Result<IndexEntry> {
    // A symlink (mode 120000) is written as a *symlink* whose target is the raw,
    // unfiltered blob bytes — git treats symlink content as an opaque path, so no
    // smudge/EOL filter ever applies. Route it through the type-aware
    // `materialize_tree_entry` (→ `write_worktree_blob_entry`) so it is never
    // materialized as a regular file holding the target string. A gitlink (mkdir,
    // no blob read) and the no-smudge case go through the same shared path.
    if smudge_config.is_none()
        || sley_index::is_gitlink(entry.mode)
        || (entry.mode & 0o170000) == 0o120000
    {
        return materialize_tree_entry(db, worktree_root, path, entry);
    }
    let config = smudge_config.expect("checked above");
    let matcher = attributes.expect("attributes are built when smudge_config is set");
    let object = read_expected_object(db, &entry.oid, ObjectType::Blob)?;
    let checks = matcher.attributes_for_path(path, &filter_attribute_names(), false);
    let body = apply_smudge_filter_with_attributes_cow_format(
        config,
        &checks,
        path,
        &object.body,
        format,
    )?;
    let file_path = worktree_path(worktree_root, path)?;
    prepare_blob_parent_dirs(worktree_root, &file_path)?;
    remove_existing_worktree_path(&file_path)?;
    fs::write(&file_path, &body)?;
    set_worktree_file_mode(&file_path, entry.mode)?;
    let metadata = fs::metadata(&file_path)?;
    let mut index_entry = index_entry_from_metadata(path.to_vec(), entry.oid, &metadata);
    index_entry.mode = entry.mode;
    Ok(index_entry)
}

/// Sparse- and skip-worktree-aware variant of
/// [`checkout_commit_to_index_and_worktree`].
///
/// When `sparse` is `None` this behaves like the plain checkout except that it
/// preserves any pre-existing skip-worktree bits (so an already-sparse worktree
/// is not silently re-expanded). When `sparse` is `Some`, every target path is
/// additionally classified against the patterns: in-cone paths are written and
/// have their skip-worktree bit cleared, while out-of-cone paths are left out
/// of the worktree, get their skip-worktree bit set, and have any stale file
/// removed.
pub(crate) fn checkout_commit_to_index_and_worktree_sparse(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    target: &ObjectId,
    sparse: Option<(&SparseCheckout, SparseCheckoutMode)>,
    smudge_config: Option<&GitConfig>,
    process_metadata: Option<Vec<(String, String)>>,
) -> Result<usize> {
    let _process_filter_metadata = set_process_filter_metadata(process_metadata);
    let previously_skipped = skip_worktree_paths(git_dir, format)?;
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let commit = read_commit(&db, format, target)?;
    let mut target_entries = BTreeMap::new();
    collect_tree_entries(&db, format, &commit.tree, &mut target_entries)?;

    // Honor skip-worktree: a path whose worktree file is intentionally absent
    // must not be treated as a dirty (deleted) change blocking the checkout.
    let mut dirty = false;
    stream_short_status(worktree_root, git_dir, format, |entry| {
        if previously_skipped.contains(entry.path) {
            return Ok(StreamControl::Continue);
        }
        // Submodule state never blocks a checkout: upstream unpack-trees
        // treats gitlinks as always up-to-date (ie_match_stat refuses to pay
        // for a submodule dirtiness probe), so new commits / dirty content in
        // a submodule must not fail the branch switch.
        if entry.index_mode.is_some_and(sley_index::is_gitlink)
            || entry.worktree_mode.is_some_and(sley_index::is_gitlink)
        {
            return Ok(StreamControl::Continue);
        }
        // An untracked embedded repository where the target tree records a
        // gitlink is reused as-is (upstream entry.c write_entry: mkdir with
        // EEXIST is success), so it does not block the checkout either.
        if entry.index == b'?' && entry.worktree == b'?' {
            let path = entry.path.strip_suffix(b"/").unwrap_or(entry.path);
            if target_entries
                .get(path)
                .is_some_and(|target| sley_index::is_gitlink(target.mode))
            {
                return Ok(StreamControl::Continue);
            }
        }
        dirty = true;
        Ok(StreamControl::Stop)
    })?;
    if dirty {
        return Err(GitError::Transaction(
            "checkout requires a clean working tree".into(),
        ));
    }

    let matcher = sparse.map(|(spec, mode)| SparseMatcher::new(spec, mode));
    let attributes = smudge_config
        .map(|_| build_tree_attribute_matcher(worktree_root, &db, format, &commit.tree))
        .transpose()?;

    for path in read_index_entries(git_dir, format)?.keys() {
        if target_entries.contains_key(path) {
            continue;
        }
        // Do not disturb the worktree state of an intentionally skipped path.
        if previously_skipped.contains(path) {
            continue;
        }
        remove_worktree_file(worktree_root, path)?;
    }

    let mut index_entries = Vec::new();
    for (path, entry) in &target_entries {
        let in_cone = matcher.as_ref().map_or_else(
            || !previously_skipped.contains(path),
            |matcher| matcher.includes_file(path),
        );
        let index_entry = if in_cone {
            materialize_tree_entry_with_optional_smudge(
                &db,
                format,
                worktree_root,
                path,
                entry,
                smudge_config,
                attributes.as_ref(),
            )?
        } else {
            // Out of cone: ensure no stale worktree file remains and synthesize
            // an index entry straight from the tree (no worktree metadata),
            // then mark it skip-worktree.
            remove_worktree_file(worktree_root, path)?;
            let mut index_entry = restored_head_index_entry(worktree_root, &db, path, entry)?;
            set_skip_worktree(&mut index_entry);
            index_entry
        };
        index_entries.push(index_entry);
    }
    index_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let mut index = Index {
        version: 2,
        entries: index_entries,
        extensions: preserved_index_extensions(git_dir, format)?,
        checksum: None,
    };
    normalize_index_version_for_extended_flags(&mut index);
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(target_entries.len())
}

pub(crate) fn skip_worktree_paths(
    git_dir: &Path,
    format: ObjectFormat,
) -> Result<BTreeSet<Vec<u8>>> {
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Ok(BTreeSet::new());
    }
    let index = Index::parse(&fs::read(index_path)?, format)?;
    Ok(index
        .entries
        .into_iter()
        .filter(index_entry_skip_worktree)
        .map(|entry| entry.path.into_bytes())
        .collect())
}

pub fn restore_worktree_paths(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    restore_worktree_paths_inner(
        worktree_root.as_ref(),
        git_dir.as_ref(),
        format,
        paths,
        None,
    )
}

/// Like [`restore_worktree_paths`], applying the smudge-side content filters
/// (CRLF / ident / filter drivers) the way a checkout writes blobs.
pub fn restore_worktree_paths_filtered(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
    config: &GitConfig,
) -> Result<RestoreResult> {
    restore_worktree_paths_inner(
        worktree_root.as_ref(),
        git_dir.as_ref(),
        format,
        paths,
        Some(config),
    )
}

pub(crate) fn restore_worktree_paths_inner(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    paths: &[PathBuf],
    smudge_config: Option<&GitConfig>,
) -> Result<RestoreResult> {
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Err(GitError::Exit(1));
    }
    let mut index = Index::parse(&fs::read(&index_path)?, format)?;
    let stat_cache = IndexStatCache::from_index(&index, &index_path);
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let mut restored = BTreeSet::new();
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let absolute = normalize_absolute_path_lexically(&absolute);
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_has_entry_under(&index.entries, &git_path);
        let mut matched = false;
        let matched_positions = index
            .entries
            .iter()
            .enumerate()
            .filter_map(|(position, entry)| {
                (entry.path.as_bytes() == git_path.as_slice()
                    || (recursive && index_entry_is_under_path(entry.path.as_bytes(), &git_path)))
                .then_some(position)
            })
            .collect::<Vec<_>>();
        for position in matched_positions {
            let refreshed = restore_index_entry(
                worktree_root,
                git_dir,
                format,
                &db,
                &index.entries[position],
                smudge_config,
                Some(&stat_cache),
            )?;
            restored.insert(index.entries[position].path.clone());
            matched = true;
            if let Some(refreshed) = refreshed {
                index.entries[position] = refreshed;
            }
        }
        if !matched {
            eprintln!(
                "error: pathspec '{}' did not match any file(s) known to git",
                path.display()
            );
            return Err(GitError::Exit(1));
        }
    }
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(RestoreResult {
        restored: restored.len(),
    })
}

pub fn checkout_index_paths(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
    options: CheckoutIndexPathOptions<'_>,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Err(GitError::Exit(1));
    }
    let mut index = Index::parse(&fs::read(&index_path)?, format)?;
    if options.merge {
        checkout_unmerge_resolve_undo_paths(worktree_root, &mut index, format, paths)?;
    }
    let stat_cache = IndexStatCache::from_index(&index, &index_path);
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let selected = checkout_selected_index_paths(worktree_root, &index, paths)?;

    if options.stage.is_none() && !options.merge && !options.force {
        for path in &selected {
            if checkout_path_is_unmerged(&index, path) {
                eprintln!(
                    "error: path '{}' is unmerged",
                    String::from_utf8_lossy(path)
                );
                return Err(GitError::Exit(1));
            }
        }
    }

    let mut refreshed = BTreeMap::new();
    let mut restored = BTreeSet::new();
    for path in selected {
        let positions = index
            .entries
            .iter()
            .enumerate()
            .filter_map(|(position, entry)| (entry.path.as_bytes() == path).then_some(position))
            .collect::<Vec<_>>();
        let stage0 = positions
            .iter()
            .copied()
            .find(|position| index.entries[*position].stage() == Stage::Normal);
        let is_unmerged = positions
            .iter()
            .any(|position| index.entries[*position].stage() != Stage::Normal);

        if is_unmerged {
            if let Some(stage) = options.stage {
                let wanted = match stage {
                    CheckoutStage::Ours => Stage::Ours,
                    CheckoutStage::Theirs => Stage::Theirs,
                };
                let Some(position) = positions
                    .iter()
                    .copied()
                    .find(|position| index.entries[*position].stage() == wanted)
                else {
                    eprintln!(
                        "error: path '{}' does not have {} version",
                        String::from_utf8_lossy(&path),
                        match stage {
                            CheckoutStage::Ours => "our",
                            CheckoutStage::Theirs => "their",
                        }
                    );
                    return Err(GitError::Exit(1));
                };
                checkout_write_index_entry_to_worktree(
                    worktree_root,
                    git_dir,
                    format,
                    &db,
                    &index.entries[position],
                    options.smudge_config,
                    Some(&stat_cache),
                )?;
                restored.insert(path);
                continue;
            }
            if options.merge {
                checkout_merge_unmerged_path(
                    worktree_root,
                    &db,
                    &index,
                    &positions,
                    options.conflict_style,
                )?;
                restored.insert(path);
                continue;
            }
            if options.force {
                continue;
            }
        }

        if let Some(position) = stage0 {
            if let Some(updated) = checkout_write_index_entry_to_worktree(
                worktree_root,
                git_dir,
                format,
                &db,
                &index.entries[position],
                options.smudge_config,
                Some(&stat_cache),
            )? {
                refreshed.insert(position, updated);
            }
            restored.insert(path);
        }
    }

    for (position, entry) in refreshed {
        index.entries[position] = entry;
    }
    if !index.entries.is_empty() {
        write_repository_index_ref(git_dir, format, &index)?;
    }
    Ok(RestoreResult {
        restored: restored.len(),
    })
}

pub fn unresolve_index_paths(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
) -> Result<()> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    if !index_path.exists() {
        return Ok(());
    }
    let mut index = Index::parse(&fs::read(&index_path)?, format)?;
    checkout_unmerge_resolve_undo_paths(worktree_root, &mut index, format, paths)?;
    write_repository_index_ref(git_dir, format, &index)
}

pub(crate) fn checkout_selected_index_paths(
    worktree_root: &Path,
    index: &Index,
    paths: &[PathBuf],
) -> Result<BTreeSet<Vec<u8>>> {
    let index_paths = index
        .entries
        .iter()
        .map(|entry| entry.path.as_bytes().to_vec())
        .collect::<BTreeSet<_>>();
    let mut selected = BTreeSet::new();
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let absolute = normalize_absolute_path_lexically(&absolute);
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_paths
                .iter()
                .any(|entry| index_entry_is_under_path(entry, &git_path));
        let matched = index_paths
            .iter()
            .filter(|entry| {
                entry.as_slice() == git_path.as_slice()
                    || (recursive && index_entry_is_under_path(entry, &git_path))
            })
            .cloned()
            .collect::<Vec<_>>();
        if matched.is_empty() {
            eprintln!(
                "error: pathspec '{}' did not match any file(s) known to git",
                path.display()
            );
            return Err(GitError::Exit(1));
        }
        selected.extend(matched);
    }
    Ok(selected)
}

pub(crate) fn checkout_unmerge_resolve_undo_paths(
    worktree_root: &Path,
    index: &mut Index,
    format: ObjectFormat,
    paths: &[PathBuf],
) -> Result<()> {
    let records = parse_resolve_undo_records(index.extension(b"REUC")?, format)?;
    if records.is_empty() {
        return Ok(());
    }
    let mut remaining = Vec::new();
    let mut unmerged_any = false;
    for record in records {
        if checkout_pathspecs_match_git_path(worktree_root, paths, &record.path)? {
            remove_index_entries_with_path(&mut index.entries, &record.path);
            for (idx, stage) in record.stages.into_iter().enumerate() {
                let Some((mode, oid)) = stage else {
                    continue;
                };
                index.entries.push(resolve_undo_index_entry(
                    record.path.clone(),
                    mode,
                    oid,
                    (idx + 1) as u16,
                ));
            }
            unmerged_any = true;
        } else {
            remaining.push(record);
        }
    }
    if unmerged_any {
        index.entries.sort_by(compare_index_key);
        normalize_index_version_for_extended_flags(index);
        set_resolve_undo_extension(index, &remaining)?;
    }
    Ok(())
}

pub(crate) fn checkout_pathspecs_match_git_path(
    worktree_root: &Path,
    paths: &[PathBuf],
    candidate: &[u8],
) -> Result<bool> {
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_entry_is_under_path(candidate, &git_path);
        if candidate == git_path.as_slice()
            || (recursive && index_entry_is_under_path(candidate, &git_path))
        {
            return Ok(true);
        }
    }
    Ok(false)
}

pub(crate) fn resolve_undo_index_entry(
    path: Vec<u8>,
    mode: u32,
    oid: ObjectId,
    stage: u16,
) -> IndexEntry {
    let name_len = (path
        .len()
        .min(sley_index::INDEX_FLAG_NAME_LENGTH_MASK as usize)) as u16;
    IndexEntry {
        ctime_seconds: 0,
        ctime_nanoseconds: 0,
        mtime_seconds: 0,
        mtime_nanoseconds: 0,
        dev: 0,
        ino: 0,
        mode,
        uid: 0,
        gid: 0,
        size: 0,
        oid,
        flags: name_len | (stage << 12),
        flags_extended: 0,
        path: path.into(),
    }
}

pub(crate) fn checkout_path_is_unmerged(index: &Index, path: &[u8]) -> bool {
    index
        .entries
        .iter()
        .any(|entry| entry.path.as_bytes() == path && entry.stage() != Stage::Normal)
}

pub(crate) fn checkout_write_index_entry_to_worktree(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    db: &FileObjectDatabase,
    entry: &IndexEntry,
    smudge_config: Option<&GitConfig>,
    stat_cache: Option<&IndexStatCache>,
) -> Result<Option<IndexEntry>> {
    restore_index_entry(
        worktree_root,
        git_dir,
        format,
        db,
        entry,
        smudge_config,
        stat_cache,
    )
}

pub(crate) fn checkout_merge_unmerged_path(
    worktree_root: &Path,
    db: &FileObjectDatabase,
    index: &Index,
    positions: &[usize],
    style: CheckoutConflictStyle,
) -> Result<()> {
    let mut base = None;
    let mut ours = None;
    let mut theirs = None;
    for position in positions {
        let entry = &index.entries[*position];
        match entry.stage() {
            Stage::Base => base = Some(entry),
            Stage::Ours => ours = Some(entry),
            Stage::Theirs => theirs = Some(entry),
            Stage::Normal => {}
        }
    }
    let Some(ours) = ours else {
        return Ok(());
    };
    let Some(theirs) = theirs else {
        return Ok(());
    };
    let base_body = match base {
        Some(entry) => read_expected_object(db, &entry.oid, ObjectType::Blob)?
            .body
            .clone(),
        None => Vec::new(),
    };
    let ours_body = read_expected_object(db, &ours.oid, ObjectType::Blob)?
        .body
        .clone();
    let theirs_body = read_expected_object(db, &theirs.oid, ObjectType::Blob)?
        .body
        .clone();
    let result = sley_diff_merge::merge_blobs(
        &base_body,
        &ours_body,
        &theirs_body,
        &sley_diff_merge::MergeBlobOptions {
            ours_label: "ours",
            theirs_label: "theirs",
            base_label: "base",
            style: match style {
                CheckoutConflictStyle::Merge => sley_diff_merge::ConflictStyle::Merge,
                CheckoutConflictStyle::Diff3 => sley_diff_merge::ConflictStyle::Diff3,
            },
            favor: sley_diff_merge::MergeFavor::None,
            ws_ignore: sley_diff_merge::WsIgnore::EMPTY,
        },
    );
    let file_path = worktree_path(worktree_root, ours.path.as_bytes())?;
    prepare_blob_parent_dirs(worktree_root, &file_path)?;
    remove_existing_worktree_path(&file_path)?;
    fs::write(&file_path, result.content)?;
    set_worktree_file_mode(&file_path, ours.mode)?;
    Ok(())
}

pub fn restore_index_paths_from_head(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let head_entries = head_tree_entries(git_dir, format, &db)?;
    restore_index_paths_from_entries(
        worktree_root,
        git_dir,
        format,
        &db,
        index,
        &head_entries,
        paths,
        false,
    )
}

pub fn restore_index_paths_from_tree(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    tree_oid: &ObjectId,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let source_entries = tree_entries(&db, format, tree_oid)?;
    restore_index_paths_from_entries(
        worktree_root,
        git_dir,
        format,
        &db,
        index,
        &source_entries,
        paths,
        false,
    )
}

pub fn restore_index_paths_from_tree_allow_unmatched(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    tree_oid: &ObjectId,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let source_entries = tree_entries(&db, format, tree_oid)?;
    restore_index_paths_from_entries(
        worktree_root,
        git_dir,
        format,
        &db,
        index,
        &source_entries,
        paths,
        true,
    )
}

pub(crate) fn restore_index_paths_from_entries(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    db: &FileObjectDatabase,
    mut index: Index,
    source_entries: &BTreeMap<Vec<u8>, TrackedEntry>,
    paths: &[PathBuf],
    allow_unmatched: bool,
) -> Result<RestoreResult> {
    let sparse = active_sparse_checkout(git_dir)?;
    if index.is_sparse() {
        expand_sparse_index(&mut index, db, format)?;
    }
    let index_version = index.version;
    let extensions = index_extensions_without_cache_tree(&index.extensions);
    let mut index_entries = index
        .entries
        .into_iter()
        .map(|entry| (entry.path.as_bytes().to_vec(), entry))
        .collect::<BTreeMap<_, _>>();
    let prior_skip_worktree = index_entries
        .iter()
        .filter(|(_, entry)| entry.is_skip_worktree())
        .map(|(path, _)| path.clone())
        .collect::<BTreeSet<_>>();
    let mut restored = BTreeSet::new();
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_entries
                .keys()
                .any(|entry| index_entry_is_under_path(entry, &git_path))
            || source_entries
                .keys()
                .any(|entry| index_entry_is_under_path(entry, &git_path));
        let mut matched_paths = BTreeSet::new();
        for path in index_entries.keys().chain(source_entries.keys()) {
            if path.as_slice() == git_path.as_slice()
                || (recursive && index_entry_is_under_path(path, &git_path))
            {
                matched_paths.insert(path.clone());
            }
        }
        if matched_paths.is_empty() {
            if allow_unmatched {
                continue;
            }
            eprintln!(
                "error: pathspec '{}' did not match any file(s) known to git",
                path.display()
            );
            return Err(GitError::Exit(1));
        }
        for path in matched_paths {
            if let Some(entry) = source_entries.get(&path) {
                // git's pathspec reset (`reset_index` → diff against the source
                // tree) only rewrites entries that actually CHANGE: an entry whose
                // oid and mode already equal the source is left untouched, so its
                // cached stat is preserved and `git diff-files` stays clean (t7102
                // "resetting an unmodified path is a no-op"). Only when the entry
                // genuinely changes does git write a fresh, stat-zeroed entry.
                let unchanged = index_entries.get(&path).is_some_and(|existing| {
                    existing.oid == entry.oid
                        && existing.mode == entry.mode
                        && !existing.is_intent_to_add()
                });
                if !unchanged {
                    let mut restored = restored_head_index_entry(worktree_root, db, &path, entry)?;
                    if prior_skip_worktree.contains(&path) {
                        restored.set_skip_worktree(true);
                    }
                    index_entries.insert(path.clone(), restored);
                }
            } else {
                index_entries.remove(&path);
            }
            restored.insert(path);
        }
    }
    let mut entries = index_entries.into_values().collect::<Vec<_>>();
    entries.sort_by(|left, right| left.path.cmp(&right.path));
    let restored_paths = restored.iter().cloned().collect::<Vec<_>>();
    let mut index = Index {
        version: index_version,
        entries,
        extensions,
        checksum: None,
    };
    invalidate_untracked_cache_for_git_paths(&mut index, format, &restored_paths)?;
    if let Some((sparse, mode)) = sparse
        && sparse.sparse_index
    {
        let matcher = SparseMatcher::new(&sparse, mode);
        collapse_to_sparse_index(&mut index, &matcher, db, format)?;
    }
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(RestoreResult {
        restored: restored.len(),
    })
}

pub fn restore_index_and_worktree_paths_from_head(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
    overlay: bool,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let head_entries = head_tree_entries(git_dir, format, &db)?;
    restore_index_and_worktree_paths_from_entries(
        worktree_root,
        git_dir,
        format,
        &db,
        index,
        &head_entries,
        paths,
        overlay,
    )
}

pub fn restore_index_and_worktree_paths_from_tree(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    tree_oid: &ObjectId,
    paths: &[PathBuf],
    overlay: bool,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let source_entries = tree_entries(&db, format, tree_oid)?;
    restore_index_and_worktree_paths_from_entries(
        worktree_root,
        git_dir,
        format,
        &db,
        index,
        &source_entries,
        paths,
        overlay,
    )
}

pub(crate) fn restore_index_and_worktree_paths_from_entries(
    worktree_root: &Path,
    git_dir: &Path,
    format: ObjectFormat,
    db: &FileObjectDatabase,
    index: Index,
    source_entries: &BTreeMap<Vec<u8>, TrackedEntry>,
    paths: &[PathBuf],
    overlay: bool,
) -> Result<RestoreResult> {
    let index_version = index.version;
    let extensions = index_extensions_without_cache_tree(&index.extensions);
    let mut index_entries = index
        .entries
        .into_iter()
        .map(|entry| (entry.path.as_bytes().to_vec(), entry))
        .collect::<BTreeMap<_, _>>();
    let mut restored = BTreeSet::new();
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_entries
                .keys()
                .any(|entry| index_entry_is_under_path(entry, &git_path))
            || source_entries
                .keys()
                .any(|entry| index_entry_is_under_path(entry, &git_path));
        let mut matched_paths = BTreeSet::new();
        for path in index_entries.keys().chain(source_entries.keys()) {
            if path.as_slice() == git_path.as_slice()
                || (recursive && index_entry_is_under_path(path, &git_path))
            {
                matched_paths.insert(path.clone());
            }
        }
        if matched_paths.is_empty() {
            eprintln!(
                "error: pathspec '{}' did not match any file(s) known to git",
                path.display()
            );
            return Err(GitError::Exit(1));
        }
        for path in matched_paths {
            if let Some(entry) = source_entries.get(&path) {
                index_entries.insert(
                    path.clone(),
                    restore_head_entry_to_worktree_and_index(worktree_root, db, &path, entry)?,
                );
            } else if overlay {
                // Overlay mode (git checkout default): a path that matches the
                // pathspec but is absent from the source tree is left untouched
                // in both the index and the working tree.
                continue;
            } else {
                // No-overlay mode (git restore default, checkout --no-overlay):
                // drop the path from the index and the working tree.
                index_entries.remove(&path);
                remove_worktree_file(worktree_root, &path)?;
            }
            restored.insert(path);
        }
    }
    let mut entries = index_entries.into_values().collect::<Vec<_>>();
    entries.sort_by(|left, right| left.path.cmp(&right.path));
    let restored_paths = restored.iter().cloned().collect::<Vec<_>>();
    let mut index = Index {
        version: index_version,
        entries,
        extensions,
        checksum: None,
    };
    invalidate_untracked_cache_for_git_paths(&mut index, format, &restored_paths)?;
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(RestoreResult {
        restored: restored.len(),
    })
}

pub fn reset_index_and_worktree_to_commit(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    commit_oid: &ObjectId,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let commit = read_commit(&db, format, commit_oid)?;
    let mut target_entries = BTreeMap::new();
    collect_tree_entries(&db, format, &commit.tree, &mut target_entries)?;
    refuse_if_current_working_directory_becomes_file(worktree_root, &target_entries)?;
    let config = sley_config::read_repo_config(git_dir, None).unwrap_or_default();
    let attributes = build_tree_attribute_matcher(worktree_root, &db, format, &commit.tree)?;

    // git's `reset --hard` runs a one-way merge through unpack-trees: EVERY path
    // present in the current index (at ANY stage) that the target tree does not
    // track is removed from the worktree. A conflicted D/F merge can leave a
    // path like `dir~HEAD` at stage 2 only — those entries are dropped by the
    // stage-0-only `read_index_entries`, so iterate the RAW index paths here
    // (deduped across stages) to match git and delete the moved-aside file.
    for path in current_index_paths(git_dir, format, &db)? {
        if !target_entries.contains_key(&path) {
            remove_worktree_file(worktree_root, &path)?;
        }
    }

    let mut index_entries = Vec::new();
    for (path, entry) in &target_entries {
        index_entries.push(materialize_tree_entry_filtered(
            &db,
            format,
            worktree_root,
            path,
            entry,
            &config,
            &attributes,
        )?);
    }
    index_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let extensions = preserved_index_extensions(git_dir, format)?;
    fs::write(
        repository_index_path(git_dir),
        Index {
            version: 2,
            entries: index_entries,
            extensions,
            checksum: None,
        }
        .write(format)?,
    )?;
    Ok(RestoreResult {
        restored: target_entries.len(),
    })
}

/// All paths the current index references, deduped across stages (a conflicted
/// path appears at stages 1–3; we want it listed once). Unlike
/// `read_index_entries`, which filters to stage 0, this keeps conflicted paths
/// so a `reset --hard` worktree sweep removes moved-aside files (`dir~HEAD`) the
/// target tree doesn't track — matching git's one-way unpack-trees behavior.
pub(crate) fn current_index_paths(
    git_dir: &Path,
    format: ObjectFormat,
    db: &FileObjectDatabase,
) -> Result<BTreeSet<Vec<u8>>> {
    let (index, _stat_cache, _head_matches) = read_index_with_stat_cache(git_dir, format, db)?;
    Ok(index
        .entries
        .into_iter()
        .map(|entry| entry.path.into_bytes())
        .collect())
}

/// Write one target tree entry into the worktree and return its index entry —
/// the shared materialization step for every checkout/reset worktree rebuild.
///
/// Gitlinks (mode 160000) never touch the object database: their oid names a
/// commit in the *submodule's* repository, not an object here. Upstream
/// (entry.c `write_entry` S_IFGITLINK) just mkdirs the path — an
/// already-populated submodule is left untouched (EEXIST is success) — and
/// records the oid in the index with a zeroed stat so status re-evaluates the
/// gitlink against the embedded repository's HEAD.
pub(crate) fn materialize_tree_entry(
    db: &FileObjectDatabase,
    worktree_root: &Path,
    path: &[u8],
    entry: &TrackedEntry,
) -> Result<IndexEntry> {
    if sley_index::is_gitlink(entry.mode) {
        let dir_path = worktree_path(worktree_root, path)?;
        materialize_gitlink_dir(worktree_root, &dir_path)?;
        return Ok(IndexEntry {
            ctime_seconds: 0,
            ctime_nanoseconds: 0,
            mtime_seconds: 0,
            mtime_nanoseconds: 0,
            dev: 0,
            ino: 0,
            mode: entry.mode,
            uid: 0,
            gid: 0,
            size: 0,
            oid: entry.oid,
            flags: path.len().min(0x0fff) as u16,
            flags_extended: 0,
            path: BString::from(path),
        });
    }
    let file_path = write_worktree_blob_entry(db, worktree_root, path, entry)?;
    let metadata = fs::symlink_metadata(&file_path)?;
    let mut index_entry = index_entry_from_metadata(path.to_vec(), entry.oid, &metadata);
    index_entry.mode = entry.mode;
    Ok(index_entry)
}

pub(crate) fn materialize_gitlink_dir(worktree_root: &Path, dir_path: &Path) -> Result<()> {
    prepare_blob_parent_dirs(worktree_root, dir_path)?;
    if fs::symlink_metadata(dir_path).is_ok_and(|metadata| !metadata.is_dir()) {
        remove_existing_worktree_path(dir_path)?;
    }
    fs::create_dir_all(dir_path)?;
    Ok(())
}

pub(crate) fn materialize_tree_entry_filtered(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    worktree_root: &Path,
    path: &[u8],
    entry: &TrackedEntry,
    config: &GitConfig,
    attributes: &AttributeMatcher,
) -> Result<IndexEntry> {
    if sley_index::is_gitlink(entry.mode) || (entry.mode & 0o170000) == 0o120000 {
        return materialize_tree_entry(db, worktree_root, path, entry);
    }
    let object = read_expected_object(db, &entry.oid, ObjectType::Blob)?;
    let checks = attributes.attributes_for_path(path, &filter_attribute_names(), false);
    let body = apply_smudge_filter_with_attributes_cow_format(
        config,
        &checks,
        path,
        &object.body,
        format,
    )?;
    let file_path = worktree_path(worktree_root, path)?;
    prepare_blob_parent_dirs(worktree_root, &file_path)?;
    remove_existing_worktree_path(&file_path)?;
    fs::write(&file_path, &body)?;
    set_worktree_file_mode(&file_path, entry.mode)?;
    let metadata = fs::symlink_metadata(&file_path)?;
    let mut index_entry = index_entry_from_metadata(path.to_vec(), entry.oid, &metadata);
    index_entry.mode = entry.mode;
    Ok(index_entry)
}

/// Materialize a blob (or symlink) tree entry into the worktree at `path`,
/// returning the absolute path written. Shared by every checkout/reset worktree
/// rebuild so the type-change handling is identical everywhere.
///
/// Mirrors git's entry.c `write_entry`: it unlinks whatever currently occupies
/// the path before creating the new object, so a type transition (regular file ⇄
/// symlink, or a stale symlink/directory in the way) is overwritten rather than
/// left in place or failing with EEXIST. A plain `fs::write` follows an existing
/// symlink and would write *through* it (leaving the link), so the unlink is
/// load-bearing for the symlink-stash / reset-hard type-change cases.
pub(crate) fn write_worktree_blob_entry(
    db: &FileObjectDatabase,
    worktree_root: &Path,
    path: &[u8],
    entry: &TrackedEntry,
) -> Result<PathBuf> {
    let object = read_expected_object(db, &entry.oid, ObjectType::Blob)?;
    let file_path = worktree_path(worktree_root, path)?;
    // Clear any non-directory blocking an ancestor component (prior tree had
    // `dir` as a FILE, target wants `dir/<child>`), creating the parent dirs.
    prepare_blob_parent_dirs(worktree_root, &file_path)?;
    // Clear whatever sits at the leaf — including a directory where the target
    // wants a plain file (reverse D/F) — before writing.
    remove_existing_worktree_path(&file_path)?;
    write_blob_body_or_symlink(&file_path, entry.mode, &object.body, &object.body)?;
    Ok(file_path)
}

/// Write the materialized worktree object at `file_path` as the right *type* for
/// `mode` — git's `entry.c` `write_entry` type-by-mode switch, factored into a
/// single primitive so no checkout/reset/restore materializer can silently write
/// a symlink blob as a regular file (the symlink-checkout bug class).
///
/// The caller is responsible for the pre-write steps (leading directories +
/// removing any blocker at the leaf). Type by `mode`:
/// * `0o120000` (symlink) → a real symlink whose target is `link_target`, the
///   **raw** blob bytes. git treats symlink content as an opaque path, so the
///   smudge/EOL filter never applies — pass the unfiltered blob here even when
///   `body` is the smudged content for the regular-file arm.
/// * everything else → a regular file holding `body`, with the user-execute bit
///   set iff `mode` has it (`set_worktree_file_mode`).
///
/// Exposed crate-publicly so out-of-crate worktree materializers (e.g.
/// `sley-cli`'s `stash -u` untracked-tree restore) route through the same
/// type-by-mode primitive instead of re-deriving an `fs::write` that drops the
/// symlink arm.
pub fn write_blob_body_or_symlink(
    file_path: &Path,
    mode: u32,
    body: &[u8],
    link_target: &[u8],
) -> Result<()> {
    if (mode & 0o170000) == 0o120000 {
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStringExt;
            let target =
                std::path::PathBuf::from(std::ffi::OsString::from_vec(link_target.to_vec()));
            std::os::unix::fs::symlink(&target, file_path)?;
        }
        #[cfg(not(unix))]
        {
            let _ = link_target;
            fs::write(file_path, body)?;
        }
    } else {
        fs::write(file_path, body)?;
        set_worktree_file_mode(file_path, mode)?;
    }
    Ok(())
}

/// Create the ancestor directories of a worktree blob path, removing any
/// regular file or symlink that occupies an ancestor *component* first.
///
/// Mirrors git's `entry.c` `create_directories`: it walks each path component
/// between `worktree_root` and the leaf and, for each, if a non-directory (a
/// regular file or symlink left by a prior tree where `dir` was a FILE) blocks
/// it, unlinks the blocker before `mkdir`. A plain `fs::create_dir_all` fails
/// with `ENOTDIR`/`EEXIST` on such a D/F transition; this is the directory-side
/// of git's force-checkout D/F clearing.
///
/// `worktree_root` itself is never touched. Only components strictly between the
/// root and the leaf are cleared, matching `create_directories`' `base_dir_len`
/// boundary.
pub(crate) fn prepare_blob_parent_dirs(worktree_root: &Path, file_path: &Path) -> Result<()> {
    let parent = match file_path.parent() {
        Some(parent) => parent,
        None => return Ok(()),
    };
    // Fast path: parent already a directory (the overwhelmingly common case).
    if parent.is_dir() {
        return Ok(());
    }
    // Collect the ancestor chain from worktree_root (exclusive) down to `parent`
    // (inclusive). We can't `create_dir_all` blindly because a non-directory may
    // sit on one of these components; walk them and clear blockers as git does.
    let mut components: Vec<&Path> = Vec::new();
    let mut cursor = Some(parent);
    while let Some(dir) = cursor {
        if dir == worktree_root {
            break;
        }
        components.push(dir);
        cursor = dir.parent();
        if cursor.is_none() {
            break;
        }
    }
    // Walk root → leaf so each parent exists before its child.
    for dir in components.iter().rev() {
        match fs::symlink_metadata(dir) {
            Ok(metadata) if metadata.is_dir() => {}
            Ok(_) => {
                // A regular file or symlink occupies this component (the prior
                // tree had `dir` as a FILE). Unlink it, then create the dir.
                fs::remove_file(dir)?;
                fs::create_dir(dir)?;
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                fs::create_dir(dir)?;
            }
            Err(err) => return Err(err.into()),
        }
    }
    Ok(())
}

/// Remove whatever currently occupies a worktree path before writing a new
/// object there — a symlink (even a dangling one, which `Path::exists` misses),
/// a regular file, or a directory subtree. Uses `symlink_metadata` (lstat) so a
/// symlink is removed as the link, never followed.
pub(crate) fn remove_existing_worktree_path(file_path: &Path) -> Result<()> {
    let metadata = match fs::symlink_metadata(file_path) {
        Ok(metadata) => metadata,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(err) => return Err(err.into()),
    };
    if metadata.is_dir() {
        if path_is_original_cwd(file_path) {
            return refuse_remove_current_working_directory(file_path);
        }
        // A directory in the way of a file (D/F transition) or a populated
        // gitlink: remove the subtree so the file can be created.
        match fs::remove_dir_all(file_path) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(err.into()),
        }
    } else {
        fs::remove_file(file_path)?;
    }
    Ok(())
}

/// chmod a freshly-materialized worktree blob to match its tree/index entry mode.
///
/// `fs::write` truncates an existing file *in place*, preserving its prior
/// permission bits. For a mode-only diff (identical oid, 100644 vs 100755) that
/// leaves the wrong exec bit on disk — which is exactly the `reset --hard` /
/// checkout bug this guards against. git's checkout path unlinks+recreates the
/// file precisely to "get the new one with the right permissions" (entry.c
/// `write_entry`); we instead chmod the just-written file.
///
/// Mirrors the observable result of git's `create_file` (entry.c):
/// `(mode & 0100) ? 0777 : 0666` masked by the standard umask (0022), i.e. 0755
/// for an executable entry and 0644 otherwise. Only regular-file entries (100644
/// / 100755) are chmod'd; gitlinks and symlinks have no meaningful exec bit.
///
/// We set the perms directly (rather than relying on a fresh `open(2)` to apply
/// the umask) because `fs::write` truncates an existing file in place, leaving its
/// old permission bits — the very thing that breaks a mode-only checkout/reset.
/// Matching git's default-umask output keeps the worktree byte-for-byte aligned
/// with the oracle, which is what the parity suite asserts.
#[cfg(unix)]
pub(crate) fn set_worktree_file_mode(file_path: &Path, entry_mode: u32) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let perms = match entry_mode {
        0o100755 => 0o755,
        0o100644 => 0o644,
        _ => return Ok(()),
    };
    fs::set_permissions(file_path, fs::Permissions::from_mode(perms))?;
    Ok(())
}

#[cfg(not(unix))]
pub(crate) fn set_worktree_file_mode(_file_path: &Path, _entry_mode: u32) -> Result<()> {
    Ok(())
}

/// Materialize a tree object into the index and worktree.
pub fn checkout_tree_to_index_and_worktree(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    tree_oid: &ObjectId,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let mut target_entries = BTreeMap::new();
    collect_tree_entries(&db, format, tree_oid, &mut target_entries)?;

    for path in read_index_entries(git_dir, format)?.keys() {
        if !target_entries.contains_key(path) {
            remove_worktree_file(worktree_root, path)?;
        }
    }

    let mut index_entries = Vec::new();
    for (path, entry) in &target_entries {
        index_entries.push(materialize_tree_entry(&db, worktree_root, path, entry)?);
    }
    index_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let extensions = preserved_index_extensions(git_dir, format)?;
    fs::write(
        repository_index_path(git_dir),
        Index {
            version: 2,
            entries: index_entries,
            extensions,
            checksum: None,
        }
        .write(format)?,
    )?;
    Ok(RestoreResult {
        restored: target_entries.len(),
    })
}

pub fn reset_index_to_commit(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    commit_oid: &ObjectId,
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let commit = read_commit(&db, format, commit_oid)?;
    let mut target_entries = BTreeMap::new();
    collect_tree_entries(&db, format, &commit.tree, &mut target_entries)?;
    // git's `reset --mixed` preserves the skip-worktree bit on entries that survive
    // the reset (t7102 "--mixed preserves skip-worktree"): carry it forward from the
    // pre-reset index keyed by path, so reconstructed entries keep CE_SKIP_WORKTREE.
    let index_path = repository_index_path(git_dir);
    let prior_skip_worktree: BTreeSet<Vec<u8>> = match fs::read(&index_path) {
        Ok(bytes) => Index::parse(&bytes, format)?
            .entries
            .iter()
            .filter(|entry| entry.is_skip_worktree())
            .map(|entry| entry.path.as_bytes().to_vec())
            .collect(),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => BTreeSet::new(),
        Err(err) => return Err(err.into()),
    };
    let mut index_entries = Vec::new();
    for (path, entry) in &target_entries {
        let mut restored = restored_head_index_entry(worktree_root, &db, path, entry)?;
        if prior_skip_worktree.contains(path) {
            restored.set_skip_worktree(true);
        }
        index_entries.push(restored);
    }
    index_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let mut index = Index {
        version: 2,
        entries: index_entries,
        extensions: preserved_index_extensions(git_dir, format)?,
        checksum: None,
    };
    index.upgrade_version_for_flags();
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(RestoreResult {
        restored: target_entries.len(),
    })
}

/// Build a fresh in-memory index that mirrors the tree `tree_oid`, the way
/// `git read-tree <tree>` does: every blob, symlink, and gitlink leaf (found by
/// recursing subtrees) becomes a stage-0 entry carrying the tree mode and oid,
/// with a fully zeroed stat (so nothing is treated as stat-clean) and size 0.
/// Entries are sorted by path; the index is version 2 with no extensions.
///
/// This does not touch the worktree or write anything to disk — serialize the
/// result with [`Index::write`] (and persist it) when you want to replace
/// `.git/index`.
pub fn index_from_tree(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    tree_oid: &ObjectId,
) -> Result<Index> {
    let mut entries: Vec<IndexEntry> = Vec::new();
    if *tree_oid != ObjectId::empty_tree(format) {
        let mut tree_entries = BTreeMap::new();
        collect_tree_entries(db, format, tree_oid, &mut tree_entries)?;
        entries.reserve(tree_entries.len());
        for (path, entry) in tree_entries {
            let name_len = (path.len().min(0x0fff)) as u16;
            entries.push(IndexEntry {
                ctime_seconds: 0,
                ctime_nanoseconds: 0,
                mtime_seconds: 0,
                mtime_nanoseconds: 0,
                dev: 0,
                ino: 0,
                mode: entry.mode,
                uid: 0,
                gid: 0,
                size: 0,
                oid: entry.oid,
                flags: name_len,
                flags_extended: 0,
                path: path.into(),
            });
        }
    }
    // git orders index entries by path bytes; BTreeMap already yields that, but
    // sort explicitly so the contract holds regardless of how entries arrive.
    entries.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(Index {
        version: 2,
        entries,
        extensions: Vec::new(),
        checksum: None,
    })
}

/// Enforces a [`SparseCheckout`] against the current index and worktree.
///
/// Every stage-0 index entry is classified with the sparse patterns (see
/// [`SparseCheckoutMode`] for the matching semantics):
///
/// * **In cone**: the skip-worktree bit is cleared and, if the worktree file is
///   missing, it is re-materialized from the entry's blob in the object
///   database. Existing worktree files are left untouched so local content is
///   preserved.
/// * **Out of cone**: the skip-worktree bit is set and any existing worktree
///   file is removed (empty parent directories are pruned).
///
/// Returns `true` when `path` is inside the sparse-checkout described by
/// `sparse` under the given matching `mode`. This is the engine behind
/// `git sparse-checkout check-rules`: a path is "in" the sparse-checkout when
/// the compiled matcher would keep its worktree file. Cone and full (gitignore)
/// grammars are both handled, exactly as the apply engine interprets them, so
/// `check-rules` and `set`/`reapply` agree by construction.
pub fn path_in_sparse_checkout(
    path: &[u8],
    sparse: &SparseCheckout,
    mode: SparseCheckoutMode,
) -> bool {
    SparseMatcher::new(sparse, mode).includes_file(path)
}

pub(crate) fn active_sparse_checkout(
    git_dir: &Path,
) -> Result<Option<(SparseCheckout, SparseCheckoutMode)>> {
    let worktree_config = GitConfig::read(git_dir.join("config.worktree")).unwrap_or_default();
    let repo_config = GitConfig::read(git_dir.join("config")).unwrap_or_default();
    let sparse_enabled = worktree_config
        .get_bool("core", None, "sparseCheckout")
        .or_else(|| repo_config.get_bool("core", None, "sparseCheckout"))
        .unwrap_or(false);
    if !sparse_enabled {
        return Ok(None);
    }
    let sparse_file = git_dir.join("info").join("sparse-checkout");
    if !sparse_file.exists() {
        return Ok(None);
    }
    let cone = worktree_config
        .get_bool("core", None, "sparseCheckoutCone")
        .or_else(|| repo_config.get_bool("core", None, "sparseCheckoutCone"))
        .unwrap_or(false);
    let sparse_index = cone
        && worktree_config
            .get_bool("index", None, "sparse")
            .or_else(|| repo_config.get_bool("index", None, "sparse"))
            .unwrap_or(false);
    let bytes = fs::read(sparse_file)?;
    let mut patterns = bytes
        .split(|byte| *byte == b'\n')
        .map(<[u8]>::to_vec)
        .collect::<Vec<_>>();
    if patterns.last().map(Vec::is_empty) == Some(true) {
        patterns.pop();
    }
    let mode = if cone {
        SparseCheckoutMode::Cone
    } else {
        SparseCheckoutMode::Full
    };
    Ok(Some((
        SparseCheckout {
            patterns,
            sparse_index,
        },
        mode,
    )))
}

/// Conflicted entries (stage != 0) are never given the skip-worktree bit and
/// are left alone, matching upstream Git. The index is rewritten in place.
pub fn apply_sparse_checkout(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    sparse: &SparseCheckout,
) -> Result<ApplySparseResult> {
    apply_sparse_checkout_with_mode(
        worktree_root,
        git_dir,
        format,
        sparse,
        SparseCheckoutMode::Auto,
    )
}

/// Like [`apply_sparse_checkout`] but lets the caller force the pattern
/// interpretation instead of auto-detecting it.
pub fn apply_sparse_checkout_with_mode(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    sparse: &SparseCheckout,
    mode: SparseCheckoutMode,
) -> Result<ApplySparseResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let mut index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        return Ok(ApplySparseResult {
            materialized: Vec::new(),
            skipped: Vec::new(),
            not_up_to_date: Vec::new(),
        });
    };
    let matcher = SparseMatcher::new(sparse, mode);
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    // Expand any collapsed sparse-directory entries to a full index before we
    // reconcile per-path: the apply loop reasons about individual blob paths, so
    // it must never see a sparse-dir entry. (Re-collapse happens at the end when
    // a sparse index is requested.)
    if index.entries.iter().any(IndexEntry::is_sparse_dir) {
        expand_sparse_index(&mut index, &db, format)?;
    }
    let mut materialized = Vec::new();
    let mut skipped = Vec::new();
    let mut not_up_to_date = Vec::new();
    for entry in &mut index.entries {
        // Never touch conflicted entries.
        if index_entry_stage(entry) != 0 {
            continue;
        }
        if matcher.includes_file(entry.path.as_bytes()) {
            clear_skip_worktree(entry);
            let file_path = worktree_path(worktree_root, entry.path.as_bytes())?;
            if !file_path.exists() {
                materialize_index_entry_file(&db, worktree_root, &file_path, entry)?;
                let metadata = fs::symlink_metadata(&file_path)?;
                *entry = index_entry_with_refreshed_stat(entry, &metadata);
            }
            materialized.push(entry.path.as_bytes().to_vec());
        } else {
            // The path is out of cone, so its worktree file should be removed and
            // the entry marked skip-worktree. But git refuses to delete a file
            // that is *not up to date* with the index (e.g. one that reappeared in
            // the worktree after the path was already sparse): it leaves the file,
            // leaves the skip-worktree bit clear, and reports the path in its "not
            // up to date" warning. Mirror that to avoid silent data loss.
            let file_path = worktree_path(worktree_root, entry.path.as_bytes())?;
            match fs::symlink_metadata(&file_path) {
                Ok(metadata) if !worktree_entry_is_uptodate(entry, &metadata) => {
                    clear_skip_worktree(entry);
                    not_up_to_date.push(entry.path.as_bytes().to_vec());
                }
                _ => {
                    set_skip_worktree(entry);
                    remove_worktree_file(worktree_root, entry.path.as_bytes())?;
                    skipped.push(entry.path.as_bytes().to_vec());
                }
            }
        }
    }
    not_up_to_date.sort();
    normalize_index_version_for_extended_flags(&mut index);
    // When a sparse index was requested (cone mode + index.sparse), collapse the
    // fully-out-of-cone directories into single sparse-directory entries and
    // mark the index with the `sdir` extension. Otherwise ensure the index is
    // written full (and any prior `sdir` marker is cleared).
    if sparse.sparse_index {
        collapse_to_sparse_index(&mut index, &matcher, &db, format)?;
    } else {
        index.clear_sparse_extension()?;
    }
    write_repository_index_ref(git_dir, format, &index)?;
    Ok(ApplySparseResult {
        materialized,
        skipped,
        not_up_to_date,
    })
}

/// Expands every sparse-directory entry in `index` back into the full set of
/// blob (and nested-directory) entries it collapses, reading each directory's
/// tree from `db`. After this the index contains no sparse-directory entries and
/// carries no `sdir` marker — it is a full index that any per-path command can
/// operate on without sparse-index awareness.
///
/// This is the **close-the-class** primitive: a command never needs to special-
/// case a sparse index, because the moment it loads the index it expands to the
/// full form. The collapsed shape is purely an on-disk storage optimization.
pub fn expand_sparse_index(
    index: &mut Index,
    db: &FileObjectDatabase,
    format: ObjectFormat,
) -> Result<bool> {
    if !index.entries.iter().any(IndexEntry::is_sparse_dir) {
        // Still strip a stray `sdir` marker so the written index is recorded full.
        let had_marker = index.is_sparse();
        index.clear_sparse_extension()?;
        if had_marker {
            sley_core::trace2::region("index", "ensure_full_index");
        }
        return Ok(had_marker);
    }
    let mut expanded: Vec<IndexEntry> = Vec::with_capacity(index.entries.len());
    for entry in std::mem::take(&mut index.entries) {
        if !entry.is_sparse_dir() {
            expanded.push(entry);
            continue;
        }
        // The sparse-dir path ends in `/`; its OID is the directory's tree.
        let dir = entry.path.as_bytes();
        let dir_prefix = dir; // includes the trailing slash
        for (rel, (mode, oid)) in sley_diff_merge::flatten_tree(db, format, &entry.oid)? {
            let mut full_path = dir_prefix.to_vec();
            full_path.extend_from_slice(&rel);
            let mut blob = blank_sparse_blob_entry(format, &full_path, mode, oid);
            // Re-collapsed entries are skip-worktree (they live outside the cone).
            blob.set_skip_worktree(true);
            expanded.push(blob);
        }
    }
    expanded.sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));
    index.entries = expanded;
    index.clear_sparse_extension()?;
    normalize_index_version_for_extended_flags(index);
    sley_core::trace2::region("index", "ensure_full_index");
    Ok(true)
}

pub(crate) fn index_sparse_dir_contains_path(index: &Index, git_path: &[u8]) -> bool {
    index.entries.iter().any(|entry| {
        entry.is_sparse_dir()
            && git_path.starts_with(entry.path.as_bytes())
            && git_path.len() > entry.path.len()
    })
}

/// Builds a minimal index entry for an expanded sparse blob: zeroed stat fields
/// (the file is not in the worktree), the given mode/oid, and a fresh name
/// length. Stat fields are zero because a skip-worktree file has no on-disk
/// presence to record.
pub(crate) fn blank_sparse_blob_entry(
    format: ObjectFormat,
    path: &[u8],
    mode: u32,
    oid: ObjectId,
) -> IndexEntry {
    let _ = format;
    let mut entry = IndexEntry {
        ctime_seconds: 0,
        ctime_nanoseconds: 0,
        mtime_seconds: 0,
        mtime_nanoseconds: 0,
        dev: 0,
        ino: 0,
        mode,
        uid: 0,
        gid: 0,
        size: 0,
        oid,
        flags: 0,
        flags_extended: 0,
        path: path.into(),
    };
    entry.refresh_name_length();
    entry
}

/// Collapses fully-out-of-cone directories in `index` into single sparse-
/// directory entries (mode `040000`, skip-worktree, the directory tree's OID),
/// then marks the index with the `sdir` extension. A directory is collapsible
/// when *every* entry under it is skip-worktree and stage 0 — i.e. nothing in it
/// is in the cone or conflicted. The shallowest such directory subsumes deeper
/// ones, matching git's `convert_to_sparse` cache-tree walk.
pub(crate) fn collapse_to_sparse_index(
    index: &mut Index,
    matcher: &SparseMatcher,
    db: &FileObjectDatabase,
    format: ObjectFormat,
) -> Result<()> {
    // First expand any pre-existing sparse-dir entries so the collapse decision
    // sees a uniform full index (idempotent re-collapse).
    if index.entries.iter().any(IndexEntry::is_sparse_dir) {
        expand_sparse_index(index, db, format)?;
    }

    // Any unmerged (stage != 0) entry forbids a sparse index entirely (the cache
    // tree cannot be built), so stay full — matching git's bail.
    if index.entries.iter().any(|e| index_entry_stage(e) != 0) {
        index.clear_sparse_extension()?;
        return Ok(());
    }

    index
        .entries
        .sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));

    // Determine, for every directory prefix, whether it contains any in-cone
    // path. A directory with no in-cone descendant is collapsible.
    use std::collections::BTreeMap;
    let mut dir_has_in_cone: BTreeMap<Vec<u8>, bool> = BTreeMap::new();
    for entry in &index.entries {
        let path = entry.path.as_bytes();
        let in_cone = matcher.includes_file(path);
        let mut start = 0usize;
        while let Some(rel) = path
            .get(start..)
            .and_then(|s| s.iter().position(|b| *b == b'/'))
        {
            let end = start + rel;
            let dir = path[..end].to_vec();
            let flag = dir_has_in_cone.entry(dir).or_insert(false);
            *flag = *flag || in_cone;
            start = end + 1;
        }
    }

    // The collapsible directories are those with no in-cone descendant; keep only
    // the shallowest (a directory whose ancestor is also collapsible is subsumed).
    let collapsible: Vec<Vec<u8>> = {
        let all: Vec<Vec<u8>> = dir_has_in_cone
            .iter()
            .filter(|(_, has)| !**has)
            .map(|(dir, _)| dir.clone())
            .collect();
        all.iter()
            .filter(|dir| {
                !all.iter().any(|other| {
                    other != *dir
                        && dir
                            .strip_prefix(other.as_slice())
                            .is_some_and(|rest| rest.first() == Some(&b'/'))
                })
            })
            .cloned()
            .collect()
    };
    if collapsible.is_empty() {
        index.clear_sparse_extension()?;
        return Ok(());
    }

    let mut checker = db.presence_checker();
    let mut new_entries: Vec<IndexEntry> = Vec::with_capacity(index.entries.len());
    let mut consumed: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
    for dir in &collapsible {
        // Gather the entries that live strictly under this directory.
        let mut subtree: Vec<&IndexEntry> = index
            .entries
            .iter()
            .filter(|e| {
                e.path
                    .as_bytes()
                    .strip_prefix(dir.as_slice())
                    .is_some_and(|rest| rest.first() == Some(&b'/'))
            })
            .collect();
        if subtree.is_empty() {
            continue;
        }
        subtree.sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));
        // Build the subtree object and capture its OID.
        let mut prefix = dir.clone();
        prefix.push(b'/');
        let tree_entries: Vec<WriteTreeEntry<'_>> = subtree
            .iter()
            .map(|e| WriteTreeEntry {
                path: e.path.as_bytes(),
                mode: e.mode,
                oid: e.oid.clone(),
            })
            .collect();
        let tree_oid =
            write_tree_entries_stream(&tree_entries, &prefix, None, db, &mut checker, false)?;
        // Mark every consumed path so the second pass drops them.
        for e in &subtree {
            consumed.insert(e.path.as_bytes().to_vec());
        }
        // The sparse-dir entry's name is the directory path WITH a trailing slash.
        let mut sparse_path = dir.clone();
        sparse_path.push(b'/');
        let mut sparse_entry =
            blank_sparse_blob_entry(format, &sparse_path, SPARSE_DIR_MODE, tree_oid);
        sparse_entry.set_skip_worktree(true);
        new_entries.push(sparse_entry);
    }
    // Carry forward every entry that was not collapsed.
    for entry in &index.entries {
        if consumed.contains(entry.path.as_bytes()) {
            continue;
        }
        new_entries.push(entry.clone());
    }
    new_entries.sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));
    index.entries = new_entries;
    index.set_sparse_extension();
    normalize_index_version_for_extended_flags(index);
    sley_core::trace2::region("index", "convert_to_sparse");
    Ok(())
}

/// Whether the worktree file described by `metadata` is up to date with `entry`'s
/// cached index stat, using the size + mtime heuristic at the core of git's
/// `ie_match_stat`. A freshly-checked-out (clean) file matches; a file that was
/// deleted and later recreated — as happens when an out-of-cone path reappears in
/// the worktree — gets a fresh mtime and so reads as modified, which is exactly
/// the state git declines to overwrite during a sparse update.
pub(crate) fn worktree_entry_is_uptodate(entry: &IndexEntry, metadata: &fs::Metadata) -> bool {
    if u64::from(entry.size) != metadata.len() {
        return false;
    }
    let Some((mtime_seconds, mtime_nanoseconds)) = file_mtime_parts(metadata) else {
        // Without a usable mtime we cannot prove the file is clean; treat it as
        // not up to date so a present file is never silently discarded.
        return false;
    };
    u64::from(entry.mtime_seconds) == mtime_seconds
        && u64::from(entry.mtime_nanoseconds) == mtime_nanoseconds
}

pub(crate) fn worktree_entry_ref_is_uptodate(
    entry: &IndexEntryRef<'_>,
    metadata: &fs::Metadata,
) -> bool {
    if u64::from(entry.size) != metadata.len() {
        return false;
    }
    let Some((mtime_seconds, mtime_nanoseconds)) = file_mtime_parts(metadata) else {
        return false;
    };
    u64::from(entry.mtime_seconds) == mtime_seconds
        && u64::from(entry.mtime_nanoseconds) == mtime_nanoseconds
}

/// The file's modification time split into whole seconds and the sub-second
/// nanosecond remainder, matching how git stores `mtime` in the index.
pub(crate) fn file_mtime_parts(metadata: &fs::Metadata) -> Option<(u64, u64)> {
    let modified = metadata.modified().ok()?;
    let duration = modified.duration_since(UNIX_EPOCH).ok()?;
    Some((duration.as_secs(), u64::from(duration.subsec_nanos())))
}

/// Write a git metadata file through a sibling `.lock` file and atomic rename.
///
/// This helper is intended for small repository/worktree metadata files such as
/// `HEAD`, `config.worktree`, or state files under `.git/`. It deliberately does
/// not try to replace object or pack writers, which have their own durability
/// and naming rules.
pub fn write_metadata_file_atomic(
    path: impl AsRef<Path>,
    bytes: &[u8],
    options: AtomicMetadataWriteOptions,
) -> Result<AtomicMetadataWriteResult> {
    let path = path.as_ref();
    let parent = path.parent().ok_or_else(|| {
        GitError::InvalidPath(format!("metadata path has no parent: {}", path.display()))
    })?;
    if !parent.as_os_str().is_empty() {
        fs::create_dir_all(parent)?;
    }
    let lock_path = metadata_lock_path(path)?;
    let mut lock = match fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&lock_path)
    {
        Ok(lock) => lock,
        Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(GitError::Transaction(format!(
                "metadata lock already exists: {}",
                lock_path.display()
            )));
        }
        Err(err) => return Err(err.into()),
    };
    if let Err(err) = lock.write_all(bytes) {
        let _ = fs::remove_file(&lock_path);
        return Err(err.into());
    }
    if options.fsync_file
        && let Err(err) = lock.sync_all()
    {
        let _ = fs::remove_file(&lock_path);
        return Err(err.into());
    }
    drop(lock);
    if let Err(err) = fs::rename(&lock_path, path) {
        let _ = fs::remove_file(&lock_path);
        return Err(err.into());
    }
    if options.fsync_dir
        && let Ok(dir) = fs::File::open(parent)
    {
        dir.sync_all()?;
    }
    let metadata = fs::metadata(path)?;
    Ok(AtomicMetadataWriteResult {
        path: path.to_path_buf(),
        len: metadata.len(),
        mtime: file_mtime_parts(&metadata),
    })
}

pub(crate) fn metadata_lock_path(path: &Path) -> Result<PathBuf> {
    let file_name = path.file_name().ok_or_else(|| {
        GitError::InvalidPath(format!("metadata path has no filename: {}", path.display()))
    })?;
    let mut lock_name = file_name.to_os_string();
    lock_name.push(".lock");
    Ok(path.with_file_name(lock_name))
}

/// Checks out `target` like [`checkout_detached`], but materializes the
/// worktree through the supplied [`SparseCheckout`]: out-of-cone paths are not
/// written, get their skip-worktree bit set, and have any stale worktree file
/// removed. Existing public checkout entry points are unchanged; this is an
/// additive sparse-aware variant.
///
/// The pattern interpretation is auto-detected ([`SparseCheckoutMode::Auto`]);
/// to reconcile an existing checkout under an explicit mode use
/// [`apply_sparse_checkout_with_mode`].
pub fn checkout_detached_sparse(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    target: &ObjectId,
    committer: Vec<u8>,
    message: Vec<u8>,
    sparse: &SparseCheckout,
) -> Result<CheckoutResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let files = checkout_commit_to_index_and_worktree_sparse(
        worktree_root,
        git_dir,
        format,
        target,
        Some((sparse, SparseCheckoutMode::Auto)),
        None,
        None,
    )?;
    let refs = FileRefStore::new(git_dir, format);
    let zero = ObjectId::null(format);
    let mut tx = refs.transaction();
    tx.update(RefUpdate {
        name: "HEAD".into(),
        expected: None,
        new: RefTarget::Direct(*target),
        reflog: Some(ReflogEntry {
            old_oid: zero,
            new_oid: *target,
            committer,
            message,
        }),
    });
    tx.commit()?;
    Ok(CheckoutResult {
        branch: target.to_string(),
        oid: *target,
        files,
    })
}

pub(crate) fn materialize_index_entry_file(
    db: &FileObjectDatabase,
    worktree_root: &Path,
    file_path: &Path,
    entry: &IndexEntry,
) -> Result<()> {
    // A gitlink (mode 160000) has no blob in this object store and materializes
    // as a directory (git's `write_entry` S_IFGITLINK arm: mkdir, never read an
    // object). Single gitlink rule via `sley_index::is_gitlink`; without it a
    // sparse re-materialization of a submodule path would fail with "not found:
    // blob object <commit-oid>".
    if sley_index::is_gitlink(entry.mode) {
        materialize_gitlink_dir(worktree_root, file_path)?;
        return Ok(());
    }
    let object = read_expected_object(db, &entry.oid, ObjectType::Blob)?;
    prepare_blob_parent_dirs(worktree_root, file_path)?;
    remove_existing_worktree_path(file_path)?;
    write_blob_body_or_symlink(file_path, entry.mode, &object.body, &object.body)?;
    Ok(())
}

pub(crate) fn set_skip_worktree(entry: &mut IndexEntry) {
    entry.flags |= INDEX_FLAG_EXTENDED;
    entry.flags_extended |= INDEX_EXTENDED_FLAG_SKIP_WORKTREE;
}

pub(crate) fn clear_skip_worktree(entry: &mut IndexEntry) {
    entry.flags_extended &= !INDEX_EXTENDED_FLAG_SKIP_WORKTREE;
    if entry.flags_extended == 0 {
        entry.flags &= !INDEX_FLAG_EXTENDED;
    }
}

pub fn restore_worktree_paths_from_head(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let head_entries = head_tree_entries(git_dir, format, &db)?;
    restore_worktree_paths_from_entries(worktree_root, &db, index, &head_entries, paths)
}

pub fn restore_worktree_paths_from_tree(
    worktree_root: impl AsRef<Path>,
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
    tree_oid: &ObjectId,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let worktree_root = worktree_root.as_ref();
    let git_dir = git_dir.as_ref();
    let index_path = repository_index_path(git_dir);
    let index = if index_path.exists() {
        Index::parse(&fs::read(&index_path)?, format)?
    } else {
        Index {
            version: 2,
            entries: Vec::new(),
            extensions: Vec::new(),
            checksum: None,
        }
    };
    let db = FileObjectDatabase::from_git_dir(git_dir, format);
    let source_entries = tree_entries(&db, format, tree_oid)?;
    restore_worktree_paths_from_entries(worktree_root, &db, index, &source_entries, paths)
}

pub(crate) fn restore_worktree_paths_from_entries(
    worktree_root: &Path,
    db: &FileObjectDatabase,
    index: Index,
    source_entries: &BTreeMap<Vec<u8>, TrackedEntry>,
    paths: &[PathBuf],
) -> Result<RestoreResult> {
    let index_entries = index
        .entries
        .into_iter()
        .map(|entry| entry.path.into_bytes())
        .collect::<BTreeSet<_>>();
    let mut restored = BTreeSet::new();
    for path in paths {
        let absolute = if path.is_absolute() {
            path.clone()
        } else {
            worktree_root.join(path)
        };
        let relative = absolute.strip_prefix(worktree_root).map_err(|_| {
            GitError::InvalidPath(format!("path {} is outside worktree", path.display()))
        })?;
        let git_path = git_path_bytes(relative)?;
        let recursive = path == Path::new(".")
            || path.to_string_lossy().ends_with('/')
            || absolute.is_dir()
            || index_entries
                .iter()
                .any(|entry| index_entry_is_under_path(entry, &git_path))
            || source_entries
                .keys()
                .any(|entry| index_entry_is_under_path(entry, &git_path));
        let mut matched_paths = BTreeSet::new();
        for path in index_entries.iter().chain(source_entries.keys()) {
            if path.as_slice() == git_path.as_slice()
                || (recursive && index_entry_is_under_path(path, &git_path))
            {
                matched_paths.insert(path.clone());
            }
        }
        if matched_paths.is_empty() {
            eprintln!(
                "error: pathspec '{}' did not match any file(s) known to git",
                path.display()
            );
            return Err(GitError::Exit(1));
        }
        for path in matched_paths {
            if let Some(entry) = source_entries.get(&path) {
                restore_head_entry_to_worktree(worktree_root, db, &path, entry)?;
            } else {
                remove_worktree_file(worktree_root, &path)?;
            }
            restored.insert(path);
        }
    }
    Ok(RestoreResult {
        restored: restored.len(),
    })
}