gitr 0.5.0

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

#[cfg(test)]
mod tests;

/// A typed handle to a git repository.
#[derive(Debug, Clone)]
pub struct Repository {
    root: PathBuf,
    cmd: GitCommand,
    cache: Option<Cache>,
}

#[cfg(feature = "stream")]
struct LogStream {
    _child: tokio::process::Child,
    lines: Pin<Box<LinesStream<BufReader<tokio::process::ChildStdout>>>>,
}

#[cfg(feature = "stream")]
impl Stream for LogStream {
    type Item = Result<crate::types::GitLogEntry, GitError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        loop {
            match this.lines.as_mut().poll_next(cx) {
                Poll::Ready(Some(Ok(line))) if line.trim().is_empty() => continue,
                Poll::Ready(Some(Ok(line))) => {
                    return Poll::Ready(Some(parse::parse_log_line(&line)));
                }
                Poll::Ready(Some(Err(e))) => {
                    return Poll::Ready(Some(Err(GitError::Io(format!("read error: {e}")))));
                }
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

#[cfg(feature = "stream")]
struct GrepStream {
    _child: tokio::process::Child,
    lines: Pin<Box<LinesStream<BufReader<tokio::process::ChildStdout>>>>,
}

#[cfg(feature = "stream")]
impl Stream for GrepStream {
    type Item = Result<crate::types::GitGrepResult, GitError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        match this.lines.as_mut().poll_next(cx) {
            Poll::Ready(Some(Ok(line))) => {
                let parts: Vec<&str> = line.splitn(3, ':').collect();
                if parts.len() != 3 {
                    return Poll::Ready(Some(Err(GitError::Parse(format!(
                        "invalid grep line: {line}"
                    )))));
                }
                let line_num = match parts[1].parse::<u32>() {
                    Ok(n) => n,
                    Err(e) => {
                        return Poll::Ready(Some(Err(GitError::Parse(format!(
                            "invalid grep line number '{line}': {e}"
                        )))));
                    }
                };
                Poll::Ready(Some(Ok(crate::types::GitGrepResult {
                    path: parts[0].to_string(),
                    line: line_num,
                    text: parts[2].to_string(),
                })))
            }
            Poll::Ready(Some(Err(e))) => {
                Poll::Ready(Some(Err(GitError::Io(format!("read error: {e}")))))
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(feature = "stream")]
struct LsFilesStream {
    _child: tokio::process::Child,
    lines: Pin<Box<LinesStream<BufReader<tokio::process::ChildStdout>>>>,
}

#[cfg(feature = "stream")]
impl Stream for LsFilesStream {
    type Item = Result<String, GitError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        match this.lines.as_mut().poll_next(cx) {
            Poll::Ready(Some(Ok(line))) => Poll::Ready(Some(Ok(line))),
            Poll::Ready(Some(Err(e))) => {
                Poll::Ready(Some(Err(GitError::Io(format!("read error: {e}")))))
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(feature = "stream")]
struct BlameStream {
    _child: tokio::process::Child,
    lines: Pin<Box<LinesStream<BufReader<tokio::process::ChildStdout>>>>,
    buf_sha: String,
    buf_author: String,
    buf_author_mail: String,
    buf_author_time: String,
}

#[cfg(feature = "stream")]
impl Stream for BlameStream {
    type Item = Result<crate::types::BlameLine, GitError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        loop {
            match this.lines.as_mut().poll_next(cx) {
                Poll::Ready(Some(Ok(line))) => {
                    if let Some(content) = line.strip_prefix('\t') {
                        // Content line — block is complete.
                        let content = content.to_string();
                        let line_no = 0usize; // Will be assigned sequentially downstream
                        let sha = std::mem::take(&mut this.buf_sha);
                        let author = std::mem::take(&mut this.buf_author);
                        let author_mail = std::mem::take(&mut this.buf_author_mail);
                        let author_time = std::mem::take(&mut this.buf_author_time);
                        return Poll::Ready(Some(Ok(crate::types::BlameLine {
                            commit: sha,
                            author,
                            author_mail,
                            author_time,
                            line_no,
                            content,
                        })));
                    } else if let Some(rest) = line.strip_prefix("author ") {
                        this.buf_author = rest.to_string();
                    } else if let Some(rest) = line.strip_prefix("author-mail ") {
                        this.buf_author_mail = rest.trim_matches('<').trim_matches('>').to_string();
                    } else if let Some(rest) = line.strip_prefix("author-time ") {
                        this.buf_author_time = rest.to_string();
                    } else if !line.is_empty()
                        && line.as_bytes()[0].is_ascii_hexdigit()
                        && line.split_whitespace().next().map(|s| s.len()) == Some(40)
                    {
                        // New blame block header — SHA <orig-line> <final-line> <group-lines>
                        this.buf_sha = line.split_whitespace().next().unwrap_or("").to_string();
                    }
                }
                Poll::Ready(Some(Err(e))) => {
                    return Poll::Ready(Some(Err(GitError::Io(format!("read error: {e}")))));
                }
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

impl Repository {
    /// Open a repository, validating that `.git` exists and git is in PATH.
    pub async fn open(path: impl AsRef<Path>) -> Result<Self, GitError> {
        let root = tokio::fs::canonicalize(path.as_ref())
            .await
            .map_err(|e| GitError::Io(format!("failed to canonicalize path: {e}")))?;
        let dot_git = root.join(".git");
        if !dot_git.exists() {
            return Err(GitError::NotARepo(root));
        }
        let cmd = GitCommand::new(root.clone())?;
        Ok(Self {
            root,
            cmd,
            cache: None,
        })
    }

    /// Open an existing worktree directory as a repository handle.
    ///
    /// This is currently an alias for [`Repository::open`](Self::open).
    /// It does not verify that the directory is actually a git worktree.
    pub async fn open_worktree(path: impl AsRef<Path>) -> Result<Self, GitError> {
        Self::open(path).await
    }

    /// Initialize a new git repository at `path` and return a handle.
    ///
    /// The parent directory must already exist.
    pub async fn init(path: impl AsRef<Path>) -> Result<Self, GitError> {
        let path = path.as_ref();
        let git_bin = crate::command::git_bin_path()?;
        let parent = path.parent().unwrap_or(Path::new("."));
        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(".");
        let output = timeout(
            Duration::from_secs(60),
            tokio::process::Command::new(&git_bin)
                .current_dir(parent)
                .args(["init", name])
                .env("GIT_TERMINAL_PROMPT", "0")
                .env("GIT_ASKPASS", "echo")
                .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
                .env("LC_ALL", "C")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .map_err(|_| GitError::Timeout(Duration::from_secs(60), "git init".to_string()))?
        .map_err(|e| GitError::Io(format!("failed to run git init: {e}")))?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: format!("git init {name}"),
                exit_code: output.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            });
        }
        Self::open(path).await
    }

    /// Clone a remote repository into `path` and return a handle.
    ///
    /// The parent directory must already exist.  The operation is subject to
    /// the default 60-second timeout.
    pub async fn clone(url: &str, path: impl AsRef<Path>) -> Result<Self, GitError> {
        let path = path.as_ref();
        let git_bin = crate::command::git_bin_path()?;
        let parent = path.parent().unwrap_or(Path::new("."));
        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("repo");
        let output = timeout(
            Duration::from_secs(60),
            tokio::process::Command::new(&git_bin)
                .current_dir(parent)
                .args(["clone", url, name])
                .env("GIT_TERMINAL_PROMPT", "0")
                .env("GIT_ASKPASS", "echo")
                .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
                .env("LC_ALL", "C")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .map_err(|_| GitError::Timeout(Duration::from_secs(60), "git clone".to_string()))?
        .map_err(|e| GitError::Io(format!("failed to run git clone: {e}")))?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: format!("git clone {url} {name}"),
                exit_code: output.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            });
        }
        Self::open(path).await
    }

    /// Clone a repository with options.
    pub async fn clone_opts(opts: &crate::types::CloneOptions<'_>) -> Result<Self, GitError> {
        let path = opts.path;
        let git_bin = crate::command::git_bin_path()?;
        let parent = path.parent().unwrap_or(Path::new("."));
        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("repo");
        let mut args: Vec<String> = vec!["clone".into(), opts.url.into(), name.into()];
        if let Some(depth) = opts.depth {
            args.push("--depth".into());
            args.push(depth.to_string());
        }
        if let Some(branch) = opts.branch {
            args.push("--branch".into());
            args.push(branch.into());
        }
        if let Some(filter) = opts.filter {
            args.push("--filter".into());
            args.push(filter.into());
        }
        if opts.bare {
            args.push("--bare".into());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let output = timeout(
            Duration::from_secs(60),
            tokio::process::Command::new(&git_bin)
                .current_dir(parent)
                .args(&args_ref)
                .env("GIT_TERMINAL_PROMPT", "0")
                .env("GIT_ASKPASS", "echo")
                .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
                .env("LC_ALL", "C")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .map_err(|_| GitError::Timeout(Duration::from_secs(60), "git clone".to_string()))?
        .map_err(|e| GitError::Io(format!("failed to run git clone: {e}")))?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: format!("git clone {}", args_ref.join(" ")),
                exit_code: output.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            });
        }
        Self::open(path).await
    }

    /// Attach a cancellation token to this repository handle.
    ///
    /// When the token is cancelled, any in-flight git command is killed
    /// and returns [`GitError::Io`] with message `"cancelled"`.
    pub fn with_cancel(mut self, cancel: tokio_util::sync::CancellationToken) -> Self {
        self.cmd = self.cmd.with_cancel(cancel);
        self
    }

    /// Override the default 60-second timeout for all git commands issued
    /// through this handle.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.cmd = self.cmd.with_timeout(timeout);
        self
    }

    /// Attach an in-memory cache to this repository handle.
    ///
    /// When caching is enabled, [`status`](Self::status) and related
    /// read-only queries may return cached results. Callers must
    /// invalidate the cache after mutating operations.
    pub fn with_cache(mut self, cache: Cache) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Add a custom environment variable to all subsequent git commands.
    ///
    /// This is useful for authentication scenarios such as setting
    /// `GIT_ASKPASS` or `GIT_SSH_COMMAND`.
    pub fn with_env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.cmd = self.cmd.with_env_var(key, value);
        self
    }

    /// Attach a circuit breaker for network operations (fetch, push, pull, clone, ls-remote).
    pub fn with_circuit_breaker(mut self, breaker: CircuitBreaker) -> Self {
        self.cmd = self.cmd.with_circuit_breaker(breaker);
        self
    }

    /// Attach a progress callback for network operations.
    ///
    /// The callback is invoked with each line of stderr as it is produced,
    /// which is useful for reporting clone/fetch/push progress to users.
    pub fn with_progress(mut self, callback: impl Fn(String) + Send + Sync + 'static) -> Self {
        self.cmd = self.cmd.with_progress(callback);
        self
    }

    /// Invalidate the attached cache, if any.
    pub fn invalidate_cache(&self) {
        if let Some(c) = &self.cache {
            c.clear();
        }
    }

    /// Path to the repository root.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get the detected git version for this repository.
    pub fn git_version(&self) -> GitVersion {
        self.cmd.git_version()
    }

    /// Ensure the working tree is clean (no staged/unstaged changes; untracked ignored).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn ensure_clean(&self) -> Result<(), GitError> {
        let status = self.status().await?;
        if !status.staged.is_empty() || !status.unstaged.is_empty() {
            let mut files: Vec<String> = status.staged;
            files.extend(status.unstaged);
            return Err(GitError::Dirty(files.join(", ")));
        }
        Ok(())
    }

    /// Get the current branch name.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn current_branch(&self) -> Result<String, GitError> {
        let out = self.cmd.run(&["rev-parse", "--abbrev-ref", "HEAD"]).await?;
        let branch = out.stdout.trim().to_string();
        if branch.is_empty() || branch == "HEAD" {
            return Err(GitError::Parse("detached HEAD or empty branch".to_string()));
        }
        Ok(branch)
    }

    /// Get the short SHA of HEAD.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn head_commit(&self) -> Result<Oid, GitError> {
        let out = self.cmd.run(&["rev-parse", "--short", "HEAD"]).await?;
        Oid::new(out.stdout.trim())
    }

