grit-lib 0.5.18

Core library for the grit Git implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
//! Reference storage — files backend + reftable backend.
//!
//! Git stores references as text files under `<git-dir>/refs/` (and
//! `<git-dir>/packed-refs` for the packed backend).  Each loose ref file
//! contains either:
//!
//! - A 40-character hex SHA-1 followed by a newline, **or**
//! - The string `"ref: <target>\n"` for symbolic refs.
//!
//! `HEAD` is a special case: it is normally a symbolic ref but may also be
//! detached (pointing directly at a commit hash).
//!
//! When `extensions.refStorage = reftable`, the reftable backend is used
//! instead.  The public API is the same; dispatch is handled internally.
//!
//! Library guide: [mod](https://grit-scm.com/docs/library/refs)
//!
//! ```rust
//! use grit_lib::repo::{InitOptions, Repository};
//! # fn main() -> grit_lib::error::Result<()> {
//! let dir = tempfile::tempdir()?;
//! let _repo = Repository::init(dir.path(), &InitOptions::default())?;
//! assert!(_repo.refs().read_raw("HEAD")?.is_some());
//!
//! # Ok(())
//! # }
//! ```

pub mod handle;
pub mod listing;
pub mod query_reachability;
pub mod store;
pub mod version_sort;

mod domain_reexports;
pub use domain_reexports::*;
pub use handle::References;

/// In-process ref-transaction and loose-object prune helpers.
pub mod gc {
    pub use crate::gc::*;
}

use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::io;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use store::{
    open_ref_store, Expected, RawRef as StoreRawRef, RefCaseOnlyRename, RefEntry, RefReflogRename,
    RefStorageFormat, RefStore, RefTransaction, RefUpdate, RefUpdateFlags, ReflogUpdate,
};

use crate::check_ref_format::{check_refname_format, RefNameOptions};
use crate::config::ConfigSet;
use crate::error::{Error, RefLockError, Result};
use crate::objects::ObjectId;
use crate::pack;

/// Maximum symbolic ref hops when resolving a ref (Git `SYMREF_MAXDEPTH`).
pub const SYMREF_MAXDEPTH: usize = 5;

fn map_public_ref_store_error(err: Error, refname: &str) -> Error {
    match err {
        Error::RefStore(store::RefStoreError::SymrefLoop) => {
            Error::InvalidRef(format!("ref symlink too deep: {refname}"))
        }
        other => other,
    }
}

/// Loose-files checks shared by legacy [`write_ref_at_storage`] and RefStore-backed writes.
fn files_legacy_write_precheck(git_dir: &Path, refname: &str) -> Result<()> {
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return Ok(());
    }
    let storage_dir = ref_storage_dir(git_dir, refname);
    let stor = crate::ref_namespace::storage_ref_name(refname);
    let path = storage_dir.join(stor);
    remove_empty_ref_directory(&path);
    if fs::symlink_metadata(&path)
        .map(|m| m.file_type().is_dir())
        .unwrap_or(false)
    {
        let display = ref_path_for_display(&path);
        return Err(crate::error::RefLockError::DirectoryInTheWay {
            refname: refname.to_owned(),
            path: display,
        }
        .into());
    }
    if path.is_file() && matches!(read_ref_file(&path), Err(Error::InvalidRef(_))) {
        return Err(Error::InvalidRef(format!(
            "cannot update ref '{refname}': reference broken"
        )));
    }
    Ok(())
}

fn legacy_ref_update_flags(refname: &str) -> RefUpdateFlags {
    let mut flags = RefUpdateFlags::default();
    // Direct updates to `HEAD` detach or reattach the worktree HEAD file; do not peel symrefs.
    if refname == "HEAD" {
        flags.no_deref = true;
    }
    flags
}

pub(crate) fn commit_store_update(git_dir: &Path, update: RefUpdate) -> Result<()> {
    let store = open_ref_store(git_dir)?;
    commit_ref_update_on_store(store.as_ref(), update)
}

/// Apply one ref update through an already-selected [`RefStore`] (for example the store on
/// [`crate::repo::Repository`] after [`crate::repo::Repository::with_ref_store`]).
///
/// # Errors
///
/// Propagates validation, compare-and-swap, and backend errors.
pub fn commit_ref_update_on_store(store: &dyn RefStore, update: RefUpdate) -> Result<()> {
    let refname = update.name.clone();
    let txn = RefTransaction::new()
        .update(update)
        .map_err(crate::error::Error::from)?;
    let prepared = store
        .prepare(txn)
        .map_err(|e| map_public_ref_store_error(Error::from(e), &refname))?;
    prepared
        .commit()
        .map_err(|e| map_public_ref_store_error(Error::from(e), &refname))
}

/// Point `refname` at `oid` using `store`, optionally running loose-files prechecks when
/// `store` uses the files backend under `git_dir`.
///
/// # Errors
///
/// Same as [`write_ref`], except updates go through `store` instead of reopening storage from
/// `git_dir`.
pub fn update_direct_ref_on_store(
    store: &dyn RefStore,
    git_dir: &Path,
    refname: &str,
    oid: &ObjectId,
) -> Result<()> {
    store_write_value_on_store(
        store,
        git_dir,
        refname,
        Some(StoreRawRef::Direct(*oid)),
        Expected::Any,
        None,
    )
}

pub(crate) fn store_write_value_on_store(
    store: &dyn RefStore,
    git_dir: &Path,
    refname: &str,
    new_value: Option<StoreRawRef>,
    expected: Expected,
    reflog: Option<ReflogUpdate>,
) -> Result<()> {
    ensure_refname_safe_for_storage(refname)?;
    if new_value.is_some() && store.format() == RefStorageFormat::Files {
        files_legacy_write_precheck(git_dir, refname)?;
    }
    commit_ref_update_on_store(
        store,
        RefUpdate {
            name: refname.to_owned(),
            new_value,
            expected,
            reflog,
            flags: legacy_ref_update_flags(refname),
        },
    )
}

/// Apply several ref updates in one [`RefStore::prepare`] / commit (all-or-nothing).
///
/// Used by batch ref paths (`fetch`, `push`, `receive-pack`, [`crate::gc::update_refs`]).
///
/// # Errors
///
/// Returns [`crate::refs::store::RefStoreError`] for duplicate names, CAS failures,
/// lock conflicts, and namespace conflicts. Propagates I/O and corrupt-store failures.
pub fn commit_ref_store_batch(git_dir: &Path, updates: &[RefUpdate]) -> Result<()> {
    if updates.is_empty() {
        return Ok(());
    }
    let store = open_ref_store(git_dir)?;
    commit_ref_updates_on_store(store.as_ref(), updates, &[])
}

/// Apply several ref updates atomically through an existing [`RefStore`].
///
/// # Errors
///
/// Propagates validation, compare-and-swap, and backend errors from [`RefStore::prepare`].
pub fn commit_ref_updates_on_store(
    store: &dyn RefStore,
    updates: &[RefUpdate],
    reflog_renames: &[RefReflogRename],
) -> Result<()> {
    commit_ref_batch_on_store(store, updates, reflog_renames, &[])
}

/// Apply ref updates, reflog renames, and optional case-only ref renames atomically.
///
/// # Errors
///
/// Propagates validation, compare-and-swap, and backend errors from [`RefStore::prepare`].
pub fn commit_ref_batch_on_store(
    store: &dyn RefStore,
    updates: &[RefUpdate],
    reflog_renames: &[RefReflogRename],
    case_only_renames: &[RefCaseOnlyRename],
) -> Result<()> {
    if updates.is_empty() && reflog_renames.is_empty() && case_only_renames.is_empty() {
        return Ok(());
    }
    let label = updates
        .first()
        .map(|u| u.name.as_str())
        .or_else(|| reflog_renames.first().map(|r| r.from.as_str()))
        .or_else(|| case_only_renames.first().map(|r| r.from.as_str()))
        .unwrap_or("refs");
    let mut txn = RefTransaction::new();
    for update in updates {
        let name = update.name.clone();
        txn = txn
            .update(update.clone())
            .map_err(|e| map_public_ref_store_error(Error::from(e), &name))?;
    }
    for rename in reflog_renames {
        txn = txn.with_reflog_rename(rename.clone());
    }
    for rename in case_only_renames {
        txn = txn.with_case_only_rename(rename.clone());
    }
    let prepared = store
        .prepare(txn)
        .map_err(|e| map_public_ref_store_error(Error::from(e), label))?;
    prepared
        .commit()
        .map_err(|e| map_public_ref_store_error(Error::from(e), label))
}

fn store_write_value(
    git_dir: &Path,
    refname: &str,
    new_value: Option<StoreRawRef>,
    expected: Expected,
    reflog: Option<ReflogUpdate>,
) -> Result<()> {
    let store = open_ref_store(git_dir)?;
    store_write_value_on_store(
        store.as_ref(),
        git_dir,
        refname,
        new_value,
        expected,
        reflog,
    )
}

fn collect_resolved_refs(store: &dyn RefStore, prefix: &str) -> Result<Vec<(String, ObjectId)>> {
    collect_resolved_ref_entries(store, |f| store.for_each_ref(prefix, f))
}

/// Resolve each entry `for_each` yields to an object id through `store`.
fn collect_resolved_ref_entries(
    store: &dyn RefStore,
    for_each: impl FnOnce(&mut dyn FnMut(&RefEntry) -> ControlFlow<()>) -> Result<()>,
) -> Result<Vec<(String, ObjectId)>> {
    let mut results = Vec::new();
    for_each(&mut |entry: &RefEntry| {
        let oid = entry
            .peeled
            .or_else(|| match &entry.value {
                StoreRawRef::Direct(oid) => Some(*oid),
                StoreRawRef::Symbolic(target) => store.resolve(target).ok(),
            })
            .or_else(|| store.resolve(&entry.name).ok());
        if let Some(oid) = oid {
            results.push((entry.name.clone(), oid));
        }
        ControlFlow::Continue(())
    })?;
    Ok(results)
}

/// A symbolic or direct reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ref {
    /// Direct reference: stores an [`ObjectId`].
    Direct(ObjectId),
    /// Symbolic reference: stores the name of the target ref.
    Symbolic(String),
}

/// Read a single reference file from `path`.
///
/// # Errors
///
/// - [`Error::InvalidRef`] if the file content is not a valid ref.
/// - [`Error::Io`] on filesystem errors.
pub fn read_ref_file(path: &Path) -> Result<Ref> {
    if let Ok(target) = fs::read_link(path) {
        return Ok(Ref::Symbolic(target.to_string_lossy().into_owned()));
    }

    let content = match fs::read_to_string(path) {
        Ok(c) => c,
        // `refs/heads/master` can be a directory when a branch named `master/...` exists, and a
        // probe like `refs/remotes/v1` can hit ENOTDIR when `refs/remotes` is a file. Treat both
        // like a missing loose ref so optional DWIM candidates fall through cleanly.
        Err(e)
            if e.kind() == io::ErrorKind::IsADirectory
                || e.kind() == io::ErrorKind::NotADirectory
                || e.raw_os_error() == Some(libc::EISDIR)
                || e.raw_os_error() == Some(libc::ENOTDIR) =>
        {
            return Err(Error::Io(io::Error::new(io::ErrorKind::NotFound, e)));
        }
        Err(e) => return Err(Error::Io(e)),
    };
    let content = content.trim_end_matches('\n');
    parse_ref_content(content)
}

/// Parse the content of a ref file (without trailing newline).
pub(crate) fn parse_ref_content(content: &str) -> Result<Ref> {
    if let Some(target) = content.strip_prefix("ref: ") {
        Ok(Ref::Symbolic(target.trim().to_owned()))
    } else if let Some(token) = content.split_whitespace().next() {
        if ObjectId::is_full_hex(token) {
            let oid: ObjectId = token.parse()?;
            Ok(Ref::Direct(oid))
        } else if content == "unknown-oid" {
            const PLACEHOLDER: &[u8; 20] = b"GritUnknownOidPlc!X!";
            let oid = ObjectId::from_bytes(PLACEHOLDER)?;
            Ok(Ref::Direct(oid))
        } else {
            Err(Error::InvalidRef(content.to_owned()))
        }
    } else {
        Err(Error::InvalidRef(content.to_owned()))
    }
}

/// Resolve a reference to its target [`ObjectId`], following symbolic refs.
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// # Parameters
///
/// - `git_dir` — path to the git directory.
/// - `refname` — reference name (e.g. `"HEAD"`, `"refs/heads/main"`).
///
/// # Errors
///
/// - [`Error::RefStore`] with [`RefStoreError::NotFound`](store::RefStoreError::NotFound) if
///   `refname`, or the target at the end of its symbolic chain, does not exist.
/// - [`Error::InvalidRef`] if the ref is malformed or forms a cycle.
pub fn resolve_ref(git_dir: &Path, refname: &str) -> Result<ObjectId> {
    open_ref_store(git_dir)?
        .resolve(refname)
        .map_err(|err| map_public_ref_store_error(err, refname))
}

/// Determine the common git directory for worktree-aware ref resolution.
///
/// If `<git_dir>/commondir` exists, its contents point to the shared
/// git directory. Returns `None` when git_dir is already the common dir.
pub fn common_dir(git_dir: &Path) -> Option<PathBuf> {
    let commondir_file = git_dir.join("commondir");
    if !commondir_file.is_file() {
        return None;
    }
    let raw = fs::read_to_string(commondir_file).ok()?;
    let rel = raw.trim();
    // Match Git: `commondir` may be relative to this gitdir or an absolute path (see
    // `git worktree add` and `refs/files-backend.c`).
    let path = if Path::new(rel).is_absolute() {
        PathBuf::from(rel)
    } else {
        git_dir.join(rel)
    };
    path.canonicalize().ok()
}

/// Outcome of a single storage-level ref lookup (Git `refs_read_raw_ref` style).
///
/// This checks whether a ref **name** exists in the ref store without applying
/// DWIM rules. A symbolic ref is considered to exist if its ref file (or
/// reftable record) is present, even when the target is missing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawRefLookup {
    /// A loose ref file, packed ref line, or reftable record exists for this name.
    Exists,
    /// No ref is recorded under this exact name.
    NotFound,
    /// A path component exists as a directory where a ref file was expected (e.g. `refs/heads`).
    IsDirectory,
}

/// Return whether `refname` exists as a ref in the repository's ref storage.
///
/// This matches `git refs exists` / `git show-ref --exists`: no DWIM, no
/// resolution of symbolic targets. Dispatches to the reftable backend when
/// configured.
///
/// # Parameters
///
/// - `git_dir` — path to the git directory (worktree gitdir or bare `.git`).
/// - `refname` — full ref name (e.g. `HEAD`, `refs/heads/main`, `CHERRY_PICK_HEAD`).
///
/// # Errors
///
/// Propagates I/O and reftable errors other than "not found".
pub fn read_raw_ref(git_dir: &Path, refname: &str) -> Result<RawRefLookup> {
    let store = open_ref_store(git_dir)?;
    match store.read_raw(refname)? {
        Some(_) => Ok(RawRefLookup::Exists),
        None => {
            let (storage_dir, stor_name) =
                crate::worktree_ref::resolve_ref_storage(git_dir, refname);
            let path = storage_dir.join(&stor_name);
            if fs::symlink_metadata(&path)
                .map(|m| m.is_dir())
                .unwrap_or(false)
            {
                Ok(RawRefLookup::IsDirectory)
            } else {
                Ok(RawRefLookup::NotFound)
            }
        }
    }
}

/// Lock file path for a loose ref file (`<refpath>.lock`), matching Git's naming for nested refs.
#[must_use]
pub fn lock_path_for_ref(path: &Path) -> PathBuf {
    let mut s = path.as_os_str().to_owned();
    s.push(".lock");
    PathBuf::from(s)
}

/// First packed ref name strictly under `refname/` (sorted `packed-refs` prefix scan).
fn first_packed_descendant_ref(store: &Path, refname: &str) -> Result<Option<String>> {
    let leaf_dir = format!("{refname}/");
    let map = read_packed_refs_map_for_prefix(store, refname)?;
    let sorted: BTreeSet<String> = map.keys().cloned().collect();
    Ok(sorted
        .range(leaf_dir.clone()..)
        .next()
        .filter(|name| name.starts_with(&leaf_dir))
        .cloned())
}

fn packed_ref_name_exists(git_dir: &Path, refname: &str) -> Result<bool> {
    Ok(lookup_packed_ref(git_dir, refname)?.is_some())
}

/// Whether any name in `sorted_packed` namespace-conflicts with `candidate`.
///
/// Uses prefix walks and one sorted range probe — `O(log n)` in the number of
/// packed refs — instead of scanning every packed name.
pub(crate) fn packed_refname_namespace_conflict(
    sorted_packed: &BTreeSet<String>,
    candidate: &str,
) -> bool {
    let segments: Vec<&str> = candidate.split('/').filter(|s| !s.is_empty()).collect();
    if segments.len() > 1 {
        let mut dirname = String::new();
        for part in &segments[..segments.len() - 1] {
            if !dirname.is_empty() {
                dirname.push('/');
            }
            dirname.push_str(part);
            if sorted_packed.contains(&dirname) {
                return true;
            }
        }
    }

    let leaf_dir = format!("{candidate}/");
    if let Some(existing) = sorted_packed.range(leaf_dir.clone()..).next() {
        if existing.starts_with(&leaf_dir) {
            return true;
        }
    }
    false
}

fn packed_ref_namespace_conflict(git_dir: &Path, refname: &str) -> Result<bool> {
    Ok(PackedRefs::load(git_dir)?.has_namespace_conflict(refname))
}

/// Returns true if `packed-refs` in the ref storage directory for `refname` contains that name.
///
/// Used to mirror Git's `is_packed_transaction_needed` behaviour: deleting a ref may open a nested
/// packed-refs transaction whose abort runs the `reference-transaction` hook in the `aborted`
/// state between `preparing` and `prepared` on the main transaction.
///
/// Returns `false` for reftable repositories and for `HEAD` (packed-refs does not store `HEAD`).
///
/// # Errors
///
/// Propagates I/O errors reading `packed-refs`.
pub fn packed_refs_entry_exists(git_dir: &Path, refname: &str) -> Result<bool> {
    if refname == "HEAD" {
        return Ok(false);
    }
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return Ok(false);
    }
    let storage_dir = ref_storage_dir(git_dir, refname);
    packed_ref_name_exists(&storage_dir, refname)
}

/// Why a reference name cannot be created (Git `refs_verify_refname_available` style).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefnameUnavailable {
    /// An ancestor ref already exists in the store (e.g. `refs/foo` blocks `refs/foo/bar`).
    AncestorExists {
        /// Existing ref that blocks creation.
        blocking: String,
        /// Ref the caller tried to create.
        new_ref: String,
    },
    /// A descendant ref already exists (e.g. `refs/foo/bar` blocks `refs/foo`).
    DescendantExists {
        /// Existing ref under `new_ref/`.
        blocking: String,
        /// Ref the caller tried to create.
        new_ref: String,
    },
    /// Two refnames in the same batch are mutually incompatible (parent vs child).
    SameBatch {
        /// Ref being validated (Git prints this first).
        refname: String,
        /// Other ref in the batch (parent dirname or descendant name).
        other: String,
    },
}

impl RefnameUnavailable {
    /// Suffix after `cannot lock ref '<display_ref>': ` for stderr (no trailing newline).
    #[must_use]
    pub fn lock_message_suffix(&self) -> String {
        match self {
            RefnameUnavailable::AncestorExists { blocking, new_ref } => {
                format!("'{blocking}' exists; cannot create '{new_ref}'")
            }
            RefnameUnavailable::DescendantExists { blocking, new_ref } => {
                format!("'{blocking}' exists; cannot create '{new_ref}'")
            }
            RefnameUnavailable::SameBatch { refname, other } => {
                format!("cannot process '{refname}' and '{other}' at the same time")
            }
        }
    }
}

fn find_descendant_in_sorted_extras(
    dirname_with_slash: &str,
    extras: &BTreeSet<String>,
) -> Option<String> {
    let start = extras
        .range(dirname_with_slash.to_string()..)
        .next()
        .cloned()?;
    if start.starts_with(dirname_with_slash) {
        Some(start)
    } else {
        None
    }
}

/// Whether a network-advertised ref name is safe to accept during fetch.
///
/// Delegates to [`crate::check_ref_format::is_valid_fetch_advertised_ref`].
#[must_use]
pub fn is_valid_fetch_advertised_ref(name: &str) -> bool {
    crate::check_ref_format::is_valid_fetch_advertised_ref(name)
}

/// Whether a name from a protocol-v2 `ls-refs` response should be kept.
///
/// `HEAD` is valid without a `refs/` prefix; every other name must pass
/// [`is_valid_fetch_advertised_ref`].
#[must_use]
pub fn is_valid_ls_refs_advertised_name(name: &str) -> bool {
    name == "HEAD" || is_valid_fetch_advertised_ref(name)
}

/// Whether a ref name is safe to store under the ref backend (post-refspec mapping).
#[must_use]
pub fn is_valid_storable_ref_name(name: &str) -> bool {
    is_valid_fetch_advertised_ref(name)
}

/// Whether a symref target from a ref advertisement is safe to record.
#[must_use]
pub fn is_valid_advertised_symref_target(name: &str) -> bool {
    crate::check_ref_format::is_valid_advertised_symref_target(name)
}