    /// Get the full SHA of HEAD.
    pub async fn head_commit_full(&self) -> Result<Oid, GitError> {
        let out = self.cmd.run(&["rev-parse", "HEAD"]).await?;
        Oid::new(out.stdout.trim())
    }

    /// List changed files (modified, staged, untracked).
    pub async fn changed_files(&self) -> Result<Vec<String>, GitError> {
        let status = self.status().await?;
        let mut files = Vec::new();
        files.extend(status.staged);
        files.extend(status.unstaged);
        files.extend(status.untracked);
        files.sort();
        files.dedup();
        Ok(files)
    }

    /// List untracked files.
    pub async fn untracked_files(&self) -> Result<Vec<String>, GitError> {
        let status = self.status().await?;
        Ok(status.untracked)
    }

    /// List files with unresolved merge/rebase conflicts.
    pub async fn conflicted_files(&self) -> Result<Vec<String>, GitError> {
        let out = self
            .cmd
            .run(&["diff", "--name-only", "--diff-filter=U"])
            .await?;
        let files: Vec<String> = out.stdout.lines().map(|s| s.to_string()).collect();
        Ok(files)
    }

    /// Whether the repository has unresolved merge/rebase conflicts.
    pub async fn is_merge_conflict(&self) -> Result<bool, GitError> {
        Ok(!self.conflicted_files().await?.is_empty())
    }

    /// Whether there are no staged or unstaged changes (untracked ignored).
    pub async fn is_nothing_to_commit(&self) -> Result<bool, GitError> {
        let status = self.status().await?;
        Ok(status.staged.is_empty() && status.unstaged.is_empty())
    }

    /// Whether there are untracked files.
    pub async fn has_untracked_files(&self) -> Result<bool, GitError> {
        let status = self.status().await?;
        Ok(!status.untracked.is_empty())
    }

    /// Raw `git status --porcelain` output.
    pub async fn status_porcelain(&self) -> Result<String, GitError> {
        let out = self.cmd.run(&["status", "--porcelain"]).await?;
        Ok(out.stdout)
    }

    /// Parse and return structured status.
    pub async fn status(&self) -> Result<GitStatus, GitError> {
        if let Some(c) = &self.cache {
            if let Some(cached) = c.get("status") {
                return parse::parse_status(&cached);
            }
        }
        let out = self.cmd.run(&["status", "--porcelain"]).await?;
        let status = parse::parse_status(&out.stdout)?;
        if let Some(c) = &self.cache {
            c.set("status".to_string(), out.stdout);
        }
        Ok(status)
    }

    /// Parse and return structured status from null-delimited porcelain.
    pub async fn status_z(&self) -> Result<GitStatus, GitError> {
        let out = self.cmd.run(&["status", "--porcelain", "-z"]).await?;
        parse::parse_status_z(&out.stdout)
    }

    /// Add a worktree at `path` tracking `branch`.
    pub async fn worktree_add(
        &self,
        path: impl AsRef<Path>,
        branch: &str,
    ) -> Result<GitWorktree, GitError> {
        let path = path.as_ref();
        let out = self
            .cmd
            .run(&["worktree", "add", &path.to_string_lossy(), branch])
            .await;

        if let Err(GitError::CommandFailed { ref stderr, .. }) = out {
            if stderr.contains("already exists") || stderr.contains("is already registered") {
                return Err(GitError::WorktreeExists(path.to_string_lossy().to_string()));
            }
        }
        out?;
        self.invalidate_cache();
        Ok(GitWorktree {
            path: path.to_path_buf(),
            branch: branch.to_string(),
        })
    }

    /// Remove a worktree at `path`.
    pub async fn worktree_remove(
        &self,
        path: impl AsRef<Path>,
        force: bool,
    ) -> Result<(), GitError> {
        let path = path.as_ref();
        let path_str = path.to_string_lossy();
        let mut args = vec!["worktree", "remove"];
        if force {
            args.push("--force");
        }
        args.push(&path_str);
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// List all worktrees.
    pub async fn worktree_list(&self) -> Result<Vec<GitWorktree>, GitError> {
        let out = self.cmd.run(&["worktree", "list", "--porcelain"]).await?;
        parse::parse_worktrees(&out.stdout)
    }

    /// Prune stale worktrees.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn worktree_prune(&self) -> Result<(), GitError> {
        self.cmd.run(&["worktree", "prune"]).await?;
        Ok(())
    }