/// Verify that `refname` can be created without directory/file conflicts with the ref store
/// and with other refnames queued in the same transaction (`extras`).
///
/// `skip` names are ignored when checking the filesystem (updates that delete or replace
/// those refs in the same batch). Matches Git's `refs_verify_refname_available`.
///
/// # Parameters
///
/// - `git_dir` — repository git directory.
/// - `refname` — full ref name to create.
/// - `extras` — other refnames touched in the same stdin batch / transaction (sorted set).
/// - `skip` — refnames that may be deleted or updated away in the same batch.
pub fn verify_refname_available_for_create(
    git_dir: &Path,
    refname: &str,
    extras: &BTreeSet<String>,
    skip: &HashSet<String>,
) -> std::result::Result<(), RefnameUnavailable> {
    // `Repository::git_dir` may be a relative path (e.g. `.git`); resolve so lookups match the
    // on-disk ref store regardless of process cwd (test harness runs from `trash/.git/...`).
    let git_dir = fs::canonicalize(git_dir).unwrap_or_else(|_| git_dir.to_path_buf());
    let mut seen_dirnames: HashSet<String> = HashSet::new();
    let segments: Vec<&str> = refname.split('/').filter(|s| !s.is_empty()).collect();
    if segments.len() <= 1 {
        // No slash-separated parent prefixes (e.g. `HEAD`).
    } else {
        let mut dirname = String::new();
        for part in &segments[..segments.len() - 1] {
            if !dirname.is_empty() {
                dirname.push('/');
            }
            dirname.push_str(part);

            if !seen_dirnames.insert(dirname.clone()) {
                continue;
            }

            if skip.contains(&dirname) {
                continue;
            }

            match read_raw_ref(&git_dir, &dirname) {
                Ok(RawRefLookup::Exists) => {
                    return Err(RefnameUnavailable::AncestorExists {
                        blocking: dirname.clone(),
                        new_ref: refname.to_owned(),
                    });
                }
                // A directory at `refs/prefix` is normal when storing `refs/prefix/child`; only a
                // real ref (loose file or packed line) blocks creating `refs/prefix/...`.
                Ok(RawRefLookup::NotFound | RawRefLookup::IsDirectory) => {}
                Err(_) => {}
            }

            if extras.contains(&dirname) {
                return Err(RefnameUnavailable::SameBatch {
                    refname: refname.to_owned(),
                    other: dirname.clone(),
                });
            }
        }
    }

    let mut leaf_dir = String::with_capacity(refname.len() + 1);
    leaf_dir.push_str(refname);
    leaf_dir.push('/');

    // Loose descendants can only exist inside a `<refname>/` directory; packed
    // and stray-file descendants are checked separately below. Skipping the
    // listing when no such directory exists keeps batch creates linear: listing
    // a missing directory walks its parent, so a clone writing N tags would
    // otherwise read every sibling ref N times.
    let packed_dir = common_dir(&git_dir).unwrap_or_else(|| git_dir.clone());
    let may_have_loose_descendants = packed_dir.join("reftable").is_dir()
        || git_dir.join(refname).is_dir()
        || packed_dir.join(refname).is_dir();
    let under = if may_have_loose_descendants {
        list_refs(&git_dir, &leaf_dir).unwrap_or_default()
    } else {
        Vec::new()
    };
    if under.is_empty() {
        if let Ok(Some(name)) = first_packed_descendant_ref(&packed_dir, refname) {
            if !skip.contains(&name) {
                return Err(RefnameUnavailable::DescendantExists {
                    blocking: name,
                    new_ref: refname.to_owned(),
                });
            }
        }
        if packed_dir != git_dir {
            if let Ok(Some(name)) = first_packed_descendant_ref(&git_dir, refname) {
                if !skip.contains(&name) {
                    return Err(RefnameUnavailable::DescendantExists {
                        blocking: name,
                        new_ref: refname.to_owned(),
                    });
                }
            }
        }
    }
    if under.is_empty()
        && fs::symlink_metadata(git_dir.join(refname))
            .map(|m| m.is_dir())
            .unwrap_or(false)
    {
        let mut blocking: Option<String> = None;
        let dir_path = git_dir.join(refname);
        if let Ok(read) = fs::read_dir(&dir_path) {
            for entry in read.flatten() {
                let path = entry.path();
                let Ok(meta) = fs::metadata(&path) else {
                    continue;
                };
                if !meta.is_file() {
                    continue;
                }
                let name = entry.file_name().to_string_lossy().into_owned();
                let full = format!("{refname}/{name}");
                blocking = Some(full);
                break;
            }
        }
        if let Some(b) = blocking {
            if !skip.contains(&b) {
                return Err(RefnameUnavailable::DescendantExists {
                    blocking: b,
                    new_ref: refname.to_owned(),
                });
            }
        }
    }

    for (existing, _) in under {
        if skip.contains(&existing) {
            continue;
        }
        return Err(RefnameUnavailable::DescendantExists {
            blocking: existing,
            new_ref: refname.to_owned(),
        });
    }

    if let Some(extra) = find_descendant_in_sorted_extras(&leaf_dir, extras) {
        if !skip.contains(&extra) {
            return Err(RefnameUnavailable::SameBatch {
                refname: refname.to_owned(),
                other: extra,
            });
        }
    }

    Ok(())
}

/// One ref create/update/delete in a batch transaction (see [`crate::gc::update_refs`]).
#[derive(Clone, Debug)]
pub struct RefBatchItem {
    /// Full ref name (e.g. `refs/heads/main`).
    pub name: String,
    /// New oid to write, or `None` to delete the ref.
    pub new_oid: Option<ObjectId>,
}

/// Verify that every *new* ref in a batch can be created without D/F or namespace
/// conflicts with the existing store or other items in the batch.
///
/// Matches Git's pre-lock `refs_verify_refnames_available` checks with an empty
/// `skip` list (refs scheduled for deletion in the same batch do not suppress
/// ancestor/descendant conflicts — see t1404 D/F batch tests).
///
/// # Errors
///
/// Returns [`RefnameUnavailable`] describing the first conflict.
pub fn verify_ref_transaction_batch(
    git_dir: &Path,
    items: &[RefBatchItem],
) -> std::result::Result<(), RefnameUnavailable> {
    if let Some((parent, child)) =
        batch_refname_prefix_conflict(items.iter().map(|i| i.name.as_str()))
    {
        return Err(RefnameUnavailable::SameBatch {
            refname: child,
            other: parent,
        });
    }

    if crate::ref_storage::detect_format(git_dir).is_ok_and(|f| f.is_reftable()) {
        return crate::reftable::verify_ref_transaction_batch_reftable(git_dir, items);
    }

    let extras: BTreeSet<String> = items.iter().map(|i| i.name.clone()).collect();
    let empty_skip = HashSet::new();
    for item in items {
        let Some(_oid) = item.new_oid else {
            continue;
        };
        if resolve_ref(git_dir, &item.name).is_ok() {
            continue;
        }
        verify_refname_available_for_create(git_dir, &item.name, &extras, &empty_skip)?;
    }
    Ok(())
}

/// First strict prefix conflict in a batch, if any (sorted adjacent scan).
pub(crate) fn batch_refname_prefix_conflict<'a>(
    names: impl Iterator<Item = &'a str>,
) -> Option<(String, String)> {
    let mut sorted: Vec<&str> = names.collect();
    sorted.sort_unstable();
    for pair in sorted.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        if refname_is_strict_prefix(a, b) {
            return Some((a.to_owned(), b.to_owned()));
        }
        if refname_is_strict_prefix(b, a) {
            return Some((b.to_owned(), a.to_owned()));
        }
    }
    None
}

fn refname_is_strict_prefix(parent: &str, child: &str) -> bool {
    child.len() > parent.len()
        && child.as_bytes().get(parent.len()) == Some(&b'/')
        && child.starts_with(parent)
}

fn packed_refs_unexpected_line(path: &Path, line: impl Into<String>) -> Error {
    Error::PackedRefsUnexpectedLine {
        path: path.display().to_string(),
        line: line.into(),
    }
}

fn packed_refs_unterminated_line(path: &Path, line: impl Into<String>) -> Error {
    Error::PackedRefsUnexpectedLine {
        path: path.display().to_string(),
        line: line.into(),
    }
}

fn parse_packed_ref_peel_line(path: &Path, line: &str, expect_peel: bool) -> Result<()> {
    if !expect_peel {
        return Err(packed_refs_unexpected_line(path, line));
    }
    let inner = line
        .strip_prefix('^')
        .ok_or_else(|| packed_refs_unexpected_line(path, line))?;
    let mut j = 0usize;
    while j < inner.len() && inner.as_bytes()[j].is_ascii_hexdigit() {
        j += 1;
    }
    if !ObjectId::is_hex_len(j) || j != inner.len() {
        return Err(packed_refs_unexpected_line(path, line));
    }
    Ok(())
}

fn packed_ref_data_line_refname(line: &str) -> Option<&str> {
    let bytes = line.as_bytes();
    let mut j = 0usize;
    while j < bytes.len() && bytes[j].is_ascii_hexdigit() {
        j += 1;
    }
    if !ObjectId::is_hex_len(j) || j + 1 >= bytes.len() || bytes[j] != b' ' {
        return None;
    }
    let refname = &line[j + 1..];
    if refname.is_empty() || refname.as_bytes().iter().any(|b| b.is_ascii_whitespace()) {
        return None;
    }
    Some(refname)
}

fn parse_packed_ref_data_line(
    path: &Path,
    line: &str,
    ref_opts: &RefNameOptions,
) -> Result<(String, ObjectId)> {
    let (refname, oid) = parse_packed_ref_data_line_borrowed(path, line, ref_opts)?;
    Ok((refname.to_owned(), oid))
}

fn parse_packed_ref_data_line_borrowed<'a>(
    path: &Path,
    line: &'a str,
    ref_opts: &RefNameOptions,
) -> Result<(&'a str, ObjectId)> {
    let bytes = line.as_bytes();
    let mut j = 0usize;
    while j < bytes.len() && bytes[j].is_ascii_hexdigit() {
        j += 1;
    }
    if !ObjectId::is_hex_len(j) || j + 1 >= bytes.len() || bytes[j] != b' ' {
        return Err(packed_refs_unexpected_line(path, line));
    }
    let refname = &line[j + 1..];
    if refname.is_empty() || refname.as_bytes().iter().any(|b| b.is_ascii_whitespace()) {
        return Err(packed_refs_unexpected_line(path, line));
    }
    if check_refname_format(refname, ref_opts).is_err() {
        return Err(packed_refs_unexpected_line(path, line));
    }
    let oid: ObjectId = line[..j].parse()?;
    Ok((refname, oid))
}

/// Parse `packed-refs` bytes the way Git reads them for ref listing (strict).
/// In-memory view of a `packed-refs` file for indexed lookup without a full parse.
#[derive(Debug, Clone)]
pub(crate) struct PackedRefsFileView {
    data: std::sync::Arc<crate::pack_map::PackData>,
    /// Records are indexed in nondecreasing name order, so binary search over them is exact.
    sorted: bool,
    /// Hex length of the repository's object ids; the refname starts one byte after it.
    hex_len: usize,
    /// Starts of the well-formed records (`<hex id> <name>`) in file order.
    data_line_starts: Vec<usize>,
    /// Which records the header promises a peel line for.
    peel_trait: PackedPeelTrait,
}

impl PackedRefsFileView {
    /// [`Self::from_data`] over an owned buffer.
    #[cfg(test)]
    fn from_bytes(path: &Path, data: Vec<u8>, hash_algo: crate::objects::HashAlgo) -> Result<Self> {
        Self::from_data(path, crate::pack_map::PackData::from_owned(data), hash_algo)
    }

    /// Index `data`, the (possibly memory-mapped) bytes of `path`, for a repository using
    /// `hash_algo`.
    ///
    /// Rejects what Git rejects before any lookup: carriage returns, a missing final newline,
    /// and a last line (after the header) too short to hold an object id. Only records with
    /// an id-sized prefix and a space are indexed; a file that declares `sorted` but whose
    /// indexed names are out of order is treated as unsorted.
    fn from_data(
        path: &Path,
        data: std::sync::Arc<crate::pack_map::PackData>,
        hash_algo: crate::objects::HashAlgo,
    ) -> Result<Self> {
        let hex_len = hash_algo.hex_len();
        if data.is_empty() {
            return Ok(Self {
                data,
                sorted: false,
                hex_len,
                data_line_starts: Vec::new(),
                peel_trait: PackedPeelTrait::None,
            });
        }
        if memchr::memchr(b'\r', &data).is_some() {
            return Err(packed_refs_unexpected_line(
                path,
                "<contains carriage return>",
            ));
        }
        if !data.ends_with(b"\n") {
            let tail = std::str::from_utf8(&data)
                .map(|s| s.rsplit('\n').next().unwrap_or(s))
                .unwrap_or("<invalid utf-8>");
            return Err(packed_refs_unterminated_line(path, tail));
        }
        let text = std::str::from_utf8(&data)
            .map_err(|_| packed_refs_unexpected_line(path, "<invalid utf-8>"))?;
        // Ranged scans never reach the end of a sorted file, so check the last line up front, as
        // Git does: past the header, it must be long enough to hold an object id.
        let body_start = if text.starts_with('#') {
            text.find('\n').map_or(text.len(), |nl| nl + 1)
        } else {
            0
        };
        let body = &text[body_start..];
        if let Some(rest) = body.strip_suffix('\n') {
            let last_line = rest.rfind('\n').map_or(rest, |nl| &rest[nl + 1..]);
            if last_line.len() < hex_len + 1 {
                return Err(packed_refs_unexpected_line(path, last_line));
            }
        }
        let (data_line_starts, in_order) = packed_refs_data_line_starts(&data, hex_len);
        Ok(Self {
            sorted: in_order && packed_refs_file_declares_sorted(text),
            hex_len,
            data_line_starts,
            peel_trait: packed_refs_peel_trait(text),
            data,
        })
    }

    /// The name of the indexed record at `line_start`: everything after `<hex id> `.
    fn record_name(&self, line_start: usize) -> &[u8] {
        let end = packed_line_end(&self.data, line_start);
        &self.data[line_start + self.hex_len + 1..end]
    }

    fn record_cmp(&self, line_start: usize, name: &str) -> std::cmp::Ordering {
        self.record_name(line_start).cmp(name.as_bytes())
    }

    /// Index of the first indexed record whose name is not less than `name`.
    fn lower_bound(&self, name: &str) -> usize {
        self.data_line_starts
            .partition_point(|&start| self.record_cmp(start, name).is_lt())
    }

    /// Object id stored for `refname`, and optional peeled tag target from the following `^` line.
    fn lookup_entry(
        &self,
        path: &Path,
        refname: &str,
    ) -> Result<Option<(ObjectId, Option<ObjectId>)>> {
        let ref_opts = RefNameOptions {
            allow_onelevel: false,
            refspec_pattern: false,
            normalize: false,
        };
        let line_start = if self.sorted {
            self.data_line_starts
                .get(self.lower_bound(refname))
                .copied()
                .filter(|&start| self.record_cmp(start, refname).is_eq())
        } else {
            self.data_line_starts
                .iter()
                .copied()
                .find(|&start| self.record_cmp(start, refname).is_eq())
        };
        let Some(start) = line_start else {
            return Ok(None);
        };
        let (name, oid) = parse_packed_line_at(path, &self.data, start, &ref_opts)?;
        debug_assert_eq!(name, refname);
        let line_end = packed_line_end(&self.data, start);
        if line_end + 1 < self.data.len() && self.data[line_end + 1] == b'^' {
            let peel_line = packed_line_as_str(&self.data, line_end + 1);
            parse_packed_ref_peel_line(path, peel_line, true)?;
        }
        let peel = peel_oid_following_line(&self.data, start);
        Ok(Some((oid, peel)))
    }

    fn lookup_oid(&self, path: &Path, refname: &str) -> Result<Option<ObjectId>> {
        Ok(self.lookup_entry(path, refname)?.map(|(oid, _)| oid))
    }

    /// Smallest packed ref strictly under `refname/`, with its object id.
    ///
    /// A sorted file only parses the records sharing `refname` as a prefix.
    pub(crate) fn first_descendant(
        &self,
        path: &Path,
        refname: &str,
    ) -> Result<Option<(String, ObjectId)>> {
        let leaf_dir = format!("{refname}/");
        Ok(self
            .map_for_prefix(path, Some(refname))?
            .into_iter()
            .filter(|(name, _)| name.starts_with(&leaf_dir))
            .min_by(|a, b| a.0.cmp(&b.0)))
    }

    /// Refs whose names start with `prefix` (all refs for `None`).
    ///
    /// Every line the scan covers is parsed strictly, peel and comment lines included. In a
    /// sorted file a prefix scan covers the binary-searched range of matching records plus
    /// whatever lies between them and the indexed records on either side, so a corrupt line
    /// in or next to the range is reported rather than skipped. Like Git, it does not read
    /// records further away. Scans without a prefix, of all of `refs/`, or of an unsorted
    /// file cover the whole file.
    fn map_for_prefix(
        &self,
        path: &Path,
        prefix: Option<&str>,
    ) -> Result<HashMap<String, ObjectId>> {
        self.map_for_prefix_filtered(path, prefix, None)
    }

    /// [`Self::map_for_prefix`], leaving out the records `keep` rejects. Rejected records are
    /// still parsed strictly; they are only spared the allocation.
    fn map_for_prefix_filtered(
        &self,
        path: &Path,
        prefix: Option<&str>,
        keep: Option<PackedRecordFilter<'_>>,
    ) -> Result<HashMap<String, ObjectId>> {
        let prefix_trim = prefix.map(|p| p.trim_end_matches('/'));
        let range_prefix = prefix_trim.filter(|p| self.sorted && !p.is_empty() && *p != "refs");
        let (lo, hi) = match range_prefix {
            Some(prefix) => (
                self.lower_bound(prefix),
                list_prefix_upper_bound(prefix).map_or(self.data_line_starts.len(), |upper| {
                    self.lower_bound(&upper)
                }),
            ),
            None => (0, self.data_line_starts.len()),
        };
        // Start after the record before the range and its peel line (which belongs to that
        // record), so anything else up to the first record in range is checked.
        let begin = match lo.checked_sub(1) {
            Some(prev) => {
                let after = packed_line_end(&self.data, self.data_line_starts[prev]) + 1;
                if self.data.get(after) == Some(&b'^') {
                    packed_line_end(&self.data, after) + 1
                } else {
                    after
                }
            }
            None => 0,
        };
        let end = self
            .data_line_starts
            .get(hi)
            .copied()
            .unwrap_or(self.data.len());
        // `from_bytes` validated the whole buffer as UTF-8 and both bounds follow a `\n`.
        let region = std::str::from_utf8(&self.data[begin..end])
            .map_err(|_| packed_refs_unexpected_line(path, "<invalid utf-8>"))?;
        parse_packed_refs_region(path, region, prefix_trim, keep, self.peel_trait)
    }
}

/// What a `packed-refs` record tells about the object its ref names, given the file's
/// `peeled` / `fully-peeled` header traits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PackedPeel {
    /// The ref names an annotated tag that peels to this object.
    Peeled(ObjectId),
    /// The ref is known not to name an annotated tag.
    NotTag,
    /// The file does not say; the object must be read to peel it.
    Unknown,
}

/// Decides, from its storage name, object id and [`PackedPeel`], whether a `packed-refs`
/// record is listed.
pub(crate) type PackedRecordFilter<'a> = &'a dyn Fn(&str, &ObjectId, PackedPeel) -> bool;

/// Strictly parse the `packed-refs` lines of `region`, keeping refs that match `prefix`.
///
/// `region` starts at the beginning of the file or of a line that is not a peel line, and ends
/// at the end of the file or just before a ref line, so peel lines stay attached to their ref.
fn parse_packed_refs_region(
    path: &Path,
    region: &str,
    prefix: Option<&str>,
    keep: Option<PackedRecordFilter<'_>>,
    peel_trait: PackedPeelTrait,
) -> Result<HashMap<String, ObjectId>> {
    let ref_opts = RefNameOptions {
        allow_onelevel: false,
        refspec_pattern: false,
        normalize: false,
    };
    let mut map = HashMap::new();
    // With a filter, a record is decided once its peel line (if any) has been seen.
    let mut pending: Option<(&str, ObjectId, Option<ObjectId>)> = None;
    let flush = |map: &mut HashMap<String, ObjectId>,
                 pending: &mut Option<(&str, ObjectId, Option<ObjectId>)>| {
        let (Some(keep), Some((refname, oid, peeled))) = (keep, pending.take()) else {
            return;
        };
        let peel = if peel_trait.covers(refname) {
            peeled.map_or(PackedPeel::NotTag, PackedPeel::Peeled)
        } else {
            PackedPeel::Unknown
        };
        if keep(refname, &oid, peel) {
            map.insert(refname.to_owned(), oid);
        }
    };
    let mut expect_peel = false;
    let mut lines = region.split('\n').peekable();
    while let Some(line) = lines.next() {
        if line.is_empty() {
            if lines.peek().is_some() {
                return Err(packed_refs_unexpected_line(path, line));
            }
            break;
        }
        if line.starts_with('#') {
            flush(&mut map, &mut pending);
            expect_peel = false;
            continue;
        }
        if let Some(peel_hex) = line.strip_prefix('^') {
            parse_packed_ref_peel_line(path, line, expect_peel)?;
            if let Some((_, _, peeled)) = pending.as_mut() {
                *peeled = ObjectId::from_hex(peel_hex).ok();
            }
            expect_peel = false;
            continue;
        }
        flush(&mut map, &mut pending);
        let (refname, oid) = parse_packed_ref_data_line_borrowed(path, line, &ref_opts)?;
        if prefix.is_none_or(|p| ref_name_matches_list_prefix(refname, p)) {
            if keep.is_some() {
                pending = Some((refname, oid, None));
            } else {
                map.insert(refname.to_owned(), oid);
            }
        }
        expect_peel = true;
    }
    flush(&mut map, &mut pending);
    Ok(map)
}

fn read_packed_refs_file_view(store: &Path) -> Result<Option<PackedRefsFileView>> {
    let packed_path = store::paths::packed_refs_path(store);
    // Writers publish `packed-refs` by renaming a new file over it, never by rewriting it in
    // place, so a large file can be mapped like a pack instead of copied.
    let data = match crate::pack_map::PackData::open_with_min_len(&packed_path, 0) {
        Ok(d) => d,
        Err(Error::Io(e)) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    let hash_algo = crate::repo::read_repository_format_from_git_dir(store)
        .map(|format| format.hash_algo())
        .unwrap_or(crate::objects::HashAlgo::Sha1);
    Ok(Some(PackedRefsFileView::from_data(
        &packed_path,
        data,
        hash_algo,
    )?))
}

/// Starts of the lines shaped like a record (`hex_len` bytes, a space, a non-empty name), and
/// whether their names are in nondecreasing order. Other lines are left for the strict parse.
fn packed_refs_data_line_starts(data: &[u8], hex_len: usize) -> (Vec<usize>, bool) {
    let mut out = Vec::new();
    let mut in_order = true;
    let mut prev_name: &[u8] = &[];
    let mut start = 0usize;
    while start < data.len() {
        let end = memchr::memchr(b'\n', &data[start..]).map_or(data.len(), |p| start + p);
        let line = &data[start..end];
        if line.len() > hex_len + 1 && line[hex_len] == b' ' && !matches!(line[0], b'#' | b'^') {
            let name = &line[hex_len + 1..];
            in_order &= prev_name <= name;
            prev_name = name;
            out.push(start);
        }
        start = end + 1;
    }
    (out, in_order)
}

fn packed_line_end(data: &[u8], line_start: usize) -> usize {
    memchr::memchr(b'\n', &data[line_start..]).map_or(data.len(), |p| line_start + p)
}

fn packed_line_as_str(data: &[u8], line_start: usize) -> &str {
    std::str::from_utf8(&data[line_start..packed_line_end(data, line_start)]).unwrap_or("")
}

fn peel_oid_following_line(data: &[u8], line_start: usize) -> Option<ObjectId> {
    let line_end = packed_line_end(data, line_start);
    if line_end >= data.len() || data[line_end] != b'\n' {
        return None;
    }
    let peel_start = line_end + 1;
    if peel_start >= data.len() || data[peel_start] != b'^' {
        return None;
    }
    let peel_end = packed_line_end(data, peel_start);
    let inner = std::str::from_utf8(&data[peel_start + 1..peel_end]).ok()?;
    ObjectId::from_hex(inner.trim()).ok()
}

fn parse_packed_line_at(
    path: &Path,
    data: &[u8],
    line_start: usize,
    ref_opts: &RefNameOptions,
) -> Result<(String, ObjectId)> {
    let line = packed_line_as_str(data, line_start);
    parse_packed_ref_data_line(path, line, ref_opts)
}

pub(crate) fn parse_packed_refs_to_map(
    path: &Path,
    data: &[u8],
) -> Result<HashMap<String, ObjectId>> {
    parse_packed_refs_to_map_with_prefix(path, data, None)
}

/// Whether the `packed-refs` header comment lists Git's `sorted` trait (`pack-refs --all`).
fn packed_refs_file_declares_sorted(text: &str) -> bool {
    for line in text.split('\n') {
        if line.is_empty() {
            break;
        }
        if !line.starts_with('#') {
            break;
        }
        let body = line[1..].trim();
        let Some(traits) = body.strip_prefix("pack-refs with:") else {
            continue;
        };
        return traits.split_whitespace().any(|t| t == "sorted");
    }
    false
}

fn parse_packed_refs_to_map_with_prefix(
    path: &Path,
    data: &[u8],
    prefix_filter: Option<&str>,
) -> Result<HashMap<String, ObjectId>> {
    if data.is_empty() {
        return Ok(HashMap::new());
    }
    if data.contains(&b'\r') {
        return Err(packed_refs_unexpected_line(
            path,
            "<contains carriage return>",
        ));
    }
    if !data.ends_with(b"\n") {
        let tail = std::str::from_utf8(data)
            .map(|s| s.rsplit('\n').next().unwrap_or(s))
            .unwrap_or("<invalid utf-8>");
        return Err(packed_refs_unterminated_line(path, tail));
    }
    let text = std::str::from_utf8(data)
        .map_err(|_| packed_refs_unexpected_line(path, "<invalid utf-8>"))?;

    let ref_opts = RefNameOptions {
        allow_onelevel: false,
        refspec_pattern: false,
        normalize: false,
    };

    let mut map = HashMap::new();
    let mut expect_peel = false;
    let prefix_trim = prefix_filter.map(|p| p.trim_end_matches('/'));
    let packed_sorted = packed_refs_file_declares_sorted(text);
    let prefix_upper = if packed_sorted {
        prefix_trim.and_then(list_prefix_upper_bound)
    } else {
        None
    };
    let mut lines = text.split('\n').peekable();
    while let Some(line) = lines.next() {
        if line.is_empty() {
            if lines.peek().is_some() {
                return Err(packed_refs_unexpected_line(path, line));
            }
            break;
        }
        if line.starts_with('#') {
            expect_peel = false;
            continue;
        }
        if line.starts_with('^') {
            parse_packed_ref_peel_line(path, line, expect_peel)?;
            expect_peel = false;
            continue;
        }

        if let Some(prefix) = prefix_trim {
            let Some(refname) = packed_ref_data_line_refname(line) else {
                return Err(packed_refs_unexpected_line(path, line));
            };
            if packed_sorted {
                if refname < prefix {
                    expect_peel = true;
                    continue;
                }
                if let Some(upper) = &prefix_upper {
                    if refname >= upper.as_str() {
                        break;
                    }
                }
            }
            if !ref_name_matches_list_prefix(refname, prefix) {
                expect_peel = true;
                continue;
            }
        }
        let (refname, oid) = parse_packed_ref_data_line(path, line, &ref_opts)?;
        map.insert(refname, oid);
        expect_peel = true;
    }
    Ok(map)
}

pub(crate) fn read_packed_refs_map(store: &Path) -> Result<HashMap<String, ObjectId>> {
    read_packed_refs_map_for_prefix(store, "")
}

pub(crate) fn read_packed_refs_map_for_prefix(
    store: &Path,
    prefix: &str,
) -> Result<HashMap<String, ObjectId>> {
    read_packed_refs_map_for_prefix_filtered(store, prefix, None)
}

/// [`read_packed_refs_map_for_prefix`], leaving out the records `keep` rejects.
pub(crate) fn read_packed_refs_map_for_prefix_filtered(
    store: &Path,
    prefix: &str,
    keep: Option<PackedRecordFilter<'_>>,
) -> Result<HashMap<String, ObjectId>> {
    let Some(view) = read_packed_refs_file_view(store)? else {
        return Ok(HashMap::new());
    };
    let packed_path = store::paths::packed_refs_path(store);
    let filter = if prefix.is_empty() {
        None
    } else {
        Some(prefix)
    };
    view.map_for_prefix_filtered(&packed_path, filter, keep)
}

/// What a `packed-refs` header promises about its `^` peel lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PackedPeelTrait {
    /// No `peeled` trait: peel lines may be missing for any ref.
    None,
    /// `peeled`: every annotated tag under `refs/tags/` has a peel line.
    Tags,
    /// `fully-peeled`: every ref that names an annotated tag has a peel line.
    All,
}

impl PackedPeelTrait {
    /// Whether a ref named `refname` without a peel line is known not to name an annotated tag.
    fn covers(self, refname: &str) -> bool {
        match self {
            Self::None => false,
            Self::Tags => refname.starts_with("refs/tags/"),
            Self::All => true,
        }
    }
}

/// Read-only snapshot of the peel lines recorded in `packed-refs`.
///
/// Lets callers that peel many refs (log decorations, for example) skip reading tag
/// objects when `packed-refs` already records the peeled value, the same shortcut
/// Git takes when iterating packed refs.
///
/// Lookups trust the record shape indexed by [`PackedRefsFileView`] and skip the strict
/// per-line validation: callers pair this with a ref listing that already parsed the
/// file strictly.
pub(crate) struct PackedRefPeels {
    view: Option<PackedRefsFileView>,
    /// Record start by name for unsorted files, where binary search is not exact.
    unsorted: Option<HashMap<Box<[u8]>, usize>>,
    peel_trait: PackedPeelTrait,
}

impl PackedRefPeels {
    /// Load the peel snapshot for the files ref store backing `git_dir`.
    ///
    /// A missing `packed-refs`, or a ref store that is not the files backend, yields a
    /// snapshot that knows nothing (every [`Self::peeled`] call returns `None`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] when `packed-refs` exists but cannot be read, or
    /// [`Error::PackedRefsUnexpectedLine`] when it is malformed.
    pub(crate) fn load(git_dir: &Path, format: RefStorageFormat) -> Result<Self> {
        let empty = Self {
            view: None,
            unsorted: None,
            peel_trait: PackedPeelTrait::None,
        };
        if format != RefStorageFormat::Files {
            return Ok(empty);
        }
        let store = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
        let Some(view) = read_packed_refs_file_view(&store)? else {
            return Ok(empty);
        };
        let peel_trait = view.peel_trait;
        if peel_trait == PackedPeelTrait::None {
            return Ok(empty);
        }
        let unsorted = (!view.sorted).then(|| {
            view.data_line_starts
                .iter()
                .map(|&start| (Box::<[u8]>::from(view.record_name(start)), start))
                .collect()
        });
        Ok(Self {
            view: Some(view),
            unsorted,
            peel_trait,
        })
    }

    /// Peeled value of `refname` when `packed-refs` vouches for it.
    ///
    /// `oid` is the ref's current value; packed data is only trusted when it records the
    /// same value (a loose ref overriding the packed one is not covered).
    ///
    /// # Returns
    ///
    /// - `Some(Some(peeled))`: the ref names an annotated tag that peels to `peeled`
    ///   (the innermost non-tag object).
    /// - `Some(None)`: the ref is known not to name an annotated tag.
    /// - `None`: `packed-refs` does not say; the caller must peel the object itself.
    pub(crate) fn peeled(&self, refname: &str, oid: &ObjectId) -> Option<Option<ObjectId>> {
        if !self.peel_trait.covers(refname) {
            return None;
        }
        let view = self.view.as_ref()?;
        let start = match &self.unsorted {
            Some(map) => *map.get(refname.as_bytes())?,
            None => view
                .data_line_starts
                .get(view.lower_bound(refname))
                .copied()
                .filter(|&start| view.record_cmp(start, refname).is_eq())?,
        };
        let hex = std::str::from_utf8(&view.data[start..start + view.hex_len]).ok()?;
        let packed_oid = ObjectId::from_hex(hex).ok()?;
        (packed_oid == *oid).then(|| peel_oid_following_line(&view.data, start))
    }
}

/// The peel guarantee declared by the `# pack-refs with:` header of `text`.
fn packed_refs_peel_trait(text: &str) -> PackedPeelTrait {
    let Some(header) = text.strip_prefix("# pack-refs with: ") else {
        return PackedPeelTrait::None;
    };
    let traits = header.split('\n').next().unwrap_or_default();
    let mut peel_trait = PackedPeelTrait::None;
    for t in traits.split_whitespace() {
        match t {
            "fully-peeled" => return PackedPeelTrait::All,
            "peeled" => peel_trait = PackedPeelTrait::Tags,
            _ => {}
        }
    }
    peel_trait
}

fn acquire_packed_refs_lock(
    git_dir: &Path,
    lock: &Path,
    lock_display: &Path,
) -> Result<crate::lockfile::LockFile> {
    use crate::lockfile::{LockError, LockFile, LockWait};
    let wait = LockWait::packed_refs_for_git_dir(git_dir);
    LockFile::acquire(lock, wait).map_err(|err| match err {
        LockError::Held { .. } => Error::from(RefLockError::PackedRefsLockHeld {
            lock_path: lock_display.display().to_string(),
        }),
        LockError::Io { source, .. } => Error::Io(source),
    })
}

/// Look up a refname in `packed-refs`.
pub(crate) fn lookup_packed_ref(git_dir: &Path, refname: &str) -> Result<Option<ObjectId>> {
    let Some(view) = read_packed_refs_file_view(git_dir)? else {
        return Ok(None);
    };
    let packed_path = store::paths::packed_refs_path(git_dir);
    view.lookup_oid(&packed_path, refname)
}

/// Look up a refname and optional peeled tag oid in `packed-refs`.
#[cfg(test)]
pub(crate) fn lookup_packed_ref_with_peel(
    git_dir: &Path,
    refname: &str,
) -> Result<Option<(ObjectId, Option<ObjectId>)>> {
    let Some(view) = read_packed_refs_file_view(git_dir)? else {
        return Ok(None);
    };
    let packed_path = store::paths::packed_refs_path(git_dir);
    view.lookup_entry(&packed_path, refname)
}

/// Write a symbolic ref (e.g. `NOTES_MERGE_REF` → `refs/notes/m`).
///
/// For reftable-backed repositories this dispatches to the reftable writer.
///
/// # Errors
///
/// Returns [`Error::InvalidRef`] when `refname` is not safe for ref storage (e.g. path
/// traversal under `refs/`), on a namespace conflict, or [`Error::Io`] on filesystem errors.
pub fn write_symbolic_ref(git_dir: &Path, refname: &str, target: &str) -> Result<()> {
    store_write_value(
        git_dir,
        refname,
        Some(StoreRawRef::Symbolic(target.to_owned())),
        Expected::Any,
        None,
    )
}

pub(crate) fn ensure_refname_safe_for_storage(refname: &str) -> Result<()> {
    if let Some(rest) = refname.strip_prefix("refs/") {
        if rest.is_empty() || !crate::check_ref_format::is_valid_fetch_advertised_ref(refname) {
            return Err(Error::InvalidRef(format!(
                "refusing to update ref with bad name '{refname}'"
            )));
        }
        return Ok(());
    }
    if crate::check_ref_format::refname_is_safe(refname) {
        Ok(())
    } else {
        Err(Error::InvalidRef(format!(
            "refusing to update ref with bad name '{refname}'"
        )))
    }
}

/// Write a ref, creating parent directories as needed.
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// # Parameters
///
/// - `git_dir` — path to the git directory.
/// - `refname` — reference name (e.g. `"refs/heads/main"`).
/// - `oid` — the new target object ID.
///
/// # Errors
///
/// Returns [`Error::InvalidRef`] when `refname` is not safe for ref storage (e.g. path
/// traversal under `refs/`), on a namespace conflict, or [`Error::Io`] on filesystem errors.
pub fn write_ref(git_dir: &Path, refname: &str, oid: &ObjectId) -> Result<()> {
    store_write_value(
        git_dir,
        refname,
        Some(StoreRawRef::Direct(*oid)),
        Expected::Any,
        None,
    )
}

/// Per-ref update flags for [`RefUpdate`] (e.g. `REF_NO_DEREF` on `HEAD`).
#[must_use]
pub fn ref_update_flags(refname: &str) -> RefUpdateFlags {
    legacy_ref_update_flags(refname)
}

/// Create a new direct ref and its initial reflog line in one store transaction.
///
/// # Errors
///
/// Returns an error when the ref already exists, the name is invalid, or ref/reflog I/O fails.
pub fn create_ref_with_reflog(
    git_dir: &Path,
    refname: &str,
    oid: &ObjectId,
    identity: &str,
    message: &str,
) -> Result<()> {
    let config = ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(git_dir),
        true,
    )
    .unwrap_or_default();
    let store = open_ref_store(git_dir)?;
    create_ref_with_reflog_on_store(
        store.as_ref(),
        git_dir,
        &config,
        refname,
        oid,
        identity,
        message,
    )
}

/// [`create_ref_with_reflog`] through an already-open store with already-loaded `config`, so
/// a caller holding a [`crate::repo::Repository`] reuses its packed-refs and config caches.
pub(crate) fn create_ref_with_reflog_on_store(
    store: &dyn RefStore,
    git_dir: &Path,
    config: &ConfigSet,
    refname: &str,
    oid: &ObjectId,
    identity: &str,
    message: &str,
) -> Result<()> {
    let reflog =
        should_autocreate_reflog_with_config(config, git_dir, refname).then(|| ReflogUpdate {
            identity: identity.to_owned(),
            message: message.to_owned(),
            time: time::OffsetDateTime::now_utc(),
            old_oid: None,
            new_oid: None,
        });
    store_write_value_on_store(
        store,
        git_dir,
        refname,
        Some(StoreRawRef::Direct(*oid)),
        Expected::Missing,
        reflog,
    )
}

/// Write a loose ref file under `storage_dir`: the body shared by [`write_ref`]
/// and [`write_ref_cached`], run after the packed-refs namespace-conflict check.
fn write_ref_at_storage(
    git_dir: &Path,
    storage_dir: &Path,
    refname: &str,
    oid: &ObjectId,
) -> Result<()> {
    let stor = crate::ref_namespace::storage_ref_name(refname);
    let path = storage_dir.join(stor);
    // An empty directory left over from a previously deleted nested ref can sit exactly where
    // this ref file must go (e.g. `refs/e-create/foo` after `refs/e-create/foo/bar` was pruned).
    // Git removes such empty directory trees before locking the ref (see t0600 "empty directory
    // should not fool create/update"); mirror that so the rename below does not hit "Is a
    // directory". Non-empty directories (containing files or `*.lock`) are left in place so the
    // subsequent write surfaces the conflict, matching Git's behaviour.
    remove_empty_ref_directory(&path);
    // If a *non-empty* directory still sits where the ref file must go, locking cannot
    // proceed. Git reports this as a "non-empty directory ... blocking reference" rather
    // than letting the rename fail with a raw "Is a directory" I/O error (see t0600
    // "non-empty directory blocks create"). Mirror that message so callers display it
    // verbatim. This only applies to direct (non-deref) writes where `refname` is also the
    // user-visible ref; indirect symref writes are handled by the caller.
    if fs::symlink_metadata(&path)
        .map(|m| m.file_type().is_dir())
        .unwrap_or(false)
    {
        let display = ref_path_for_display(&path);
        return Err(crate::error::RefLockError::DirectoryInTheWay {
            refname: refname.to_owned(),
            path: display,
        }
        .into());
    }
    if path.is_file() && matches!(read_ref_file(&path), Err(Error::InvalidRef(_))) {
        return Err(Error::InvalidRef(format!(
            "cannot update ref '{refname}': reference broken"
        )));
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let content = format!("{oid}\n");
    // Write via lock file for atomicity (`O_CREAT|O_EXCL`), with optional backoff
    // per `core.filesRefLockTimeout`. Callers (e.g. fetch) map a held lock to
    // "cannot lock ref … File exists." and skip that ref while updating the rest.
    let lock = lock_path_for_ref(&path);
    use crate::lockfile::{LockError, LockFile, LockWait};
    use std::io::Write as _;
    let wait = LockWait::files_ref_lock_for_git_dir(git_dir);
    let mut lock = LockFile::acquire(&lock, wait).map_err(|err| match err {
        LockError::Held { path } => {
            Error::Io(crate::lockfile::lock_held_as_ref_present(LockError::Held {
                path,
            }))
        }
        LockError::Io { source, .. } => Error::Io(source),
    })?;
    lock.write_all(content.as_bytes()).map_err(Error::Io)?;
    lock.commit_to(&path).map_err(|err| match err {
        LockError::Io { source, .. } => Error::Io(source),
        LockError::Held { path } => {
            Error::Io(crate::lockfile::lock_held_as_ref_present(LockError::Held {
                path,
            }))
        }
    })?;
    Ok(())
}

/// Like [`write_ref`], but requires `expected_old` to match the ref's current value
/// while the loose-ref lock is held (atomic CAS for concurrent updaters).
///
/// # Errors
///
/// Same as [`write_ref`], plus [`store::RefStoreError::ExpectedMismatch`] when the CAS check
/// fails under lock.
pub fn write_ref_cas(
    git_dir: &Path,
    refname: &str,
    oid: &ObjectId,
    expected_old: ObjectId,
) -> Result<()> {
    store_write_value(
        git_dir,
        refname,
        Some(StoreRawRef::Direct(*oid)),
        Expected::Oid(expected_old),
        None,
    )
}

/// Like [`delete_ref`], but requires `expected_old` to match under the ref lock.
///
/// # Errors
///
/// Same as [`delete_ref`], plus [`store::RefStoreError::ExpectedMismatch`] when the CAS check
/// fails.
pub fn delete_ref_cas(git_dir: &Path, refname: &str, expected_old: ObjectId) -> Result<()> {
    store_write_value(git_dir, refname, None, Expected::Oid(expected_old), None)
}

/// Unlink a loose ref file after `packed-refs` was updated, when the file still contains
/// `expected`. Does not modify `packed-refs` (unlike [`delete_ref`] / [`delete_ref_cas`]).
///
/// Returns `Ok(true)` when the loose file was removed, `Ok(false)` when the OID differed or the
/// file was already absent.
///
/// # Errors
///
/// Propagates I/O failures and when the ref lock is already held.
pub(crate) fn prune_loose_ref_cas(
    git_dir: &Path,
    refname: &str,
    expected: ObjectId,
) -> Result<bool> {
    ensure_refname_safe_for_storage(refname)?;
    let storage_dir = ref_storage_dir(git_dir, refname);
    let stor = crate::ref_namespace::storage_ref_name(refname);
    let path = storage_dir.join(&stor);
    let lock_path = lock_path_for_ref(&path);
    use crate::lockfile::{LockFile, LockWait};
    let wait = LockWait::files_ref_lock_for_git_dir(git_dir);
    let _lock = LockFile::acquire(&lock_path, wait)
        .map_err(|err| Error::Io(crate::lockfile::lock_held_as_ref_present(err)))?;
    let outcome = (|| -> Result<bool> {
        if !path.is_file() {
            return Ok(true);
        }
        let Ok(Ref::Direct(oid)) = read_ref_file(&path) else {
            return Ok(false);
        };
        if oid != expected {
            return Ok(false);
        }
        remove_empty_ref_directory(&path);
        fs::remove_file(&path).map_err(Error::Io)?;
        if let Some(parent) = path.parent() {
            remove_empty_ref_directory(parent);
        }
        Ok(true)
    })();
    outcome
}

/// A one-time, in-memory snapshot of a ref store's `packed-refs` file.
///
/// Bulk ref operations — notably `fetch`'s apply phase — resolve and write
/// thousands of refs back-to-back. Going through [`resolve_ref`] / [`write_ref`]
/// for each one re-reads and re-scans the *entire* `packed-refs` file on every
/// call, making the apply O(refs × packed-refs size). On a repository with tens
/// of thousands of packed refs that dominates the whole fetch even when no
/// objects are transferred. Loading the file once into this snapshot and using
/// [`resolve_ref_cached`] / [`write_ref_cached`] makes the apply linear.
///
/// The snapshot reflects `packed-refs` at load time. [`write_ref_cached`] may
/// update the snapshot in place so later namespace checks in the same apply batch
/// see loose refs without reloading the file. Otherwise
/// treat it as read-only: stale packed data only omits refs that were loose on
/// disk (resolved outside the snapshot) to begin with.
pub struct PackedRefs {
    map: HashMap<String, ObjectId>,
    sorted_names: BTreeSet<String>,
}

fn packed_refs_from_map(map: HashMap<String, ObjectId>) -> PackedRefs {
    let sorted_names = map.keys().cloned().collect();
    PackedRefs { map, sorted_names }
}

impl PackedRefs {
    /// Load the `packed-refs` snapshot for the ref store backing `git_dir` (the
    /// shared common dir for linked worktrees). A missing file yields an empty
    /// snapshot; reftable repositories also yield an empty snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] if `packed-refs` exists but cannot be read, or
    /// [`Error::PackedRefsUnexpectedLine`] when the file contains lines Git would reject.
    pub fn load(git_dir: &Path) -> Result<Self> {
        let store = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
        let map = read_packed_refs_map(&store)?;
        Ok(packed_refs_from_map(map))
    }

    /// The packed value recorded for `refname`, if any.
    #[must_use]
    pub fn get(&self, refname: &str) -> Option<ObjectId> {
        self.map.get(refname).copied()
    }

    /// Whether any packed ref name conflicts with `refname` as a path prefix
    /// (e.g. an existing `refs/heads/x` blocks creating `refs/heads/x/y`).
    /// Mirrors the internal `packed_ref_namespace_conflict` helper against the snapshot.
    #[must_use]
    pub fn has_namespace_conflict(&self, refname: &str) -> bool {
        packed_refname_namespace_conflict(&self.sorted_names, refname)
    }

    /// Record a ref written as loose during a cached apply batch so later
    /// namespace checks in the same batch see it without reloading `packed-refs`.
    pub(crate) fn record_loose_write(&mut self, refname: &str, oid: ObjectId) {
        self.map.insert(refname.to_owned(), oid);
        self.sorted_names.insert(refname.to_owned());
    }
}

/// Resolve `refname` to its current object id using a preloaded [`PackedRefs`]
/// snapshot instead of re-reading `packed-refs`. Loose refs win over packed
/// (matching [`resolve_ref`]); a symbolic loose ref falls back to the full
/// [`resolve_ref`] resolver (rare for the tracking/tag refs this is used for).
/// Returns `Ok(None)` when the ref does not exist.
///
/// # Errors
///
/// Returns an error on ref-file I/O failures other than "not found".
pub fn resolve_ref_cached(
    git_dir: &Path,
    refname: &str,
    packed: &PackedRefs,
) -> Result<Option<ObjectId>> {
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return Ok(resolve_ref(git_dir, refname).ok());
    }
    resolve_files_ref_cached(git_dir, refname, packed)
}

/// Resolves many refs of one repository with the storage format detected and
/// `packed-refs` loaded once, instead of per ref as [`resolve_ref_cached`] does.
pub(crate) struct CachedRefResolver<'a> {
    git_dir: &'a Path,
    /// `Some` for the files backend; `None` for reftable, which resolves directly.
    packed: Option<PackedRefs>,
}

impl<'a> CachedRefResolver<'a> {
    /// Open a resolver for `git_dir`.
    ///
    /// # Errors
    ///
    /// Returns an error when the ref store format cannot be detected or
    /// `packed-refs` cannot be read.
    pub(crate) fn open(git_dir: &'a Path) -> Result<Self> {
        let packed = if open_ref_store(git_dir)?.format() == RefStorageFormat::Files {
            Some(PackedRefs::load(git_dir)?)
        } else {
            None
        };
        Ok(Self { git_dir, packed })
    }

    /// Resolve `refname` with the same rules as [`resolve_ref_cached`].
    /// Returns `Ok(None)` when the ref does not exist.
    ///
    /// # Errors
    ///
    /// Returns an error on ref-file I/O failures other than "not found".
    pub(crate) fn resolve(&self, refname: &str) -> Result<Option<ObjectId>> {
        match &self.packed {
            Some(packed) => resolve_files_ref_cached(self.git_dir, refname, packed),
            None => Ok(resolve_ref(self.git_dir, refname).ok()),
        }
    }
}