    /// Lock a worktree to prevent pruning.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn worktree_lock(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        self.cmd.run(&["worktree", "lock", &path_str]).await?;
        Ok(())
    }

    /// Unlock a worktree.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn worktree_unlock(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        self.cmd.run(&["worktree", "unlock", &path_str]).await?;
        Ok(())
    }

    /// Move a worktree to a new location.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn worktree_move(
        &self,
        old_path: impl AsRef<Path>,
        new_path: impl AsRef<Path>,
    ) -> Result<(), GitError> {
        let old = old_path.as_ref().to_string_lossy();
        let new = new_path.as_ref().to_string_lossy();
        self.cmd.run(&["worktree", "move", &old, &new]).await?;
        Ok(())
    }

    /// Create a new branch.
    pub async fn branch_create(
        &self,
        name: &str,
        start_point: Option<&str>,
    ) -> Result<(), GitError> {
        let mut args = vec!["branch", name];
        if let Some(sp) = start_point {
            args.push(sp);
        }
        let out = self.cmd.run(&args).await;
        if let Err(GitError::CommandFailed { ref stderr, .. }) = out {
            if stderr.contains("already exists") {
                return Err(GitError::BranchExists(name.to_string()));
            }
        }
        out?;
        self.invalidate_cache();
        Ok(())
    }

    /// Delete a local branch.
    pub async fn branch_delete(&self, name: &str, force: bool) -> Result<(), GitError> {
        let flag = if force { "-D" } else { "-d" };
        let out = self.cmd.run(&["branch", flag, name]).await;
        if let Err(GitError::CommandFailed { ref stderr, .. }) = out {
            if stderr.contains("not found") {
                return Err(GitError::BranchNotFound(name.to_string()));
            }
        }
        out?;
        self.invalidate_cache();
        Ok(())
    }

    /// Rename a branch.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn branch_rename(&self, old: &str, new: &str, force: bool) -> Result<(), GitError> {
        if force {
            self.cmd.run(&["branch", "-M", old, new]).await?;
        } else {
            self.cmd.run(&["branch", "-m", old, new]).await?;
        }
        self.invalidate_cache();
        Ok(())
    }

    /// Check whether a branch exists (local or remote-tracking).
    pub async fn branch_exists(&self, name: &str) -> Result<bool, GitError> {
        let out = self
            .cmd
            .run(&["branch", "--format=%(refname:short)"])
            .await?;
        let branches = parse::parse_branches(&out.stdout)?;
        Ok(branches.iter().any(|b| b == name))
    }

    /// Checkout a branch.
    pub async fn checkout(&self, branch: &str) -> Result<(), GitError> {
        let out = self.cmd.run(&["checkout", branch]).await;
        if let Err(GitError::CommandFailed { ref stderr, .. }) = out {
            if stderr.contains("did not match") || stderr.contains("not found") {
                return Err(GitError::BranchNotFound(branch.to_string()));
            }
        }
        out?;
        self.invalidate_cache();
        Ok(())
    }

    /// Switch to a branch (modern alternative to checkout).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn switch(&self, branch: &str, create: bool) -> Result<(), GitError> {
        let mut args = vec!["switch"];
        if create {
            args.push("-c");
        }
        args.push(branch);
        let out = self.cmd.run(&args).await;
        if let Err(GitError::CommandFailed { ref stderr, .. }) = out {
            if stderr.contains("did not match") || stderr.contains("not found") {
                return Err(GitError::BranchNotFound(branch.to_string()));
            }
        }
        out?;
        self.invalidate_cache();
        Ok(())
    }

    /// Restore working tree files (modern alternative to checkout --).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn restore(
        &self,
        paths: &[impl AsRef<Path>],
        staged: bool,
        source: Option<&str>,
    ) -> Result<(), GitError> {
        let mut args = vec!["restore"];
        if staged {
            args.push("--staged");
        }
        if let Some(src) = source {
            args.push("--source");
            args.push(src);
        }
        for p in paths {
            if let Some(s) = p.as_ref().to_str() {
                args.push(s);
            }
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Read-only merge-tree conflict detection.
    pub async fn merge_tree(&self, base: &str, branch: &str) -> Result<GitMergeResult, GitError> {
        let out = self.cmd.run(&["merge-tree", base, branch]).await;
        match out {
            Ok(o) => parse::parse_merge_tree(&o.stdout),
            Err(GitError::CommandFailed {
                stdout,
                stderr,
                exit_code,
                command,
            }) => {
                let combined = format!("{stdout}\n{stderr}");
                let result = parse::parse_merge_tree(&combined)?;
                if result.has_conflicts {
                    #[cfg(feature = "tracing")]
                    debug!(
                        base,
                        branch,
                        files = ?result.conflict_files,
                        "merge-tree detected conflicts"
                    );
                    Ok(result)
                } else {
                    Err(GitError::CommandFailed {
                        command,
                        exit_code,
                        stderr,
                        stdout,
                    })
                }
            }
            Err(other) => Err(other),
        }
    }

    /// Commit with options.
    pub async fn commit_opts(&self, opts: &CommitOptions<'_>) -> Result<String, GitError> {
        let mut args: Vec<String> = vec!["commit".into(), "-m".into(), opts.message.into()];
        if opts.no_verify {
            args.push("--no-verify".into());
        }
        if opts.amend {
            args.push("--amend".into());
        }
        if opts.signoff {
            args.push("--signoff".into());
        }
        if opts.paths.is_empty() {
            args.push("-a".into());
        } else {
            args.push("--".into());
            for p in opts.paths {
                args.push(p.to_string_lossy().into());
            }
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let _out = self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        let sha = self.head_commit().await?;
        #[cfg(feature = "tracing")]
        debug!(%sha, "committed");
        Ok(sha.to_string())
    }

    /// Commit with `message`. If `paths` is empty, commits all changes (`-a`).
    pub async fn commit(
        &self,
        message: &str,
        paths: &[impl AsRef<Path>],
        no_verify: bool,
    ) -> Result<String, GitError> {
        let paths: Vec<&Path> = paths.iter().map(|p| p.as_ref()).collect();
        self.commit_opts(&CommitOptions {
            message,
            paths: &paths,
            no_verify,
            amend: false,
            signoff: false,
        })
        .await
    }

    /// Push with options.
    pub async fn push_opts(&self, opts: &PushOptions<'_>) -> Result<(), GitError> {
        let mut args = vec!["push", opts.remote, opts.branch];
        if opts.force {
            args.push("--force");
        }
        if opts.force_with_lease {
            args.push("--force-with-lease");
        }
        if opts.set_upstream {
            args.push("--set-upstream");
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Push `branch` to `remote`.
    pub async fn push(&self, remote: &str, branch: &str, force: bool) -> Result<(), GitError> {
        self.push_opts(&PushOptions {
            remote,
            branch,
            force_with_lease: force,
            ..Default::default()
        })
        .await
    }

    /// Push with `--force` (not `--force-with-lease`).
    pub async fn push_force(&self, remote: &str, branch: &str) -> Result<(), GitError> {
        self.cmd.run(&["push", "--force", remote, branch]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Fetch with options.
    pub async fn fetch_opts(&self, opts: &FetchOptions<'_>) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["fetch".into(), opts.remote.into()];
        if opts.prune {
            args.push("--prune".into());
        }
        if opts.tags {
            args.push("--tags".into());
        }
        if let Some(depth) = opts.depth {
            args.push("--depth".into());
            args.push(depth.to_string());
        }
        if let Some(filter) = opts.filter {
            args.push("--filter".into());
            args.push(filter.into());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        Ok(())
    }

    /// Fetch from `remote`.
    pub async fn fetch(&self, remote: &str) -> Result<(), GitError> {
        self.fetch_opts(&FetchOptions {
            remote,
            ..Default::default()
        })
        .await
    }

    /// Get the URL for `remote`, if configured.
    pub async fn remote_url(&self, remote: &str) -> Result<Option<String>, GitError> {
        let out = self.cmd.run(&["remote", "get-url", remote]).await;
        match out {
            Ok(o) => Ok(Some(o.stdout.trim().to_string())),
            Err(GitError::CommandFailed { stderr, .. }) if stderr.contains("No such remote") => {
                Ok(None)
            }
            Err(other) => Err(other),
        }
    }

    /// Add a new remote.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn remote_add(&self, name: &str, url: &str) -> Result<(), GitError> {
        self.cmd.run(&["remote", "add", name, url]).await?;
        Ok(())
    }

    /// Remove a remote.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn remote_remove(&self, name: &str) -> Result<(), GitError> {
        self.cmd.run(&["remote", "remove", name]).await?;
        Ok(())
    }

    /// Rename a remote.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn remote_rename(&self, old: &str, new: &str) -> Result<(), GitError> {
        self.cmd.run(&["remote", "rename", old, new]).await?;
        Ok(())
    }

    /// List refs on a remote without fetching.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn ls_remote(
        &self,
        remote: &str,
        refs: Option<&[&str]>,
    ) -> Result<Vec<(String, String)>, GitError> {
        let mut args = vec!["ls-remote", remote];
        if let Some(r) = refs {
            for ref_name in r {
                args.push(ref_name);
            }
        }
        let out = self.cmd.run(&args).await?;
        let mut result = Vec::new();
        for line in out.stdout.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() == 2 {
                result.push((parts[0].to_string(), parts[1].to_string()));
            }
        }
        Ok(result)
    }

    /// Pull from a remote branch.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn pull(&self, remote: &str, branch: &str, rebase: bool) -> Result<(), GitError> {
        let mut args = vec!["pull", remote, branch];
        if rebase {
            args.push("--rebase");
        } else {
            args.push("--no-rebase");
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Get unstaged diff.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn diff(&self) -> Result<String, GitError> {
        let out = self.cmd.run(&["diff"]).await?;
        Ok(out.stdout)
    }

    /// Get diff statistics via `--shortstat`.
    pub async fn diff_shortstat(&self) -> Result<crate::parse::DiffShortstat, GitError> {
        let out = self.cmd.run(&["diff", "--shortstat"]).await?;
        crate::parse::parse_diff_shortstat(&out.stdout)
    }

    /// Get diff for specific paths.
    pub async fn diff_files(&self, paths: &[impl AsRef<Path>]) -> Result<String, GitError> {
        let mut args: Vec<String> = vec!["diff".into(), "--".into()];
        for p in paths {
            args.push(p.as_ref().to_string_lossy().into_owned());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let out = self.cmd.run(&args_ref).await?;
        Ok(out.stdout.to_string())
    }

    /// Get a structured diff of unstaged changes.
    pub async fn diff_structured(&self) -> Result<Vec<crate::types::FileDiff>, GitError> {
        let out = self.cmd.run(&["diff"]).await?;
        crate::parse::parse_diff(&out.stdout)
    }

    /// Get a structured diff of staged changes.
    pub async fn diff_cached_structured(&self) -> Result<Vec<crate::types::FileDiff>, GitError> {
        let out = self.cmd.run(&["diff", "--cached"]).await?;
        crate::parse::parse_diff(&out.stdout)
    }

    /// Get a structured diff for specific paths.
    pub async fn diff_files_structured(
        &self,
        paths: &[impl AsRef<Path>],
    ) -> Result<Vec<crate::types::FileDiff>, GitError> {
        let mut args: Vec<String> = vec!["diff".into(), "--".into()];
        for p in paths {
            args.push(p.as_ref().to_string_lossy().into_owned());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let out = self.cmd.run(&args_ref).await?;
        crate::parse::parse_diff(&out.stdout)
    }

    /// Stage all changes (including untracked).
    pub async fn add_all(&self) -> Result<(), GitError> {
        self.cmd.run(&["add", "-A"]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Stage a specific path.
    pub async fn add(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        self.cmd.run(&["add", &path_str]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Move or rename a tracked file.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn mv(
        &self,
        source: impl AsRef<Path>,
        dest: impl AsRef<Path>,
    ) -> Result<(), GitError> {
        let src = source.as_ref().to_string_lossy();
        let dst = dest.as_ref().to_string_lossy();
        self.cmd.run(&["mv", &src, &dst]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Remove tracked files.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn rm(&self, paths: &[impl AsRef<Path>], cached: bool) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["rm".into()];
        if cached {
            args.push("--cached".into());
        }
        for p in paths {
            args.push(p.as_ref().to_string_lossy().into_owned());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Stash changes with an optional message.
    pub async fn stash(&self, message: Option<&str>) -> Result<(), GitError> {
        let mut args = vec!["stash", "push"];
        if let Some(msg) = message {
            args.push("-m");
            args.push(msg);
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Pop the latest stash.
    pub async fn stash_pop(&self) -> Result<(), GitError> {
        self.cmd.run(&["stash", "pop"]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Drop a stash entry.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn stash_drop(&self, index: Option<usize>) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["stash".into(), "drop".into()];
        if let Some(i) = index {
            args.push(format!("stash@{{{i}}}"));
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Apply a stash entry without removing it.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn stash_apply(&self, index: Option<usize>) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["stash".into(), "apply".into()];
        if let Some(i) = index {
            args.push(format!("stash@{{{i}}}"));
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Show the diff of a stash entry.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn stash_show(&self, index: Option<usize>) -> Result<String, GitError> {
        let mut args: Vec<String> = vec!["stash".into(), "show".into(), "-p".into()];
        if let Some(i) = index {
            args.push(format!("stash@{{{i}}}"));
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let out = self.cmd.run(&args_ref).await?;
        Ok(out.stdout)
    }

    /// Merge with options.
    pub async fn merge_opts(&self, opts: &MergeOptions<'_>) -> Result<(), GitError> {
        let mut args = vec!["merge", opts.branch];
        if opts.no_edit {
            args.push("--no-edit");
        }
        if opts.no_ff {
            args.push("--no-ff");
        }
        if opts.squash {
            args.push("--squash");
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Merge branch into current HEAD (mutating).
    pub async fn merge(&self, branch: &str, no_edit: bool) -> Result<(), GitError> {
        self.merge_opts(&MergeOptions {
            branch,
            no_edit,
            ..Default::default()
        })
        .await
    }

    /// Find the best common ancestor(s) between commits.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn merge_base(&self, commits: &[&str]) -> Result<String, GitError> {
        let mut args = vec!["merge-base"];
        for c in commits {
            args.push(c);
        }
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout.trim().to_string())
    }

    /// Rebase with options.
    pub async fn rebase_opts(&self, opts: &RebaseOptions<'_>) -> Result<(), GitError> {
        let mut args = vec!["rebase"];
        if opts.interactive {
            args.push("--interactive");
        }
        if opts.autosquash {
            args.push("--autosquash");
        }
        if let Some(onto) = opts.onto {
            args.push("--onto");
            args.push(onto);
        }
        args.push(opts.branch);
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Rebase current HEAD onto branch.
    pub async fn rebase(&self, branch: &str) -> Result<(), GitError> {
        self.rebase_opts(&RebaseOptions {
            branch,
            ..Default::default()
        })
        .await
    }

    /// Abort an in-progress rebase.
    pub async fn rebase_abort(&self) -> Result<(), GitError> {
        self.cmd.run(&["rebase", "--abort"]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Continue an in-progress rebase after conflicts are resolved.
    pub async fn rebase_continue(&self) -> Result<(), GitError> {
        self.cmd
            .run_with_env(&["rebase", "--continue"], &[("GIT_EDITOR", "true")])
            .await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Get the commit log.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn log(
        &self,
        max_count: Option<usize>,
    ) -> Result<Vec<crate::types::GitLogEntry>, GitError> {
        let mut args: Vec<String> = vec!["log".into(), "--format=%H|%s|%an|%at".into()];
        if let Some(n) = max_count {
            args.push("-n".into());
            args.push(n.to_string());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let out = self.cmd.run(&args_ref).await?;
        parse::parse_log(&out.stdout)
    }

    /// Get a paginated slice of the commit log.
    ///
    /// Use `skip` to offset and `max_count` to limit. Useful for large
    /// repositories where loading the entire log into memory is impractical.
    pub async fn log_paginated(
        &self,
        skip: usize,
        max_count: usize,
    ) -> Result<Vec<crate::types::GitLogEntry>, GitError> {
        let args_ref: Vec<String> = vec![
            "log".into(),
            "--format=%H|%s|%an|%at".into(),
            "--skip".into(),
            skip.to_string(),
            "-n".into(),
            max_count.to_string(),
        ];
        let args_str: Vec<&str> = args_ref.iter().map(|s| s.as_str()).collect();
        let out = self.cmd.run(&args_str).await?;
        parse::parse_log(&out.stdout)
    }

    /// Stream commit log entries asynchronously.
    ///
    /// Returns a [`Stream`](tokio_stream::Stream) that yields
    /// [`GitLogEntry`](crate::types::GitLogEntry) values as they are produced
    /// by `git log`.  This avoids buffering the entire log in memory.
    ///
    /// Available only when the **`stream`** feature is enabled.
    #[cfg(feature = "stream")]
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn log_stream(
        &self,
    ) -> Result<impl Stream<Item = Result<crate::types::GitLogEntry, GitError>>, GitError> {
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["log", "--format=%H|%s|%an|%at"])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git log: {e}")))?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| GitError::Io("missing stdout".to_string()))?;
        let lines = LinesStream::new(BufReader::new(stdout).lines());
        Ok(LogStream {
            _child: child,
            lines: Box::pin(lines),
        })
    }

    /// List configured remotes.
    pub async fn remotes(&self) -> Result<Vec<crate::types::GitRemote>, GitError> {
        let out = self.cmd.run(&["remote", "-v"]).await?;
        parse::parse_remotes(&out.stdout)
    }

    /// Get the default branch name from remote.
    pub async fn default_branch(&self) -> Result<String, GitError> {
        let out = self
            .cmd
            .run(&["symbolic-ref", "refs/remotes/origin/HEAD"])
            .await?;
        let stdout = out.stdout.trim();
        if let Some(branch) = stdout.strip_prefix("refs/remotes/origin/") {
            if !branch.is_empty() {
                return Ok(branch.to_string());
            }
        }
        Err(GitError::Parse(format!(
            "unexpected origin/HEAD format: {stdout}"
        )))
    }

    /// Read a git config value.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn config_get(&self, key: &str) -> Result<Option<String>, GitError> {
        let out = self.cmd.run(&["config", key]).await;
        match out {
            Ok(o) => Ok(Some(o.stdout.trim().to_string())),
            Err(GitError::CommandFailed {
                ref stderr,
                ref stdout,
                exit_code,
                ..
            }) if stderr.contains("not in config")
                || stderr.contains("has no value")
                || (exit_code == 1 && stderr.is_empty() && stdout.is_empty()) =>
            {
                Ok(None)
            }
            Err(other) => Err(other),
        }
    }

    /// Set a git config value.
    pub async fn config_set(&self, key: &str, value: &str) -> Result<(), GitError> {
        self.cmd.run(&["config", key, value]).await?;
        Ok(())
    }

    /// Unset a git config value.
    ///
    /// Returns `Ok(())` even if the key did not exist.
    pub async fn config_unset(&self, key: &str) -> Result<(), GitError> {
        let out = self.cmd.run(&["config", "--unset", key]).await;
        match out {
            Ok(_) => Ok(()),
            Err(GitError::CommandFailed {
                ref stderr,
                exit_code,
                ..
            }) if exit_code == 5 || stderr.contains("not in config") => Ok(()),
            Err(other) => Err(other),
        }
    }

    /// List all tags.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn tag_list(&self) -> Result<Vec<crate::types::GitTag>, GitError> {
        let out = self
            .cmd
            .run(&[
                "tag",
                "--list",
                "--format=%(refname:short)|%(objectname:short)|%(subject)",
            ])
            .await?;
        let mut tags = Vec::new();
        for line in out.stdout.lines() {
            let parts: Vec<&str> = line.splitn(3, '|').collect();
            if parts.len() == 3 {
                tags.push(crate::types::GitTag {
                    name: parts[0].to_string(),
                    sha: parts[1].to_string(),
                    message: parts[2].to_string(),
                });
            }
        }
        Ok(tags)
    }

    /// Create a new tag.
    pub async fn tag_create(
        &self,
        name: &str,
        message: Option<&str>,
        force: bool,
    ) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["tag".into()];
        if force {
            args.push("-f".into());
        }
        if let Some(msg) = message {
            args.push("-a".into());
            args.push("-m".into());
            args.push(msg.into());
        }
        args.push(name.into());
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Delete a tag.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn tag_delete(&self, name: &str) -> Result<(), GitError> {
        self.cmd.run(&["tag", "-d", name]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Create a signed (annotated) tag.
    ///
    /// If `gpg_key` is `Some`, it is passed as `-u <key>`; otherwise the
    /// default signing key configured in git is used.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn tag_create_signed(
        &self,
        name: &str,
        message: &str,
        gpg_key: Option<&str>,
    ) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["tag".into(), "-s".into(), "-m".into(), message.into()];
        if let Some(key) = gpg_key {
            args.push("-u".into());
            args.push(key.into());
        }
        args.push(name.into());
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Verify the GPG/SSH signature of a tag.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn verify_tag(&self, name: &str) -> Result<crate::types::GitVerification, GitError> {
        let out = self.cmd.run(&["tag", "-v", name]).await;
        match out {
            Ok(_) => Ok(crate::types::GitVerification {
                valid: true,
                signer: None,
                fingerprint: None,
                status: "G".to_string(),
            }),
            Err(GitError::CommandFailed {
                ref stderr,
                exit_code,
                ..
            }) if exit_code == 1
                && (stderr.contains("no signature")
                    || stderr.contains("Can't check signature")
                    || stderr.contains("no GPG signature")) =>
            {
                Ok(crate::types::GitVerification {
                    valid: false,
                    signer: None,
                    fingerprint: None,
                    status: "N".to_string(),
                })
            }
            Err(other) => Err(other),
        }
    }

    /// Show file contents at a given revision.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn show(&self, path: &str, rev: Option<&str>) -> Result<String, GitError> {
        let spec = match rev {
            Some(r) => format!("{r}:{path}"),
            None => format!("HEAD:{path}"),
        };
        let out = self.cmd.run(&["show", &spec]).await?;
        Ok(out.stdout)
    }

    /// Resolve a revision to a full SHA.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn rev_parse(&self, rev: &str) -> Result<String, GitError> {
        let out = self.cmd.run(&["rev-parse", rev]).await?;
        Ok(out.stdout.trim().to_string())
    }

    /// Get blame information for a file.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn blame(&self, path: &str) -> Result<String, GitError> {
        let out = self.cmd.run(&["blame", "--line-porcelain", path]).await?;
        Ok(out.stdout)
    }

    /// Get structured blame information for a file.
    pub async fn blame_structured(
        &self,
        path: &str,
    ) -> Result<Vec<crate::types::BlameLine>, GitError> {
        let out = self.cmd.run(&["blame", "--line-porcelain", path]).await?;
        crate::parse::parse_blame(&out.stdout)
    }

    /// Stream blame information for a file line-by-line.
    #[cfg(feature = "stream")]
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn blame_stream(
        &self,
        path: &str,
    ) -> Result<impl Stream<Item = Result<crate::types::BlameLine, GitError>>, GitError> {
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["blame", "--line-porcelain", path])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git blame: {e}")))?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| GitError::Io("missing stdout".to_string()))?;
        let lines = LinesStream::new(BufReader::new(stdout).lines());
        Ok(BlameStream {
            _child: child,
            lines: Box::pin(lines),
            buf_sha: String::new(),
            buf_author: String::new(),
            buf_author_mail: String::new(),
            buf_author_time: String::new(),
        })
    }

    /// Generate patches for a commit range using `git format-patch --stdout`.
    pub async fn format_patch(&self, range: &str) -> Result<Vec<crate::types::Patch>, GitError> {
        let out = self.cmd.run(&["format-patch", "--stdout", range]).await?;
        crate::parse::parse_format_patch(&out.stdout)
    }

    /// Apply a patch string to the working tree.
    ///
    /// When `dry_run` is `true`, only checks whether the patch can be applied
    /// without making any changes.
    pub async fn apply_patch(&self, patch: &str, dry_run: bool) -> Result<(), GitError> {
        let tmp = std::env::temp_dir().join(format!("gitr-patch-{}", std::process::id()));
        tokio::fs::write(&tmp, patch)
            .await
            .map_err(|e| GitError::Io(e.to_string()))?;
        let result = self.apply_patch_file(&tmp, dry_run).await;
        // Best-effort cleanup of the temporary patch file.
        #[allow(unused_must_use)]
        let _ = tokio::fs::remove_file(&tmp).await;
        result
    }

    /// Apply a patch file to the working tree.
    ///
    /// When `dry_run` is `true`, only checks whether the patch can be applied
    /// without making any changes.
    pub async fn apply_patch_file(
        &self,
        path: impl AsRef<Path>,
        dry_run: bool,
    ) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        if dry_run {
            self.cmd.run(&["apply", "--check", &path_str]).await?;
        } else {
            self.cmd.run(&["apply", &path_str]).await?;
        }
        Ok(())
    }

    /// List reflog entries for a ref (defaults to HEAD).
    pub async fn reflog_list(
        &self,
        ref_name: Option<&str>,
    ) -> Result<Vec<crate::types::ReflogEntry>, GitError> {
        let ref_name = ref_name.unwrap_or("HEAD");
        let out = self
            .cmd
            .run(&[
                "reflog",
                "show",
                "--format=%H|%an|%ae|%at|%gs|%gd",
                ref_name,
            ])
            .await?;
        crate::parse::parse_reflog(&out.stdout)
    }

    /// Expire reflog entries older than `expire_time` for a ref.
    ///
    /// `expire_time` can be an absolute timestamp or a relative date
    /// (e.g. "2.weeks.ago"). If `None`, uses git's default expiration.
    pub async fn reflog_expire(
        &self,
        ref_name: &str,
        expire_time: Option<&str>,
    ) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["reflog".into(), "expire".into(), ref_name.into()];
        if let Some(time) = expire_time {
            // git <2.38 requires `--expire=time` (single token); newer versions
            // accept both forms. Use the compatible form.
            args.push(format!("--expire={time}"));
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        Ok(())
    }

    /// List installed hooks in `.git/hooks/`.
    pub async fn hooks_list(&self) -> Result<Vec<crate::types::Hook>, GitError> {
        let hooks_dir = self.root.join(".git").join("hooks");
        let mut hooks = Vec::new();
        let mut entries = tokio::fs::read_dir(&hooks_dir)
            .await
            .map_err(|e| GitError::Io(format!("failed to read hooks dir: {e}")))?;
        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| GitError::Io(format!("failed to read hooks dir entry: {e}")))?
        {
            let path = entry.path();
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("")
                .to_string();
            if name.starts_with('.') {
                continue;
            }
            let active = is_executable(&path).await;
            hooks.push(crate::types::Hook { name, path, active });
        }
        Ok(hooks)
    }

    /// Install a hook script.
    ///
    /// The script is written to `.git/hooks/<name>` and made executable on Unix.
    pub async fn hook_install(&self, name: &str, script: &str) -> Result<(), GitError> {
        let hook_path = self.root.join(".git").join("hooks").join(name);
        tokio::fs::write(&hook_path, script)
            .await
            .map_err(|e| GitError::Io(format!("failed to write hook: {e}")))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = tokio::fs::metadata(&hook_path)
                .await
                .map_err(|e| GitError::Io(format!("failed to read hook metadata: {e}")))?
                .permissions();
            perms.set_mode(perms.mode() | 0o111);
            tokio::fs::set_permissions(&hook_path, perms)
                .await
                .map_err(|e| GitError::Io(format!("failed to set hook permissions: {e}")))?;
        }
        Ok(())
    }

    /// Remove a hook.
    pub async fn hook_remove(&self, name: &str) -> Result<(), GitError> {
        let hook_path = self.root.join(".git").join("hooks").join(name);
        tokio::fs::remove_file(&hook_path)
            .await
            .map_err(|e| GitError::Io(format!("failed to remove hook: {e}")))?;
        Ok(())
    }

    /// Run a hook and capture its output.
    ///
    /// Uses the default 60-second timeout.
    pub async fn run_hook(&self, name: &str) -> Result<crate::types::HookOutput, GitError> {
        self.run_hook_with_timeout(name, Duration::from_secs(60))
            .await
    }

    /// Run a hook with a custom timeout and capture its output.
    pub async fn run_hook_with_timeout(
        &self,
        name: &str,
        timeout: Duration,
    ) -> Result<crate::types::HookOutput, GitError> {
        let hook_path = self.root.join(".git").join("hooks").join(name);
        let out = tokio::time::timeout(
            timeout,
            tokio::process::Command::new(&hook_path)
                .current_dir(&self.root)
                .env("GIT_TERMINAL_PROMPT", "0")
                .env("GIT_ASKPASS", "echo")
                .env("LC_ALL", "C")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .map_err(|_| GitError::Timeout(timeout, format!("hook {name}")))?
        .map_err(|e| GitError::Io(format!("failed to run hook: {e}")))?;
        Ok(crate::types::HookOutput {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            exit_code: out.status.code().unwrap_or(-1),
        })
    }

    /// Run a hook and stream its stdout/stderr line-by-line.
    ///
    /// Each line is sent through the corresponding channel.  The method
    /// returns the process exit code when the hook finishes.
    ///
    /// A default timeout of 60 seconds is applied.
    pub async fn run_hook_streaming(
        &self,
        name: &str,
        stdout_tx: tokio::sync::mpsc::Sender<String>,
        stderr_tx: tokio::sync::mpsc::Sender<String>,
    ) -> Result<i32, GitError> {
        let hook_path = self.root.join(".git").join("hooks").join(name);
        let mut child = tokio::process::Command::new(&hook_path)
            .current_dir(&self.root)
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("LC_ALL", "C")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn hook: {e}")))?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| GitError::Io("missing stdout".to_string()))?;
        let stderr = child
            .stderr
            .take()
            .ok_or_else(|| GitError::Io("missing stderr".to_string()))?;

        let stdout_handle = tokio::spawn(async move {
            let mut reader = BufReader::new(stdout).lines();
            while let Some(line) = reader.next_line().await.transpose() {
                let line = match line {
                    Ok(l) => l,
                    Err(e) => return Err(GitError::Io(format!("stdout read error: {e}"))),
                };
                if stdout_tx.send(line).await.is_err() {
                    break;
                }
            }
            Ok(())
        });

        let stderr_handle = tokio::spawn(async move {
            let mut reader = BufReader::new(stderr).lines();
            while let Some(line) = reader.next_line().await.transpose() {
                let line = match line {
                    Ok(l) => l,
                    Err(e) => return Err(GitError::Io(format!("stderr read error: {e}"))),
                };
                if stderr_tx.send(line).await.is_err() {
                    break;
                }
            }
            Ok(())
        });

        let timeout_dur = Duration::from_secs(60);
        let status = match tokio::time::timeout(timeout_dur, child.wait()).await {
            Ok(Ok(s)) => s,
            Ok(Err(e)) => return Err(GitError::Io(format!("failed to wait for hook: {e}"))),
            Err(_) => {
                // Best-effort kill of the timed-out hook process.
                #[allow(unused_must_use)]
                let _ = child.kill().await;
                return Err(GitError::Timeout(timeout_dur, format!("hook {name}")));
            }
        };

        stdout_handle
            .await
            .map_err(|e| GitError::Io(format!("stdout task panicked: {e}")))??;
        stderr_handle
            .await
            .map_err(|e| GitError::Io(format!("stderr task panicked: {e}")))??;

        Ok(status.code().unwrap_or(-1))
    }

    /// Reset the index and working tree.
    pub async fn reset(
        &self,
        mode: crate::types::ResetMode,
        target: Option<&str>,
    ) -> Result<(), GitError> {
        let mode_flag = match mode {
            crate::types::ResetMode::Soft => "--soft",
            crate::types::ResetMode::Mixed => "--mixed",
            crate::types::ResetMode::Hard => "--hard",
        };
        let mut args = vec!["reset", mode_flag];
        if let Some(t) = target {
            args.push(t);
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Start a bisect session.
    pub async fn bisect_start(
        &self,
        bad: Option<&str>,
        good: &[&str],
    ) -> Result<crate::types::BisectState, GitError> {
        let mut args: Vec<String> = vec!["bisect".into(), "start".into()];
        if let Some(b) = bad {
            args.push(b.into());
        }
        for g in good {
            args.push((*g).into());
        }
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.bisect_state().await
    }

    /// Mark a commit as bad during bisect.
    pub async fn bisect_bad(
        &self,
        commit: Option<&str>,
    ) -> Result<crate::types::BisectState, GitError> {
        let mut args = vec!["bisect", "bad"];
        if let Some(c) = commit {
            args.push(c);
        }
        self.cmd.run(&args).await?;
        self.bisect_state().await
    }

    /// Mark a commit as good during bisect.
    pub async fn bisect_good(
        &self,
        commit: Option<&str>,
    ) -> Result<crate::types::BisectState, GitError> {
        let mut args = vec!["bisect", "good"];
        if let Some(c) = commit {
            args.push(c);
        }
        self.cmd.run(&args).await?;
        self.bisect_state().await
    }

    /// Reset an active bisect session.
    pub async fn bisect_reset(&self) -> Result<(), GitError> {
        self.cmd.run(&["bisect", "reset"]).await?;
        Ok(())
    }

    /// Run a command automatically during bisect.
    pub async fn bisect_run(&self, command: &str) -> Result<String, GitError> {
        let out = self.cmd.run(&["bisect", "run", command]).await?;
        Ok(out.stdout)
    }

    async fn bisect_state(&self) -> Result<crate::types::BisectState, GitError> {
        let out = self.cmd.run(&["rev-parse", "BISECT_HEAD"]).await;
        let current = match out {
            Ok(o) => {
                let sha = o.stdout.trim();
                if sha.is_empty() {
                    None
                } else {
                    Some(sha.to_string())
                }
            }
            Err(_) => None,
        };
        Ok(crate::types::BisectState { current })
    }

    /// List git notes.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn notes_list(
        &self,
        namespace: Option<&str>,
    ) -> Result<Vec<crate::types::GitNote>, GitError> {
        let mut args = vec!["notes".to_string(), "list".to_string()];
        if let Some(ns) = namespace {
            args.push(format!("--ref={ns}"));
        }
        let out = self.cmd.run(&args).await?;
        let mut notes = Vec::new();
        for line in out.stdout.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let mut parts = line.split_whitespace();
            let commit = parts.next().map(String::from);
            let object = parts.next().map(String::from);
            if let (Some(commit), Some(object)) = (commit, object) {
                notes.push(crate::types::GitNote { object, commit });
            }
        }
        Ok(notes)
    }

    /// Show the note for a given object.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn notes_show(
        &self,
        object: &str,
        namespace: Option<&str>,
    ) -> Result<String, GitError> {
        let mut args = vec!["notes".to_string(), "show".to_string()];
        if let Some(ns) = namespace {
            args.push(format!("--ref={ns}"));
        }
        args.push(object.to_string());
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout)
    }

    /// Add a note to an object.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn notes_add(
        &self,
        message: &str,
        object: &str,
        namespace: Option<&str>,
        force: bool,
    ) -> Result<(), GitError> {
        let mut args = vec!["notes".to_string(), "add".to_string()];
        if let Some(ns) = namespace {
            args.push(format!("--ref={ns}"));
        }
        if force {
            args.push("--force".to_string());
        }
        args.push("-m".to_string());
        args.push(message.to_string());
        args.push(object.to_string());
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// Remove the note from an object.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn notes_remove(
        &self,
        object: &str,
        namespace: Option<&str>,
    ) -> Result<(), GitError> {
        let mut args = vec!["notes".to_string(), "remove".to_string()];
        if let Some(ns) = namespace {
            args.push(format!("--ref={ns}"));
        }
        args.push(object.to_string());
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// List stash entries.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn stash_list(&self) -> Result<Vec<crate::types::GitStash>, GitError> {
        let out = self
            .cmd
            .run(&["stash", "list", "--format=%H|%gd|%s"])
            .await?;
        let mut stashes = Vec::new();
        for line in out.stdout.lines() {
            let parts: Vec<&str> = line.splitn(3, '|').collect();
            if parts.len() == 3 {
                stashes.push(crate::types::GitStash {
                    sha: parts[0].to_string(),
                    ref_name: parts[1].to_string(),
                    message: parts[2].to_string(),
                });
            }
        }
        Ok(stashes)
    }

    /// Cherry-pick with options.
    pub async fn cherry_pick_opts(&self, opts: &CherryPickOptions<'_>) -> Result<(), GitError> {
        let mut args = vec!["cherry-pick"];
        if opts.no_commit {
            args.push("--no-commit");
        }
        for c in opts.commits {
            args.push(c);
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Cherry-pick one or more commits.
    pub async fn cherry_pick(&self, commits: &[&str]) -> Result<(), GitError> {
        self.cherry_pick_opts(&CherryPickOptions {
            commits,
            ..Default::default()
        })
        .await
    }

    /// Revert one or more commits.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn revert(&self, commits: &[&str], no_edit: bool) -> Result<(), GitError> {
        let mut args = vec!["revert"];
        if no_edit {
            args.push("--no-edit");
        }
        for c in commits {
            args.push(c);
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Create a GPG-signed commit.
    ///
    /// If `gpg_key` is `Some`, it is passed as `-S <key>`; otherwise the
    /// default signing key configured in git is used.
    /// When `no_verify` is `true`, `--no-verify` is passed to skip hooks.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, paths)))]
    pub async fn commit_signed(
        &self,
        paths: &[&Path],
        message: &str,
        gpg_key: Option<&str>,
        no_verify: bool,
    ) -> Result<(), GitError> {
        let mut args: Vec<String> = vec!["commit".into(), "-S".into()];
        if let Some(key) = gpg_key {
            args.push(key.into());
        }
        if no_verify {
            args.push("--no-verify".into());
        }
        for p in paths {
            args.push(p.to_string_lossy().to_string());
        }
        args.push("-m".into());
        args.push(message.into());
        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        self.cmd.run(&args_ref).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Verify the GPG signature of a commit.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn verify_commit(
        &self,
        sha: &str,
    ) -> Result<crate::types::GitVerification, GitError> {
        let out = self
            .cmd
            .run(&["log", "-1", "--format=%G?|%GS|%GK", sha])
            .await?;
        let line = out.stdout.trim();
        let parts: Vec<&str> = line.splitn(3, '|').collect();
        if parts.len() != 3 {
            return Err(GitError::Parse(format!("unexpected verify output: {line}")));
        }
        let status = parts[0];
        let valid = status == "G" || status == "U";
        let signer = if parts[1].is_empty() {
            None
        } else {
            Some(parts[1].to_string())
        };
        let fingerprint = if parts[2].is_empty() {
            None
        } else {
            Some(parts[2].to_string())
        };
        Ok(crate::types::GitVerification {
            valid,
            signer,
            fingerprint,
            status: status.to_string(),
        })
    }

    /// List submodules and their current state.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn submodule_list(&self) -> Result<Vec<crate::types::GitSubmodule>, GitError> {
        let out = self
            .cmd
            .run(&["submodule", "status", "--recursive"])
            .await?;
        parse::parse_submodules(&out.stdout)
    }

    /// Add a new submodule.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn submodule_add(&self, url: &str, path: impl AsRef<Path>) -> Result<(), GitError> {
        self.cmd
            .run(&[
                "submodule",
                "add",
                url,
                path.as_ref().to_string_lossy().as_ref(),
            ])
            .await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Update submodules (optionally initializing and recursing).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn submodule_update(&self, init: bool, recursive: bool) -> Result<(), GitError> {
        let mut args = vec!["submodule", "update"];
        if init {
            args.push("--init");
        }
        if recursive {
            args.push("--recursive");
        }
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Deinitialize a submodule.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn submodule_deinit(
        &self,
        path: impl AsRef<Path>,
        force: bool,
    ) -> Result<(), GitError> {
        let mut args = vec!["submodule", "deinit"];
        if force {
            args.push("-f");
        }
        let path_str = path.as_ref().to_string_lossy();
        args.push(&path_str);
        self.cmd.run(&args).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// Synchronize submodule remote URLs.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn submodule_sync(&self) -> Result<(), GitError> {
        self.cmd.run(&["submodule", "sync", "--recursive"]).await?;
        self.invalidate_cache();
        Ok(())
    }

    /// List tracked files matching optional filters.
    ///
    /// * `deleted` — include deleted files (`--deleted`).
    /// * `others` — include untracked files (`--others`).
    /// * `exclude_standard` — respect `.gitignore` when listing others
    ///   (`--exclude-standard`).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn ls_files(
        &self,
        deleted: bool,
        others: bool,
        exclude_standard: bool,
    ) -> Result<Vec<String>, GitError> {
        let mut args = vec!["ls-files"];
        if deleted {
            args.push("--deleted");
        }
        if others {
            args.push("--others");
        }
        if exclude_standard {
            args.push("--exclude-standard");
        }
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }

    /// Stream `git ls-files` results line-by-line.
    #[cfg(feature = "stream")]
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn ls_files_stream(
        &self,
        deleted: bool,
        others: bool,
        exclude_standard: bool,
    ) -> Result<impl Stream<Item = Result<String, GitError>>, GitError> {
        let mut args = vec!["ls-files"];
        if deleted {
            args.push("--deleted");
        }
        if others {
            args.push("--others");
        }
        if exclude_standard {
            args.push("--exclude-standard");
        }
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(&args)
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git ls-files: {e}")))?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| GitError::Io("missing stdout".to_string()))?;
        let lines = LinesStream::new(BufReader::new(stdout).lines());
        Ok(LsFilesStream {
            _child: child,
            lines: Box::pin(lines),
        })
    }

    /// Check which paths are ignored by git.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, paths)))]
    pub async fn check_ignore(&self, paths: &[impl AsRef<Path>]) -> Result<Vec<String>, GitError> {
        let mut args = vec!["check-ignore".to_string()];
        for p in paths {
            args.push(p.as_ref().to_string_lossy().to_string());
        }
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }

    /// Check git attributes for given paths.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, paths, attrs)))]
    pub async fn check_attr(
        &self,
        paths: &[impl AsRef<Path>],
        attrs: &[&str],
    ) -> Result<Vec<crate::types::GitAttr>, GitError> {
        let mut args: Vec<String> = vec!["check-attr".to_string(), "-z".to_string()];
        for a in attrs {
            args.push(a.to_string());
        }
        args.push("--".to_string());
        for p in paths {
            args.push(p.as_ref().to_string_lossy().to_string());
        }
        let out = self.cmd.run(&args).await?;
        let mut results = Vec::new();
        let parts: Vec<&str> = out.stdout.split('\0').collect();
        for chunk in parts.chunks(3) {
            if chunk.len() == 3 {
                results.push(crate::types::GitAttr {
                    path: chunk[0].to_string(),
                    attr: chunk[1].to_string(),
                    value: chunk[2].to_string(),
                });
            }
        }
        Ok(results)
    }

    /// Get the staged (cached) diff.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn diff_cached(&self) -> Result<String, GitError> {
        let out = self.cmd.run(&["diff", "--cached"]).await?;
        Ok(out.stdout)
    }

    /// Create an archive of `ref_name` (e.g. a tag or branch) at `output`.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, output)))]
    pub async fn archive(&self, ref_name: &str, output: impl AsRef<Path>) -> Result<(), GitError> {
        let output = output.as_ref().to_string_lossy();
        self.cmd.run(&["archive", ref_name, "-o", &output]).await?;
        Ok(())
    }

    /// Create a bundle file containing the specified refs.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, output)))]
    pub async fn bundle_create(
        &self,
        output: impl AsRef<Path>,
        refs: Option<&[&str]>,
    ) -> Result<(), GitError> {
        let output = output.as_ref().to_string_lossy();
        let mut args = vec![
            "bundle".to_string(),
            "create".to_string(),
            output.to_string(),
        ];
        if let Some(refs) = refs {
            for r in refs {
                args.push(r.to_string());
            }
        } else {
            args.push("--all".to_string());
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// List refs contained in a bundle file.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn bundle_list_heads(&self, path: impl AsRef<Path>) -> Result<Vec<String>, GitError> {
        let path = path.as_ref().to_string_lossy();
        let out = self.cmd.run(&["bundle", "list-heads", &path]).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }

    /// Verify a bundle file is valid and can be applied.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn bundle_verify(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        let path = path.as_ref().to_string_lossy();
        self.cmd.run(&["bundle", "verify", &path]).await?;
        Ok(())
    }

    /// Unbundle (fetch from) a bundle file into the repository.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn bundle_unbundle(&self, path: impl AsRef<Path>) -> Result<Vec<String>, GitError> {
        let path = path.as_ref().to_string_lossy();
        let out = self.cmd.run(&["bundle", "unbundle", &path]).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }

    /// Compute the SHA of a blob from raw bytes without writing to the object DB.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, data)))]
    pub async fn hash_object(&self, data: &[u8]) -> Result<Oid, GitError> {
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["hash-object", "--stdin"])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git hash-object: {e}")))?;

        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| GitError::Io("missing stdin".to_string()))?;
        stdin
            .write_all(data)
            .await
            .map_err(|e| GitError::Io(format!("stdin write: {e}")))?;
        drop(stdin);

        let out = child
            .wait_with_output()
            .await
            .map_err(|e| GitError::Io(format!("wait: {e}")))?;
        if !out.status.success() {
            return Err(GitError::CommandFailed {
                command: "hash-object --stdin".to_string(),
                exit_code: out.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&out.stderr).to_string(),
                stdout: String::new(),
            });
        }
        Oid::new(String::from_utf8_lossy(&out.stdout).trim())
    }

    /// Write a blob to the object DB and return its OID.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, data)))]
    pub async fn write_blob(&self, data: &[u8]) -> Result<Oid, GitError> {
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["hash-object", "-w", "--stdin"])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git hash-object: {e}")))?;

        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| GitError::Io("missing stdin".to_string()))?;
        stdin
            .write_all(data)
            .await
            .map_err(|e| GitError::Io(format!("stdin write: {e}")))?;
        drop(stdin);

        let out = child
            .wait_with_output()
            .await
            .map_err(|e| GitError::Io(format!("wait: {e}")))?;
        if !out.status.success() {
            return Err(GitError::CommandFailed {
                command: "hash-object -w --stdin".to_string(),
                exit_code: out.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&out.stderr).to_string(),
                stdout: String::new(),
            });
        }
        Oid::new(String::from_utf8_lossy(&out.stdout).trim())
    }

    /// Create a tree object from entries and return its OID.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, entries)))]
    pub async fn mktree(&self, entries: &[TreeEntry]) -> Result<Oid, GitError> {
        // Build a tree object manually and write it via hash-object.
        // Tree format: sorted entries, each: "<mode> <path>\0<20-byte binary sha>"
        let mut sorted: Vec<&TreeEntry> = entries.iter().collect();
        sorted.sort_by_key(|e| &e.path);

        let mut input: Vec<u8> = Vec::new();
        for e in sorted {
            input.extend_from_slice(e.mode.as_bytes());
            input.push(b' ');
            input.extend_from_slice(e.path.as_bytes());
            input.push(0);
            let oid_bytes = hex_to_bytes(e.oid.as_ref())
                .map_err(|e| GitError::Parse(format!("invalid oid: {e}")))?;
            input.extend_from_slice(&oid_bytes);
        }

        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["hash-object", "-t", "tree", "-w", "--stdin"])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git hash-object: {e}")))?;

        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| GitError::Io("missing stdin".to_string()))?;
        stdin
            .write_all(&input)
            .await
            .map_err(|e| GitError::Io(format!("stdin write: {e}")))?;
        drop(stdin);

        let out = child
            .wait_with_output()
            .await
            .map_err(|e| GitError::Io(format!("wait: {e}")))?;
        if !out.status.success() {
            return Err(GitError::CommandFailed {
                command: "hash-object -t tree -w --stdin".to_string(),
                exit_code: out.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&out.stderr).to_string(),
                stdout: String::new(),
            });
        }
        Oid::new(String::from_utf8_lossy(&out.stdout).trim())
    }

    /// Write a tree object to the object DB and return its OID.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, entries)))]
    pub async fn write_tree(&self, entries: &[TreeEntry]) -> Result<Oid, GitError> {
        self.mktree(entries).await
    }

    /// Read a git object by OID.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn read_object(&self, oid: &Oid) -> Result<ObjectContent, GitError> {
        let oid_str = oid.as_ref();
        let out = self.cmd.run(&["cat-file", "-p", oid_str]).await?;
        let kind_out = self.cmd.run(&["cat-file", "-t", oid_str]).await?;
        let kind_str = kind_out.stdout.trim();
        let kind = kind_str.parse().map_err(|e: GitError| {
            GitError::Parse(format!("invalid object kind for {oid}: {e}"))
        })?;
        Ok(ObjectContent {
            oid: oid.clone(),
            kind,
            size: out.stdout.len(),
            data: out.stdout.into_bytes(),
        })
    }

    /// Read a tree object and return its entries.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn read_tree(&self, oid: &Oid) -> Result<Vec<TreeEntry>, GitError> {
        let obj = self.read_object(oid).await?;
        let mut entries = Vec::new();
        let text = String::from_utf8_lossy(&obj.data);
        for line in text.lines() {
            // Format from `git cat-file -p <tree>`: "<mode> <type> <sha>\t<path>"
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 4 {
                let mode = parts[0];
                let sha = parts[2];
                if let Some(tab_pos) = line.find('\t') {
                    let path = &line[tab_pos + 1..];
                    entries.push(TreeEntry {
                        mode: mode.to_string(),
                        path: path.to_string(),
                        oid: Oid::new(sha)?,
                    });
                }
            }
        }
        Ok(entries)
    }

    /// Read a blob object and return its raw bytes.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn read_blob(&self, oid: &Oid) -> Result<Vec<u8>, GitError> {
        let obj = self.read_object(oid).await?;
        Ok(obj.data)
    }

    /// Read a commit object and parse it.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn read_commit(&self, oid: &Oid) -> Result<crate::types::GitCommit, GitError> {
        let obj = self.read_object(oid).await?;
        let text = String::from_utf8_lossy(&obj.data);
        let mut tree = None;
        let mut parents = Vec::new();
        let mut author = String::new();
        let mut committer = String::new();
        let mut message = String::new();
        let mut in_message = false;
        for line in text.lines() {
            if in_message {
                message.push_str(line);
                message.push('\n');
            } else if line.is_empty() {
                in_message = true;
            } else if let Some(rest) = line.strip_prefix("tree ") {
                tree = Some(Oid::new(rest)?);
            } else if let Some(rest) = line.strip_prefix("parent ") {
                parents.push(Oid::new(rest)?);
            } else if let Some(rest) = line.strip_prefix("author ") {
                author = rest.to_string();
            } else if let Some(rest) = line.strip_prefix("committer ") {
                committer = rest.to_string();
            }
        }
        let tree =
            tree.ok_or_else(|| GitError::Parse("missing tree in commit object".to_string()))?;
        Ok(crate::types::GitCommit {
            tree,
            parents,
            author,
            committer,
            message: message.trim_end_matches('\n').to_string(),
        })
    }

    /// Write a commit object and return its OID.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn write_commit(
        &self,
        parents: &[&Oid],
        tree: &Oid,
        message: &str,
    ) -> Result<Oid, GitError> {
        let mut content = format!("tree {}\n", tree.as_ref());
        for p in parents {
            content.push_str(&format!("parent {}\n", p.as_ref()));
        }
        content.push_str(&format!(
            "author gitr <gitr@localhost> {} +0000\n",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
        ));
        content.push_str(&format!(
            "committer gitr <gitr@localhost> {} +0000\n",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
        ));
        content.push('\n');
        content.push_str(message);
        content.push('\n');

        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["hash-object", "-t", "commit", "-w", "--stdin"])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git hash-object: {e}")))?;

        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| GitError::Io("missing stdin".to_string()))?;
        stdin
            .write_all(content.as_bytes())
            .await
            .map_err(|e| GitError::Io(format!("stdin write: {e}")))?;
        drop(stdin);

        let out = child
            .wait_with_output()
            .await
            .map_err(|e| GitError::Io(format!("wait: {e}")))?;
        if !out.status.success() {
            return Err(GitError::CommandFailed {
                command: "hash-object -t commit -w --stdin".to_string(),
                exit_code: out.status.code().unwrap_or(-1),
                stderr: String::from_utf8_lossy(&out.stderr).to_string(),
                stdout: String::new(),
            });
        }
        Oid::new(String::from_utf8_lossy(&out.stdout).trim())
    }

    /// Read the index.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn read_index(&self) -> Result<Vec<IndexEntry>, GitError> {
        let out = self.cmd.run(&["ls-files", "--stage"]).await?;
        let mut entries = Vec::new();
        for line in out.stdout.lines() {
            // Format: "<mode> <oid> <stage>\t<path>"
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 4 {
                if let Ok(mode) = parts[0].parse::<u32>() {
                    let path = parts[3..].join(" ");
                    entries.push(IndexEntry {
                        mode,
                        oid: Oid::new(parts[1])?,
                        path,
                    });
                }
            }
        }
        Ok(entries)
    }

    /// Update the index for a single path.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn update_index(
        &self,
        path: impl AsRef<Path>,
        oid: &Oid,
        mode: u32,
    ) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        let oid_str = oid.as_ref();
        self.cmd
            .run(&[
                "update-index",
                "--add",
                "--cacheinfo",
                &format!("{:o},{oid_str},{path_str}", mode),
            ])
            .await?;
        Ok(())
    }

    /// Remove a path from the index.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, path)))]
    pub async fn remove_index(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        let path_str = path.as_ref().to_string_lossy();
        self.cmd
            .run(&["update-index", "--remove", &path_str])
            .await?;
        Ok(())
    }

    /// Run `git grep` for `pattern` and return structured matches.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn grep(&self, pattern: &str) -> Result<Vec<crate::types::GitGrepResult>, GitError> {
        let out = self.cmd.run(&["grep", "-n", pattern]).await?;
        parse::parse_grep(&out.stdout)
    }

    /// Stream `git grep` results line-by-line.
    #[cfg(feature = "stream")]
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn grep_stream(
        &self,
        pattern: &str,
    ) -> Result<impl Stream<Item = Result<crate::types::GitGrepResult, GitError>>, GitError> {
        let mut child = tokio::process::Command::new(self.cmd.git_bin())
            .current_dir(self.cmd.cwd())
            .args(["grep", "-n", pattern])
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_ASKPASS", "echo")
            .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
            .env("LC_ALL", "C")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| GitError::Io(format!("failed to spawn git grep: {e}")))?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| GitError::Io("missing stdout".to_string()))?;
        let lines = LinesStream::new(BufReader::new(stdout).lines());
        Ok(GrepStream {
            _child: child,
            lines: Box::pin(lines),
        })
    }

    /// Describe the current commit in terms of the nearest tag.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn describe(&self, tags: bool, long: bool) -> Result<String, GitError> {
        let mut args = vec!["describe"];
        if tags {
            args.push("--tags");
        }
        if long {
            args.push("--long");
        }
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout.trim().to_string())
    }

    /// Remove untracked files from the working tree.
    ///
    /// * `force` — actually remove files (`-f`). Without this `git clean` refuses
    ///   to run unless `clean.requireForce` is false.
    /// * `directories` — remove untracked directories in addition to files (`-d`).
    /// * `dry_run` — only show what would be removed (`-n`).
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn clean(
        &self,
        force: bool,
        directories: bool,
        dry_run: bool,
    ) -> Result<Vec<String>, GitError> {
        let mut args = vec!["clean"];
        if force {
            args.push("-f");
        }
        if directories {
            args.push("-d");
        }
        if dry_run {
            args.push("-n");
        }
        let out = self.cmd.run(&args).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }

    // ------------------------------------------------------------------
    // Git LFS
    // ------------------------------------------------------------------

    /// Start tracking file paths matching `patterns` with Git LFS.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn lfs_track(&self, patterns: &[&str]) -> Result<(), GitError> {
        let mut args = vec!["lfs", "track"];
        for p in patterns {
            args.push(p);
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// Stop tracking file paths matching `patterns` with Git LFS.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn lfs_untrack(&self, patterns: &[&str]) -> Result<(), GitError> {
        let mut args = vec!["lfs", "untrack"];
        for p in patterns {
            args.push(p);
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// List files tracked by Git LFS.
    ///
    /// Parses the output of `git lfs ls-files --long`.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn lfs_ls_files(&self) -> Result<Vec<GitLfsFile>, GitError> {
        let out = self.cmd.run(&["lfs", "ls-files", "--long"]).await?;
        let mut files = Vec::new();
        for line in out.stdout.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 3 {
                continue;
            }
            let oid = parts[1].to_string();
            let size = if parts[2] == "-" {
                None
            } else {
                parts[2].parse::<u64>().ok()
            };
            let path = if parts.len() > 3 {
                parts[3..].join(" ")
            } else {
                String::new()
            };
            files.push(GitLfsFile { oid, path, size });
        }
        Ok(files)
    }

    /// Lock a file path with Git LFS.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn lfs_lock(&self, path: &str) -> Result<(), GitError> {
        self.cmd.run(&["lfs", "lock", path]).await?;
        Ok(())
    }

    /// Unlock a file path with Git LFS.
    ///
    /// When `force` is `true`, passes `--force`.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn lfs_unlock(&self, path: &str, force: bool) -> Result<(), GitError> {
        let mut args = vec!["lfs", "unlock"];
        if force {
            args.push("--force");
        }
        args.push(path);
        self.cmd.run(&args).await?;
        Ok(())
    }

    // ------------------------------------------------------------------
    // Sparse checkout
    // ------------------------------------------------------------------

    /// Initialize sparse checkout.
    ///
    /// When `cone` is `true`, passes `--cone`.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn sparse_checkout_init(&self, cone: bool) -> Result<(), GitError> {
        let mut args = vec!["sparse-checkout", "init"];
        if cone {
            args.push("--cone");
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// Set the sparse-checkout paths, replacing the existing list.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn sparse_checkout_set(&self, paths: &[&str]) -> Result<(), GitError> {
        let mut args = vec!["sparse-checkout", "set"];
        for p in paths {
            args.push(p);
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// Add paths to the sparse-checkout list.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn sparse_checkout_add(&self, paths: &[&str]) -> Result<(), GitError> {
        let mut args = vec!["sparse-checkout", "add"];
        for p in paths {
            args.push(p);
        }
        self.cmd.run(&args).await?;
        Ok(())
    }

    /// Disable sparse checkout.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn sparse_checkout_disable(&self) -> Result<(), GitError> {
        self.cmd.run(&["sparse-checkout", "disable"]).await?;
        Ok(())
    }

    /// List the current sparse-checkout paths.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
    pub async fn sparse_checkout_list(&self) -> Result<Vec<String>, GitError> {
        let out = self.cmd.run(&["sparse-checkout", "list"]).await?;
        Ok(out.stdout.lines().map(|l| l.to_string()).collect())
    }
}

fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
    if hex.len() % 2 != 0 {
        return Err("odd length".to_string());
    }
    let mut bytes = Vec::with_capacity(hex.len() / 2);
    for chunk in hex.as_bytes().chunks_exact(2) {
        let hi = (chunk[0] as char).to_digit(16).ok_or("invalid hex")?;
        let lo = (chunk[1] as char).to_digit(16).ok_or("invalid hex")?;
        bytes.push((hi * 16 + lo) as u8);
    }
    Ok(bytes)
}

// async on unix because it uses tokio::fs::metadata; sync on windows
// where the answer is always true
#[allow(clippy::unused_async)]
async fn is_executable(path: &std::path::Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        tokio::fs::metadata(path)
            .await
            .map(|m| m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        true
    }
}

#[async_trait]
impl GitApi for Repository {
    async fn ensure_clean(&self) -> Result<(), GitError> {
        self.ensure_clean().await
    }

    async fn status(&self) -> Result<GitStatus, GitError> {
        self.status().await
    }

    async fn current_branch(&self) -> Result<String, GitError> {
        self.current_branch().await
    }

    async fn head_commit(&self) -> Result<Oid, GitError> {
        self.head_commit().await
    }

    async fn changed_files(&self) -> Result<Vec<String>, GitError> {
        self.changed_files().await
    }