fn resolve_files_ref_cached(
    git_dir: &Path,
    refname: &str,
    packed: &PackedRefs,
) -> Result<Option<ObjectId>> {
    let (store, stor_name) = crate::worktree_ref::resolve_ref_storage(git_dir, refname);
    let storage_owned = crate::ref_namespace::storage_ref_name(&stor_name);
    let try_names: Vec<&str> = if storage_owned != stor_name {
        vec![storage_owned.as_str(), stor_name.as_str()]
    } else {
        vec![stor_name.as_str()]
    };

    for name in &try_names {
        let path = store.join(name);
        match read_ref_file(&path) {
            Ok(Ref::Direct(oid)) => return Ok(Some(oid)),
            Ok(Ref::Symbolic(target)) => return Ok(resolve_ref(git_dir, &target).ok()),
            Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
    }

    for name in &try_names {
        if let Some(oid) = packed.get(name) {
            return Ok(Some(oid));
        }
    }
    Ok(None)
}

/// Like [`write_ref`], but checks the packed-refs namespace conflict against a
/// preloaded [`PackedRefs`] snapshot instead of re-reading `packed-refs` on
/// every call. Behaves identically to [`write_ref`] otherwise.
///
/// # Errors
///
/// Returns [`Error::InvalidRef`] when `refname` is not safe for ref storage, on a namespace
/// conflict, or [`Error::Io`] / [`Error::Message`] on filesystem errors.
pub fn write_ref_cached(
    git_dir: &Path,
    refname: &str,
    oid: &ObjectId,
    packed: &mut PackedRefs,
) -> Result<()> {
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return write_ref(git_dir, refname, oid);
    }
    ensure_refname_safe_for_storage(refname)?;
    if packed.has_namespace_conflict(refname) {
        return Err(Error::InvalidRef(format!(
            "cannot update ref '{refname}': reference namespace conflict"
        )));
    }
    let storage_dir = ref_storage_dir(git_dir, refname);
    write_ref_at_storage(git_dir, &storage_dir, refname, oid)?;
    packed.record_loose_write(refname, *oid);
    Ok(())
}

/// Render a ref-store path for user-facing diagnostics the way Git does: relative to the
/// current working directory when possible (e.g. `.git/refs/foo/bar`), otherwise the full
/// path. Git builds these paths relative to the worktree root, so under the normal in-tree
/// case this yields the `.git/...` form that the upstream tests expect.
fn ref_path_for_display(path: &Path) -> String {
    let cwd = crate::environment::Environment::empty().cwd.clone();
    if let Ok(rel) = path.strip_prefix(&cwd) {
        return rel.to_string_lossy().into_owned();
    }
    // On platforms where the cwd and the (canonicalized) ref path disagree only by a
    // symlinked prefix (e.g. macOS `/tmp` -> `/private/tmp`), retry with both sides
    // canonicalized so the relative form is still recovered.
    if let (Ok(cwd_c), Ok(path_c)) = (cwd.canonicalize(), path.canonicalize()) {
        if let Ok(rel) = path_c.strip_prefix(&cwd_c) {
            return rel.to_string_lossy().into_owned();
        }
    }
    path.to_string_lossy().into_owned()
}

/// Remove the directory at `path` if it is an empty directory tree (contains only empty
/// directories, no regular files or lock files). Best-effort: returns silently on any error or
/// if `path` is not a directory. Mirrors Git's `remove_empty_directories`
/// (`remove_dir_recursively(REMOVE_DIR_EMPTY_ONLY)`), used to clear stale directories that sit
/// where a ref file must be created or deleted.
pub(crate) fn remove_empty_ref_directory(path: &Path) {
    match fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_dir() => {}
        _ => return,
    }
    // `remove_dir_all` would also delete files; we only want to remove trees that are entirely
    // empty of files. `fs::remove_dir` fails (non-empty) unless we recurse, so walk first.
    if dir_tree_has_files(path) {
        return;
    }
    let _ = remove_dir_tree(path);
}

/// Return true if the directory tree rooted at `dir` contains any non-directory entry.
fn dir_tree_has_files(dir: &Path) -> bool {
    let Ok(entries) = fs::read_dir(dir) else {
        // Unreadable: treat conservatively as "has files" so we do not delete it.
        return true;
    };
    for entry in entries.flatten() {
        match entry.file_type() {
            Ok(ft) if ft.is_dir() => {
                if dir_tree_has_files(&entry.path()) {
                    return true;
                }
            }
            Ok(_) => return true, // a file, symlink, or `*.lock`
            Err(_) => return true,
        }
    }
    false
}

/// Walk upward from `ref_path`'s parent, removing empty directories until `refs/`.
pub(crate) fn prune_empty_loose_ref_parents(storage_dir: &Path, ref_path: &Path) {
    let refs_root = storage_dir.join("refs");
    let mut current = ref_path.parent();
    while let Some(dir) = current {
        if dir == refs_root.as_path() || !dir.starts_with(&refs_root) {
            break;
        }
        if dir_tree_has_files(dir) {
            break;
        }
        if fs::remove_dir(dir).is_err() {
            break;
        }
        current = dir.parent();
    }
}

/// Recursively remove an empty directory tree (assumes [`dir_tree_has_files`] returned false).
fn remove_dir_tree(dir: &Path) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            remove_dir_tree(&entry.path())?;
        }
    }
    fs::remove_dir(dir)
}

/// Delete a ref.
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// # Errors
///
/// Returns [`RefStoreError::NotFound`](store::RefStoreError::NotFound) (inside
/// [`Error::RefStore`]) when `refname` does not exist, [`Error::InvalidRef`] when it is not
/// safe for ref storage, or [`Error::Io`] for filesystem failures.
pub fn delete_ref(git_dir: &Path, refname: &str) -> Result<()> {
    if matches!(read_raw_ref(git_dir, refname)?, RawRefLookup::NotFound) {
        return Err(store::RefStoreError::not_found(refname).into());
    }
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        let store = open_ref_store(git_dir)?;
        let mut flags = legacy_ref_update_flags(refname);
        if refname != "HEAD" {
            if let Ok(Some(StoreRawRef::Symbolic(_))) = store.read_raw(refname) {
                flags.no_deref = true;
            }
        }
        return commit_store_update(
            git_dir,
            RefUpdate {
                name: refname.to_owned(),
                new_value: None,
                expected: Expected::Exists,
                reflog: None,
                flags,
            },
        )
        .map_err(|e| map_public_ref_store_error(e, refname));
    }
    ensure_refname_safe_for_storage(refname)?;
    let storage_dir = ref_storage_dir(git_dir, refname);
    let stor = crate::ref_namespace::storage_ref_name(refname);
    let path = storage_dir.join(&stor);
    let lock = lock_path_for_ref(&path);
    if fs::symlink_metadata(&lock).is_ok() {
        return Err(Error::Io(io::Error::new(
            io::ErrorKind::AlreadyExists,
            format!("ref lock present: {}", lock.display()),
        )));
    }

    // Remove the packed-refs entry *first* (acquiring the packed-refs lock). Git deletes the
    // packed version while holding the lock before unlinking the loose ref, so that a failure to
    // rewrite packed-refs (lock held, stale `packed-refs.new`, ...) leaves the reference fully
    // intact rather than dropping the loose file and exposing a stale packed value. See t0600
    // "delete fails cleanly if packed-refs file is locked / .new write fails".
    remove_packed_ref(&storage_dir, &stor)?;

    // Remove the loose ref file. An empty directory tree may occupy the ref path (a leftover
    // from a previously deleted nested ref); clear it so the delete succeeds rather than failing
    // with "Is a directory" (see t0600 "empty directory should not fool 0/1-arg delete").
    remove_empty_ref_directory(&path);
    match fs::remove_file(&path) {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
        Err(e)
            if e.kind() == io::ErrorKind::NotADirectory
                || e.raw_os_error() == Some(libc::ENOTDIR) => {}
        // The path is (still) a directory — e.g. a non-empty tree we declined to remove.
        // Treat as "loose ref not present"; the packed-refs entry was already removed above.
        Err(e)
            if e.raw_os_error() == Some(libc::EISDIR) || e.raw_os_error() == Some(libc::EPERM) => {}
        Err(e) => return Err(Error::Io(e)),
    }

    prune_empty_loose_ref_parents(&storage_dir, &path);

    let log_path = storage_dir.join("logs").join(&stor);

    // Remove the ref's reflog and clean up empty parent directories, matching Git's
    // `files_transaction_finish` (which deletes the reflog of any deleted ref and then calls
    // `try_remove_empty_parents`). Leaving the reflog behind would block a later nested ref
    // (e.g. deleting `k/l` then creating `k/l/m`, which needs `logs/refs/heads/k/l` to be a
    // directory) — see t0601 and t1410 "stale dirs do not cause d/f conflicts".
    let _ = fs::remove_file(&log_path);

    let logs_root = storage_dir.join("logs");
    let mut parent = log_path.parent();
    while let Some(p) = parent {
        if p == logs_root.as_path() || !p.starts_with(&logs_root) {
            break;
        }
        if fs::remove_dir(p).is_err() {
            break; // not empty or other error
        }
        parent = p.parent();
    }

    Ok(())
}

/// Remove a single entry from the packed-refs file, rewriting it.
pub(crate) fn remove_packed_ref(git_dir: &Path, refname: &str) -> Result<()> {
    remove_packed_ref_inner(git_dir, refname, false)
}

pub(crate) fn remove_packed_ref_under_lock(git_dir: &Path, refname: &str) -> Result<()> {
    remove_packed_ref_inner(git_dir, refname, true)
}

fn remove_packed_ref_inner(git_dir: &Path, refname: &str, lock_already_held: bool) -> Result<()> {
    let packed_path = store::paths::packed_refs_path(git_dir);
    let content = match fs::read(&packed_path) {
        Ok(c) => c,
        Err(e)
            if e.kind() == io::ErrorKind::NotFound
                || e.kind() == io::ErrorKind::NotADirectory
                || e.raw_os_error() == Some(libc::ENOTDIR) =>
        {
            return Ok(());
        }
        Err(e) => return Err(Error::Io(e)),
    };
    // Fail before mutating anything if the on-disk file is not readable like Git's.
    parse_packed_refs_to_map(&packed_path, &content)?;

    let content = String::from_utf8(content)
        .map_err(|_| packed_refs_unexpected_line(&packed_path, "<invalid utf-8>"))?;

    let mut out = String::new();
    let mut skip_peeled = false;
    let mut changed = false;
    // Write a fresh header (don't preserve old comment lines — real git
    // regenerates the header on every rewrite).
    let mut header_written = false;

    for line in content.lines() {
        if skip_peeled {
            if line.starts_with('^') {
                changed = true;
                continue;
            }
            skip_peeled = false;
        }

        if line.starts_with('#') {
            // Skip old header lines — we'll write a fresh one
            continue;
        }
        if line.starts_with('^') {
            out.push_str(line);
            out.push('\n');
            continue;
        }

        // Write fresh header before the first data line
        if !header_written {
            out.insert_str(0, "# pack-refs with: peeled fully-peeled sorted\n");
            header_written = true;
        }

        // Check if this line matches the ref to remove
        let mut parts = line.splitn(2, ' ');
        let _hash = parts.next().unwrap_or("");
        let name = parts.next().unwrap_or("").trim();
        if name == refname {
            changed = true;
            skip_peeled = true;
            continue;
        }

        out.push_str(line);
        out.push('\n');
    }

    if changed {
        // Git rewrites packed-refs under two files: it first takes the `packed-refs.lock`
        // lockfile (failing if another process holds it), then writes the new content to the
        // `packed-refs.new` tempfile and renames it over `packed-refs`. Mirror both so that
        // `update-ref -d` fails cleanly — leaving the reference intact — when either file is
        // already present (t0600 "delete fails cleanly if packed-refs file is locked / .new
        // write fails").
        let lock = lock_path_for_ref(&packed_path); // packed-refs.lock
        let _packed_lock = if !lock_already_held {
            let abs_lock = fs::canonicalize(git_dir)
                .map(|d| d.join("packed-refs.lock"))
                .unwrap_or_else(|_| lock.clone());
            Some(acquire_packed_refs_lock(git_dir, &lock, &abs_lock)?)
        } else {
            None
        };

        let tmp = packed_path.with_extension("new");
        let mut created_tmp = false;
        let write_result = (|| -> Result<()> {
            // Staged packed-refs body (not a lock file); exclusive create avoids clobber.
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&tmp)
                .map_err(Error::Io)?;
            created_tmp = true;
            use std::io::Write as _;
            file.write_all(out.as_bytes()).map_err(Error::Io)?;
            drop(file);
            fs::rename(&tmp, &packed_path).map_err(Error::Io)?;
            created_tmp = false; // consumed by rename
            Ok(())
        })();

        if write_result.is_err() && created_tmp {
            let _ = fs::remove_file(&tmp);
        }
        write_result?;
    }

    Ok(())
}

/// Read the symbolic ref target of `HEAD`.
///
/// Returns `None` if HEAD is detached (points directly to a commit hash).
///
/// # Errors
///
/// Returns [`Error::Io`] or [`Error::InvalidRef`] on failures.
pub fn read_head(git_dir: &Path) -> Result<Option<String>> {
    read_symbolic_ref(git_dir, "HEAD")
}

/// Read symbolic target of any ref.
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// Returns `Ok(Some(target))` when `refname` exists and is symbolic,
/// `Ok(None)` when it is direct or missing.
pub fn read_symbolic_ref(git_dir: &Path, refname: &str) -> Result<Option<String>> {
    match open_ref_store(git_dir)?.read_raw(refname)? {
        Some(StoreRawRef::Symbolic(target)) => Ok(Some(target)),
        Some(StoreRawRef::Direct(_)) | None => Ok(None),
    }
}

/// Like [`read_symbolic_ref`] but uses an open [`crate::repo::Repository`] ref store (no format re-detection).
pub fn read_symbolic_ref_for_repository(
    repo: &crate::repo::Repository,
    refname: &str,
) -> Result<Option<String>> {
    match repo.refs().read_raw(refname)? {
        Some(StoreRawRef::Symbolic(target)) => Ok(Some(target)),
        Some(StoreRawRef::Direct(_)) | None => Ok(None),
    }
}

/// Core `logAllRefUpdates` modes (after config lookup), matching Git's `log_refs_config`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogRefsConfig {
    /// `core.logAllRefUpdates` not set; resolved per-repo (bare vs non-bare).
    Unset,
    /// Explicitly disabled.
    None,
    /// `true` — log branch-like refs only (see [`should_autocreate_reflog`]).
    Normal,
    /// `always` — log updates to any ref.
    Always,
}

impl LogRefsConfig {
    /// Parse a `core.logAllRefUpdates` value; `None` when it is not a recognised mode.
    pub(crate) fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "always" => Some(Self::Always),
            "1" | "true" | "yes" | "on" => Some(Self::Normal),
            "0" | "false" | "no" | "off" | "never" => Some(Self::None),
            _ => None,
        }
    }
}

/// Read `[core] logAllRefUpdates` from the repository config.
///
/// Returns [`LogRefsConfig::Unset`] when the key is absent.
pub fn read_log_refs_config(git_dir: &Path) -> LogRefsConfig {
    ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(git_dir),
        true,
    )
    .map(|cfg| cfg.log_refs_config())
    .unwrap_or(LogRefsConfig::Unset)
}

/// Effective `logAllRefUpdates` after applying Git's `LOG_REFS_UNSET` rule.
///
/// Falls back to [`LogRefsConfig::Normal`] when the config cannot be loaded.
pub fn effective_log_refs_config(git_dir: &Path) -> LogRefsConfig {
    ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(git_dir),
        true,
    )
    .map(|cfg| cfg.effective_log_refs_config())
    .unwrap_or(LogRefsConfig::Normal)
}

/// Whether a new reflog file may be auto-created for `refname` given an already-resolved
/// `core.logAllRefUpdates` mode (including command-line config).
#[must_use]
pub fn should_autocreate_reflog_for_mode(refname: &str, mode: LogRefsConfig) -> bool {
    match mode {
        LogRefsConfig::Always => true,
        LogRefsConfig::Normal => {
            refname == "HEAD"
                || refname.starts_with("refs/heads/")
                || refname.starts_with("refs/remotes/")
                || refname.starts_with("refs/notes/")
        }
        LogRefsConfig::None | LogRefsConfig::Unset => false,
    }
}

/// Whether a new reflog file may be auto-created for `refname` (Git `should_autocreate_reflog`).
#[must_use]
pub fn should_autocreate_reflog(git_dir: &Path, refname: &str) -> bool {
    should_autocreate_reflog_for_mode(refname, effective_log_refs_config(git_dir))
}

/// Like [`should_autocreate_reflog`], using an already-loaded repository config snapshot.
#[must_use]
pub fn should_autocreate_reflog_with_config(
    config: &ConfigSet,
    _git_dir: &Path,
    refname: &str,
) -> bool {
    should_autocreate_reflog_for_mode(refname, config.effective_log_refs_config())
}

/// Write a reflog entry.
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// # Parameters
///
/// - `git_dir` — path to the git directory.
/// - `refname` — reference name (e.g. `"refs/heads/main"`).
/// - `old_oid` — previous OID (use `ObjectId::from_bytes(&[0;20])` for a new ref).
/// - `new_oid` — new OID.
/// - `identity` — `"Name <email> <timestamp> <tz>"` formatted string.
/// - `message` — short log message.
/// - `force_create` — if true, create the log file even when [`should_autocreate_reflog`] would not.
///
/// # Errors
///
/// Returns [`Error::Io`] on filesystem errors.
/// Remove stale reflog *files* that occupy path components which must become directories.
///
/// When a branch is deleted we keep its reflog file (so `branch -D` + later recreate can
/// retain history). If a later nested branch (e.g. `k/l/m`) needs `logs/refs/heads/k/l` to be
/// a directory, the leftover file at that path blocks `create_dir_all`. Walk from `logs_root`
/// down toward `target` and remove any regular file sitting where a directory is required, so
/// the directory can be created. Best-effort: filesystem errors are ignored (the subsequent
/// `create_dir_all` surfaces any real problem).
fn clear_conflicting_reflog_files(logs_root: &Path, target: &Path) {
    let Ok(rel) = target.strip_prefix(logs_root) else {
        return;
    };
    let mut cur = logs_root.to_path_buf();
    for component in rel.components() {
        cur.push(component);
        match fs::symlink_metadata(&cur) {
            Ok(meta) if meta.file_type().is_dir() => {}
            Ok(_) => {
                // A non-directory (stale reflog file or symlink) is in the way of a needed
                // directory. Remove it so the directory hierarchy can be created.
                let _ = fs::remove_file(&cur);
            }
            Err(_) => break, // does not exist yet (or unreadable); nothing more to clear
        }
    }
}

/// Render a reflog entry's `(old, new)` OIDs as hex, widening a null OID to the
/// width of the non-null side so the line matches the repository hash algorithm.
pub(crate) fn reflog_oid_hex_pair(old: &ObjectId, new: &ObjectId) -> (String, String) {
    let width = if !old.is_zero() {
        old.algo().hex_len()
    } else if !new.is_zero() {
        new.algo().hex_len()
    } else {
        old.algo().hex_len()
    };
    let render = |oid: &ObjectId| {
        if oid.is_zero() {
            "0".repeat(width)
        } else {
            oid.to_hex()
        }
    };
    (render(old), render(new))
}

/// Append one line to the reflog for `refname`.
///
/// Creates the reflog file when `force_create` is true or when the ref already
/// has a reflog. Identity and message are written in Git's standard reflog format.
///
/// # Errors
///
/// Propagates I/O failures and invalid refname errors.
pub fn append_reflog(
    git_dir: &Path,
    refname: &str,
    old_oid: &ObjectId,
    new_oid: &ObjectId,
    identity: &str,
    message: &str,
    force_create: bool,
) -> Result<()> {
    append_reflog_with_config(
        git_dir,
        refname,
        old_oid,
        new_oid,
        identity,
        message,
        force_create,
        None,
    )
}

/// Like [`append_reflog`], reusing `config` for reflog auto-create policy when provided.
#[allow(clippy::too_many_arguments)]
pub fn append_reflog_with_config(
    git_dir: &Path,
    refname: &str,
    old_oid: &ObjectId,
    new_oid: &ObjectId,
    identity: &str,
    message: &str,
    force_create: bool,
    config: Option<&ConfigSet>,
) -> Result<()> {
    test_inject_reflog_fail(refname)?;
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return crate::reftable::reftable_append_reflog(
            git_dir,
            refname,
            old_oid,
            new_oid,
            identity,
            message,
            force_create,
        );
    }
    let storage_dir = ref_storage_dir(git_dir, refname);
    let stor = crate::ref_namespace::storage_ref_name(refname);
    let log_path = storage_dir.join("logs").join(&stor);
    let may_create = force_create
        || match config {
            Some(cfg) => should_autocreate_reflog_with_config(cfg, git_dir, refname),
            None => should_autocreate_reflog(git_dir, refname),
        };
    if !may_create && !log_path.exists() {
        return Ok(());
    }
    if let Some(parent) = log_path.parent() {
        // A stale reflog *file* left behind by a deleted branch (e.g. `logs/refs/heads/k/l`)
        // can occupy a path component that must now become a directory (for `k/l/m`). Git
        // removes such leftovers while creating the reflog; mirror that so `create_dir_all`
        // does not fail with "File exists" / "Not a directory".
        let logs_root = storage_dir.join("logs");
        clear_conflicting_reflog_files(&logs_root, parent);
        fs::create_dir_all(parent)?;
    }
    // A reflog records `<old> <new>` at the repository's hash width. The null
    // ("0000…") side of a ref creation/deletion is stored at SHA-1 width by
    // callers; widen it to match the non-null side so sha256 reflogs are
    // internally consistent (and re-parseable).
    let (old_hex, new_hex) = reflog_oid_hex_pair(old_oid, new_oid);
    let line = if message.is_empty() {
        format!("{old_hex} {new_hex} {identity}\n")
    } else {
        format!("{old_hex} {new_hex} {identity}\t{message}\n")
    };
    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)?;
    use io::Write;
    file.write_all(line.as_bytes())?;
    Ok(())
}

fn pack_ref_include_pattern(all: bool) -> &'static [u8] {
    if all {
        b"*"
    } else {
        b"refs/tags/*"
    }
}

fn ref_matches_pack_include(refname: &str, all: bool) -> bool {
    crate::wildmatch::wildmatch(pack_ref_include_pattern(all), refname.as_bytes(), 0)
}

fn collect_loose_ref_files(
    dir: &Path,
    prefix: &str,
    out: &mut Vec<(String, PathBuf)>,
) -> Result<()> {
    let read = match fs::read_dir(dir) {
        Ok(r) => r,
        Err(e)
            if e.kind() == io::ErrorKind::NotFound
                || e.kind() == io::ErrorKind::NotADirectory
                || e.raw_os_error() == Some(libc::ENOTDIR) =>
        {
            return Ok(());
        }
        Err(e) => return Err(Error::Io(e)),
    };
    for entry in read {
        let entry = entry?;
        let name = entry.file_name().to_string_lossy().to_string();
        let refname = format!("{prefix}{name}");
        let path = entry.path();
        if path.is_dir() {
            collect_loose_ref_files(&path, &format!("{refname}/"), out)?;
        } else if path.is_file() {
            out.push((refname, path));
        }
    }
    Ok(())
}

fn load_packed_refs_with_peel(
    packed_path: &Path,
    merged: &mut HashMap<String, (ObjectId, Option<ObjectId>)>,
) -> Result<()> {
    if !packed_path.is_file() {
        return Ok(());
    }
    let data = fs::read(packed_path)?;
    parse_packed_refs_to_map(packed_path, &data)?;
    let content = String::from_utf8(data)
        .map_err(|_| packed_refs_unexpected_line(packed_path, "<invalid utf-8>"))?;
    let mut last_name: Option<String> = None;
    for line in content.lines() {
        if line.starts_with('#') {
            continue;
        }
        if let Some(hex) = line.strip_prefix('^') {
            let Ok(peel_oid) = ObjectId::from_hex(hex.trim()) else {
                continue;
            };
            if let Some(name) = &last_name {
                if let Some(entry) = merged.get_mut(name) {
                    entry.1 = Some(peel_oid);
                }
            }
            continue;
        }
        let mut parts = line.splitn(2, ' ');
        let Some(hex) = parts.next() else {
            continue;
        };
        let Some(name) = parts.next() else {
            continue;
        };
        let name = name.trim();
        let Ok(oid) = ObjectId::from_hex(hex) else {
            continue;
        };
        merged.insert(name.to_owned(), (oid, None));
        last_name = Some(name.to_owned());
    }
    Ok(())
}

/// Pack loose refs for `repo` (files `packed-refs` or reftable compaction).
pub(crate) fn pack_refs_for_repository(
    repo: &crate::repo::Repository,
    all: bool,
) -> Result<(PathBuf, usize, usize)> {
    let git_dir = repo.git_dir();
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return pack_refs_reftable(git_dir);
    }
    pack_refs_files(git_dir, repo.odb(), all)
}

fn pack_refs_reftable(git_dir: &Path) -> Result<(PathBuf, usize, usize)> {
    use crate::reftable::ReftableStack;
    let store_git_dir = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
    let rt_dir = store_git_dir.join("reftable");
    let tables_before = fs::read_to_string(rt_dir.join("tables.list"))
        .map(|s| s.lines().filter(|l| !l.is_empty()).count())
        .unwrap_or(0);
    let mut stack = ReftableStack::open(&store_git_dir)?;
    stack.compact()?;
    let tables_after = fs::read_to_string(rt_dir.join("tables.list"))
        .map(|s| s.lines().filter(|l| !l.is_empty()).count())
        .unwrap_or(0);
    Ok((rt_dir, 0, tables_before.saturating_sub(tables_after)))
}

fn pack_refs_files(
    git_dir: &Path,
    odb: &crate::odb::Odb,
    all: bool,
) -> Result<(PathBuf, usize, usize)> {
    let storage_git_dir = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
    let packed_path = store::paths::packed_refs_path(&storage_git_dir);

    let mut merged: HashMap<String, (ObjectId, Option<ObjectId>)> = HashMap::new();
    load_packed_refs_with_peel(&packed_path, &mut merged)?;

    let mut loose_files = Vec::new();
    collect_loose_ref_files(&storage_git_dir.join("refs"), "refs/", &mut loose_files)?;

    let mut packed_loose = 0usize;
    let mut to_prune: Vec<(String, ObjectId)> = Vec::new();

    for (refname, path) in loose_files {
        if crate::worktree_ref::is_per_worktree_ref(&refname) {
            continue;
        }
        if !ref_matches_pack_include(&refname, all) {
            continue;
        }
        let Ok(Ref::Direct(oid)) = read_ref_file(&path) else {
            continue;
        };
        if odb.read(&oid).is_err() {
            continue;
        }
        let peel = if refname.starts_with("refs/tags/") {
            packed_ref_peel(odb, oid)
        } else {
            None
        };
        merged.insert(refname.clone(), (oid, peel));
        to_prune.push((refname, oid));
        let _ = path;
        packed_loose += 1;
    }

    if packed_loose == 0 && merged.is_empty() {
        return Ok((packed_path, 0, 0));
    }

    let mut names: Vec<String> = merged.keys().cloned().collect();
    names.sort();

    let mut body = String::from("# pack-refs with: peeled fully-peeled sorted\n");
    for name in &names {
        let Some((oid, peel)) = merged.get(name) else {
            continue;
        };
        body.push_str(&oid.to_hex());
        body.push(' ');
        body.push_str(name);
        body.push('\n');
        if let Some(p) = peel {
            body.push('^');
            body.push_str(&p.to_hex());
            body.push('\n');
        }
    }

    atomic_rewrite_packed_refs(&storage_git_dir, &body)?;

    #[cfg(test)]
    pack_refs_test_hooks::run_before_prune();

    let mut pruned = 0usize;
    for (refname, expected) in &to_prune {
        match prune_loose_ref_cas(git_dir, refname, *expected) {
            Ok(true) => pruned += 1,
            Ok(false) => {
                remove_packed_ref(git_dir, refname)?;
            }
            Err(e) => return Err(e),
        }
    }

    Ok((packed_path, packed_loose, pruned))
}

/// Test hook: runs once after `packed-refs` is rewritten and before loose refs are pruned.
#[cfg(test)]
mod pack_refs_test_hooks {
    use std::cell::RefCell;

    thread_local! {
        static BEFORE_PRUNE: RefCell<Option<Box<dyn Fn()>>> = const { RefCell::new(None) };
    }

    pub fn set_before_prune(f: Option<Box<dyn Fn()>>) {
        BEFORE_PRUNE.with(|c| *c.borrow_mut() = f);
    }

    pub fn run_before_prune() {
        BEFORE_PRUNE.with(|c| {
            if let Some(f) = c.borrow_mut().take() {
                f();
            }
        });
    }
}

/// Test hook: when set to a ref name, the next [`append_reflog`] for that ref fails.
///
/// Only active in debug builds; used by regression tests for commit ref/reflog atomicity.
#[cfg(test)]
mod reflog_fail_inject {
    use std::cell::RefCell;

    // hygiene: test-only reflog failure injection hook
    thread_local! {
        pub static INJECT: RefCell<Option<String>> = const { RefCell::new(None) };
    }
}

/// Test hook: fail the next reflog append for `refname` (or any ref when `None`).
#[cfg(test)]
pub fn set_test_inject_reflog_fail(refname: Option<&str>) {
    reflog_fail_inject::INJECT.with(|c| {
        *c.borrow_mut() = refname.map(str::to_owned);
    });
}

#[cfg(test)]
fn test_inject_reflog_fail(refname: &str) -> Result<()> {
    reflog_fail_inject::INJECT.with(|c| {
        if c.borrow().as_deref() == Some(refname) {
            return Err(Error::Io(std::io::Error::other("injected reflog failure")));
        }
        Ok(())
    })
}

#[cfg(not(test))]
fn test_inject_reflog_fail(_refname: &str) -> Result<()> {
    Ok(())
}

/// Move a checked-out branch to `new_oid` and append matching branch and `HEAD` reflogs.
///
/// Verifies `HEAD` is a symbolic ref to `branch_ref`, then runs a storage transaction:
/// on the files backend the branch ref lock is held from CAS through reflog writes and
/// ref commit; on reftable, branch and `HEAD` logs are written in one transaction.
/// Reflog failures before the ref commit do not advance the branch tip.
///
/// # Errors
///
/// Returns [`Error::Message`] when `HEAD` does not point at `branch_ref`,
/// [`store::RefStoreError::ExpectedMismatch`] (see [`verify_branch_commit_cas`]) when the
/// CAS check fails, or an I/O error when ref/reflog writes fail.
pub struct BranchCommitRefUpdate<'a> {
    /// Branch ref to update (e.g. `refs/heads/main`).
    pub branch_ref: &'a str,
    /// Expected current tip; `None` when the branch must not exist yet (unborn).
    pub expected_old: Option<ObjectId>,
    /// New commit OID for the branch tip.
    pub new_oid: ObjectId,
    /// Committer identity for reflog lines.
    pub identity: &'a str,
    /// Reflog message (without trailing newline).
    pub reflog_message: &'a str,
}

/// Compare expected and current branch tips for compare-and-swap ref updates.
///
/// `None` means the branch is absent (unborn) on either side.
///
/// # Errors
///
/// Returns [`Error::RefStore`] with [`store::RefStoreError::ExpectedMismatch`] when
/// `current` does not match `expected`; `expected` is [`Expected::Missing`] when the branch
/// had to be absent, and `actual` is `None` when it was.
pub fn verify_branch_commit_cas(
    expected: Option<ObjectId>,
    current: Option<ObjectId>,
    refname: &str,
) -> Result<()> {
    verify_branch_cas(expected, current, refname)
}

fn verify_branch_cas(
    expected: Option<ObjectId>,
    current: Option<ObjectId>,
    refname: &str,
) -> Result<()> {
    if expected == current {
        return Ok(());
    }
    Err(store::RefStoreError::ExpectedMismatch {
        name: refname.to_owned(),
        expected: expected.map_or(Expected::Missing, Expected::Oid),
        actual: current.map(StoreRawRef::Direct),
    }
    .into())
}

fn read_loose_or_packed_oid(git_dir: &Path, refname: &str) -> Result<Option<ObjectId>> {
    let (store, stor_name) = crate::worktree_ref::resolve_ref_storage(git_dir, refname);
    let storage_owned = crate::ref_namespace::storage_ref_name(&stor_name);
    let try_names: Vec<&str> = if storage_owned != stor_name {
        vec![storage_owned.as_str(), stor_name.as_str()]
    } else {
        vec![stor_name.as_str()]
    };
    for name in try_names {
        let path = store.join(name);
        if let Ok(Ref::Direct(oid)) = read_ref_file(&path) {
            return Ok(Some(oid));
        }
        if let Some(oid) = lookup_packed_ref(&store, name)? {
            return Ok(Some(oid));
        }
    }
    Ok(None)
}

#[cfg(test)]
mod test_pause_inject_serial {
    use std::sync::{Mutex, OnceLock};

    // hygiene: test-only pause injection serialization
    static SERIAL: OnceLock<Mutex<()>> = OnceLock::new();

    pub fn lock() -> std::sync::MutexGuard<'static, ()> {
        SERIAL
            .get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }
}

/// Serialize tests that install global ref pause injection hooks (parallel `cargo test` safe).
#[cfg(test)]
pub fn test_pause_injection_serial_guard() -> std::sync::MutexGuard<'static, ()> {
    test_pause_inject_serial::lock()
}

#[cfg(test)]
mod branch_ref_pause_inject {
    use std::sync::{Condvar, Mutex, OnceLock};

    pub struct PauseGate {
        pub wait: Mutex<bool>,
        pub cv: Condvar,
    }

    // hygiene: test-only branch-ref commit pause injection
    static PAUSE_BEFORE_COMMIT: OnceLock<Mutex<Option<std::sync::Arc<PauseGate>>>> =
        OnceLock::new();

    pub fn pause_slot() -> &'static Mutex<Option<std::sync::Arc<PauseGate>>> {
        PAUSE_BEFORE_COMMIT.get_or_init(|| Mutex::new(None))
    }
}

/// Synchronization gate used with [`set_test_inject_branch_ref_pause_before_commit`].
#[cfg(test)]
pub type BranchRefPauseGate = std::sync::Arc<branch_ref_pause_inject::PauseGate>;

/// Test-only: pause [`update_branch_for_commit`] on the files backend after reflogs, before committing the ref.
#[cfg(test)]
pub fn set_test_inject_branch_ref_pause_before_commit(gate: Option<BranchRefPauseGate>) {
    *branch_ref_pause_inject::pause_slot()
        .lock()
        .unwrap_or_else(|e| e.into_inner()) = gate;
}

#[cfg(test)]
fn test_branch_ref_pause_before_commit() {
    let gate = branch_ref_pause_inject::pause_slot()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    if let Some(gate) = gate {
        let mut wait = gate.wait.lock().unwrap_or_else(|e| e.into_inner());
        *wait = true;
        gate.cv.notify_all();
        while *wait {
            wait = gate.cv.wait(wait).unwrap_or_else(|e| e.into_inner());
        }
    }
}

#[cfg(not(test))]
fn test_branch_ref_pause_before_commit() {}

#[cfg(test)]
mod ref_store_batch_pause_inject {
    use std::sync::{Condvar, Mutex, OnceLock};

    pub struct PauseGate {
        pub wait: Mutex<bool>,
        pub cv: Condvar,
    }

    // hygiene: test-only ref-store batch commit pause injection
    /// Armed pause: ref index, the repository it applies to, and the gate.
    pub type PauseSlot = Option<(usize, std::path::PathBuf, std::sync::Arc<PauseGate>)>;

    static PAUSE_AFTER_REF_WRITE: OnceLock<Mutex<PauseSlot>> = OnceLock::new();

    pub fn pause_slot() -> &'static Mutex<PauseSlot> {
        PAUSE_AFTER_REF_WRITE.get_or_init(|| Mutex::new(None))
    }
}

/// Synchronization gate used with [`set_test_inject_ref_store_batch_pause_after_apply`].
#[cfg(test)]
pub type RefStoreBatchPauseGate = std::sync::Arc<ref_store_batch_pause_inject::PauseGate>;

/// Test-only: build a pause gate for [`set_test_inject_ref_store_batch_pause_after_apply`].
#[cfg(test)]
pub fn new_ref_store_batch_pause_gate() -> RefStoreBatchPauseGate {
    std::sync::Arc::new(ref_store_batch_pause_inject::PauseGate {
        wait: std::sync::Mutex::new(false),
        cv: std::sync::Condvar::new(),
    })
}

/// Test-only: pause files ref-store batch commit after persisting the ref at `apply_index` (0-based).
///
/// Only ref stores for `git_dir` pause, so tests running in parallel against
/// other repositories are unaffected.
#[cfg(test)]
pub fn set_test_inject_ref_store_batch_pause_after_apply(
    apply_index: usize,
    git_dir: &Path,
    gate: Option<RefStoreBatchPauseGate>,
) {
    *ref_store_batch_pause_inject::pause_slot()
        .lock()
        .unwrap_or_else(|e| e.into_inner()) = gate.map(|g| (apply_index, git_dir.to_path_buf(), g));
}

#[cfg(test)]
struct RefStorePauseTestSerial {
    /// Held while one test owns ref-store batch pause injection.
    holder: Option<std::thread::ThreadId>,
}

#[cfg(test)]
static REF_STORE_PAUSE_TEST_SERIAL: std::sync::Mutex<RefStorePauseTestSerial> =
    std::sync::Mutex::new(RefStorePauseTestSerial { holder: None });

/// Serialize ref-store batch pause injection tests and clear injection on drop.
#[cfg(test)]
pub(crate) struct RefStoreBatchPauseTestScope {
    _serial: std::sync::MutexGuard<'static, RefStorePauseTestSerial>,
}

#[cfg(test)]
pub(crate) fn ref_store_batch_pause_test_scope() -> RefStoreBatchPauseTestScope {
    let mut serial = REF_STORE_PAUSE_TEST_SERIAL
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    assert!(
        serial.holder.is_none(),
        "ref_store_batch_pause_test_scope must not nest"
    );
    serial.holder = Some(std::thread::current().id());
    set_test_inject_ref_store_batch_pause_after_apply(0, Path::new(""), None);
    RefStoreBatchPauseTestScope { _serial: serial }
}

#[cfg(test)]
impl Drop for RefStoreBatchPauseTestScope {
    fn drop(&mut self) {
        set_test_inject_ref_store_batch_pause_after_apply(0, Path::new(""), None);
        self._serial.holder = None;
    }
}

#[cfg(test)]
pub(crate) fn test_ref_store_batch_pause_after_ref_write(idx: usize, git_dir: &Path) {
    let slot = ref_store_batch_pause_inject::pause_slot()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    if let Some((target, target_dir, gate)) = slot {
        let same_repo = |a: &Path, b: &Path| {
            a == b || matches!((a.canonicalize(), b.canonicalize()), (Ok(a), Ok(b)) if a == b)
        };
        if idx != target || !same_repo(git_dir, &target_dir) {
            return;
        }
        let mut wait = gate.wait.lock().unwrap_or_else(|e| e.into_inner());
        *wait = true;
        gate.cv.notify_all();
        while *wait {
            wait = gate.cv.wait(wait).unwrap_or_else(|e| e.into_inner());
        }
    }
}

#[cfg(not(test))]
pub(crate) fn test_ref_store_batch_pause_after_ref_write(_idx: usize, _git_dir: &Path) {}

/// Loose branch ref lock held between CAS validation and the ref file commit.
///
/// Dropping without [`commit_branch_commit_ref_lock`](Self::commit) aborts the lock file.
pub struct BranchCommitRefLock {
    lock: Option<crate::lockfile::LockFile>,
    disarmed: bool,
}

impl BranchCommitRefLock {
    /// Acquire the branch ref lock and verify `expected_old` before worktree mutations.
    ///
    /// # Errors
    ///
    /// Same as [`update_branch_for_commit_with_config`], except no reflogs or ref write occur yet.
    pub fn acquire(
        git_dir: &Path,
        branch_ref: &str,
        expected_old: Option<ObjectId>,
    ) -> Result<Self> {
        ensure_refname_safe_for_storage(branch_ref)?;
        let storage_dir = ref_storage_dir(git_dir, branch_ref);
        if packed_ref_namespace_conflict(&storage_dir, branch_ref)? {
            return Err(Error::InvalidRef(format!(
                "cannot update ref '{}': reference namespace conflict",
                branch_ref
            )));
        }
        let stor = crate::ref_namespace::storage_ref_name(branch_ref);
        let path = storage_dir.join(&stor);
        remove_empty_ref_directory(&path);
        if fs::symlink_metadata(&path)
            .map(|m| m.file_type().is_dir())
            .unwrap_or(false)
        {
            let display = ref_path_for_display(&path);
            return Err(crate::error::RefLockError::DirectoryInTheWay {
                refname: branch_ref.to_owned(),
                path: display,
            }
            .into());
        }
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        let lock_path = lock_path_for_ref(&path);
        use crate::lockfile::{LockError, LockFile, LockWait};
        let wait = LockWait::files_ref_lock_for_git_dir(git_dir);
        let lock = LockFile::acquire(&lock_path, wait).map_err(|err| match err {
            LockError::Held { path } => {
                Error::Io(crate::lockfile::lock_held_as_ref_present(LockError::Held {
                    path,
                }))
            }
            LockError::Io { source, .. } => Error::Io(source),
        })?;

        let current = read_loose_or_packed_oid(git_dir, branch_ref)?;
        verify_branch_cas(expected_old, current, branch_ref)?;

        Ok(Self {
            lock: Some(lock),
            disarmed: false,
        })
    }

    /// Append branch and `HEAD` reflog entries while holding the lock from [`Self::acquire`].
    ///
    /// Intended to run before worktree checkout so reflog I/O failures do not leave the
    /// index or working tree ahead of `HEAD`.
    ///
    /// # Errors
    ///
    /// Returns I/O or reflog failures; the ref lock is aborted and any branch reflog line
    /// written in this call is truncated.
    pub fn write_reflogs(
        &mut self,
        git_dir: &Path,
        update: &BranchCommitRefUpdate<'_>,
        reflog_old: &ObjectId,
        config: &ConfigSet,
    ) -> Result<()> {
        write_branch_commit_reflogs(git_dir, self, update, reflog_old, config)
    }

    /// Write the new OID into the held lock file and rename it over the branch ref.
    ///
    /// Call after the worktree matches `update.new_oid` when splitting reflog work from checkout.
    ///
    /// # Errors
    ///
    /// Returns I/O failures; the ref lock is aborted unless the rename succeeds.
    pub fn finish_ref_commit(
        mut self,
        git_dir: &Path,
        update: &BranchCommitRefUpdate<'_>,
    ) -> Result<()> {
        finish_branch_commit_ref_lock_files(git_dir, &mut self, update)?;
        self.disarmed = true;
        Ok(())
    }

    /// Write reflogs and commit the branch ref while holding the lock from [`Self::acquire`].
    ///
    /// # Errors
    ///
    /// Returns I/O or reflog failures; the lock is aborted unless the ref commit succeeds.
    pub fn commit(
        mut self,
        git_dir: &Path,
        update: &BranchCommitRefUpdate<'_>,
        reflog_old: &ObjectId,
        config: &ConfigSet,
    ) -> Result<()> {
        write_branch_commit_reflogs(git_dir, &mut self, update, reflog_old, config)?;
        finish_branch_commit_ref_lock_files(git_dir, &mut self, update)?;
        self.disarmed = true;
        Ok(())
    }
}

impl Drop for BranchCommitRefLock {
    fn drop(&mut self) {
        drop(self.lock.take());
    }
}

fn write_branch_commit_reflogs(
    git_dir: &Path,
    lock: &mut BranchCommitRefLock,
    update: &BranchCommitRefUpdate<'_>,
    reflog_old: &ObjectId,
    config: &ConfigSet,
) -> Result<()> {
    let mut branch_reflog_written = false;
    if should_autocreate_reflog_with_config(config, git_dir, update.branch_ref) {
        match append_reflog_with_config(
            git_dir,
            update.branch_ref,
            reflog_old,
            &update.new_oid,
            update.identity,
            update.reflog_message,
            false,
            Some(config),
        ) {
            Ok(()) => branch_reflog_written = true,
            Err(err) => {
                drop(lock.lock.take());
                return Err(err);
            }
        }
    }

    if should_autocreate_reflog_with_config(config, git_dir, "HEAD") {
        if let Err(err) = append_reflog_with_config(
            git_dir,
            "HEAD",
            reflog_old,
            &update.new_oid,
            update.identity,
            update.reflog_message,
            false,
            Some(config),
        ) {
            if branch_reflog_written {
                let _ = crate::reflog::truncate_last_reflog_line(git_dir, update.branch_ref);
            }
            drop(lock.lock.take());
            return Err(err);
        }
    }

    Ok(())
}

fn finish_branch_commit_ref_lock_files(
    git_dir: &Path,
    lock: &mut BranchCommitRefLock,
    update: &BranchCommitRefUpdate<'_>,
) -> Result<()> {
    test_branch_ref_pause_before_commit();

    let storage_dir = ref_storage_dir(git_dir, update.branch_ref);
    let stor = crate::ref_namespace::storage_ref_name(update.branch_ref);
    let path = storage_dir.join(&stor);
    let content = format!("{}\n", update.new_oid);
    use crate::lockfile::LockError;
    use std::io::Write as _;
    let mut file_lock = lock
        .lock
        .take()
        .ok_or_else(|| Error::Message("branch ref lock already released".into()))?;
    file_lock.write_all(content.as_bytes()).map_err(Error::Io)?;
    file_lock.commit_to(&path).map_err(|err| match err {
        LockError::Io { source, .. } => Error::Io(source),
        LockError::Held { path } => {
            Error::Io(crate::lockfile::lock_held_as_ref_present(LockError::Held {
                path,
            }))
        }
    })?;
    Ok(())
}

fn update_branch_for_commit_files(
    git_dir: &Path,
    update: &BranchCommitRefUpdate<'_>,
    reflog_old: &ObjectId,
    config: &ConfigSet,
) -> Result<()> {
    let lock = BranchCommitRefLock::acquire(git_dir, update.branch_ref, update.expected_old)?;
    lock.commit(git_dir, update, reflog_old, config)
}

fn update_branch_for_commit_reftable(
    git_dir: &Path,
    update: &BranchCommitRefUpdate<'_>,
    reflog_old: &ObjectId,
) -> Result<()> {
    let current = resolve_ref(git_dir, update.branch_ref).ok();
    verify_branch_cas(update.expected_old, current, update.branch_ref)?;

    let mut updates = Vec::new();
    let branch_log = if should_autocreate_reflog(git_dir, update.branch_ref) {
        Some(crate::reftable::reftable_log_record_for_commit(
            git_dir,
            update.branch_ref,
            reflog_old,
            &update.new_oid,
            update.identity,
            update.reflog_message,
        )?)
    } else {
        None
    };
    updates.push(crate::reftable::ReftableTransactionUpdate {
        refname: update.branch_ref.to_owned(),
        value: Some(crate::reftable::RefValue::Val1(update.new_oid)),
        log: branch_log,
        expected_old: update.expected_old,
    });

    if should_autocreate_reflog(git_dir, "HEAD") {
        updates.push(crate::reftable::ReftableTransactionUpdate {
            refname: "HEAD".to_owned(),
            value: None,
            log: Some(crate::reftable::reftable_log_record_for_commit(
                git_dir,
                "HEAD",
                reflog_old,
                &update.new_oid,
                update.identity,
                update.reflog_message,
            )?),
            expected_old: None,
        });
    }

    crate::reftable::reftable_write_transaction(git_dir, updates)
}