    async fn worktree_add(&self, path: &Path, branch: &str) -> Result<GitWorktree, GitError> {
        self.worktree_add(path, branch).await
    }

    async fn worktree_remove(&self, path: &Path, force: bool) -> Result<(), GitError> {
        self.worktree_remove(path, force).await
    }

    async fn worktree_list(&self) -> Result<Vec<GitWorktree>, GitError> {
        self.worktree_list().await
    }

    async fn branch_create(&self, name: &str, start_point: Option<&str>) -> Result<(), GitError> {
        self.branch_create(name, start_point).await
    }

    async fn branch_delete(&self, name: &str, force: bool) -> Result<(), GitError> {
        self.branch_delete(name, force).await
    }

    async fn branch_exists(&self, name: &str) -> Result<bool, GitError> {
        self.branch_exists(name).await
    }

    async fn checkout(&self, branch: &str) -> Result<(), GitError> {
        self.checkout(branch).await
    }

    async fn commit_opts(&self, opts: &CommitOptions<'_>) -> Result<String, GitError> {
        self.commit_opts(opts).await
    }

    async fn push_opts(&self, opts: &PushOptions<'_>) -> Result<(), GitError> {
        self.push_opts(opts).await
    }

    async fn fetch_opts(&self, opts: &FetchOptions<'_>) -> Result<(), GitError> {
        self.fetch_opts(opts).await
    }