/// Apply [`BranchCommitRefUpdate`]: branch CAS, ref write, branch + `HEAD` reflogs.
pub fn update_branch_for_commit(git_dir: &Path, update: &BranchCommitRefUpdate<'_>) -> Result<()> {
    let config = ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(git_dir),
        true,
    )
    .unwrap_or_default();
    update_branch_for_commit_with_config(git_dir, update, &config)
}

/// Like [`update_branch_for_commit`], using a repository config snapshot for reflog policy.
pub fn update_branch_for_commit_with_config(
    git_dir: &Path,
    update: &BranchCommitRefUpdate<'_>,
    config: &ConfigSet,
) -> Result<()> {
    let head_target = read_head(git_dir)?;
    if head_target.as_deref() != Some(update.branch_ref) {
        return Err(Error::Message(format!(
            "HEAD does not point at branch '{}'",
            update.branch_ref
        )));
    }

    let reflog_old = update.expected_old.unwrap_or_else(crate::diff::zero_oid);

    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return update_branch_for_commit_reftable(git_dir, update, &reflog_old);
    }

    update_branch_for_commit_files(git_dir, update, &reflog_old, config)
}

/// Advance detached `HEAD` to a new commit with CAS and optional `HEAD` reflog.
///
/// Uses the ref store (files or reftable) so detached tips stored only in `.git/HEAD`
/// participate in CAS the same way as branch updates.
///
/// # Errors
///
/// Returns [`Error::Message`] when `HEAD` is symbolic (not detached),
/// [`store::RefStoreError::ExpectedMismatch`] when the CAS check fails, or an I/O error
/// when ref/reflog writes fail.
pub(crate) fn update_detached_head_for_commit_with_config(
    git_dir: &Path,
    expected_old: Option<ObjectId>,
    new_oid: ObjectId,
    identity: &str,
    reflog_message: &str,
    config: &ConfigSet,
) -> Result<()> {
    if read_head(git_dir)?.is_some() {
        return Err(Error::Message(
            "HEAD points at a branch; use update_branch_for_commit".into(),
        ));
    }
    let current = resolve_ref(git_dir, "HEAD").ok();
    verify_branch_cas(expected_old, current, "HEAD")?;
    let reflog_old = expected_old.unwrap_or_else(crate::diff::zero_oid);

    write_ref_cas(git_dir, "HEAD", &new_oid, reflog_old)?;
    if should_autocreate_reflog_with_config(config, git_dir, "HEAD") {
        if let Err(err) = append_reflog_with_config(
            git_dir,
            "HEAD",
            &reflog_old,
            &new_oid,
            identity,
            reflog_message,
            false,
            Some(config),
        ) {
            let _ = write_ref_cas(git_dir, "HEAD", &reflog_old, new_oid);
            return Err(err);
        }
    }
    Ok(())
}

/// Filesystem path to the reflog file for `refname` (same layout as [`append_reflog`]).
///
/// Branch and tag reflogs live under the shared [`common_dir`] when the repository uses a
/// `commondir` link (linked worktrees / `git clone --shared` member repos); `HEAD` stays under
/// `git_dir`.
#[must_use]
pub fn reflog_file_path(git_dir: &Path, refname: &str) -> PathBuf {
    let (store, stor_name) = crate::worktree_ref::resolve_ref_storage(git_dir, refname);
    store.join("logs").join(stor_name)
}

fn ref_storage_dir(git_dir: &Path, refname: &str) -> PathBuf {
    crate::worktree_ref::resolve_ref_storage(git_dir, refname).0
}

/// Normalize a ref prefix for filesystem traversal and packed-ref filtering.
///
/// Loose refs live in a directory tree mirroring ref names. A prefix like
/// `refs/remotes/origin` (no trailing slash) must map to the `origin/` directory
/// under `refs/remotes/`, not to a sibling file named `origin`. When the prefix
/// already names a **single loose ref file** (e.g. `refs/heads/main`), keep it
/// without a trailing slash so we read that file instead of a non-existent
/// directory.
fn normalize_list_refs_prefix(git_dir: &Path, prefix: &str) -> String {
    if prefix.is_empty() {
        return String::new();
    }
    if prefix.ends_with('/') {
        return prefix.to_string();
    }
    let candidate = ref_storage_dir(git_dir, prefix).join(prefix);
    if candidate.is_file() {
        prefix.to_string()
    } else {
        format!("{prefix}/")
    }
}

/// The `^` line of a `fully-peeled` `packed-refs` entry: the innermost non-tag object when `oid`
/// is an annotated tag. Lightweight refs, and tags whose chain cannot be read, get no peel line.
fn packed_ref_peel(odb: &crate::odb::Odb, oid: ObjectId) -> Option<ObjectId> {
    odb.peel_tag_target(oid).ok().flatten()
}

/// After the first clone fetch, batch remote-tracking refs into `packed-refs`
/// (Git's post-clone layout). Leaves `refs/remotes/{remote}/HEAD` as a loose
/// symbolic ref.
///
/// # Errors
///
/// Returns [`Error::Io`] on filesystem failures, or when a tag peel cannot be read.
pub fn pack_remote_tracking_refs_for_clone(git_dir: &Path, remote: &str) -> Result<()> {
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return Ok(());
    }
    let prefix = format!("refs/remotes/{remote}/");
    let head_sym = format!("refs/remotes/{remote}/HEAD");
    let mut entries = list_refs(git_dir, &prefix)?;
    entries.retain(|(name, _)| name != &head_sym);
    if entries.is_empty() {
        return Ok(());
    }
    entries.sort_by(|a, b| a.0.cmp(&b.0));

    let odb =
        crate::odb::Odb::new(&git_dir.join("objects")).with_config_git_dir(git_dir.to_path_buf());
    let mut merged: HashMap<String, (ObjectId, Option<ObjectId>)> = HashMap::new();
    let packed_path = store::paths::packed_refs_path(git_dir);
    if let Ok(data) = fs::read(&packed_path) {
        parse_packed_refs_to_map(&packed_path, &data)?;
        let content = String::from_utf8(data)
            .map_err(|_| packed_refs_unexpected_line(&packed_path, "<invalid utf-8>"))?;
        let mut last_name: Option<String> = None;
        for line in content.split('\n') {
            if line.starts_with('#') {
                continue;
            }
            if let Some(hex) = line.strip_prefix('^') {
                let Ok(peel_oid) = ObjectId::from_hex(hex.trim()) else {
                    continue;
                };
                if let Some(name) = &last_name {
                    if let Some(entry) = merged.get_mut(name) {
                        entry.1 = Some(peel_oid);
                    }
                }
                continue;
            }
            let mut parts = line.splitn(2, ' ');
            let Some(hex) = parts.next() else {
                continue;
            };
            let Some(name) = parts.next() else {
                continue;
            };
            let name = name.trim();
            let Ok(oid) = ObjectId::from_hex(hex) else {
                continue;
            };
            if name.starts_with(&prefix) {
                last_name = None;
                continue;
            }
            merged.insert(name.to_owned(), (oid, None));
            last_name = Some(name.to_owned());
        }
    }

    for (name, oid) in &entries {
        merged.insert(name.clone(), (*oid, packed_ref_peel(&odb, *oid)));
    }

    let mut names: Vec<String> = merged.keys().cloned().collect();
    names.sort();

    let mut body = String::from("# pack-refs with: peeled fully-peeled sorted\n");
    for name in &names {
        let Some((oid, peel)) = merged.get(name) else {
            continue;
        };
        body.push_str(&oid.to_hex());
        body.push(' ');
        body.push_str(name);
        body.push('\n');
        if let Some(p) = peel {
            body.push('^');
            body.push_str(&p.to_hex());
            body.push('\n');
        }
    }

    atomic_rewrite_packed_refs(git_dir, &body)?;

    for (name, _) in &entries {
        let storage_dir = ref_storage_dir(git_dir, name);
        let stor = crate::ref_namespace::storage_ref_name(name);
        let path = storage_dir.join(&stor);
        if path.is_file() {
            let _ = fs::remove_file(&path);
        }
        if let Some(parent) = path.parent() {
            remove_empty_ref_directory(parent);
        }
    }
    Ok(())
}

/// Rewrite `packed-refs` under the packed-refs lock (tempfile + rename).
fn atomic_rewrite_packed_refs(git_dir: &Path, body: &str) -> Result<()> {
    let packed_path = store::paths::packed_refs_path(git_dir);
    let lock = lock_path_for_ref(&packed_path);
    let abs_lock = fs::canonicalize(git_dir)
        .map(|d| d.join("packed-refs.lock"))
        .unwrap_or_else(|_| lock.clone());
    let _packed_lock = acquire_packed_refs_lock(git_dir, &lock, &abs_lock)?;

    let tmp = packed_path.with_extension("new");
    let mut created_tmp = false;
    let write_result = (|| -> Result<()> {
        // Staged packed-refs body (not a lock file); exclusive create avoids clobber.
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)
            .map_err(Error::Io)?;
        created_tmp = true;
        use std::io::Write as _;
        file.write_all(body.as_bytes()).map_err(Error::Io)?;
        drop(file);
        fs::rename(&tmp, &packed_path).map_err(Error::Io)?;
        created_tmp = false;
        Ok(())
    })();
    if write_result.is_err() && created_tmp {
        let _ = fs::remove_file(&tmp);
    }
    write_result
}

/// One reference line (and optional peel) for [`write_packed_refs_file`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackedRefRecord {
    /// Full ref name (for example `refs/heads/feature`).
    pub refname: String,
    /// Object id stored at this ref.
    pub oid: ObjectId,
    /// When set, emit a following `^` peeled line (annotated tags).
    pub peeled: Option<ObjectId>,
}

/// Replace `packed-refs` with `records`, sorted by ref name.
///
/// Existing loose ref files for names present in `records` are removed so the
/// packed file is authoritative (Git's `pack-refs` behaviour).
///
/// # Errors
///
/// Returns [`Error::InvalidRef`] for unsafe ref names, or [`Error::Io`] on failure.
pub fn write_packed_refs_file(git_dir: &Path, records: &[PackedRefRecord]) -> Result<()> {
    let mut sorted: Vec<&PackedRefRecord> = records.iter().collect();
    sorted.sort_by(|a, b| a.refname.cmp(&b.refname));
    for rec in &sorted {
        ensure_refname_safe_for_storage(&rec.refname)?;
    }
    let mut body = String::from("# pack-refs with: peeled fully-peeled sorted\n");
    for rec in &sorted {
        body.push_str(&rec.oid.to_hex());
        body.push(' ');
        body.push_str(&rec.refname);
        body.push('\n');
        if let Some(peeled) = rec.peeled {
            body.push('^');
            body.push_str(&peeled.to_hex());
            body.push('\n');
        }
    }
    atomic_rewrite_packed_refs(git_dir, &body)?;
    for rec in &sorted {
        let storage_dir = ref_storage_dir(git_dir, &rec.refname);
        let stor = crate::ref_namespace::storage_ref_name(&rec.refname);
        let loose = storage_dir.join(stor);
        if loose.is_file() {
            fs::remove_file(&loose).map_err(Error::Io)?;
        }
        if let Some(parent) = loose.parent() {
            remove_empty_ref_directory(parent);
        }
    }
    Ok(())
}

/// List all refs under a given prefix (e.g. `"refs/heads/"`).
///
/// Dispatches to the reftable backend when `extensions.refStorage = reftable`.
///
/// Returns a sorted list of `(refname, ObjectId)` pairs.
///
/// # Errors
///
/// Returns [`Error::Io`] on directory traversal errors.
/// List refs under `prefix` using the given repository's ref store.
pub fn list_refs_for_repository(
    repo: &crate::repo::Repository,
    prefix: &str,
) -> Result<Vec<(String, ObjectId)>> {
    let git_dir = &repo.git_dir();
    let prefix_norm = normalize_list_refs_prefix(git_dir, prefix);
    let mut results = collect_resolved_refs(repo.refs(), prefix_norm.as_str())?;
    if crate::worktree_ref::is_linked_worktree_git_dir(git_dir) {
        results.retain(|(name, _)| crate::worktree_ref::ref_visible_from_worktree(git_dir, name));
    }
    results.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(results)
}

/// List resolved refs under `git_dir` whose full names start with `prefix`.
///
/// Uses the on-disk ref backend (files or reftable) and applies linked-worktree
/// visibility rules when `git_dir` is a linked worktree git directory.
///
/// # Errors
///
/// Propagates ref-store open/read failures.
pub fn list_refs(git_dir: &Path, prefix: &str) -> Result<Vec<(String, ObjectId)>> {
    let prefix_norm = normalize_list_refs_prefix(git_dir, prefix);
    let prefix = prefix_norm.as_str();
    let store = open_ref_store(git_dir)?;
    if store.format() != RefStorageFormat::Files {
        return crate::reftable::reftable_list_refs(git_dir, prefix);
    }
    let mut results = collect_resolved_refs(store.as_ref(), prefix)?;
    if crate::worktree_ref::is_linked_worktree_git_dir(git_dir) {
        results.retain(|(name, _)| crate::worktree_ref::ref_visible_from_worktree(git_dir, name));
    }
    results.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(results)
}

/// [`list_refs`], except that `packed-refs` records `keep` rejects may be left out.
///
/// `keep` receives each packed record's name, object id and what the file records about
/// peeling it, before anything is allocated for the record. Loose refs, and every ref of a
/// reftable repository, are always listed, so `keep` only ever narrows the listing to a
/// subset of [`list_refs`].
///
/// # Errors
///
/// Propagates ref-store open/read failures, like [`list_refs`].
pub(crate) fn list_refs_filtering_packed(
    git_dir: &Path,
    prefix: &str,
    keep: PackedRecordFilter<'_>,
) -> Result<Vec<(String, ObjectId)>> {
    let Some(store) = store::open_files_ref_store(git_dir)? else {
        return list_refs(git_dir, prefix);
    };
    let prefix_norm = normalize_list_refs_prefix(git_dir, prefix);
    let prefix = prefix_norm.as_str();
    let mut results = collect_resolved_ref_entries(&store, |f| {
        store.for_each_ref_filtered(prefix, Some(keep), f)
    })?;
    if crate::worktree_ref::is_linked_worktree_git_dir(git_dir) {
        results.retain(|(name, _)| crate::worktree_ref::ref_visible_from_worktree(git_dir, name));
    }
    results.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(results)
}

/// Resolve a ref using Git DWIM rules (`expand_ref` / `repo_dwim_ref`).
pub fn resolve_ref_dwim(git_dir: &Path, spec: &str) -> (usize, Option<ObjectId>) {
    crate::worktree_ref::resolve_ref_dwim(|candidate| resolve_ref(git_dir, candidate).ok(), spec)
}

/// List refs under `prefix` using **literal** on-disk paths (ignores `GIT_NAMESPACE`).
///
/// Used by `receive-pack` when advertising: the server must see every physical ref so refs outside
/// the active namespace can be offered as `.have` lines (matches Git `show_ref_cb`).
pub fn list_refs_physical(git_dir: &Path, prefix: &str) -> Result<Vec<(String, ObjectId)>> {
    if open_ref_store(git_dir)?.format() != RefStorageFormat::Files {
        return crate::reftable::reftable_list_refs(git_dir, prefix);
    }
    let mut by_name: HashMap<String, ObjectId> = HashMap::new();
    let stored_prefix = prefix.to_owned();

    if let Some(cdir) = common_dir(git_dir) {
        if cdir != git_dir {
            collect_packed_refs_into_map(&cdir, &stored_prefix, true, &mut by_name)?;
            let (loose_root, loose_prefix) = loose_ref_list_walk_root(&cdir, &stored_prefix);
            collect_loose_refs_into_map(
                &loose_root,
                &loose_prefix,
                &stored_prefix,
                &cdir,
                true,
                &mut by_name,
            )?;
        }
    }

    collect_packed_refs_into_map(git_dir, &stored_prefix, true, &mut by_name)?;
    let (loose_root, loose_prefix) = loose_ref_list_walk_root(git_dir, &stored_prefix);
    collect_loose_refs_into_map(
        &loose_root,
        &loose_prefix,
        &stored_prefix,
        git_dir,
        true,
        &mut by_name,
    )?;

    let mut results: Vec<(String, ObjectId)> = by_name.into_iter().collect();
    results.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(results)
}

/// Collect commit OIDs from alternate repositories' refs, matching Git's
/// `git for-each-ref --format=%(objectname)` on each alternate (with optional
/// `core.alternateRefsPrefixes` arguments).
///
/// Order is preserved: alternates file order, then ref iteration order from
/// [`list_refs`] under each configured prefix (or all of `refs/` when no
/// prefixes are set). Duplicate OIDs are skipped while preserving first-seen
/// order.
pub fn collect_alternate_ref_oids(receiving_git_dir: &Path) -> Result<Vec<ObjectId>> {
    let config = ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(receiving_git_dir),
        true,
    )?;
    let objects_dir = receiving_git_dir.join("objects");
    let alternates = pack::read_alternates_recursive(&objects_dir).unwrap_or_default();
    let mut out = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for alt_objects in alternates {
        let Some(alt_git_dir) = alt_objects.parent().map(PathBuf::from) else {
            continue;
        };
        if !alt_git_dir.join("refs").is_dir() {
            continue;
        }
        if let Some(prefixes) = config
            .get("core.alternaterefsprefixes")
            .or_else(|| config.get("core.alternateRefsPrefixes"))
        {
            for part in prefixes.split_whitespace() {
                if let Ok(oid) = resolve_ref(&alt_git_dir, part) {
                    if seen.insert(oid) {
                        out.push(oid);
                    }
                    continue;
                }
                for (_, oid) in list_refs(&alt_git_dir, part)? {
                    if seen.insert(oid) {
                        out.push(oid);
                    }
                }
            }
        } else {
            for (_, oid) in list_refs(&alt_git_dir, "refs/")? {
                if seen.insert(oid) {
                    out.push(oid);
                }
            }
        }
    }
    Ok(out)
}

/// List refs matching a glob pattern (e.g. `refs/heads/topic/*`) using `repo`'s ref store.
pub fn list_refs_glob_for_repository(
    repo: &crate::repo::Repository,
    pattern: &str,
) -> Result<Vec<(String, ObjectId)>> {
    let glob_pos = pattern.find(['*', '?', '[']);
    let prefix_owned: String = match glob_pos {
        Some(pos) => pattern[..pos].to_owned(),
        None => {
            let mut p = pattern.trim_end_matches('/').to_owned();
            if !p.is_empty() {
                p.push('/');
            }
            p
        }
    };
    let all = list_refs_for_repository(repo, prefix_owned.as_str())?;
    let mut results = Vec::new();
    for (refname, oid) in all {
        if ref_matches_glob(&refname, pattern) {
            results.push((refname, oid));
        }
    }
    Ok(results)
}

/// List refs matching a glob pattern (e.g. `refs/heads/topic/*`).
pub fn list_refs_glob(git_dir: &Path, pattern: &str) -> Result<Vec<(String, ObjectId)>> {
    let glob_pos = pattern.find(['*', '?', '[']);
    let prefix_owned: String = match glob_pos {
        // Literal segment before the first wildcard (e.g. `refs/heads/b05*` → `refs/heads/b05`).
        Some(pos) => pattern[..pos].to_owned(),
        None => {
            let mut p = pattern.trim_end_matches('/').to_owned();
            if !p.is_empty() {
                p.push('/');
            }
            p
        }
    };
    let prefix = prefix_owned.as_str();
    let all = list_refs(git_dir, prefix)?;
    let mut results = Vec::new();
    for (refname, oid) in all {
        if ref_matches_glob(&refname, pattern) {
            results.push((refname, oid));
        }
    }
    Ok(results)
}

/// Check whether a ref name matches a glob pattern.
///
/// Supports `*`, `?`, and `[…]` wildcards. An exact string match is also accepted.
pub fn ref_matches_glob(refname: &str, pattern: &str) -> bool {
    // For exact matches (no glob characters), check suffix match
    if !pattern.contains('*') && !pattern.contains('?') && !pattern.contains('[') {
        return refname == pattern
            || refname.ends_with(&format!("/{pattern}"))
            || refname.starts_with(&format!("{pattern}/"));
    }
    glob_match(pattern, refname)
}