    async fn merge_tree(&self, base: &str, branch: &str) -> Result<GitMergeResult, GitError> {
        self.merge_tree(base, branch).await
    }

    async fn merge_opts(&self, opts: &MergeOptions<'_>) -> Result<(), GitError> {
        self.merge_opts(opts).await
    }

    async fn rebase_opts(&self, opts: &RebaseOptions<'_>) -> Result<(), GitError> {
        self.rebase_opts(opts).await
    }

    async fn stash(&self, message: Option<&str>) -> Result<(), GitError> {
        self.stash(message).await
    }

    async fn diff(&self) -> Result<String, GitError> {
        self.diff().await
    }

    async fn diff_structured(&self) -> Result<Vec<crate::types::FileDiff>, GitError> {
        self.diff_structured().await
    }

    async fn diff_cached_structured(&self) -> Result<Vec<crate::types::FileDiff>, GitError> {
        self.diff_cached_structured().await
    }

    async fn log(
        &self,
        max_count: Option<usize>,
    ) -> Result<Vec<crate::types::GitLogEntry>, GitError> {
        self.log(max_count).await
    }

    async fn log_paginated(
        &self,
        skip: usize,
        max_count: usize,
    ) -> Result<Vec<crate::types::GitLogEntry>, GitError> {
        self.log_paginated(skip, max_count).await
    }

    async fn remotes(&self) -> Result<Vec<crate::types::GitRemote>, GitError> {
        self.remotes().await
    }

    async fn config_get(&self, key: &str) -> Result<Option<String>, GitError> {
        self.config_get(key).await
    }

    async fn config_set(&self, key: &str, value: &str) -> Result<(), GitError> {
        self.config_set(key, value).await
    }

    async fn config_unset(&self, key: &str) -> Result<(), GitError> {
        self.config_unset(key).await
    }

    async fn tag_list(&self) -> Result<Vec<crate::types::GitTag>, GitError> {
        self.tag_list().await
    }

    async fn tag_create(
        &self,
        name: &str,
        message: Option<&str>,
        force: bool,
    ) -> Result<(), GitError> {
        self.tag_create(name, message, force).await
    }

    async fn show(&self, path: &str, rev: Option<&str>) -> Result<String, GitError> {
        self.show(path, rev).await
    }

    async fn blame(&self, path: &str) -> Result<String, GitError> {
        self.blame(path).await
    }

    async fn blame_structured(&self, path: &str) -> Result<Vec<crate::types::BlameLine>, GitError> {
        self.blame_structured(path).await
    }

    async fn format_patch(&self, range: &str) -> Result<Vec<crate::types::Patch>, GitError> {
        self.format_patch(range).await
    }

    async fn apply_patch(&self, patch: &str, dry_run: bool) -> Result<(), GitError> {
        self.apply_patch(patch, dry_run).await
    }

    async fn apply_patch_file(&self, path: &Path, dry_run: bool) -> Result<(), GitError> {
        self.apply_patch_file(path, dry_run).await
    }

    async fn reflog_list(
        &self,
        ref_name: Option<&str>,
    ) -> Result<Vec<crate::types::ReflogEntry>, GitError> {
        self.reflog_list(ref_name).await
    }