fn glob_match(pattern: &str, text: &str) -> bool {
    let pat = pattern.as_bytes();
    let txt = text.as_bytes();
    let (mut pi, mut ti) = (0, 0);
    let (mut star_pi, mut star_ti) = (usize::MAX, 0);
    while ti < txt.len() {
        if pi < pat.len() && (pat[pi] == b'?' || pat[pi] == txt[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < pat.len() && pat[pi] == b'*' {
            star_pi = pi;
            star_ti = ti;
            pi += 1;
        } else if star_pi != usize::MAX {
            pi = star_pi + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }
    while pi < pat.len() && pat[pi] == b'*' {
        pi += 1;
    }
    pi == pat.len()
}

/// OID stored directly in a loose ref file (40 hex), ignoring symbolic targets.
fn loose_ref_file_direct_oid(path: &Path) -> Option<ObjectId> {
    let content = fs::read_to_string(path).ok()?;
    let content = content.trim_end_matches('\n').trim();
    if ObjectId::is_full_hex(content) {
        content.parse().ok()
    } else {
        None
    }
}

fn collect_loose_refs_into_map(
    dir: &Path,
    prefix: &str,
    filter_prefix: &str,
    resolve_git_dir: &Path,
    physical_keys: bool,
    out: &mut HashMap<String, ObjectId>,
) -> Result<()> {
    let read = match fs::read_dir(dir) {
        Ok(r) => r,
        Err(e)
            if e.kind() == io::ErrorKind::NotFound
                || e.kind() == io::ErrorKind::NotADirectory
                || e.raw_os_error() == Some(libc::ENOTDIR) =>
        {
            return Ok(());
        }
        Err(e) => return Err(Error::Io(e)),
    };

    for entry in read {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        let refname = format!("{prefix}{name_str}");
        let path = entry.path();
        let meta = match fs::metadata(&path) {
            Ok(m) => m,
            Err(_) => continue,
        };

        if meta.is_dir() {
            collect_loose_refs_into_map(
                &path,
                &format!("{refname}/"),
                filter_prefix,
                resolve_git_dir,
                physical_keys,
                out,
            )?;
        } else if meta.is_file() {
            if physical_keys {
                if let Some(oid) = loose_ref_file_direct_oid(&path) {
                    out.insert(refname, oid);
                } else if let Ok(Ref::Symbolic(target)) = read_ref_file(&path) {
                    if let Ok(oid) = resolve_ref(resolve_git_dir, target.trim()) {
                        out.insert(refname, oid);
                    }
                }
            } else {
                let logical = crate::ref_namespace::logical_ref_name_from_storage(&refname)
                    .unwrap_or_else(|| refname.clone());
                if !ref_name_matches_list_prefix(&logical, filter_prefix.trim_end_matches('/')) {
                    continue;
                }
                if let Some(oid) = loose_ref_file_direct_oid(&path) {
                    out.insert(logical, oid);
                } else if let Ok(Ref::Symbolic(target)) = read_ref_file(&path) {
                    if let Ok(oid) = resolve_ref(resolve_git_dir, target.trim()) {
                        out.insert(logical, oid);
                    }
                }
            }
        }
    }
    Ok(())
}

/// Resolve `@{-N}` syntax to the branch name (not an OID).
/// Returns the branch name of the Nth previously checked out branch.
pub fn resolve_at_n_branch(git_dir: &Path, spec: &str) -> Result<String> {
    // Parse the N from @{-N}
    let inner = spec
        .strip_prefix("@{-")
        .and_then(|s| s.strip_suffix('}'))
        .ok_or_else(|| Error::InvalidRef(format!("not an @{{-N}} ref: {spec}")))?;
    let n: usize = inner
        .parse()
        .map_err(|_| Error::InvalidRef(format!("invalid N in {spec}")))?;
    if n == 0 {
        return Err(Error::InvalidRef("@{-0} is not valid".to_string()));
    }
    let entries = crate::reflog::read_reflog(git_dir, "HEAD")?;
    let mut count = 0usize;
    for entry in entries.iter().rev() {
        let msg = &entry.message;
        if let Some(rest) = msg.strip_prefix("checkout: moving from ") {
            count += 1;
            if count == n {
                if let Some(to_pos) = rest.find(" to ") {
                    return Ok(rest[..to_pos].to_string());
                }
            }
        }
    }
    Err(Error::InvalidRef(format!(
        "{spec}: only {count} checkout(s) in reflog"
    )))
}

fn ref_name_matches_list_prefix(refname: &str, prefix: &str) -> bool {
    let prefix = prefix.trim_end_matches('/');
    if prefix.is_empty() {
        return true;
    }
    if refname.starts_with(prefix) {
        return true;
    }
    if refname == prefix {
        return true;
    }
    false
}

fn list_prefix_upper_bound(prefix: &str) -> Option<String> {
    let base = prefix.trim_end_matches('/');
    let (head, tail) = base.rsplit_once('/')?;
    let mut chars: Vec<char> = tail.chars().collect();
    while let Some(last) = chars.pop() {
        if last != '\u{10ffff}' {
            chars.push(char::from_u32(last as u32 + 1).unwrap_or(last));
            return Some(format!("{head}/{}", chars.into_iter().collect::<String>()));
        }
    }
    None
}

/// When `prefix` names a partial ref (e.g. `refs/heads/b05/` with no `b05/` directory),
/// start the walk at the parent directory (`refs/heads/`) and filter by prefix.
pub(crate) fn loose_ref_list_walk_root(git_dir: &Path, prefix: &str) -> (PathBuf, String) {
    let trimmed = prefix.trim_end_matches('/');
    if trimmed.is_empty() {
        return (git_dir.join("refs"), "refs/".to_owned());
    }
    let direct = git_dir.join(trimmed);
    if direct.is_dir() {
        return (direct, format!("{trimmed}/"));
    }
    if let Some(slash) = trimmed.rfind('/') {
        let parent = &trimmed[..slash];
        return (git_dir.join(parent), format!("{parent}/"));
    }
    (git_dir.to_path_buf(), String::new())
}

fn collect_packed_refs_into_map(
    git_dir: &Path,
    prefix: &str,
    physical_keys: bool,
    out: &mut HashMap<String, ObjectId>,
) -> Result<()> {
    let map = read_packed_refs_map_for_prefix(git_dir, prefix)?;
    for (refname, oid) in map {
        let key = if physical_keys {
            refname.clone()
        } else {
            crate::ref_namespace::logical_ref_name_from_storage(&refname).unwrap_or(refname)
        };
        out.insert(key, oid);
    }
    Ok(())
}

#[cfg(test)]
mod update_branch_for_commit_tests {
    use super::*;
    use crate::reflog::read_reflog;
    use crate::repo::init_repository;
    use std::sync::{Arc, Condvar, Mutex};
    use std::thread;
    use tempfile::TempDir;

    fn sample_oid(hex: &str) -> ObjectId {
        hex.parse().unwrap()
    }

    #[test]
    fn update_branch_for_commit_holds_lock_until_ref_commit() {
        let _pause_serial = super::test_pause_injection_serial_guard();
        let tmp = TempDir::new().unwrap();
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .unwrap();
        let git_dir = repo.git_dir().to_path_buf();
        let oid1 = sample_oid("67bf698f3ab735e92fb011a99cff3497c44d30c1");
        let oid2 = sample_oid("1111111111111111111111111111111111111111");
        let oid3 = sample_oid("2222222222222222222222222222222222222222");
        write_ref(&git_dir, "refs/heads/main", &oid1).unwrap();

        let gate = Arc::new(branch_ref_pause_inject::PauseGate {
            wait: Mutex::new(false),
            cv: Condvar::new(),
        });
        set_test_inject_branch_ref_pause_before_commit(Some(gate.clone()));

        let git_dir_thread = git_dir.clone();
        let handle = thread::spawn(move || {
            update_branch_for_commit(
                &git_dir_thread,
                &BranchCommitRefUpdate {
                    branch_ref: "refs/heads/main",
                    expected_old: Some(oid1),
                    new_oid: oid2,
                    identity: "T <t@e.com> 1 +0000",
                    reflog_message: "commit: test",
                },
            )
        });

        let mut wait = gate.wait.lock().unwrap();
        while !*wait {
            wait = gate.cv.wait(wait).unwrap();
        }

        assert!(
            write_ref(&git_dir, "refs/heads/main", &oid3).is_err(),
            "concurrent branch update must block on the held ref lock"
        );

        *wait = false;
        gate.cv.notify_all();
        drop(wait);
        handle.join().unwrap().unwrap();
        set_test_inject_branch_ref_pause_before_commit(None);

        assert_eq!(resolve_ref(&git_dir, "refs/heads/main").unwrap(), oid2);
    }

    #[test]
    fn update_branch_for_commit_reftable_transaction_is_all_or_nothing() {
        let tmp = TempDir::new().unwrap();
        let repo = init_repository(
            tmp.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Reftable,
        )
        .unwrap();
        let git_dir = repo.git_dir().to_path_buf();
        let new_oid = sample_oid("3333333333333333333333333333333333333333");

        crate::reftable::set_test_inject_reftable_transaction_fail(true);
        let err = update_branch_for_commit(
            &git_dir,
            &BranchCommitRefUpdate {
                branch_ref: "refs/heads/main",
                expected_old: None,
                new_oid,
                identity: "T <t@e.com> 1 +0000",
                reflog_message: "commit (initial): test",
            },
        )
        .unwrap_err();
        crate::reftable::set_test_inject_reftable_transaction_fail(false);
        assert!(!matches!(err, Error::Message(_)));

        assert!(resolve_ref(&git_dir, "refs/heads/main").is_err());
        assert!(read_reflog(&git_dir, "refs/heads/main").unwrap().is_empty());
        assert!(read_reflog(&git_dir, "HEAD").unwrap().is_empty());
    }
}

#[cfg(test)]
mod refname_available_tests {
    use super::*;
    use std::collections::{BTreeSet, HashSet};
    use tempfile::tempdir;

    #[test]
    fn verify_ref_transaction_batch_rejects_same_batch_parent_child() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        let items = vec![
            RefBatchItem {
                name: "refs/heads/c".to_owned(),
                new_oid: Some(sample_oid()),
            },
            RefBatchItem {
                name: "refs/heads/c/x".to_owned(),
                new_oid: Some(sample_oid()),
            },
        ];
        let err = verify_ref_transaction_batch(git_dir, &items).unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::SameBatch { refname, .. } if refname == "refs/heads/c/x"
        ));
    }

    fn sample_oid() -> ObjectId {
        "67bf698f3ab735e92fb011a99cff3497c44d30c1".parse().unwrap()
    }

    #[test]
    fn loose_parent_blocks_child_create() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/1l")).unwrap();
        fs::write(
            git_dir.join("refs/1l/c"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/1l/c").unwrap(),
            RawRefLookup::Exists
        );
        let extras = BTreeSet::from([
            "refs/1l/b".to_string(),
            "refs/1l/c/x".to_string(),
            "refs/1l/d".to_string(),
        ]);
        let skip = HashSet::new();
        let err = verify_refname_available_for_create(git_dir, "refs/1l/c/x", &extras, &skip)
            .unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::AncestorExists { ref blocking, .. } if blocking == "refs/1l/c"
        ));
    }

    #[test]
    fn verify_sees_loose_ref_after_canonical_git_dir() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path().join(".git");
        fs::create_dir_all(git_dir.join("refs/1l")).unwrap();
        fs::write(
            git_dir.join("refs/1l/c"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        let skip = HashSet::new();
        let extras = BTreeSet::new();
        let err = verify_refname_available_for_create(&git_dir, "refs/1l/c/x", &extras, &skip)
            .unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::AncestorExists { ref blocking, .. } if blocking == "refs/1l/c"
        ));
    }

    fn refname_namespace_conflicts(existing: &str, candidate: &str) -> bool {
        if existing == candidate {
            return false;
        }
        existing
            .strip_prefix(candidate)
            .is_some_and(|rest| rest.starts_with('/'))
            || candidate
                .strip_prefix(existing)
                .is_some_and(|rest| rest.starts_with('/'))
    }

    #[test]
    fn packed_namespace_index_matches_pairwise_scan() {
        let mut sorted: BTreeSet<String> = BTreeSet::new();
        for i in 0..500 {
            sorted.insert(format!("refs/heads/b{i:05}"));
        }
        sorted.insert("refs/heads/parent".into());
        sorted.insert("refs/heads/a/b".into());
        let candidates = [
            "refs/heads/b00001",
            "refs/heads/parent/child",
            "refs/heads/new",
            "refs/heads/a",
        ];
        for candidate in candidates {
            let indexed = packed_refname_namespace_conflict(&sorted, candidate);
            let linear = sorted
                .iter()
                .any(|existing| refname_namespace_conflicts(existing, candidate));
            assert_eq!(indexed, linear, "candidate {candidate}");
        }
    }

    #[test]
    fn list_refs_glob_b05_star_matches_one_thousand_packed_refs() {
        let git_dir = Path::new("/tmp/grit-bench-refs-cache/refs-100k-packed");
        if !git_dir.is_dir() {
            return;
        }
        let listed = list_refs_glob(git_dir, "refs/heads/b05*").unwrap();
        assert_eq!(listed.len(), 1000, "expected 1k b05* refs");
        assert!(listed
            .iter()
            .all(|(name, _)| name.starts_with("refs/heads/b05")));
    }

    #[test]
    fn list_refs_finds_sibling_under_parent_directory() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/ns/p")).unwrap();
        fs::write(
            git_dir.join("refs/ns/p/x"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        let listed = list_refs(git_dir, "refs/ns/p/").unwrap();
        assert!(
            listed.iter().any(|(n, _)| n == "refs/ns/p/x"),
            "got {listed:?}"
        );
    }

    #[test]
    fn verify_blocks_parent_when_child_ref_exists() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/ns/p")).unwrap();
        fs::write(
            git_dir.join("refs/ns/p/x"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        let extras = BTreeSet::from(["refs/ns/p".to_string()]);
        let skip = HashSet::new();
        let err =
            verify_refname_available_for_create(git_dir, "refs/ns/p", &extras, &skip).unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::DescendantExists { ref blocking, .. }
                if blocking == "refs/ns/p/x"
        ));
    }

    #[test]
    fn verify_blocks_parent_when_only_a_packed_child_exists() {
        // No `refs/ns/q/` directory on disk, so the loose listing is skipped;
        // the packed-refs check must still find the descendant.
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs")).unwrap();
        fs::write(
            store::paths::packed_refs_path(git_dir),
            "# pack-refs with: peeled fully-peeled\n\
             67bf698f3ab735e92fb011a99cff3497c44d30c1 refs/ns/q/x\n",
        )
        .unwrap();
        let err = verify_refname_available_for_create(
            git_dir,
            "refs/ns/q",
            &BTreeSet::new(),
            &HashSet::new(),
        )
        .unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::DescendantExists { ref blocking, .. }
                if blocking == "refs/ns/q/x"
        ));
    }

    #[test]
    fn verify_allows_name_whose_siblings_share_a_prefix() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/tags")).unwrap();
        for name in ["v1.0.1", "v1.0-rc1"] {
            fs::write(
                git_dir.join("refs/tags").join(name),
                "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
            )
            .unwrap();
        }
        verify_refname_available_for_create(
            git_dir,
            "refs/tags/v1.0",
            &BTreeSet::new(),
            &HashSet::new(),
        )
        .expect("siblings are not descendants");
    }

    #[test]
    fn verify_blocks_parent_git_style_nested_path() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/3l/c")).unwrap();
        fs::write(
            git_dir.join("refs/3l/c/x"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        let extras = BTreeSet::from(["refs/3l/c".to_string()]);
        let skip = HashSet::new();
        let err =
            verify_refname_available_for_create(git_dir, "refs/3l/c", &extras, &skip).unwrap_err();
        assert!(matches!(
            err,
            RefnameUnavailable::DescendantExists { ref blocking, .. }
                if blocking == "refs/3l/c/x"
        ));
    }

    #[test]
    fn intermediate_directory_does_not_block_nested_create() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/ns")).unwrap();
        fs::write(
            git_dir.join("refs/ns/existing"),
            "67bf698f3ab735e92fb011a99cff3497c44d30c1\n",
        )
        .unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/ns").unwrap(),
            RawRefLookup::IsDirectory
        );
        let extras = BTreeSet::from(["refs/ns/newchild".to_string()]);
        let skip = HashSet::new();
        verify_refname_available_for_create(git_dir, "refs/ns/newchild", &extras, &skip).unwrap();
    }
}

#[cfg(test)]
mod ref_storage_traversal_guard_tests {
    use super::*;
    use crate::objects::ObjectId;
    use tempfile::tempdir;

    const TRAVERSAL_REF: &str = "refs/heads/../../config";

    fn bare_repo_with_config() -> (tempfile::TempDir, PathBuf) {
        let dir = tempdir().unwrap();
        let git_dir = dir.path().to_path_buf();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        fs::write(
            git_dir.join("config"),
            "[core]\nrepositoryformatversion = 0\n",
        )
        .unwrap();
        (dir, git_dir)
    }

    fn sample_oid() -> ObjectId {
        "67bf698f3ab735e92fb011a99cff3497c44d30c1".parse().unwrap()
    }

    fn assert_invalid_ref_preserves_config(git_dir: &Path, result: Result<()>) {
        assert!(matches!(result, Err(Error::InvalidRef(_))));
        assert!(
            git_dir.join("config").is_file(),
            "repository config must not be touched"
        );
    }

    #[test]
    fn write_ref_rejects_traversal_refname() {
        let (_dir, git_dir) = bare_repo_with_config();
        let result = write_ref(&git_dir, TRAVERSAL_REF, &sample_oid());
        assert_invalid_ref_preserves_config(&git_dir, result);
    }

    #[test]
    fn write_ref_cached_rejects_traversal_refname() {
        let (_dir, git_dir) = bare_repo_with_config();
        let mut packed = PackedRefs::load(&git_dir).unwrap();
        let result = write_ref_cached(&git_dir, TRAVERSAL_REF, &sample_oid(), &mut packed);
        assert_invalid_ref_preserves_config(&git_dir, result);
    }

    #[test]
    fn write_symbolic_ref_rejects_traversal_refname() {
        let (_dir, git_dir) = bare_repo_with_config();
        let result = write_symbolic_ref(&git_dir, TRAVERSAL_REF, "refs/heads/main");
        assert_invalid_ref_preserves_config(&git_dir, result);
    }

    #[test]
    fn delete_ref_rejects_traversal_refname() {
        let (_dir, git_dir) = bare_repo_with_config();
        let result = delete_ref(&git_dir, TRAVERSAL_REF);
        assert_invalid_ref_preserves_config(&git_dir, result);
    }

    #[test]
    fn write_ref_rejects_illegal_branch_refname() {
        let (_dir, git_dir) = bare_repo_with_config();
        for refname in [
            "refs/heads/bad name",
            "refs/heads/x..y",
            "refs/heads/a~b",
            "refs/heads/a.lock",
        ] {
            let result = write_ref(&git_dir, refname, &sample_oid());
            assert_invalid_ref_preserves_config(&git_dir, result);
            assert!(
                !git_dir
                    .join(refname.strip_prefix("refs/").unwrap())
                    .exists(),
                "must not write loose ref for {refname}"
            );
        }
    }

    #[test]
    fn write_ref_accepts_refs_heads_head() {
        let (_dir, git_dir) = bare_repo_with_config();
        write_ref(&git_dir, "refs/heads/HEAD", &sample_oid())
            .expect("refs/heads/HEAD is valid ref syntax");
        assert!(git_dir.join("refs/heads/HEAD").is_file());
    }
}

#[cfg(test)]
mod log_refs_config_tests {
    use super::*;
    use crate::config::{ConfigFile, ConfigScope};

    fn set(text: &str) -> ConfigSet {
        let file = ConfigFile::parse(Path::new("config"), text, ConfigScope::Local).unwrap();
        let mut set = ConfigSet::new();
        set.merge(&file);
        set
    }

    #[test]
    fn parse_accepts_modes_and_bool_spellings() {
        for (raw, mode) in [
            ("always", LogRefsConfig::Always),
            (" ALWAYS ", LogRefsConfig::Always),
            ("true", LogRefsConfig::Normal),
            ("Yes", LogRefsConfig::Normal),
            ("on", LogRefsConfig::Normal),
            ("1", LogRefsConfig::Normal),
            ("false", LogRefsConfig::None),
            ("no", LogRefsConfig::None),
            ("OFF", LogRefsConfig::None),
            ("0", LogRefsConfig::None),
            ("never", LogRefsConfig::None),
        ] {
            assert_eq!(LogRefsConfig::parse(raw), Some(mode), "{raw}");
        }
        assert_eq!(LogRefsConfig::parse("sometimes"), None);
    }

    #[test]
    fn effective_mode_applies_bare_default_only_when_unset() {
        assert_eq!(set("").log_refs_config(), LogRefsConfig::Unset);
        assert_eq!(set("").effective_log_refs_config(), LogRefsConfig::Normal);
        let bare = set("[core]\n\tbare = true\n");
        assert_eq!(bare.effective_log_refs_config(), LogRefsConfig::None);
        let bogus = set("[core]\n\tbare = true\n\tlogAllRefUpdates = sometimes\n");
        assert_eq!(bogus.log_refs_config(), LogRefsConfig::Unset);
        assert_eq!(bogus.effective_log_refs_config(), LogRefsConfig::None);
        let bare_logged = set("[core]\n\tbare = true\n\tlogAllRefUpdates\n");
        assert_eq!(
            bare_logged.effective_log_refs_config(),
            LogRefsConfig::Normal
        );
        let always = set("[core]\n\tlogAllRefUpdates = always\n");
        assert_eq!(always.effective_log_refs_config(), LogRefsConfig::Always);
    }

    #[test]
    fn autocreate_with_config_matches_mode() {
        let normal = set("[core]\n\tlogAllRefUpdates = true\n");
        let git_dir = Path::new(".git");
        assert!(should_autocreate_reflog_with_config(
            &normal,
            git_dir,
            "refs/heads/main"
        ));
        assert!(!should_autocreate_reflog_with_config(
            &normal,
            git_dir,
            "refs/tags/v1"
        ));
        let none = set("[core]\n\tlogAllRefUpdates = false\n");
        assert!(!should_autocreate_reflog_with_config(
            &none, git_dir, "HEAD"
        ));
    }
}

#[cfg(test)]
mod read_raw_ref_tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn loose_ref_file_is_exists() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        fs::write(
            git_dir.join("refs/heads/side"),
            "0000000000000000000000000000000000000000\n",
        )
        .unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/heads/side").unwrap(),
            RawRefLookup::Exists
        );
    }

    #[test]
    fn missing_ref_is_not_found() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/heads/nope").unwrap(),
            RawRefLookup::NotFound
        );
    }

    #[test]
    fn directory_where_ref_expected_is_is_directory() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/heads").unwrap(),
            RawRefLookup::IsDirectory
        );
    }

    #[test]
    fn packed_ref_name_is_exists() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        fs::write(
            store::paths::packed_refs_path(git_dir),
            "# pack-refs with: peeled fully-peeled \n\
             0000000000000000000000000000000000000000 refs/heads/packed\n",
        )
        .unwrap();
        assert_eq!(
            read_raw_ref(git_dir, "refs/heads/packed").unwrap(),
            RawRefLookup::Exists
        );
    }
}

#[cfg(test)]
mod packed_refs_parse_tests {
    use super::*;
    use crate::objects::HashAlgo;
    use tempfile::tempdir;

    #[test]
    fn parse_rejects_garbage_line() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        fs::write(
            &path,
            "# pack-refs with: peeled\n\
             0000000000000000000000000000000000000000 refs/heads/main\n\
             not a ref line\n",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
    }

    #[test]
    fn parse_rejects_carriage_return_bytes() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        fs::write(
            &path,
            "# pack-refs with: peeled\n\
             0000000000000000000000000000000000000000 refs/heads/main\r\n",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
    }