    async fn reflog_expire(
        &self,
        ref_name: &str,
        expire_time: Option<&str>,
    ) -> Result<(), GitError> {
        self.reflog_expire(ref_name, expire_time).await
    }

    async fn hooks_list(&self) -> Result<Vec<crate::types::Hook>, GitError> {
        self.hooks_list().await
    }

    async fn hook_install(&self, name: &str, script: &str) -> Result<(), GitError> {
        self.hook_install(name, script).await
    }

    async fn hook_remove(&self, name: &str) -> Result<(), GitError> {
        self.hook_remove(name).await
    }

    async fn run_hook(&self, name: &str) -> Result<crate::types::HookOutput, GitError> {
        self.run_hook(name).await
    }

    async fn bisect_start(
        &self,
        bad: Option<&str>,
        good: &[&str],
    ) -> Result<crate::types::BisectState, GitError> {
        self.bisect_start(bad, good).await
    }

    async fn bisect_bad(
        &self,
        commit: Option<&str>,
    ) -> Result<crate::types::BisectState, GitError> {
        self.bisect_bad(commit).await
    }

    async fn bisect_good(
        &self,
        commit: Option<&str>,
    ) -> Result<crate::types::BisectState, GitError> {
        self.bisect_good(commit).await
    }

    async fn bisect_reset(&self) -> Result<(), GitError> {
        self.bisect_reset().await
    }

    async fn bisect_run(&self, command: &str) -> Result<String, GitError> {
        self.bisect_run(command).await
    }

    async fn notes_list(
        &self,
        namespace: Option<&str>,
    ) -> Result<Vec<crate::types::GitNote>, GitError> {
        self.notes_list(namespace).await
    }

    async fn notes_show(&self, object: &str, namespace: Option<&str>) -> Result<String, GitError> {
        self.notes_show(object, namespace).await
    }

    async fn notes_add(
        &self,
        message: &str,
        object: &str,
        namespace: Option<&str>,
        force: bool,
    ) -> Result<(), GitError> {
        self.notes_add(message, object, namespace, force).await
    }

    async fn notes_remove(&self, object: &str, namespace: Option<&str>) -> Result<(), GitError> {
        self.notes_remove(object, namespace).await
    }

    async fn reset(
        &self,
        mode: crate::types::ResetMode,
        target: Option<&str>,
    ) -> Result<(), GitError> {
        self.reset(mode, target).await
    }

    async fn stash_list(&self) -> Result<Vec<crate::types::GitStash>, GitError> {
        self.stash_list().await
    }

    async fn cherry_pick_opts(&self, opts: &CherryPickOptions<'_>) -> Result<(), GitError> {
        self.cherry_pick_opts(opts).await
    }

    async fn commit_signed(
        &self,
        paths: &[&Path],
        message: &str,
        gpg_key: Option<&str>,
        no_verify: bool,
    ) -> Result<(), GitError> {
        self.commit_signed(paths, message, gpg_key, no_verify).await
    }

    async fn verify_commit(&self, sha: &str) -> Result<crate::types::GitVerification, GitError> {
        self.verify_commit(sha).await
    }

    async fn submodule_list(&self) -> Result<Vec<crate::types::GitSubmodule>, GitError> {
        self.submodule_list().await
    }

    async fn submodule_add(&self, url: &str, path: &Path) -> Result<(), GitError> {
        self.submodule_add(url, path).await
    }

    async fn submodule_update(&self, init: bool, recursive: bool) -> Result<(), GitError> {
        self.submodule_update(init, recursive).await
    }

    async fn submodule_deinit(&self, path: &Path, force: bool) -> Result<(), GitError> {
        self.submodule_deinit(path, force).await
    }

    async fn submodule_sync(&self) -> Result<(), GitError> {
        self.submodule_sync().await
    }

    async fn ls_files(
        &self,
        deleted: bool,
        others: bool,
        exclude_standard: bool,
    ) -> Result<Vec<String>, GitError> {
        self.ls_files(deleted, others, exclude_standard).await
    }

    async fn diff_cached(&self) -> Result<String, GitError> {
        self.diff_cached().await
    }

    async fn archive(&self, ref_name: &str, output: &Path) -> Result<(), GitError> {
        self.archive(ref_name, output).await
    }

    async fn bundle_create(&self, output: &Path, refs: Option<&[&str]>) -> Result<(), GitError> {
        self.bundle_create(output, refs).await
    }

    async fn bundle_list_heads(&self, path: &Path) -> Result<Vec<String>, GitError> {
        self.bundle_list_heads(path).await
    }

    async fn bundle_verify(&self, path: &Path) -> Result<(), GitError> {
        self.bundle_verify(path).await
    }

    async fn bundle_unbundle(&self, path: &Path) -> Result<Vec<String>, GitError> {
        self.bundle_unbundle(path).await
    }

    async fn grep(&self, pattern: &str) -> Result<Vec<crate::types::GitGrepResult>, GitError> {
        self.grep(pattern).await
    }

    async fn check_ignore(&self, paths: &[&Path]) -> Result<Vec<String>, GitError> {
        self.check_ignore(paths).await
    }

    async fn check_attr(
        &self,
        paths: &[&Path],
        attrs: &[&str],
    ) -> Result<Vec<crate::types::GitAttr>, GitError> {
        self.check_attr(paths, attrs).await
    }

    async fn describe(&self, tags: bool, long: bool) -> Result<String, GitError> {
        self.describe(tags, long).await
    }

    async fn clean(
        &self,
        force: bool,
        directories: bool,
        dry_run: bool,
    ) -> Result<Vec<String>, GitError> {
        self.clean(force, directories, dry_run).await
    }

    async fn lfs_track(&self, patterns: &[&str]) -> Result<(), GitError> {
        self.lfs_track(patterns).await
    }

    async fn lfs_untrack(&self, patterns: &[&str]) -> Result<(), GitError> {
        self.lfs_untrack(patterns).await
    }

    async fn lfs_ls_files(&self) -> Result<Vec<crate::types::GitLfsFile>, GitError> {
        self.lfs_ls_files().await
    }

    async fn lfs_lock(&self, path: &str) -> Result<(), GitError> {
        self.lfs_lock(path).await
    }

    async fn lfs_unlock(&self, path: &str, force: bool) -> Result<(), GitError> {
        self.lfs_unlock(path, force).await
    }

    async fn sparse_checkout_init(&self, cone: bool) -> Result<(), GitError> {
        self.sparse_checkout_init(cone).await
    }

    async fn sparse_checkout_set(&self, paths: &[&str]) -> Result<(), GitError> {
        self.sparse_checkout_set(paths).await
    }

    async fn sparse_checkout_add(&self, paths: &[&str]) -> Result<(), GitError> {
        self.sparse_checkout_add(paths).await
    }

    async fn sparse_checkout_disable(&self) -> Result<(), GitError> {
        self.sparse_checkout_disable().await
    }

    async fn sparse_checkout_list(&self) -> Result<Vec<String>, GitError> {
        self.sparse_checkout_list().await
    }

    async fn pull(&self, remote: &str, branch: &str, rebase: bool) -> Result<(), GitError> {
        self.pull(remote, branch, rebase).await
    }

    async fn switch(&self, branch: &str, create: bool) -> Result<(), GitError> {
        self.switch(branch, create).await
    }

    async fn restore(
        &self,
        paths: &[&Path],
        staged: bool,
        source: Option<&str>,
    ) -> Result<(), GitError> {
        self.restore(paths, staged, source).await
    }

    async fn revert(&self, commits: &[&str], no_edit: bool) -> Result<(), GitError> {
        self.revert(commits, no_edit).await
    }

    async fn stash_drop(&self, index: Option<usize>) -> Result<(), GitError> {
        self.stash_drop(index).await
    }

    async fn stash_apply(&self, index: Option<usize>) -> Result<(), GitError> {
        self.stash_apply(index).await
    }

    async fn stash_show(&self, index: Option<usize>) -> Result<String, GitError> {
        self.stash_show(index).await
    }

    async fn remote_add(&self, name: &str, url: &str) -> Result<(), GitError> {
        self.remote_add(name, url).await
    }

    async fn remote_remove(&self, name: &str) -> Result<(), GitError> {
        self.remote_remove(name).await
    }

    async fn remote_rename(&self, old: &str, new: &str) -> Result<(), GitError> {
        self.remote_rename(old, new).await
    }

    async fn ls_remote(
        &self,
        remote: &str,
        refs: Option<&[&str]>,
    ) -> Result<Vec<(String, String)>, GitError> {
        self.ls_remote(remote, refs).await
    }

    async fn branch_rename(&self, old: &str, new: &str, force: bool) -> Result<(), GitError> {
        self.branch_rename(old, new, force).await
    }

    async fn tag_delete(&self, name: &str) -> Result<(), GitError> {
        self.tag_delete(name).await
    }

    async fn tag_create_signed(
        &self,
        name: &str,
        message: &str,
        gpg_key: Option<&str>,
    ) -> Result<(), GitError> {
        self.tag_create_signed(name, message, gpg_key).await
    }

    async fn verify_tag(&self, name: &str) -> Result<crate::types::GitVerification, GitError> {
        self.verify_tag(name).await
    }

    async fn worktree_prune(&self) -> Result<(), GitError> {
        self.worktree_prune().await
    }

    async fn worktree_lock(&self, path: &Path) -> Result<(), GitError> {
        self.worktree_lock(path).await
    }

    async fn worktree_unlock(&self, path: &Path) -> Result<(), GitError> {
        self.worktree_unlock(path).await
    }

    async fn worktree_move(&self, old_path: &Path, new_path: &Path) -> Result<(), GitError> {
        self.worktree_move(old_path, new_path).await
    }

    async fn mv(&self, source: &Path, dest: &Path) -> Result<(), GitError> {
        self.mv(source, dest).await
    }

    async fn rm(&self, paths: &[&Path], cached: bool) -> Result<(), GitError> {
        self.rm(paths, cached).await
    }

    async fn merge_base(&self, commits: &[&str]) -> Result<String, GitError> {
        self.merge_base(commits).await
    }

    async fn rev_parse(&self, rev: &str) -> Result<String, GitError> {
        self.rev_parse(rev).await
    }

    async fn hash_object(&self, data: &[u8]) -> Result<Oid, GitError> {
        self.hash_object(data).await
    }

    async fn write_blob(&self, data: &[u8]) -> Result<Oid, GitError> {
        self.write_blob(data).await
    }

    async fn mktree(&self, entries: &[TreeEntry]) -> Result<Oid, GitError> {
        self.mktree(entries).await
    }

    async fn write_tree(&self, entries: &[TreeEntry]) -> Result<Oid, GitError> {
        self.write_tree(entries).await
    }

    async fn read_object(&self, oid: &Oid) -> Result<ObjectContent, GitError> {
        self.read_object(oid).await
    }

    async fn read_tree(&self, oid: &Oid) -> Result<Vec<TreeEntry>, GitError> {
        self.read_tree(oid).await
    }

    async fn read_blob(&self, oid: &Oid) -> Result<Vec<u8>, GitError> {
        self.read_blob(oid).await
    }

    async fn read_commit(&self, oid: &Oid) -> Result<crate::types::GitCommit, GitError> {
        self.read_commit(oid).await
    }

    async fn write_commit(
        &self,
        parents: &[&Oid],
        tree: &Oid,
        message: &str,
    ) -> Result<Oid, GitError> {
        self.write_commit(parents, tree, message).await
    }

    async fn read_index(&self) -> Result<Vec<IndexEntry>, GitError> {
        self.read_index().await
    }

    async fn update_index(&self, path: &Path, oid: &Oid, mode: u32) -> Result<(), GitError> {
        self.update_index(path, oid, mode).await
    }

    async fn remove_index(&self, path: &Path) -> Result<(), GitError> {
        self.remove_index(path).await
    }
}