    #[test]
    fn prefix_filter_unsorted_packed_refs_scans_past_later_names() {
        let dir = tempdir().unwrap();
        let git_dir = dir.path();
        let oid = "1111111111111111111111111111111111111111";
        fs::write(
            store::paths::packed_refs_path(git_dir),
            format!(
                "# pack-refs with: peeled fully-peeled\n{oid} refs/heads/zzz\n{oid} refs/heads/aaa\n{oid} refs/heads/main\n"
            ),
        )
        .unwrap();
        let listed = list_refs_glob(git_dir, "refs/heads/a*").unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].0, "refs/heads/aaa");
    }

    #[test]
    fn parse_rejects_blank_line_and_missing_final_newline() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        fs::write(
            &path,
            "# pack-refs with: peeled\n\n\
             0000000000000000000000000000000000000000 refs/heads/main\n",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));

        fs::write(
            &path,
            "# pack-refs with: peeled\n\
             0000000000000000000000000000000000000000 refs/heads/main",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
    }

    #[test]
    fn packed_record_filter_sees_trusted_peels_and_keeps_strictness() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let a = "1111111111111111111111111111111111111111";
        let b = "2222222222222222222222222222222222222222";
        let peel = "3333333333333333333333333333333333333333";
        let body = |header: &str| {
            format!(
                "{header}{a} refs/heads/main\n\
                 {b} refs/heads/tagged\n\
                 ^{peel}\n\
                 {a} refs/tags/light\n\
                 {b} refs/tags/v1\n\
                 ^{peel}\n"
            )
        };
        let a: ObjectId = a.parse().unwrap();
        let b: ObjectId = b.parse().unwrap();
        let peel: ObjectId = peel.parse().unwrap();
        let cases = [
            (
                "# pack-refs with: peeled fully-peeled sorted \n",
                [
                    PackedPeel::NotTag,
                    PackedPeel::Peeled(peel),
                    PackedPeel::NotTag,
                    PackedPeel::Peeled(peel),
                ],
            ),
            (
                "# pack-refs with: peeled sorted \n",
                [
                    PackedPeel::Unknown,
                    PackedPeel::Unknown,
                    PackedPeel::NotTag,
                    PackedPeel::Peeled(peel),
                ],
            ),
            ("", [PackedPeel::Unknown; 4]),
        ];
        for (header, want) in cases {
            let data = body(header).into_bytes();
            let view = PackedRefsFileView::from_bytes(&path, data, HashAlgo::Sha1).unwrap();
            let seen = std::cell::RefCell::new(Vec::new());
            let keep = |name: &str, oid: &ObjectId, peel: PackedPeel| {
                seen.borrow_mut().push((name.to_owned(), *oid, peel));
                name.starts_with("refs/tags/")
            };
            let kept = view
                .map_for_prefix_filtered(&path, Some("refs"), Some(&keep))
                .unwrap();
            assert_eq!(
                seen.into_inner(),
                vec![
                    ("refs/heads/main".to_owned(), a, want[0]),
                    ("refs/heads/tagged".to_owned(), b, want[1]),
                    ("refs/tags/light".to_owned(), a, want[2]),
                    ("refs/tags/v1".to_owned(), b, want[3]),
                ],
                "header {header:?}"
            );
            let mut kept: Vec<_> = kept.into_iter().collect();
            kept.sort();
            assert_eq!(
                kept,
                vec![
                    ("refs/tags/light".to_owned(), a),
                    ("refs/tags/v1".to_owned(), b)
                ]
            );
            assert_eq!(
                view.map_for_prefix_filtered(&path, Some("refs"), None)
                    .unwrap(),
                view.map_for_prefix(&path, Some("refs")).unwrap()
            );
        }

        // A malformed record is an error even when the filter would drop it.
        let bad = format!("# pack-refs with: peeled fully-peeled \n{a} refs/heads/bad..name\n");
        let view = PackedRefsFileView::from_bytes(&path, bad.into_bytes(), HashAlgo::Sha1).unwrap();
        assert!(matches!(
            view.map_for_prefix_filtered(&path, None, Some(&|_: &str, _: &ObjectId, _| false)),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
    }

    #[test]
    fn indexed_lookup_matches_full_parse_sorted_and_unsorted() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let oid = "1111111111111111111111111111111111111111";
        let peel = "2222222222222222222222222222222222222222";
        let sorted_body = format!(
            "# pack-refs with: peeled fully-peeled sorted\n\
             {oid} refs/heads/aaa\n\
             {oid} refs/heads/main\n\
             {oid} refs/heads/zzz\n\
             {oid} refs/tags/v1\n\
             ^{peel}\n"
        );
        fs::write(&path, &sorted_body).unwrap();
        let data = fs::read(&path).unwrap();
        let view = PackedRefsFileView::from_bytes(&path, data.clone(), HashAlgo::Sha1).unwrap();
        let full = parse_packed_refs_to_map(&path, &data).unwrap();
        for (name, want) in &full {
            assert_eq!(view.lookup_oid(&path, name).unwrap(), Some(*want));
        }
        assert_eq!(
            lookup_packed_ref_with_peel(dir.path(), "refs/tags/v1")
                .unwrap()
                .map(|(o, p)| (o, p.unwrap())),
            Some((oid.parse().unwrap(), peel.parse().unwrap()))
        );

        let unsorted_body = format!(
            "# pack-refs with: peeled\n{oid} refs/heads/zzz\n{oid} refs/heads/aaa\n{oid} refs/heads/main\n"
        );
        fs::write(&path, unsorted_body).unwrap();
        let data = fs::read(&path).unwrap();
        let view = PackedRefsFileView::from_bytes(&path, data.clone(), HashAlgo::Sha1).unwrap();
        let full = parse_packed_refs_to_map(&path, &data).unwrap();
        for (name, want) in &full {
            assert_eq!(view.lookup_oid(&path, name).unwrap(), Some(*want));
        }
        assert_eq!(
            view.map_for_prefix(&path, Some("refs/heads/a")).unwrap(),
            parse_packed_refs_to_map_with_prefix(&path, &data, Some("refs/heads/a")).unwrap()
        );
    }

    #[test]
    fn sorted_prefix_without_upper_bound_filters_names() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let oid = "1111111111111111111111111111111111111111";
        let sorted_body = format!(
            "# pack-refs with: peeled fully-peeled sorted\n\
             {oid} refs/heads/aaa\n\
             {oid} refs/heads/zzz\n\
             {oid} refs/tags/v1\n"
        );
        fs::write(&path, sorted_body).unwrap();
        let data = fs::read(&path).unwrap();
        let view = PackedRefsFileView::from_bytes(&path, data.clone(), HashAlgo::Sha1).unwrap();
        assert_eq!(
            view.map_for_prefix(&path, Some("refs/heads/a")).unwrap(),
            parse_packed_refs_to_map_with_prefix(&path, &data, Some("refs/heads/a")).unwrap()
        );
        assert!(
            !view
                .map_for_prefix(&path, Some("refs/heads/a"))
                .unwrap()
                .contains_key("refs/heads/zzz"),
            "prefix refs/heads/a must not include refs/heads/zzz"
        );
        assert_eq!(
            view.map_for_prefix(&path, Some("refs")).unwrap(),
            parse_packed_refs_to_map_with_prefix(&path, &data, Some("refs")).unwrap()
        );
    }

    #[test]
    fn sorted_prefix_scan_validates_only_its_range() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let oid = "1111111111111111111111111111111111111111";
        let view_of =
            |body: String| PackedRefsFileView::from_bytes(&path, body.into_bytes(), HashAlgo::Sha1);

        let bad_peel_on_branch = view_of(format!(
            "# pack-refs with: peeled fully-peeled sorted\n\
             {oid} refs/heads/main\n\
             ^not-hex\n\
             {oid} refs/tags/v1\n"
        ))
        .unwrap();
        assert!(matches!(
            bad_peel_on_branch.map_for_prefix(&path, Some("refs/heads")),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
        let tags = bad_peel_on_branch
            .map_for_prefix(&path, Some("refs/tags"))
            .unwrap();
        assert_eq!(tags.keys().collect::<Vec<_>>(), ["refs/tags/v1"]);
        assert!(bad_peel_on_branch.map_for_prefix(&path, None).is_err());

        let blank_among_tags = view_of(format!(
            "# pack-refs with: peeled fully-peeled sorted\n\
             {oid} refs/heads/main\n\
             {oid} refs/tags/v1\n\
             \n\
             {oid} refs/tags/v2\n"
        ))
        .unwrap();
        assert_eq!(
            blank_among_tags
                .map_for_prefix(&path, Some("refs/heads"))
                .unwrap()
                .len(),
            1
        );
        assert!(blank_among_tags
            .map_for_prefix(&path, Some("refs/tags"))
            .is_err());

        let no_match = blank_among_tags
            .map_for_prefix(&path, Some("refs/notes"))
            .unwrap();
        assert!(no_match.is_empty());
    }

    #[test]
    fn scan_of_file_without_ref_lines_still_validates_it() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let view = PackedRefsFileView::from_bytes(
            &path,
            b"# pack-refs with: peeled fully-peeled sorted\n\
              ^1111111111111111111111111111111111111111\n"
                .to_vec(),
            HashAlgo::Sha1,
        )
        .unwrap();
        for prefix in [None, Some("refs/heads")] {
            assert!(matches!(
                view.map_for_prefix(&path, prefix),
                Err(Error::PackedRefsUnexpectedLine { .. })
            ));
        }
        let header_only = PackedRefsFileView::from_bytes(
            &path,
            b"# pack-refs with: peeled fully-peeled sorted\n".to_vec(),
            HashAlgo::Sha1,
        )
        .unwrap();
        assert!(header_only.map_for_prefix(&path, None).unwrap().is_empty());
    }

    #[test]
    fn view_checks_last_line_length_against_the_repository_hash() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let sha1 = "1111111111111111111111111111111111111111";
        let sha256 = "2".repeat(64);
        let view =
            |body: String, algo| PackedRefsFileView::from_bytes(&path, body.into_bytes(), algo);
        let header = "# pack-refs with: peeled fully-peeled sorted\n";
        let fifty_bytes = "x".repeat(49);

        for (body, algo) in [
            (
                format!("{header}{sha1} refs/heads/main\ngarbage\n"),
                HashAlgo::Sha1,
            ),
            (
                format!("{header}{sha1} refs/heads/main\n^{}\n", &sha1[1..]),
                HashAlgo::Sha1,
            ),
            (
                format!("{header}{sha1} refs/heads/main\n#\n"),
                HashAlgo::Sha1,
            ),
            (
                format!("{header}{sha256} refs/heads/main\n{fifty_bytes}\n"),
                HashAlgo::Sha256,
            ),
            (format!("{header}{sha1} refs/heads/a\n"), HashAlgo::Sha256),
        ] {
            assert!(
                matches!(
                    view(body.clone(), algo),
                    Err(Error::PackedRefsUnexpectedLine { .. })
                ),
                "{algo:?}: {body:?}"
            );
        }
        for (body, algo) in [
            (header.to_owned(), HashAlgo::Sha1),
            (header.to_owned(), HashAlgo::Sha256),
            ("# pack-refs with: peeled\n".to_owned(), HashAlgo::Sha256),
            (
                format!("{header}{sha1} refs/heads/main\n{fifty_bytes}\n"),
                HashAlgo::Sha1,
            ),
            (
                format!("{header}{sha1} refs/heads/main\n^{sha1}\n"),
                HashAlgo::Sha1,
            ),
            (
                format!("{header}{sha256} refs/heads/main\n^{sha256}\n"),
                HashAlgo::Sha256,
            ),
        ] {
            assert!(view(body.clone(), algo).is_ok(), "{algo:?}: {body:?}");
        }
    }

    #[test]
    fn sha256_short_last_record_fails_branch_listing() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let sha256 = "2".repeat(64);
        let body = format!(
            "# pack-refs with: peeled fully-peeled sorted\n{sha256} refs/heads/main\n{}\n",
            "x".repeat(49)
        );
        assert!(
            PackedRefsFileView::from_bytes(&path, body.into_bytes(), HashAlgo::Sha256).is_err()
        );
    }

    #[test]
    fn corrupt_line_inside_prefix_range_fails_instead_of_dropping_refs() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let oid = "1111111111111111111111111111111111111111";
        let header = "# pack-refs with: peeled fully-peeled sorted\n";
        let view = |body: String| {
            PackedRefsFileView::from_bytes(&path, body.into_bytes(), HashAlgo::Sha1).unwrap()
        };

        let garbage_after_first_branch = view(format!(
            "{header}{oid} refs/heads/a\ngarbage line\n{oid} refs/heads/b\n{oid} refs/heads/c\n\
             {oid} refs/tags/t1\n"
        ));
        assert!(matches!(
            garbage_after_first_branch.map_for_prefix(&path, Some("refs/heads")),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
        let tags = garbage_after_first_branch
            .map_for_prefix(&path, Some("refs/tags"))
            .unwrap();
        assert_eq!(tags.keys().collect::<Vec<_>>(), ["refs/tags/t1"]);

        let garbage_before_range = view(format!(
            "{header}{oid} refs/heads/a\ngarbage line\n{oid} refs/tags/t1\n"
        ));
        for prefix in ["refs/heads", "refs/tags", "refs/notes"] {
            assert!(
                garbage_before_range
                    .map_for_prefix(&path, Some(prefix))
                    .is_err(),
                "{prefix}"
            );
        }
        assert_eq!(
            garbage_before_range
                .map_for_prefix(&path, Some("refs/zz"))
                .unwrap()
                .len(),
            0
        );

        let peeled_tag_before_range = view(format!(
            "{header}{oid} refs/heads/a\n^{oid}\n{oid} refs/tags/t1\n"
        ));
        let orphan_peel_before_range = view(format!(
            "{header}{oid} refs/heads/a\n^{oid}\n^{oid}\n{oid} refs/tags/t1\n"
        ));
        assert!(orphan_peel_before_range
            .map_for_prefix(&path, Some("refs/tags"))
            .is_err());
        assert_eq!(
            peeled_tag_before_range
                .map_for_prefix(&path, Some("refs/tags"))
                .unwrap()
                .len(),
            1
        );
    }

    #[test]
    fn sorted_trait_is_ignored_when_names_are_out_of_order() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        let oid = "1111111111111111111111111111111111111111";
        let view = PackedRefsFileView::from_bytes(
            &path,
            format!(
                "# pack-refs with: peeled fully-peeled sorted\n\
                 {oid} refs/heads/b\n{oid} refs/heads/a\n{oid} refs/tags/t\n"
            )
            .into_bytes(),
            HashAlgo::Sha1,
        )
        .unwrap();
        assert!(!view.sorted);
        let heads = view.map_for_prefix(&path, Some("refs/heads")).unwrap();
        assert_eq!(heads.len(), 2);
        assert!(view.lookup_oid(&path, "refs/heads/a").unwrap().is_some());
    }

    #[test]
    fn line_index_keeps_only_record_shaped_lines() {
        let data = b"# header\nAAA x\n^peel\n\nBBB y\n#c\nshort\nCCCz\nDDD z";
        let (starts, in_order) = packed_refs_data_line_starts(data, 3);
        assert_eq!(starts, [9, 22, 42]);
        assert!(in_order);
        assert_eq!(packed_refs_data_line_starts(b"", 3), (Vec::new(), true));
        let (starts, in_order) = packed_refs_data_line_starts(b"AAA b\nAAA a\n", 3);
        assert_eq!(starts, [0, 6]);
        assert!(!in_order);
    }

    #[test]
    fn parse_rejects_orphan_peel_and_double_space() {
        let dir = tempdir().unwrap();
        let path = store::paths::packed_refs_path(dir.path());
        fs::write(
            &path,
            "# pack-refs with: peeled\n\
             ^0000000000000000000000000000000000000000\n\
             0000000000000000000000000000000000000000 refs/heads/main\n",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));

        fs::write(
            &path,
            "# pack-refs with: peeled\n\
             0000000000000000000000000000000000000000  refs/heads/main\n",
        )
        .unwrap();
        let data = fs::read(&path).unwrap();
        assert!(matches!(
            parse_packed_refs_to_map(&path, &data),
            Err(Error::PackedRefsUnexpectedLine { .. })
        ));
    }
}

#[cfg(test)]
mod pack_refs_tests {
    use super::*;
    use crate::objects::{serialize_commit, CommitData, ObjectKind};
    use crate::repo::{init_repository, Repository};
    use std::fs;
    use std::sync::Arc;

    fn write_commit(repo: &Repository, parents: Vec<ObjectId>) -> ObjectId {
        let tree = repo.odb().write(ObjectKind::Tree, b"").expect("tree");
        let raw = serialize_commit(&CommitData {
            tree,
            parents,
            author: "T <t@example.com> 1 +0000".into(),
            committer: "T <t@example.com> 1 +0000".into(),
            author_raw: Vec::new(),
            committer_raw: Vec::new(),
            encoding: None,
            message: "m\n".into(),
            raw_message: None,
            extra_headers: Vec::new(),
        });
        repo.odb().write(ObjectKind::Commit, &raw).expect("commit")
    }

    #[test]
    fn pack_refs_skips_concurrent_loose_update() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = init_repository(
            dir.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let git_dir = repo.git_dir().to_path_buf();
        let c1 = write_commit(&repo, vec![]);
        let c2 = write_commit(&repo, vec![c1]);
        write_ref(&git_dir, "refs/heads/race", &c1).expect("seed loose");

        let git_dir_hook = git_dir.clone();
        let c2 = Arc::new(c2);
        let c2_hook = Arc::clone(&c2);
        pack_refs_test_hooks::set_before_prune(Some(Box::new(move || {
            write_ref(&git_dir_hook, "refs/heads/race", &c2_hook).expect("concurrent update");
        })));

        let (_path, packed, pruned) = pack_refs_files(&git_dir, repo.odb(), true).expect("pack");
        pack_refs_test_hooks::set_before_prune(None);
        assert!(packed >= 1);
        assert_eq!(pruned, 0, "stale CAS must not delete the updated loose ref");

        let resolved = resolve_ref(&git_dir, "refs/heads/race").expect("resolve");
        assert_eq!(resolved, *c2);
        let packed_body =
            fs::read_to_string(store::paths::packed_refs_path(&git_dir)).unwrap_or_default();
        assert!(
            !packed_body.contains("refs/heads/race"),
            "packed entry for concurrently updated ref must be removed"
        );
    }

    #[test]
    fn pack_refs_nested_tag_peel_line_points_at_commit() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = init_repository(
            dir.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let commit = write_commit(&repo, vec![]);
        let inner_tag_body = format!(
            "object {}\ntype commit\ntagger T <t@example.com> 1 +0000\n\ninner\n",
            commit.to_hex()
        );
        let inner = repo
            .odb()
            .write(ObjectKind::Tag, inner_tag_body.as_bytes())
            .expect("inner tag");
        let outer_tag_body = format!(
            "object {}\ntype tag\ntagger T <t@example.com> 2 +0000\n\nouter\n",
            inner.to_hex()
        );
        let outer = repo
            .odb()
            .write(ObjectKind::Tag, outer_tag_body.as_bytes())
            .expect("outer tag");
        write_ref(repo.git_dir(), "refs/tags/outer", &outer).expect("tag ref");

        pack_refs_files(repo.git_dir(), repo.odb(), false).expect("pack");
        let body =
            fs::read_to_string(store::paths::packed_refs_path(repo.git_dir())).expect("packed");
        let mut lines = body.lines();
        let tag_line = lines
            .find(|l| l.contains("refs/tags/outer"))
            .expect("tag line");
        assert!(tag_line.starts_with(&outer.to_hex()));
        let peel_line = lines.find(|l| l.starts_with('^')).expect("peel line");
        assert!(
            peel_line.contains(&commit.to_hex()),
            "peel must reach commit through nested tags, got {peel_line}"
        );
    }

    #[test]
    fn pack_refs_tree_target_tag_has_peel_line() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = init_repository(
            dir.path(),
            false,
            "main",
            None,
            crate::RefStorageFormat::Files,
        )
        .expect("init");
        let tree = repo.odb().write(ObjectKind::Tree, b"").expect("tree");
        let tag_body = format!(
            "object {}\ntype tree\ntagger T <t@example.com> 1 +0000\n\ntree tag\n",
            tree.to_hex()
        );
        let tag = repo
            .odb()
            .write(ObjectKind::Tag, tag_body.as_bytes())
            .expect("tag");
        write_ref(repo.git_dir(), "refs/tags/tree-tag", &tag).expect("tag ref");

        pack_refs_files(repo.git_dir(), repo.odb(), true).expect("pack");
        let body =
            fs::read_to_string(store::paths::packed_refs_path(repo.git_dir())).expect("packed");
        assert!(body.contains("refs/tags/tree-tag"));
        assert!(
            body.contains(&format!("^{}", tree.to_hex())),
            "expected peel to tree: {body}"
        );
    }

    #[test]
    fn write_packed_refs_file_survives_publish_failure() {
        let dir = tempfile::tempdir().expect("tempdir");
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).expect("refs/heads");
        let oid = ObjectId::from_hex("0000000000000000000000000000000000000001").expect("oid");
        fs::write(git_dir.join("refs/heads/keep"), format!("{oid}\n")).expect("loose ref");
        fs::create_dir_all(store::paths::packed_refs_path(git_dir))
            .expect("block packed-refs file");
        let err = write_packed_refs_file(
            git_dir,
            &[PackedRefRecord {
                refname: "refs/heads/keep".into(),
                oid,
                peeled: None,
            }],
        )
        .expect_err("publish should fail");
        assert!(matches!(err, Error::Io(_)));
        assert!(git_dir.join("refs/heads/keep").is_file());
    }

    #[test]
    fn write_packed_refs_file_replaces_loose_and_sorts() {
        let dir = tempfile::tempdir().expect("tempdir");
        let git_dir = dir.path();
        fs::create_dir_all(git_dir.join("refs/heads")).expect("refs/heads");
        let oid_a = ObjectId::from_hex("0000000000000000000000000000000000000001").expect("oid a");
        let oid_b = ObjectId::from_hex("0000000000000000000000000000000000000002").expect("oid b");
        fs::write(git_dir.join("refs/heads/a-first"), format!("{oid_b}\n")).expect("loose ref");
        write_packed_refs_file(
            git_dir,
            &[
                PackedRefRecord {
                    refname: "refs/heads/z-last".into(),
                    oid: oid_b,
                    peeled: None,
                },
                PackedRefRecord {
                    refname: "refs/heads/a-first".into(),
                    oid: oid_a,
                    peeled: None,
                },
            ],
        )
        .expect("write packed-refs");
        assert!(!git_dir.join("refs/heads/a-first").exists());
        let body =
            fs::read_to_string(store::paths::packed_refs_path(git_dir)).expect("packed-refs");
        assert!(body.contains("refs/heads/a-first"));
        assert!(body.find("a-first").expect("a-first") < body.find("z-last").expect("z-last"));
    }
}

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

    fn oid(n: u8) -> ObjectId {
        ObjectId::from_bytes(&[n; 20]).expect("oid")
    }

    fn peels_for(body: &str) -> (tempfile::TempDir, PackedRefPeels) {
        let dir = tempfile::tempdir().expect("tempdir");
        fs::write(store::paths::packed_refs_path(dir.path()), body).expect("packed-refs");
        let peels = PackedRefPeels::load(dir.path(), RefStorageFormat::Files).expect("load");
        (dir, peels)
    }

    fn body(header: &str, records: &[(&str, ObjectId, Option<ObjectId>)]) -> String {
        let mut out = String::from(header);
        for (name, oid, peel) in records {
            out.push_str(&format!("{oid} {name}\n"));
            if let Some(peel) = peel {
                out.push_str(&format!("^{peel}\n"));
            }
        }
        out
    }

    #[test]
    fn fully_peeled_file_answers_for_every_ref() {
        for header in [
            "# pack-refs with: peeled fully-peeled sorted \n",
            "# pack-refs with: peeled fully-peeled \n",
        ] {
            let records = [
                ("refs/heads/main", oid(1), None),
                ("refs/remotes/origin/tag-ish", oid(2), Some(oid(3))),
                ("refs/tags/v1", oid(4), Some(oid(1))),
                ("refs/tags/light", oid(1), None),
            ];
            let mut unsorted = records;
            unsorted.reverse();
            let (_dir, peels) = peels_for(&body(header, &unsorted));
            assert_eq!(peels.peeled("refs/heads/main", &oid(1)), Some(None));
            assert_eq!(
                peels.peeled("refs/remotes/origin/tag-ish", &oid(2)),
                Some(Some(oid(3)))
            );
            assert_eq!(peels.peeled("refs/tags/v1", &oid(4)), Some(Some(oid(1))));
            assert_eq!(peels.peeled("refs/tags/light", &oid(1)), Some(None));
            // A loose ref that overrides the packed value is not vouched for.
            assert_eq!(peels.peeled("refs/tags/v1", &oid(9)), None);
            assert_eq!(peels.peeled("refs/tags/missing", &oid(1)), None);
        }
    }

    #[test]
    fn peeled_trait_only_covers_tags_and_no_trait_covers_nothing() {
        let records = [
            ("refs/heads/main", oid(1), None),
            ("refs/tags/v1", oid(4), Some(oid(1))),
        ];
        let (_dir, peels) = peels_for(&body("# pack-refs with: peeled sorted\n", &records));
        assert_eq!(peels.peeled("refs/heads/main", &oid(1)), None);
        assert_eq!(peels.peeled("refs/tags/v1", &oid(4)), Some(Some(oid(1))));

        for header in [
            "",
            "# pack-refs with: sorted\n",
            "# some comment\n",
            "#pack-refs with: peeled fully-peeled\n",
            "#  pack-refs with: peeled fully-peeled\n",
        ] {
            let (_dir, peels) = peels_for(&body(header, &records));
            assert_eq!(peels.peeled("refs/heads/main", &oid(1)), None, "{header:?}");
            assert_eq!(peels.peeled("refs/tags/v1", &oid(4)), None, "{header:?}");
        }
    }

    #[test]
    fn missing_file_and_other_backends_know_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let peels = PackedRefPeels::load(dir.path(), RefStorageFormat::Files).expect("load");
        assert_eq!(peels.peeled("refs/heads/main", &oid(1)), None);

        let records = [("refs/heads/main", oid(1), None)];
        fs::write(
            store::paths::packed_refs_path(dir.path()),
            body("# pack-refs with: peeled fully-peeled sorted\n", &records),
        )
        .expect("packed-refs");
        let peels = PackedRefPeels::load(dir.path(), RefStorageFormat::Reftable).expect("load");
        assert_eq!(peels.peeled("refs/heads/main", &oid(1)), None);
    }
}