ngit 2.4.1

nostr plugin for git
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
use std::{
    env::current_dir,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, bail};
use git2::{DiffOptions, Oid, Revwalk};
pub use identify_ahead_behind::identify_ahead_behind;
use nostr_sdk::{
    Tags,
    hashes::{Hash, sha1::Hash as Sha1Hash},
};
use nostr_url::NostrUrlDecoded;

use crate::git_events::{get_commit_id_from_patch, tag_value};
pub mod identify_ahead_behind;
pub mod nostr_url;
pub mod utils;

pub struct Repo {
    pub git_repo: git2::Repository,
}

impl Repo {
    pub fn discover() -> Result<Self> {
        Ok(Self {
            git_repo: git2::Repository::discover(current_dir()?)?,
        })
    }
    pub fn from_path(path: &PathBuf) -> Result<Self> {
        Ok(Self {
            git_repo: git2::Repository::open(path)?,
        })
    }
}

// pub type CommitId = [u8; 7];
// pub type Sha1 = [u8; 20];

pub trait RepoActions {
    fn get_path(&self) -> Result<&Path>;
    fn get_origin_url(&self) -> Result<String>;
    fn get_remote_branch_names(&self) -> Result<Vec<String>>;
    fn get_local_branch_names(&self) -> Result<Vec<String>>;
    fn get_origin_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)>;
    fn get_local_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)>;
    fn get_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)>;
    fn get_checked_out_branch_name(&self) -> Result<String>;
    fn get_tip_of_branch(&self, branch_name: &str) -> Result<Sha1Hash>;
    fn get_commit_or_tip_of_reference(&self, reference: &str) -> Result<Sha1Hash>;
    fn get_root_commit(&self) -> Result<Sha1Hash>;
    fn does_commit_exist(&self, commit: &str) -> Result<bool>;
    fn get_head_commit(&self) -> Result<Sha1Hash>;
    fn get_commit_parent(&self, commit: &Sha1Hash) -> Result<Sha1Hash>;
    fn get_commit_message(&self, commit: &Sha1Hash) -> Result<String>;
    fn get_commit_message_summary(&self, commit: &Sha1Hash) -> Result<String>;
    #[allow(clippy::doc_link_with_quotes)]
    /// returns vector ["name", "email", "unixtime", "offset"]
    /// eg ["joe bloggs", "joe@pm.me", "12176","-300"]
    fn get_commit_author(&self, commit: &Sha1Hash) -> Result<Vec<String>>;
    #[allow(clippy::doc_link_with_quotes)]
    /// returns vector ["name", "email", "unixtime", "offset"]
    /// eg ["joe bloggs", "joe@pm.me", "12176","-300"]
    fn get_commit_comitter(&self, commit: &Sha1Hash) -> Result<Vec<String>>;
    fn get_commit_committer_time(&self, commit: &Sha1Hash) -> Result<i64>;
    fn find_best_guess_parent_commit(&self, patch_timestamp: i64) -> Result<Option<Sha1Hash>>;
    fn get_commits_ahead_behind(
        &self,
        base_commit: &Sha1Hash,
        latest_commit: &Sha1Hash,
    ) -> Result<(Vec<Sha1Hash>, Vec<Sha1Hash>)>;
    fn get_refs(&self, commit: &Sha1Hash) -> Result<Vec<String>>;
    // including (un)staged changes and (un)tracked files
    fn has_outstanding_changes(&self) -> Result<bool>;
    fn make_patch_from_commit(
        &self,
        commit: &Sha1Hash,
        series_count: &Option<(u64, u64)>,
    ) -> Result<String>;
    fn are_commits_too_big_for_patches(&self, commits: &[Sha1Hash]) -> bool;
    fn extract_commit_pgp_signature(&self, commit: &Sha1Hash) -> Result<String>;
    fn checkout(&self, ref_name: &str) -> Result<Sha1Hash>;
    fn create_branch_at_commit(&self, branch_name: &str, commit: &str) -> Result<()>;
    fn apply_patch_chain(
        &self,
        branch_name: &str,
        patch_and_ancestors: Vec<nostr::Event>,
    ) -> Result<Vec<nostr::Event>>;
    fn create_commit_from_patch(
        &self,
        patch: &nostr::Event,
        parent_commit_id_override: Option<String>,
    ) -> Result<Oid>;
    fn parse_starting_commits(&self, starting_commits: &str) -> Result<Vec<Sha1Hash>>;
    fn ancestor_of(&self, decendant: &Sha1Hash, ancestor: &Sha1Hash) -> Result<bool>;
    fn get_upstream_for_branch(&self, branch_name: &str) -> Result<Option<String>>;
    fn get_git_config_item(&self, item: &str, global: Option<bool>) -> Result<Option<String>>;
    fn save_git_config_item(&self, item: &str, value: &str, global: bool) -> Result<()>;
    fn remove_git_config_item(&self, item: &str, global: bool) -> Result<bool>;
    #[allow(async_fn_in_trait)]
    async fn get_first_nostr_remote_when_in_ngit_binary(
        &self,
    ) -> Result<Option<(String, NostrUrlDecoded)>>;
}

impl RepoActions for Repo {
    fn get_path(&self) -> Result<&Path> {
        self.git_repo.workdir().context(
            "failed to find repository working directory (bare repositories are not supported)",
        )
    }

    fn get_origin_url(&self) -> Result<String> {
        Ok(self
            .git_repo
            .find_remote("origin")
            .context("failed to find origin")?
            .url()
            .context("failed to find origin url")?
            .to_string())
    }

    fn get_origin_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)> {
        let main_branch_name = {
            let remote_branches = self
                .get_remote_branch_names()
                .context("failed to find any local branches")?;
            if remote_branches.contains(&"origin/main".to_string()) {
                "origin/main"
            } else if remote_branches.contains(&"origin/master".to_string()) {
                "origin/master"
            } else {
                bail!("no main or master branch locally in this git repository to initiate from",)
            }
        };

        let tip = self
            .get_tip_of_branch(main_branch_name)
            .context(format!(
                "branch {main_branch_name} was listed as a remote branch but failed to get its tip commit id",
            ))?;

        Ok((main_branch_name, tip))
    }

    fn get_local_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)> {
        let main_branch_name = {
            let local_branches = self
                .get_local_branch_names()
                .context("failed to find any local branches")?;
            if local_branches.contains(&"main".to_string()) {
                "main"
            } else if local_branches.contains(&"master".to_string()) {
                "master"
            } else {
                bail!("no main or master branch locally in this git repository to initiate from",)
            }
        };

        let tip = self
            .get_tip_of_branch(main_branch_name)
            .context(format!(
                "branch {main_branch_name} was listed as a local branch but failed to get its tip commit id",
            ))?;

        Ok((main_branch_name, tip))
    }

    fn get_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)> {
        if let Ok(main_tuple) = self
            .get_origin_main_or_master_branch()
            .context("the default branches (main or master) do not exist")
        {
            Ok(main_tuple)
        } else {
            self.get_local_main_or_master_branch()
                .context("the default branches (main or master) do not exist")
        }
    }

    fn get_local_branch_names(&self) -> Result<Vec<String>> {
        let local_branches = self
            .git_repo
            .branches(Some(git2::BranchType::Local))
            .context("getting GitRepo branches should not error even for a blank repository")?;

        let mut branch_names = vec![];

        for iter in local_branches {
            let branch = iter?.0;
            if let Some(name) = branch.name()? {
                branch_names.push(name.to_string());
            }
        }
        Ok(branch_names)
    }

    fn get_remote_branch_names(&self) -> Result<Vec<String>> {
        let remote_branches = self
            .git_repo
            .branches(Some(git2::BranchType::Remote))
            .context("getting GitRepo branches should not error even for a blank repository")?;

        let mut branch_names = vec![];

        for iter in remote_branches {
            let branch = iter?.0;
            if let Some(name) = branch.name()? {
                branch_names.push(name.to_string());
            }
        }
        Ok(branch_names)
    }

    fn get_checked_out_branch_name(&self) -> Result<String> {
        Ok(self
            .git_repo
            .head()?
            .shorthand()
            .context("an object without a shorthand is checked out")?
            .to_string())
    }

    fn get_tip_of_branch(&self, branch_name: &str) -> Result<Sha1Hash> {
        let branch = if let Ok(branch) = self
            .git_repo
            .find_branch(branch_name, git2::BranchType::Local)
            .context(format!("failed to find local branch {branch_name}"))
        {
            branch
        } else {
            self.git_repo
                .find_branch(branch_name, git2::BranchType::Remote)
                .context(format!(
                    "failed to find local or remote branch {branch_name}"
                ))?
        };
        Ok(oid_to_sha1(&branch.into_reference().peel_to_commit()?.id()))
    }

    fn get_commit_or_tip_of_reference(&self, sha1_or_reference: &str) -> Result<Sha1Hash> {
        let oid = {
            if let Ok(oid) = Oid::from_str(sha1_or_reference) {
                self.git_repo.find_commit(oid)?;
                oid
            } else {
                self.git_repo
                    .find_reference(sha1_or_reference)?
                    .peel_to_commit()?
                    .id()
            }
        };
        Ok(oid_to_sha1(&oid))
    }

    fn get_root_commit(&self) -> Result<Sha1Hash> {
        let mut revwalk = self
            .git_repo
            .revwalk()
            .context("revwalk should be created from git repo")?;
        revwalk
            .push(sha1_to_oid(&self.get_head_commit()?)?)
            .context("revwalk should accept tip oid")?;
        Ok(oid_to_sha1(
            &revwalk
                .last()
                .context("revwalk from tip should be at least contain the tip oid")?
                .context("revwalk iter from branch tip should not result in an error")?,
        ))
    }

    fn does_commit_exist(&self, commit: &str) -> Result<bool> {
        if self.git_repo.find_commit(Oid::from_str(commit)?).is_ok() {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn get_head_commit(&self) -> Result<Sha1Hash> {
        let head = self
            .git_repo
            .head()
            .context("failed to get git repo head")?;
        let oid = head.peel_to_commit()?.id();
        Ok(oid_to_sha1(&oid))
    }

    fn get_commit_parent(&self, commit: &Sha1Hash) -> Result<Sha1Hash> {
        let parent_oid = self
            .git_repo
            .find_commit(sha1_to_oid(commit)?)
            .context(format!("could not find commit {commit}"))?
            .parent_id(0)
            .context(format!("could not find parent of commit {commit}"))?;
        Ok(oid_to_sha1(&parent_oid))
    }

    fn get_commit_message(&self, commit: &Sha1Hash) -> Result<String> {
        Ok(self
            .git_repo
            .find_commit(sha1_to_oid(commit)?)
            .context(format!("could not find commit {commit}"))?
            .message_raw()
            .context("commit message has unusual characters in (not valid utf-8)")?
            .to_string())
    }

    fn get_commit_message_summary(&self, commit: &Sha1Hash) -> Result<String> {
        Ok(self
            .git_repo
            .find_commit(sha1_to_oid(commit)?)
            .context(format!("could not find commit {commit}"))?
            .message_raw()
            .context("commit message has unusual characters in (not valid utf-8)")?
            .split('\r')
            .collect::<Vec<&str>>()[0]
            .split('\n')
            .collect::<Vec<&str>>()[0]
            .to_string()
            .trim()
            .to_string())
    }

    fn get_commit_author(&self, commit: &Sha1Hash) -> Result<Vec<String>> {
        let commit = self
            .git_repo
            .find_commit(sha1_to_oid(commit)?)
            .context(format!("could not find commit {commit}"))?;
        let sig = commit.author();
        Ok(git_sig_to_tag_vec(&sig))
    }

    fn get_commit_comitter(&self, commit: &Sha1Hash) -> Result<Vec<String>> {
        let commit = self
            .git_repo
            .find_commit(sha1_to_oid(commit)?)
            .context(format!("could not find commit {commit}"))?;
        let sig = commit.committer();
        Ok(git_sig_to_tag_vec(&sig))
    }

    fn get_commit_committer_time(&self, commit_hash: &Sha1Hash) -> Result<i64> {
        let commit = self
            .git_repo
            .find_commit(sha1_to_oid(commit_hash)?)
            .context(format!("could not find commit {commit_hash}"))?;
        let time = commit.committer().when().seconds();
        Ok(time)
    }

    fn find_best_guess_parent_commit(&self, patch_timestamp: i64) -> Result<Option<Sha1Hash>> {
        let (main_branch_name, _) = self
            .get_main_or_master_branch()
            .context("failed to get main/master branch")?;

        let mut revwalk = self
            .git_repo
            .revwalk()
            .context("failed to create revwalk")?;

        revwalk
            .push_ref(&format!("refs/heads/{}", main_branch_name))
            .context("failed to push main branch to revwalk")?;

        let mut best_commit: Option<(i64, Sha1Hash)> = None;

        for oid_result in revwalk {
            let oid = oid_result.context("failed to get oid from revwalk")?;
            let commit = self
                .git_repo
                .find_commit(oid)
                .context("failed to find commit")?;

            let committer_time = commit.committer().when().seconds();

            if committer_time < patch_timestamp
                && (best_commit.is_none() || committer_time > best_commit.as_ref().unwrap().0)
            {
                best_commit = Some((committer_time, oid_to_sha1(&oid)));
            }
        }

        Ok(best_commit.map(|(_, sha1)| sha1))
    }

    fn get_refs(&self, commit: &Sha1Hash) -> Result<Vec<String>> {
        Ok(self
            .git_repo
            .references()?
            .filter(|r| {
                if let Ok(r) = r {
                    if let Ok(ref_tip) = r.peel_to_commit() {
                        ref_tip.id().to_string().eq(&commit.to_string())
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
            .map(|r| r.unwrap().shorthand().unwrap().to_string())
            .collect::<Vec<String>>())
    }

    fn make_patch_from_commit(
        &self,
        commit: &Sha1Hash,
        series_count: &Option<(u64, u64)>,
    ) -> Result<String> {
        let c = self
            .git_repo
            .find_commit(Oid::from_bytes(commit.as_byte_array()).context(format!(
                "failed to convert commit_id format for {}",
                &commit
            ))?)
            .context(format!("failed to find commit {}", &commit))?;
        let mut options = git2::EmailCreateOptions::default();
        // Explicitly set a/b prefixes so that the user's `diff.noprefix` git
        // config (or any other prefix override) does not affect the generated
        // patch. Patches must use standard a/b prefixes to be parseable by
        // git2::Diff::from_buffer when applying them.
        options.diff_options().old_prefix("a/").new_prefix("b/");
        if let Some((n, total)) = series_count {
            options.subject_prefix(format!("PATCH {n}/{total}"));
        }
        let patch = git2::Email::from_commit(&c, &mut options)
            .context(format!("failed to create patch from commit {}", &commit))?;

        Ok(std::str::from_utf8(patch.as_slice())
            .context("patch content could not be converted to a utf8 string")?
            .to_owned())
    }

    fn are_commits_too_big_for_patches(&self, commits: &[Sha1Hash]) -> bool {
        commits.iter().any(|commit| {
            if let Ok(patch) = self.make_patch_from_commit(commit, &None) {
                patch.len()
                    > ((65 // max recomended patch event size specified in nip34 in kb
                // allownace for nostr event wrapper (id, pubkey, tags, sig)
                - 1) * 1024)
            } else {
                true
            }
        })
    }

    fn extract_commit_pgp_signature(&self, commit: &Sha1Hash) -> Result<String> {
        let oid = Oid::from_bytes(commit.as_byte_array()).context(format!(
            "failed to convert commit_id format for {}",
            &commit
        ))?;

        let (sign, _data) = self
            .git_repo
            .extract_signature(&oid, None)
            .context("failed to extract signature - perhaps there is no signature?")?;

        Ok(std::str::from_utf8(&sign)
            .context("commit signature failed to be converted to a utf8 string")?
            .to_owned())
    }

    // including (un)staged changes and (un)tracked files
    fn has_outstanding_changes(&self) -> Result<bool> {
        let diff = self.git_repo.diff_tree_to_workdir_with_index(
            Some(&self.git_repo.head()?.peel_to_tree()?),
            Some(DiffOptions::new().include_untracked(true)),
        )?;

        Ok(diff.deltas().len().gt(&0))
    }

    // youngest first
    fn get_commits_ahead_behind(
        &self,
        base_commit: &Sha1Hash,
        latest_commit: &Sha1Hash,
    ) -> Result<(Vec<Sha1Hash>, Vec<Sha1Hash>)> {
        let mut ahead: Vec<Sha1Hash> = vec![];
        let mut behind: Vec<Sha1Hash> = vec![];

        let get_revwalk = |commit: &Sha1Hash| -> Result<Revwalk> {
            let mut revwalk = self
                .git_repo
                .revwalk()
                .context("revwalk should be created from git repo")?;
            revwalk
                .push(sha1_to_oid(commit)?)
                .context("revwalk should accept commit oid")?;
            Ok(revwalk)
        };

        // scan through the base commit ancestory until a common ancestor is found
        let most_recent_shared_commit = match get_revwalk(base_commit)
            .context("failed to get revwalk for base_commit")?
            .find(|base_res| {
                let base_oid = base_res.as_ref().unwrap();

                if get_revwalk(latest_commit)
                    .unwrap()
                    .any(|latest_res| base_oid.eq(latest_res.as_ref().unwrap()))
                {
                    true
                } else {
                    // add commits not found in latest ancestory to 'behind' vector
                    behind.push(oid_to_sha1(base_oid));
                    false
                }
            }) {
            None => {
                bail!(format!(
                    "{latest_commit} is not an ancestor of {base_commit}"
                ));
            }
            Some(res) => res.context("revwalk failed to reveal commit")?,
        };

        // scan through the latest commits until shared commit is reached
        get_revwalk(latest_commit)
            .context("failed to get revwalk for latest_commit")?
            .any(|latest_res| {
                let latest_oid = latest_res.as_ref().unwrap();
                if latest_oid.eq(&most_recent_shared_commit) {
                    true
                } else {
                    // add commits not found in base to 'ahead' vector
                    ahead.push(oid_to_sha1(latest_oid));
                    false
                }
            });
        Ok((ahead, behind))
    }

    fn checkout(&self, ref_name: &str) -> Result<Sha1Hash> {
        let (object, reference) = self.git_repo.revparse_ext(ref_name)?;

        self.git_repo.checkout_tree(&object, None)?;

        match reference {
            // gref is an actual reference like branches or tags
            Some(gref) => self.git_repo.set_head(gref.name().unwrap()),
            // this is a commit, not a reference
            None => self.git_repo.set_head_detached(object.id()),
        }?;
        let oid = self.git_repo.head()?.peel_to_commit()?.id();

        Ok(oid_to_sha1(&oid))
    }

    fn create_branch_at_commit(&self, branch_name: &str, commit: &str) -> Result<()> {
        let branch_checkedout = self.get_checked_out_branch_name()?.eq(branch_name);
        if branch_checkedout {
            let (name, _) = self.get_main_or_master_branch()?;
            self.checkout(name)?;
        }

        self.git_repo
            .branch(
                branch_name,
                &self.git_repo.find_commit(Oid::from_str(commit)?)?,
                true,
            )
            .context("branch could not be created")?;

        if branch_checkedout {
            self.checkout(branch_name)?;
        }
        Ok(())
    }
    /* returns patches applied */
    fn apply_patch_chain(
        &self,
        branch_name: &str,
        patch_and_ancestors: Vec<nostr::Event>,
    ) -> Result<Vec<nostr::Event>> {
        let branch_tip_result = self.get_tip_of_branch(branch_name);

        // filter out existing ancestors in branch
        let mut patches_to_apply: Vec<nostr::Event> = patch_and_ancestors
            .into_iter()
            .filter(|e| {
                // When the commit tag is absent, the commit id from the mbox envelope
                // may not match the reconstructed commit's OID (e.g. GPG-signed commits).
                // In that case we conservatively include the patch for application —
                // create_commit_from_patch handles idempotency via content-addressed storage.
                let Ok(commit_id) = get_commit_id_from_patch(e) else {
                    return true;
                };
                let Ok(branch_tip) = branch_tip_result else {
                    return true;
                };
                let Ok(commit_sha1) = str_to_sha1(&commit_id) else {
                    // Commit id is not a valid SHA1 (e.g. placeholder from mbox envelope).
                    // Include conservatively.
                    return true;
                };
                !branch_tip.to_string().eq(&commit_id)
                    && !self.ancestor_of(&branch_tip, &commit_sha1).unwrap_or(false)
            })
            .collect();

        let parent_commit_id = match patches_to_apply.last() {
            Some(last_patch) => {
                crate::git_events::get_parent_commit_from_patch(last_patch, Some(self))?
            }
            None => {
                self.checkout(branch_name)
                    .context("no patches and so failed to create a proposal branch")?;
                return Ok(vec![]);
            }
        };

        // check patches can be applied
        if !self.does_commit_exist(&parent_commit_id)? {
            bail!("failed to find parent commit ({parent_commit_id}). run git pull and try again.")
        }

        // checkout branch
        self.create_branch_at_commit(branch_name, &parent_commit_id)?;
        self.checkout(branch_name)?;

        // apply commits
        patches_to_apply.reverse();

        // When optional tags are absent, the reconstructed OID of each applied patch
        // may differ from its tagged commit id (e.g. GPG-signed commits, different
        // tooling). We therefore thread the actual applied OID forward as the
        // parent override for the next patch, so the chain builds correctly
        // even when parent-commit tags are absent or point to a
        // pre-reconstruction OID.
        let mut next_parent_override: Option<String> = None;

        for patch in &patches_to_apply {
            let tag_commit_id = get_commit_id_from_patch(patch).ok();
            let applied_oid = if let Some(ref id) = tag_commit_id {
                if self.does_commit_exist(id)? && next_parent_override.is_none() {
                    // Commit already exists and we have no override from a prior
                    // reconstruction — use the existing commit directly.
                    id.clone()
                } else {
                    self.create_commit_from_patch(patch, next_parent_override.take())?
                        .to_string()
                }
            } else {
                // No commit id available at all — apply and use the resulting OID.
                self.create_commit_from_patch(patch, next_parent_override.take())?
                    .to_string()
            };
            next_parent_override = Some(applied_oid.clone());
            self.create_branch_at_commit(branch_name, &applied_oid)?;
            self.checkout(branch_name)?;
        }
        Ok(patches_to_apply)
    }
    fn create_commit_from_patch(
        &self,
        patch: &nostr::Event,
        parent_commit_id_override: Option<String>,
    ) -> Result<Oid> {
        let commit_id = get_commit_id_from_patch(patch);
        if parent_commit_id_override.is_none() {
            if let Ok(commit_id) = &commit_id {
                if self.does_commit_exist(commit_id).unwrap_or(false) {
                    return Ok(Oid::from_str(commit_id)?);
                }
            }
        }

        let parent_commit_id = if let Some(commit_id) = parent_commit_id_override.clone() {
            commit_id
        } else if let Ok(parent) = tag_value(patch, "parent-commit") {
            parent
        } else {
            let metadata = crate::mbox_parser::parse_mbox_patch(&patch.content)
                .context("failed to parse patch for timestamp")?;
            let timestamp = metadata
                .committer_timestamp
                .unwrap_or(metadata.author_timestamp);

            let best_guess = self
                .find_best_guess_parent_commit(timestamp)
                .context("failed to find best guess parent commit")?;

            match best_guess {
                Some(sha1) => sha1.to_string(),
                None => bail!(
                    "no parent-commit tag and could not determine best guess parent from patch timestamp"
                ),
            }
        };

        let parent_commit = self
            .git_repo
            .find_commit(Oid::from_str(&parent_commit_id)?)
            .context("parrent commit doesnt exist")?;
        let parent_tree = parent_commit.tree()?;

        // let mut apply_opts = git2::ApplyOptions::new();
        // apply_opts.check(false);
        let mut existing_index = self.git_repo.index()?;
        let normalized_content = normalize_diff_prefix(&patch.content);
        let mut index = self.git_repo.apply_to_tree(
            &parent_tree,
            &git2::Diff::from_buffer(normalized_content.as_bytes())?,
            // Some(&mut apply_opts),
            None,
        )?;
        let tree = self
            .git_repo
            .find_tree(index.write_tree_to(&self.git_repo)?)?;

        let pgp_sig = if let Ok(pgp_sig) = tag_value(patch, "commit-pgp-sig") {
            if pgp_sig.is_empty() {
                None
            } else {
                Some(pgp_sig)
            }
        } else {
            None
        };

        let author_data =
            extract_signature_data_with_fallback(&patch.tags, "author", &patch.content)?;
        let committer_data =
            extract_signature_data_with_fallback(&patch.tags, "committer", &patch.content)?;
        let author_sig = author_data.to_signature()?;
        let committer_sig = committer_data.to_signature()?;

        let commit_buff = self.git_repo.commit_create_buffer(
            &author_sig,
            &committer_sig,
            extract_description_from_patch(patch)?.as_str(),
            &tree,
            &[&parent_commit],
        )?;

        let mut applied_oid = self
            .git_repo
            .commit_signed(
                commit_buff.as_str().unwrap(),
                pgp_sig.as_deref().unwrap_or(""),
                None,
            )
            .context("failed to create signed commit")?;

        // I beleive this was added to address a bug where commit author / committer
        // were identical when in a scenario when they should be different but I dont
        // think we have a test case for it. surely we should be using the
        // extract_sig_from_patch_tags outputs to address this?
        let custom_parent = if let Some(ovderride_parent) = parent_commit_id_override {
            if let Ok(tag_parent) = tag_value(patch, "parent-commit") {
                ovderride_parent != tag_parent
            } else {
                true
            }
        } else {
            false
        };
        if !custom_parent {
            if let Ok(commit_id) = &commit_id {
                if !applied_oid.to_string().eq(commit_id) {
                    let commit = self.git_repo.find_commit(applied_oid)?;
                    applied_oid = commit
                        .amend(
                            None,
                            Some(&commit.author()),
                            Some(&commit.committer()),
                            None,
                            None,
                            None,
                        )
                        .context("failed to amend commit to produce new oid")?;
                }
                // If the OID still doesn't match after the amend, accept
                // the amend result and continue. The amend always produces
                // an unsigned commit (git_commit_amend goes through
                // git_commit__create_internal, not
                // commit_create_with_signature) so any GPG sig
                // from the original is stripped — correct
                // behaviour since the reconstructed commit object differs
                // from what was originally signed. The diff is applied
                // correctly regardless. apply_patch_chain threads the actual
                // OID forward via next_parent_override so the chain remains
                // consistent.
            }
        }
        self.git_repo.set_index(&mut existing_index)?;
        Ok(applied_oid)
    }
    fn parse_starting_commits(&self, starting_commits: &str) -> Result<Vec<Sha1Hash>> {
        let revspec = self
            .git_repo
            .revparse(starting_commits)
            .context("specified value not in a valid format")?;
        if revspec.mode().is_no_single() {
            let (ahead, _) = self
                .get_commits_ahead_behind(
                    &oid_to_sha1(
                        &revspec
                            .from()
                            .context("failed to get starting commit from specified value")?
                            .id(),
                    ),
                    &self
                        .get_head_commit()
                        .context("failed to get head commit with gitlib2")?,
                )
                .context("specified commit is not an ancestor of current head")?;
            Ok(ahead)
        } else if revspec.mode().is_range() {
            let (ahead, _) = self
                .get_commits_ahead_behind(
                    &oid_to_sha1(
                        &revspec
                            .from()
                            .context("failed to get starting commit of range from specified value")?
                            .id(),
                    ),
                    &oid_to_sha1(
                        &revspec
                            .to()
                            .context("failed to get end of range commit from specified value")?
                            .id(),
                    ),
                )
                .context("specified commit is not an ancestor of current head")?;
            Ok(ahead)
        } else {
            bail!("specified value not in a supported format")
        }
    }

    fn ancestor_of(&self, decendant: &Sha1Hash, ancestor: &Sha1Hash) -> Result<bool> {
        if let Ok(res) = self
            .git_repo
            .graph_descendant_of(sha1_to_oid(decendant)?, sha1_to_oid(ancestor)?)
            .context("could not run graph_descendant_of in gitlib2")
        {
            Ok(res)
        } else {
            Ok(false)
        }
    }

    fn get_upstream_for_branch(&self, branch_name: &str) -> Result<Option<String>> {
        let branch = self
            .git_repo
            .find_branch(branch_name, git2::BranchType::Local)
            .context(format!("failed to find local branch {branch_name}"))?;
        let upstream = branch.upstream();
        match upstream {
            Ok(upstream_branch) => {
                let name = upstream_branch.name()?.map(|s| s.to_string());
                Ok(name)
            }
            Err(_) => Ok(None),
        }
    }

    /// setting global to None will suppliment local config with global items
    /// not in local
    fn get_git_config_item(&self, item: &str, global: Option<bool>) -> Result<Option<String>> {
        let just_global = global.unwrap_or(false);
        match if just_global {
            self.git_repo
                .config()
                .context("failed to open git config")?
                .open_global()
                .context("failed to open global git config")?
        } else {
            self.git_repo
                .config()
                .context("failed to open git config")?
        }
        .get_entry(item)
        {
            Ok(item) => {
                if let Some(global) = global {
                    if item.level().eq(&git2::ConfigLevel::Local) {
                        if global {
                            // bail!("only local repository login available")
                            return Ok(None);
                        }
                    } else if !global {
                        // bail!("only global repository login available")
                        return Ok(None);
                    }
                }
                Ok(Some(
                    item.value()
                        .context("failed to find git config item")?
                        .to_string(),
                ))
            }
            Err(_) => Ok(None),
        }
    }

    fn save_git_config_item(&self, item: &str, value: &str, global: bool) -> Result<()> {
        if global {
            self.git_repo
                .config()
                .context("failed to open git config")?
                .open_global()
                .context("failed to open global git config")?
        } else {
            self.git_repo
                .config()
                .context("failed to open git config")?
        }
        .set_str(item, value)
        .context(format!(
            "failed to set {} git config item {}",
            if global { "global" } else { "local" },
            item
        ))?;
        Ok(())
    }

    /// returns false if item doesn't exist
    fn remove_git_config_item(&self, item: &str, global: bool) -> Result<bool> {
        if self.get_git_config_item(item, Some(global))?.is_none() {
            Ok(false)
        } else {
            if global {
                self.git_repo
                    .config()
                    .context("failed to open git config")?
                    .open_global()
                    .context("failed to open global git config")?
            } else {
                self.git_repo
                    .config()
                    .context("failed to open git config")?
            }
            .remove(item)
            .context("failed to remove existing git config item")?;
            Ok(true)
        }
    }

    async fn get_first_nostr_remote_when_in_ngit_binary(
        &self,
    ) -> Result<Option<(String, NostrUrlDecoded)>> {
        for remote_name in self.git_repo.remotes()?.iter().flatten() {
            if let Some(remote_url) = self.git_repo.find_remote(remote_name)?.url() {
                if let Ok(nostr_url_decoded) =
                    NostrUrlDecoded::parse_and_resolve(remote_url, &Some(self)).await
                {
                    return Ok(Some((remote_name.to_string(), nostr_url_decoded)));
                }
            }
        }
        Ok(None)
    }
}

fn oid_to_u8_20_bytes(oid: &Oid) -> [u8; 20] {
    let b = oid.as_bytes();
    [
        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13],
        b[14], b[15], b[16], b[17], b[18], b[19],
    ]
}

pub fn oid_to_shorthand_string(oid: Oid) -> Result<String> {
    let binding = oid.to_string();
    let b = binding.as_bytes();
    String::from_utf8(vec![b[0], b[1], b[2], b[3], b[4], b[5], b[6]])
        .context("oid should always start with 7 u8 btyes of utf8")
}

// fn oid_to_sha1_string(oid: Oid) -> Result<String> {
//     let b = oid.as_bytes();
//     String::from_utf8(vec![
//         b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10],
// b[11], b[12], b[13],         b[14], b[15], b[16], b[17], b[18], b[19],
//     ])
//     .context("oid should contain 20 u8 btyes of utf8")
// }

// git2 Oid object to Sha1Hash
pub fn oid_to_sha1(oid: &Oid) -> Sha1Hash {
    Sha1Hash::from_byte_array(oid_to_u8_20_bytes(oid))
}

/// `Sha1Hash` to git2 `Oid` object
pub fn sha1_to_oid(hash: &Sha1Hash) -> Result<Oid> {
    Oid::from_bytes(hash.as_byte_array()).context("Sha1Hash bytes failed to produce a valid Oid")
}

pub fn str_to_sha1(s: &str) -> Result<Sha1Hash> {
    Ok(oid_to_sha1(
        &Oid::from_str(s).context("string is not a sha1 hash")?,
    ))
}

fn git_sig_to_tag_vec(sig: &git2::Signature) -> Vec<String> {
    vec![
        sig.name().unwrap_or("").to_string(),
        sig.email().unwrap_or("").to_string(),
        format!("{}", sig.when().seconds()),
        format!("{}", sig.when().offset_minutes()),
    ]
}

struct SignatureData {
    name: String,
    email: String,
    timestamp: i64,
    offset_minutes: i32,
}

fn extract_signature_data_from_tags(tags: &Tags, tag_name: &str) -> Result<SignatureData> {
    let v = tags
        .iter()
        .find(|t| !t.as_slice().is_empty() && t.as_slice()[0].eq(tag_name))
        .context(format!("tag '{tag_name}' not present in patch"))?
        .as_slice();
    if v.len() != 5 {
        bail!("tag '{tag_name}' is incorrectly formatted")
    }
    Ok(SignatureData {
        name: v[1].clone(),
        email: v[2].clone(),
        timestamp: v[3].parse().context("tag time is incorrectly formatted")?,
        offset_minutes: v[4]
            .parse()
            .context("tag time offset is incorrectly formatted")?,
    })
}

fn extract_signature_data_with_fallback(
    tags: &Tags,
    tag_name: &str,
    patch_content: &str,
) -> Result<SignatureData> {
    if let Ok(data) = extract_signature_data_from_tags(tags, tag_name) {
        return Ok(data);
    }

    let metadata = crate::mbox_parser::parse_mbox_patch(patch_content)
        .context("failed to parse patch content for fallback metadata")?;

    if tag_name == "author" {
        Ok(SignatureData {
            name: metadata.author_name,
            email: metadata.author_email,
            timestamp: metadata.author_timestamp,
            offset_minutes: metadata.author_offset_minutes,
        })
    } else if tag_name == "committer" {
        let timestamp = metadata
            .committer_timestamp
            .unwrap_or(metadata.author_timestamp);
        Ok(SignatureData {
            name: metadata.author_name,
            email: metadata.author_email,
            timestamp,
            offset_minutes: metadata.author_offset_minutes,
        })
    } else {
        bail!("unknown tag name for signature extraction: {}", tag_name)
    }
}

impl SignatureData {
    fn to_signature(&self) -> Result<git2::Signature<'_>> {
        git2::Signature::new(
            &self.name,
            &self.email,
            &git2::Time::new(self.timestamp, self.offset_minutes),
        )
        .context("failed to create git signature")
    }
}

/// Normalize a patch that uses no-prefix diff format (produced by libgit2 with
/// `--no-prefix`, e.g. `diff --git src/foo.rs src/foo.rs`) to the standard
/// `a/`/`b/` prefix format that `git2::Diff::from_buffer` requires.
///
/// If the patch already uses standard prefixes this function is a no-op.
fn normalize_diff_prefix(content: &str) -> String {
    // Detect whether any diff header is missing the a/b prefix.
    // A standard header looks like: diff --git a/<path> b/<path>
    // A no-prefix header looks like: diff --git <path> <path>
    let needs_normalization = content
        .lines()
        .filter(|l| l.starts_with("diff --git "))
        .any(|l| {
            let rest = &l["diff --git ".len()..];
            !rest.starts_with("a/")
        });

    if !needs_normalization {
        return content.to_string();
    }

    let mut out = String::with_capacity(content.len() + 64);
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("diff --git ") {
            // rest is "<old-path> <new-path>". For paths without spaces the
            // split is unambiguous. For paths with spaces we rely on the fact
            // that old == new for renames-in-place; we find the midpoint by
            // trying each space as a split and checking old == new.
            let (old, new) = split_diff_git_paths(rest);
            out.push_str("diff --git a/");
            out.push_str(old);
            out.push_str(" b/");
            out.push_str(new);
        } else if let Some(rest) = line.strip_prefix("--- ") {
            if rest == "/dev/null" {
                out.push_str(line);
            } else {
                out.push_str("--- a/");
                out.push_str(rest);
            }
        } else if let Some(rest) = line.strip_prefix("+++ ") {
            if rest == "/dev/null" {
                out.push_str(line);
            } else {
                out.push_str("+++ b/");
                out.push_str(rest);
            }
        } else {
            out.push_str(line);
        }
        out.push('\n');
    }
    // Preserve trailing newline behaviour of the original.
    if !content.ends_with('\n') && out.ends_with('\n') {
        out.pop();
    }
    out
}

/// Split the path portion of a `diff --git <old> <new>` line into (old, new).
///
/// For paths without spaces this is trivial. For paths with spaces we try each
/// space as a candidate split point and return the first one where the two
/// halves are equal (which is always the case for non-rename patches). If no
/// equal split is found we fall back to splitting at the first space.
fn split_diff_git_paths(rest: &str) -> (&str, &str) {
    // Fast path: no spaces → split at the single space
    if let Some(pos) = rest.find(' ') {
        let (old, new_with_space) = rest.split_at(pos);
        let new = &new_with_space[1..];
        if !old.contains(' ') {
            return (old, new);
        }
        // Paths contain spaces: try each space as a split point.
        let bytes = rest.as_bytes();
        for (i, &b) in bytes.iter().enumerate() {
            if b == b' ' {
                let candidate_old = &rest[..i];
                let candidate_new = &rest[i + 1..];
                if candidate_old == candidate_new {
                    return (candidate_old, candidate_new);
                }
            }
        }
        // Fallback: split at first space
        (old, new)
    } else {
        // No space at all — malformed, return as-is
        (rest, rest)
    }
}

fn extract_description_from_patch(patch: &nostr::Event) -> Result<String> {
    if let Ok(desc) = tag_value(patch, "description") {
        return Ok(desc);
    }

    crate::mbox_parser::extract_description_from_patch(&patch.content)
        .context("failed to extract description from patch content")
}

pub fn get_git_config_item(git_repo: &Option<&Repo>, item: &str) -> Result<Option<String>> {
    if let Some(git_repo) = git_repo {
        git_repo.get_git_config_item(item, Some(false))
    } else {
        Ok(
            match git2::Config::open_default()?.open_global()?.get_entry(item) {
                Ok(item) => item.value().map(|v| v.to_string()),
                Err(_) => None,
            },
        )
    }
}

/// Read a config item from the system-level git config only (e.g.
/// /etc/gitconfig).
pub fn get_git_config_item_system(item: &str) -> Result<Option<String>> {
    let config = git2::Config::open_default().context("failed to open git config")?;
    // Try system level first, then ProgramData (Windows equivalent)
    for level in [git2::ConfigLevel::System, git2::ConfigLevel::ProgramData] {
        if let Ok(level_config) = config.open_level(level) {
            match level_config.get_entry(item) {
                Ok(entry) => return Ok(entry.value().map(|v| v.to_string())),
                Err(_) => continue,
            }
        }
    }
    Ok(None)
}

pub fn save_git_config_item(git_repo: &Option<&Repo>, item: &str, value: &str) -> Result<()> {
    if let Some(git_repo) = git_repo {
        git_repo.save_git_config_item(item, value, false)
    } else {
        git2::Config::open_default()?
            .open_global()?
            .set_str(item, value)
            .context(format!("failed to set global git config item {item}"))
    }
}

pub fn remove_git_config_item(git_repo: &Option<&Repo>, item: &str) -> Result<bool> {
    if let Some(git_repo) = git_repo {
        git_repo.remove_git_config_item(item, false)
    } else if get_git_config_item(&None, item)?.is_none() {
        Ok(false)
    } else {
        git2::Config::open_default()?
            .open_global()?
            .remove(item)
            .context(format!("failed to remove existing git config item {item}"))?;
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use test_utils::{generate_repo_ref_event, git::GitTestRepo};

    use super::*;

    mod normalize_diff_prefix {
        use super::*;

        #[test]
        fn no_op_when_already_prefixed() {
            let patch = "\
diff --git a/src/foo.rs b/src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- a/src/foo.rs\n\
+++ b/src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n";
            assert_eq!(normalize_diff_prefix(patch), patch);
        }

        #[test]
        fn adds_prefix_to_no_prefix_diff() {
            let patch_no_prefix = "\
diff --git src/foo.rs src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- src/foo.rs\n\
+++ src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n";
            let expected = "\
diff --git a/src/foo.rs b/src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- a/src/foo.rs\n\
+++ b/src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n";
            assert_eq!(normalize_diff_prefix(patch_no_prefix), expected);
        }

        #[test]
        fn preserves_dev_null_for_new_file() {
            let patch_no_prefix = "\
diff --git src/new.rs src/new.rs\n\
new file mode 100644\n\
index 0000000..a21e91c\n\
--- /dev/null\n\
+++ src/new.rs\n\
@@ -0,0 +1 @@\n\
+hello\n";
            let expected = "\
diff --git a/src/new.rs b/src/new.rs\n\
new file mode 100644\n\
index 0000000..a21e91c\n\
--- /dev/null\n\
+++ b/src/new.rs\n\
@@ -0,0 +1 @@\n\
+hello\n";
            assert_eq!(normalize_diff_prefix(patch_no_prefix), expected);
        }

        #[test]
        fn preserves_dev_null_for_deleted_file() {
            let patch_no_prefix = "\
diff --git src/old.rs src/old.rs\n\
deleted file mode 100644\n\
index a21e91c..0000000\n\
--- src/old.rs\n\
+++ /dev/null\n\
@@ -1 +0,0 @@\n\
-hello\n";
            let expected = "\
diff --git a/src/old.rs b/src/old.rs\n\
deleted file mode 100644\n\
index a21e91c..0000000\n\
--- a/src/old.rs\n\
+++ /dev/null\n\
@@ -1 +0,0 @@\n\
-hello\n";
            assert_eq!(normalize_diff_prefix(patch_no_prefix), expected);
        }

        #[test]
        fn handles_multiple_files() {
            let patch_no_prefix = "\
diff --git src/foo.rs src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- src/foo.rs\n\
+++ src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n\
diff --git src/bar.rs src/bar.rs\n\
index 1234567..abcdef0 100644\n\
--- src/bar.rs\n\
+++ src/bar.rs\n\
@@ -1 +1 @@\n\
-foo\n\
+baz\n";
            let expected = "\
diff --git a/src/foo.rs b/src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- a/src/foo.rs\n\
+++ b/src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n\
diff --git a/src/bar.rs b/src/bar.rs\n\
index 1234567..abcdef0 100644\n\
--- a/src/bar.rs\n\
+++ b/src/bar.rs\n\
@@ -1 +1 @@\n\
-foo\n\
+baz\n";
            assert_eq!(normalize_diff_prefix(patch_no_prefix), expected);
        }

        #[test]
        fn libgit2_can_parse_normalized_no_prefix_diff() {
            // Verify that after normalization, git2::Diff::from_buffer succeeds
            let patch_no_prefix = "\
diff --git src/foo.rs src/foo.rs\n\
index ce01362..a21e91c 100644\n\
--- src/foo.rs\n\
+++ src/foo.rs\n\
@@ -1 +1 @@\n\
-hello\n\
+world\n";
            let normalized = normalize_diff_prefix(patch_no_prefix);
            let result = git2::Diff::from_buffer(normalized.as_bytes());
            assert!(
                result.is_ok(),
                "libgit2 failed to parse normalized diff: {:?}",
                result.err()
            );
            assert_eq!(result.unwrap().deltas().count(), 1);
        }
    }

    mod git_config_item_local {
        use super::*;

        #[test]
        fn save_git_config_item_returns_ok() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.save_git_config_item("test.item", "testvalue", false)?;
            Ok(())
        }

        #[test]
        fn get_git_config_item_returns_item_just_saved() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.save_git_config_item("test.item", "testvalue", false)?;
            assert_eq!(
                git_repo
                    .get_git_config_item("test.item", Some(false))?
                    .unwrap(),
                "testvalue",
            );
            Ok(())
        }

        #[test]
        fn get_git_config_item_returns_none_if_not_present() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            assert_eq!(
                git_repo.get_git_config_item("test.item", Some(false))?,
                None
            );
            Ok(())
        }

        #[test]
        fn get_git_config_item_empty_string_returns_empty_string_instead_of_none() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.save_git_config_item("test.item", "", false)?;
            assert_eq!(
                git_repo.get_git_config_item("test.item", Some(false))?,
                Some("".to_string()),
            );
            Ok(())
        }

        #[test]
        fn remove_local_git_config_item() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.save_git_config_item("test.item", "testvalue", false)?;
            assert!(git_repo.remove_git_config_item("test.item", false)?);
            assert_eq!(
                git_repo.get_git_config_item("test.item", Some(false))?,
                None,
            );
            Ok(())
        }

        #[test]
        fn remove_git_config_item_returns_false_if_item_wasnt_set() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            assert!(!(git_repo.remove_git_config_item("test.item", false)?));
            Ok(())
        }
    }

    #[test]
    fn get_commit_parent() -> Result<()> {
        let test_repo = GitTestRepo::default();
        let parent_oid = test_repo.populate()?;
        std::fs::write(test_repo.dir.join("t100.md"), "some content")?;
        let child_oid = test_repo.stage_and_commit("add t100.md")?;

        let git_repo = Repo::from_path(&test_repo.dir)?;

        assert_eq!(
            // Sha1Hash::from_byte_array("bla".to_string().as_bytes()),
            oid_to_sha1(&parent_oid),
            git_repo.get_commit_parent(&oid_to_sha1(&child_oid))?,
        );
        Ok(())
    }

    mod get_commit_message {
        use super::*;
        fn run(message: &str) -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            std::fs::write(test_repo.dir.join("t100.md"), "some content")?;
            let oid = test_repo.stage_and_commit(message)?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert_eq!(message, git_repo.get_commit_message(&oid_to_sha1(&oid))?,);
            Ok(())
        }
        #[test]
        fn one_liner() -> Result<()> {
            run("add t100.md")
        }

        #[test]
        fn multiline() -> Result<()> {
            run("add t100.md\r\nanother line\r\nthird line")
        }

        #[test]
        fn trailing_newlines() -> Result<()> {
            run("add t100.md\r\n\r\n\r\n\r\n\r\n\r\n")
        }

        #[test]
        fn unicode_characters() -> Result<()> {
            run("add t100.md ❤️")
        }
    }

    mod get_commit_message_summary {
        use super::*;
        fn run(message: &str, summary: &str) -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            std::fs::write(test_repo.dir.join("t100.md"), "some content")?;
            let oid = test_repo.stage_and_commit(message)?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert_eq!(
                summary,
                git_repo.get_commit_message_summary(&oid_to_sha1(&oid))?,
            );
            Ok(())
        }
        #[test]
        fn one_liner() -> Result<()> {
            run("add t100.md", "add t100.md")
        }

        #[test]
        fn multiline() -> Result<()> {
            run("add t100.md\r\nanother line\r\nthird line", "add t100.md")
        }

        #[test]
        fn trailing_newlines() -> Result<()> {
            run("add t100.md\r\n\r\n\r\n\r\n\r\n\r\n", "add t100.md")
        }

        #[test]
        fn unicode_characters() -> Result<()> {
            run("add t100.md ❤️", "add t100.md ❤️")
        }
    }

    mod get_commit_author {
        use super::*;

        static NAME: &str = "carole";
        static EMAIL: &str = "carole@pm.me";

        fn prep(time: &git2::Time) -> Result<Vec<String>> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            fs::write(test_repo.dir.join("x1.md"), "some content")?;
            let oid = test_repo.stage_and_commit_custom_signature(
                "add x1.md",
                Some(&git2::Signature::new(NAME, EMAIL, time)?),
                None,
            )?;

            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.get_commit_author(&oid_to_sha1(&oid))
        }

        #[test]
        fn name() -> Result<()> {
            let res = prep(&git2::Time::new(5000, 0))?;
            assert_eq!(NAME, res[0]);
            Ok(())
        }

        #[test]
        fn email() -> Result<()> {
            let res = prep(&git2::Time::new(5000, 0))?;
            assert_eq!(EMAIL, res[1]);
            Ok(())
        }

        mod time {
            use super::*;

            #[test]
            fn no_offset() -> Result<()> {
                let res = prep(&git2::Time::new(5000, 0))?;
                assert_eq!("5000", res[2]);
                assert_eq!("0", res[3]);
                Ok(())
            }
            #[test]
            fn positive_offset() -> Result<()> {
                let res = prep(&git2::Time::new(5000, 300))?;
                assert_eq!("5000", res[2]);
                assert_eq!("300", res[3]);
                Ok(())
            }
            #[test]
            fn negative_offset() -> Result<()> {
                let res = prep(&git2::Time::new(5000, -300))?;
                assert_eq!("5000", res[2]);
                assert_eq!("-300", res[3]);
                Ok(())
            }
        }

        mod extract_signature_data_from_tags {
            use super::*;

            fn test(time: git2::Time) -> Result<()> {
                let data = extract_signature_data_from_tags(
                    &Tags::from_list(vec![nostr::Tag::custom(
                        nostr::TagKind::Custom("author".to_string().into()),
                        prep(&time)?,
                    )]),
                    "author",
                )?;
                let sig = data.to_signature()?;
                assert_eq!(
                    sig.to_string(),
                    git2::Signature::new(NAME, EMAIL, &time)?.to_string(),
                );
                Ok(())
            }

            #[test]
            fn no_offset() -> Result<()> {
                test(git2::Time::new(5000, 0))
            }

            #[test]
            fn positive_offset() -> Result<()> {
                test(git2::Time::new(5000, 300))
            }

            #[test]
            fn negative_offset() -> Result<()> {
                test(git2::Time::new(5000, -300))
            }
        }
    }

    mod get_commit_comitter {
        use super::*;

        static NAME: &str = "carole";
        static EMAIL: &str = "carole@pm.me";

        fn prep(time: &git2::Time) -> Result<Vec<String>> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            fs::write(test_repo.dir.join("x1.md"), "some content")?;
            let oid = test_repo.stage_and_commit_custom_signature(
                "add x1.md",
                None,
                Some(&git2::Signature::new(NAME, EMAIL, time)?),
            )?;

            let git_repo = Repo::from_path(&test_repo.dir)?;
            git_repo.get_commit_comitter(&oid_to_sha1(&oid))
        }

        #[test]
        fn name() -> Result<()> {
            let res = prep(&git2::Time::new(5000, 0))?;
            assert_eq!(NAME, res[0]);
            Ok(())
        }

        #[test]
        fn email() -> Result<()> {
            let res = prep(&git2::Time::new(5000, 0))?;
            assert_eq!(EMAIL, res[1]);
            Ok(())
        }
    }

    mod does_commit_exist {
        use super::*;

        #[test]
        fn existing_commits_results_in_true() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(git_repo.does_commit_exist("431b84edc0d2fa118d63faa3c2db9c73d630a5ae")?);
            Ok(())
        }

        #[test]
        fn correctly_formatted_hash_that_doesnt_correspond_to_an_existing_commit_results_in_false()
        -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(!git_repo.does_commit_exist("000004edc0d2fa118d63faa3c2db9c73d630a5ae")?);
            Ok(())
        }

        #[test]
        fn incorrectly_formatted_hash_that_doesnt_correspond_to_an_existing_commit_results_in_error()
        -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(git_repo.does_commit_exist("00").is_ok());
            Ok(())
        }
    }

    mod make_patch_from_commit {
        use super::*;
        #[test]
        fn simple_patch_matches_string() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let oid = test_repo.populate()?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert_eq!(
                "\
                From 431b84edc0d2fa118d63faa3c2db9c73d630a5ae Mon Sep 17 00:00:00 2001\n\
                From: Joe Bloggs <joe.bloggs@pm.me>\n\
                Date: Thu, 1 Jan 1970 00:00:00 +0000\n\
                Subject: [PATCH] add t2.md\n\
                \n\
                ---\n \
                t2.md | 1 +\n \
                1 file changed, 1 insertion(+)\n \
                create mode 100644 t2.md\n\
                \n\
                diff --git a/t2.md b/t2.md\n\
                new file mode 100644\n\
                index 0000000..a66525d\n\
                --- /dev/null\n\
                +++ b/t2.md\n\
                @@ -0,0 +1 @@\n\
                +some content1\n\\ \
                No newline at end of file\n\
                --\n\
                libgit2 1.9.2\n\
                \n\
                ",
                git_repo.make_patch_from_commit(&oid_to_sha1(&oid), &None)?,
            );
            Ok(())
        }

        #[test]
        fn series_count() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let oid = test_repo.populate()?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert_eq!(
                "\
                From 431b84edc0d2fa118d63faa3c2db9c73d630a5ae Mon Sep 17 00:00:00 2001\n\
                From: Joe Bloggs <joe.bloggs@pm.me>\n\
                Date: Thu, 1 Jan 1970 00:00:00 +0000\n\
                Subject: [PATCH 3/5] add t2.md\n\
                \n\
                ---\n \
                t2.md | 1 +\n \
                1 file changed, 1 insertion(+)\n \
                create mode 100644 t2.md\n\
                \n\
                diff --git a/t2.md b/t2.md\n\
                new file mode 100644\n\
                index 0000000..a66525d\n\
                --- /dev/null\n\
                +++ b/t2.md\n\
                @@ -0,0 +1 @@\n\
                +some content1\n\\ \
                No newline at end of file\n\
                --\n\
                libgit2 1.9.2\n\
                \n\
                ",
                git_repo.make_patch_from_commit(&oid_to_sha1(&oid), &Some((3, 5)))?,
            );
            Ok(())
        }
    }

    mod get_main_or_master_branch {

        use super::*;

        #[test]
        fn return_origin_main_if_exists() -> Result<()> {
            let test_origin_repo = GitTestRepo::new("main")?;
            let main_origin_oid = test_origin_repo.populate()?;

            let test_repo = GitTestRepo::new("main")?;
            test_repo.populate()?;
            test_repo.add_remote("origin", test_origin_repo.dir.to_str().unwrap())?;
            test_repo
                .git_repo
                .find_remote("origin")?
                .fetch(&["main"], None, None)?;

            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            test_repo.stage_and_commit("add t3.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;
            let (name, commit_hash) = git_repo.get_main_or_master_branch()?;
            assert_eq!(name, "origin/main");
            assert_eq!(commit_hash, oid_to_sha1(&main_origin_oid));
            Ok(())
        }

        mod returns_main {
            use super::*;
            #[test]
            fn when_it_exists() -> Result<()> {
                let test_repo = GitTestRepo::new("main")?;
                let main_oid = test_repo.populate()?;
                let git_repo = Repo::from_path(&test_repo.dir)?;
                let (name, commit_hash) = git_repo.get_main_or_master_branch()?;
                assert_eq!(name, "main");
                assert_eq!(commit_hash, oid_to_sha1(&main_oid));
                Ok(())
            }

            #[test]
            fn when_it_exists_and_other_branch_checkedout() -> Result<()> {
                let test_repo = GitTestRepo::new("main")?;
                let main_oid = test_repo.populate()?;
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let feature_oid = test_repo.stage_and_commit("add t3.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;
                let (name, commit_hash) = git_repo.get_main_or_master_branch()?;
                assert_eq!(name, "main");
                assert_eq!(commit_hash, oid_to_sha1(&main_oid));
                assert_ne!(commit_hash, oid_to_sha1(&feature_oid));
                Ok(())
            }

            #[test]
            fn when_exists_even_if_master_is_checkedout() -> Result<()> {
                let test_repo = GitTestRepo::new("main")?;
                let main_oid = test_repo.populate()?;
                test_repo.create_branch("master")?;
                test_repo.checkout("master")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let master_oid = test_repo.stage_and_commit("add t3.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;
                let (name, commit_hash) = git_repo.get_main_or_master_branch()?;
                assert_eq!(name, "main");
                assert_eq!(commit_hash, oid_to_sha1(&main_oid));
                assert_ne!(commit_hash, oid_to_sha1(&master_oid));
                Ok(())
            }
        }

        #[test]
        fn returns_master_if_exists_and_main_doesnt() -> Result<()> {
            let test_repo = GitTestRepo::new("master")?;
            let master_oid = test_repo.populate()?;
            test_repo.create_branch("feature")?;
            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            let feature_oid = test_repo.stage_and_commit("add t3.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;
            let (name, commit_hash) = git_repo.get_main_or_master_branch()?;
            assert_eq!(name, "master");
            assert_eq!(commit_hash, oid_to_sha1(&master_oid));
            assert_ne!(commit_hash, oid_to_sha1(&feature_oid));
            Ok(())
        }
        #[test]
        fn returns_error_if_no_main_or_master() -> Result<()> {
            let test_repo = GitTestRepo::new("feature")?;
            test_repo.populate()?;
            let git_repo = Repo::from_path(&test_repo.dir)?;
            assert!(git_repo.get_main_or_master_branch().is_err());
            Ok(())
        }
    }

    mod get_origin_url {
        use super::*;

        #[test]
        fn returns_origin_url() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.add_remote("origin", "https://localhost:1000")?;
            let git_repo = Repo::from_path(&test_repo.dir)?;
            assert_eq!(git_repo.get_origin_url()?, "https://localhost:1000");
            Ok(())
        }
    }
    mod get_checked_out_branch_name {
        use super::*;

        #[test]
        fn returns_checked_out_branch_name() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let _ = test_repo.populate()?;
            // create feature branch
            test_repo.create_branch("example-feature")?;
            test_repo.checkout("example-feature")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert_eq!(
                git_repo.get_checked_out_branch_name()?,
                "example-feature".to_string()
            );
            Ok(())
        }
    }

    mod get_commits_ahead_behind {
        use super::*;
        mod returns_main {
            use super::*;

            #[test]
            fn when_on_same_commit_return_empty() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let oid = test_repo.populate()?;
                // create feature branch
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let (ahead, behind) =
                    git_repo.get_commits_ahead_behind(&oid_to_sha1(&oid), &oid_to_sha1(&oid))?;
                assert_eq!(ahead, vec![]);
                assert_eq!(behind, vec![]);
                Ok(())
            }

            #[test]
            fn when_2_commit_behind() -> Result<()> {
                let test_repo = GitTestRepo::default();
                test_repo.populate()?;
                // create feature branch
                test_repo.create_branch("feature")?;
                let feature_oid = test_repo.checkout("feature")?;
                // checkout main and add 2 commits
                test_repo.checkout("main")?;
                std::fs::write(test_repo.dir.join("t5.md"), "some content")?;
                let behind_1_oid = test_repo.stage_and_commit("add t5.md")?;
                std::fs::write(test_repo.dir.join("t6.md"), "some content")?;
                let behind_2_oid = test_repo.stage_and_commit("add t6.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let (ahead, behind) = git_repo.get_commits_ahead_behind(
                    &oid_to_sha1(&behind_2_oid),
                    &oid_to_sha1(&feature_oid),
                )?;
                assert_eq!(ahead, vec![]);
                assert_eq!(
                    behind,
                    vec![oid_to_sha1(&behind_2_oid), oid_to_sha1(&behind_1_oid),],
                );
                Ok(())
            }

            #[test]
            fn when_2_commit_ahead() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let main_oid = test_repo.populate()?;
                // create feature branch and add 2 commits
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
                std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
                let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let (ahead, behind) = git_repo.get_commits_ahead_behind(
                    &oid_to_sha1(&main_oid),
                    &oid_to_sha1(&ahead_2_oid),
                )?;
                assert_eq!(
                    ahead,
                    vec![oid_to_sha1(&ahead_2_oid), oid_to_sha1(&ahead_1_oid),],
                );
                assert_eq!(behind, vec![]);
                Ok(())
            }

            #[test]
            fn when_2_commit_ahead_and_2_commits_behind() -> Result<()> {
                let test_repo = GitTestRepo::default();
                test_repo.populate()?;
                // create feature branch and add 2 commits
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
                std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
                let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;
                // checkout main and add 2 commits
                test_repo.checkout("main")?;
                std::fs::write(test_repo.dir.join("t5.md"), "some content")?;
                let behind_1_oid = test_repo.stage_and_commit("add t5.md")?;
                std::fs::write(test_repo.dir.join("t6.md"), "some content")?;
                let behind_2_oid = test_repo.stage_and_commit("add t6.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let (ahead, behind) = git_repo.get_commits_ahead_behind(
                    &oid_to_sha1(&behind_2_oid),
                    &oid_to_sha1(&ahead_2_oid),
                )?;
                assert_eq!(
                    ahead,
                    vec![oid_to_sha1(&ahead_2_oid), oid_to_sha1(&ahead_1_oid)],
                );
                assert_eq!(
                    behind,
                    vec![oid_to_sha1(&behind_2_oid), oid_to_sha1(&behind_1_oid)],
                );
                Ok(())
            }
        }
    }

    mod create_branch_at_commit {
        use super::*;
        #[test]
        fn doesnt_error() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;
            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            let branch_name = "test-name-1";
            git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;

            Ok(())
        }

        #[test]
        fn branch_gets_created() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;
            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            let branch_name = "test-name-1";
            git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;

            assert!(test_repo.checkout(branch_name).is_ok());
            Ok(())
        }

        #[test]
        fn branch_created_with_correct_commit() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;
            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            let branch_name = "test-name-1";
            git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;

            assert_eq!(test_repo.checkout(branch_name)?, ahead_1_oid);
            Ok(())
        }

        mod when_branch_already_exists {
            use super::*;

            #[test]
            fn when_new_tip_specified_it_is_updated() -> Result<()> {
                let test_repo = GitTestRepo::default();
                test_repo.populate()?;
                // create feature branch and add 2 commits
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
                std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
                let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let branch_name = "test-name-1";
                git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;

                git_repo.create_branch_at_commit(branch_name, &ahead_2_oid.to_string())?;
                assert_eq!(test_repo.checkout(branch_name)?, ahead_2_oid);
                Ok(())
            }

            #[test]
            fn when_same_tip_is_specified_it_doesnt_error() -> Result<()> {
                let test_repo = GitTestRepo::default();
                test_repo.populate()?;
                // create feature branch and add 2 commits
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
                std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
                test_repo.stage_and_commit("add t4.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let branch_name = "test-name-1";
                git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;

                git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;
                assert_eq!(test_repo.checkout(branch_name)?, ahead_1_oid);
                Ok(())
            }

            #[test]
            fn when_branch_is_checkedout_new_tip_specified_it_is_updated() -> Result<()> {
                let test_repo = GitTestRepo::default();
                test_repo.populate()?;
                // create feature branch and add 2 commits
                test_repo.create_branch("feature")?;
                test_repo.checkout("feature")?;
                std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
                let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
                std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
                let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

                let git_repo = Repo::from_path(&test_repo.dir)?;

                let branch_name = "test-name-1";
                git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?;
                test_repo.checkout(branch_name)?;
                git_repo.create_branch_at_commit(branch_name, &ahead_2_oid.to_string())?;
                test_repo.checkout("main")?;

                assert_eq!(test_repo.checkout(branch_name)?, ahead_2_oid);
                Ok(())
            }
        }
    }

    mod create_commit_from_patch {

        use test_utils::TEST_KEY_1_SIGNER;

        use super::*;
        use crate::{git_events::generate_patch_event, repo_ref::RepoRef};

        async fn generate_patch_from_head_commit(test_repo: &GitTestRepo) -> Result<nostr::Event> {
            let original_oid = test_repo.git_repo.head()?.peel_to_commit()?.id();
            let git_repo = Repo::from_path(&test_repo.dir)?;
            generate_patch_event(
                &git_repo,
                &git_repo.get_root_commit()?,
                &oid_to_sha1(&original_oid),
                Some(nostr::EventId::all_zeros()),
                &TEST_KEY_1_SIGNER,
                &RepoRef::try_from((generate_repo_ref_event(), None)).unwrap(),
                None,
                None,
                None,
                &None,
                &[],
            )
            .await
        }
        fn test_patch_applies_to_repository(patch_event: nostr::Event) -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;
            let git_repo = Repo::from_path(&test_repo.dir)?;
            println!("{:?}", &patch_event);
            git_repo.create_commit_from_patch(&patch_event, None)?;
            let commit_id = tag_value(&patch_event, "commit")?;
            // does commit with id exist?
            assert!(git_repo.does_commit_exist(&commit_id)?);
            Ok(())
        }

        mod patch_created_as_commit_with_matching_id {
            use test_utils::git::joe_signature;

            use super::*;

            #[tokio::test]
            async fn simple_signature_author_committer_same_as_git_user_0_unixtime_no_pgp_signature()
            -> Result<()> {
                let source_repo = GitTestRepo::default();
                source_repo.populate()?;
                fs::write(source_repo.dir.join("x1.md"), "some content")?;
                source_repo.stage_and_commit("add x1.md")?;

                test_patch_applies_to_repository(
                    generate_patch_from_head_commit(&source_repo).await?,
                )
            }

            #[tokio::test]
            async fn signature_with_specific_author_time() -> Result<()> {
                let source_repo = GitTestRepo::default();
                source_repo.populate()?;
                fs::write(source_repo.dir.join("x1.md"), "some content")?;
                source_repo.stage_and_commit_custom_signature(
                    "add x1.md",
                    Some(&git2::Signature::new(
                        joe_signature().name().unwrap(),
                        joe_signature().email().unwrap(),
                        &git2::Time::new(5000, 0),
                    )?),
                    None,
                )?;

                test_patch_applies_to_repository(
                    generate_patch_from_head_commit(&source_repo).await?,
                )
            }

            #[tokio::test]
            async fn author_name_and_email_not_current_git_user() -> Result<()> {
                let source_repo = GitTestRepo::default();
                source_repo.populate()?;
                fs::write(source_repo.dir.join("x1.md"), "some content")?;
                source_repo.stage_and_commit_custom_signature(
                    "add x1.md",
                    Some(&git2::Signature::new(
                        "carole",
                        "carole@pm.me",
                        &git2::Time::new(0, 0),
                    )?),
                    None,
                )?;

                test_patch_applies_to_repository(
                    generate_patch_from_head_commit(&source_repo).await?,
                )
            }

            #[tokio::test]
            async fn comiiter_name_and_email_not_current_git_user_or_author() -> Result<()> {
                let source_repo = GitTestRepo::default();
                source_repo.populate()?;
                fs::write(source_repo.dir.join("x1.md"), "some content")?;
                source_repo.stage_and_commit_custom_signature(
                    "add x1.md",
                    Some(&git2::Signature::new(
                        "carole",
                        "carole@pm.me",
                        &git2::Time::new(0, 0),
                    )?),
                    Some(&git2::Signature::new(
                        "bob",
                        "bob@pm.me",
                        &git2::Time::new(0, 0),
                    )?),
                )?;

                test_patch_applies_to_repository(
                    generate_patch_from_head_commit(&source_repo).await?,
                )
            }

            // TODO: pgp signature

            #[tokio::test]
            async fn unique_author_and_commiter_details() -> Result<()> {
                let source_repo = GitTestRepo::default();
                source_repo.populate()?;
                fs::write(source_repo.dir.join("x1.md"), "some content")?;
                source_repo.stage_and_commit_custom_signature(
                    "add x1.md",
                    Some(&git2::Signature::new(
                        "carole",
                        "carole@pm.me",
                        &git2::Time::new(5000, 0),
                    )?),
                    Some(&git2::Signature::new(
                        "bob",
                        "bob@pm.me",
                        &git2::Time::new(1000, 0),
                    )?),
                )?;

                test_patch_applies_to_repository(
                    generate_patch_from_head_commit(&source_repo).await?,
                )
            }
        }
    }

    mod apply_patch_chain {
        use test_utils::TEST_KEY_1_SIGNER;

        use super::*;
        use crate::{git_events::generate_cover_letter_and_patch_events, repo_ref::RepoRef};

        static BRANCH_NAME: &str = "add-example-feature";
        // returns original_repo, cover_letter_event, patch_events
        async fn generate_test_repo_and_events()
        -> Result<(GitTestRepo, nostr::Event, Vec<nostr::Event>)> {
            let original_repo = GitTestRepo::default();
            let oid3 = original_repo.populate_with_test_branch()?;
            let oid2 = original_repo.git_repo.find_commit(oid3)?.parent_id(0)?;
            let oid1 = original_repo.git_repo.find_commit(oid2)?.parent_id(0)?;
            // TODO: generate cover_letter and patch events
            let git_repo = Repo::from_path(&original_repo.dir)?;

            let mut events = generate_cover_letter_and_patch_events(
                Some(("test".to_string(), "test".to_string())),
                &git_repo,
                &[oid_to_sha1(&oid1), oid_to_sha1(&oid2), oid_to_sha1(&oid3)],
                &TEST_KEY_1_SIGNER,
                &RepoRef::try_from((generate_repo_ref_event(), None)).unwrap(),
                &None,
                &[],
            )
            .await?;

            events.reverse();

            Ok((original_repo, events.pop().unwrap(), events))
        }

        mod when_branch_and_commits_dont_exist {
            use super::*;

            mod when_branch_root_is_tip_of_main {
                use super::*;

                #[tokio::test]
                async fn branch_gets_created_with_name_specified_in_proposal() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert!(
                        git_repo
                            .get_local_branch_names()?
                            .contains(&BRANCH_NAME.to_string())
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn branch_checked_out() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        git_repo.get_checked_out_branch_name()?,
                        BRANCH_NAME.to_string(),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn patches_get_created_as_commits() -> Result<()> {
                    let (original_repo, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        test_repo.git_repo.head()?.peel_to_commit()?.id(),
                        original_repo.git_repo.head()?.peel_to_commit()?.id(),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn branch_tip_is_most_recent_patch() -> Result<()> {
                    let (original_repo, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        git_repo.get_tip_of_branch(BRANCH_NAME)?,
                        oid_to_sha1(&original_repo.git_repo.head()?.peel_to_commit()?.id(),),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn previously_checked_out_branch_tip_does_not_change() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let existing_branch = test_repo.get_checked_out_branch_name()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    let previous_tip_of_existing_branch =
                        git_repo.get_tip_of_branch(existing_branch.as_str())?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        previous_tip_of_existing_branch,
                        git_repo.get_tip_of_branch(existing_branch.as_str())?,
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn returns_all_patches_applied() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 3);
                    Ok(())
                }
            }

            mod when_branch_root_is_tip_behind_main {
                use super::*;

                #[tokio::test]
                async fn branch_gets_created_with_name_specified_in_proposal() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    std::fs::write(test_repo.dir.join("m3.md"), "some content")?;
                    test_repo.stage_and_commit("add m3.md")?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert!(
                        git_repo
                            .get_local_branch_names()?
                            .contains(&BRANCH_NAME.to_string())
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn branch_checked_out() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    std::fs::write(test_repo.dir.join("m3.md"), "some content")?;
                    test_repo.stage_and_commit("add m3.md")?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        git_repo.get_checked_out_branch_name()?,
                        BRANCH_NAME.to_string(),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn branch_tip_is_most_recent_patch() -> Result<()> {
                    let (original_repo, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    std::fs::write(test_repo.dir.join("m3.md"), "some content")?;
                    test_repo.stage_and_commit("add m3.md")?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        git_repo.get_tip_of_branch(BRANCH_NAME)?,
                        oid_to_sha1(&original_repo.git_repo.head()?.peel_to_commit()?.id(),),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn previously_checked_out_branch_tip_does_not_change() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    std::fs::write(test_repo.dir.join("m3.md"), "some content")?;
                    test_repo.stage_and_commit("add m3.md")?;
                    let existing_branch = test_repo.get_checked_out_branch_name()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    let previous_tip_of_existing_branch =
                        git_repo.get_tip_of_branch(existing_branch.as_str())?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(
                        previous_tip_of_existing_branch,
                        git_repo.get_tip_of_branch(existing_branch.as_str())?,
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn returns_all_patches_applied() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 3);
                    Ok(())
                }
            }

            // TODO when_proposal_root_is_tip_ahead_of_main_and_doesnt_exist
        }

        mod when_branch_and_first_commits_exists {
            use super::*;

            mod when_branch_already_checked_out {
                use super::*;

                #[tokio::test]
                async fn branch_tip_is_most_recent_patch() -> Result<()> {
                    let (original_repo, _, mut patch_events) =
                        generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, vec![patch_events.pop().unwrap()])?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;

                    assert_eq!(
                        git_repo.get_tip_of_branch(BRANCH_NAME)?,
                        oid_to_sha1(&original_repo.git_repo.head()?.peel_to_commit()?.id(),),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn returns_all_patches_applied() -> Result<()> {
                    let (_, _, mut patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, vec![patch_events.pop().unwrap()])?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 2);
                    Ok(())
                }
            }
            mod when_branch_not_checked_out {
                use super::*;

                #[tokio::test]
                async fn branch_tip_is_most_recent_patch() -> Result<()> {
                    let (original_repo, _, mut patch_events) =
                        generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, vec![patch_events.pop().unwrap()])?;
                    git_repo.checkout("main")?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;

                    assert_eq!(
                        git_repo.get_tip_of_branch(BRANCH_NAME)?,
                        oid_to_sha1(&original_repo.git_repo.head()?.peel_to_commit()?.id(),),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn branch_checked_out() -> Result<()> {
                    let (_, _, mut patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, vec![patch_events.pop().unwrap()])?;
                    git_repo.checkout("main")?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;

                    assert_eq!(
                        git_repo.get_checked_out_branch_name()?,
                        BRANCH_NAME.to_string(),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn returns_all_patches_applied() -> Result<()> {
                    let (_, _, mut patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, vec![patch_events.pop().unwrap()])?;
                    git_repo.checkout("main")?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 2);
                    Ok(())
                }
            }
            // TODO when branch ahead (rebased or user commits)
        }
        mod when_branch_exists_and_is_up_to_date {
            use super::*;

            mod when_branch_already_checked_out {
                use super::*;

                #[tokio::test]
                async fn returns_all_patches_applied_0() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events.clone())?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 0);
                    Ok(())
                }
            }
            mod when_branch_not_checked_out {
                use super::*;

                #[tokio::test]
                async fn branch_checked_out() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events.clone())?;
                    git_repo.checkout("main")?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;

                    assert_eq!(
                        git_repo.get_checked_out_branch_name()?,
                        BRANCH_NAME.to_string(),
                    );
                    Ok(())
                }

                #[tokio::test]
                async fn returns_all_patches_applied_0() -> Result<()> {
                    let (_, _, patch_events) = generate_test_repo_and_events().await?;
                    let test_repo = GitTestRepo::default();
                    test_repo.populate()?;
                    let git_repo = Repo::from_path(&test_repo.dir)?;
                    git_repo.apply_patch_chain(BRANCH_NAME, patch_events.clone())?;
                    git_repo.checkout("main")?;
                    let res = git_repo.apply_patch_chain(BRANCH_NAME, patch_events)?;
                    assert_eq!(res.len(), 0);
                    Ok(())
                }
            }
        }
    }
    mod parse_starting_commits {
        use super::*;

        mod head_1_returns_latest_commit {
            use super::*;

            #[test]
            fn when_on_main_and_other_commits_are_more_recent_on_feature_branch() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let git_repo = Repo::from_path(&test_repo.dir)?;
                test_repo.populate_with_test_branch()?;
                test_repo.checkout("main")?;

                assert_eq!(
                    git_repo.parse_starting_commits("HEAD~1")?,
                    vec![str_to_sha1("431b84edc0d2fa118d63faa3c2db9c73d630a5ae")?],
                );
                Ok(())
            }

            #[test]
            fn when_checked_out_branch_ahead_of_main() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let git_repo = Repo::from_path(&test_repo.dir)?;
                test_repo.populate_with_test_branch()?;

                assert_eq!(
                    git_repo.parse_starting_commits("HEAD~1")?,
                    vec![str_to_sha1("82ff2bcc9aa94d1bd8faee723d4c8cc190d6061c")?],
                );
                Ok(())
            }
        }
        mod head_2_returns_latest_2_commits_youngest_first {
            use super::*;

            #[test]
            fn when_on_main_and_other_commits_are_more_recent_on_feature_branch() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let git_repo = Repo::from_path(&test_repo.dir)?;
                test_repo.populate_with_test_branch()?;
                test_repo.checkout("main")?;

                assert_eq!(
                    git_repo.parse_starting_commits("HEAD~2")?,
                    vec![
                        str_to_sha1("431b84edc0d2fa118d63faa3c2db9c73d630a5ae")?,
                        str_to_sha1("af474d8d271490e5c635aad337abdc050034b16a")?,
                    ],
                );
                Ok(())
            }
        }
        mod head_3_returns_latest_3_commits_youngest_first {
            use super::*;

            #[test]
            fn when_checked_out_branch_ahead_of_main() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let git_repo = Repo::from_path(&test_repo.dir)?;
                test_repo.populate_with_test_branch()?;

                assert_eq!(
                    git_repo.parse_starting_commits("HEAD~3")?,
                    vec![
                        str_to_sha1("82ff2bcc9aa94d1bd8faee723d4c8cc190d6061c")?,
                        str_to_sha1("a23e6b05aaeb7d1471b4a838b51f337d5644eeb0")?,
                        str_to_sha1("7ab82116068982671a8111f27dc10599172334b2")?,
                    ],
                );
                Ok(())
            }
        }
        mod range_of_3_commits_not_in_branch_history_returns_3_commits_youngest_first {
            use super::*;

            #[test]
            fn when_checked_out_branch_ahead_of_main() -> Result<()> {
                let test_repo = GitTestRepo::default();
                let git_repo = Repo::from_path(&test_repo.dir)?;
                test_repo.populate_with_test_branch()?;
                test_repo.checkout("main")?;

                assert_eq!(
                    git_repo.parse_starting_commits("af474d8..a23e6b0")?,
                    vec![
                        str_to_sha1("a23e6b05aaeb7d1471b4a838b51f337d5644eeb0")?,
                        str_to_sha1("7ab82116068982671a8111f27dc10599172334b2")?,
                        str_to_sha1("431b84edc0d2fa118d63faa3c2db9c73d630a5ae")?,
                    ],
                );
                Ok(())
            }
        }
    }
    mod ancestor_of {
        use super::*;

        #[test]
        fn deep_ancestor_returns_true() -> Result<()> {
            let test_repo = GitTestRepo::default();
            let from_main_in_feature_history = test_repo.populate()?;

            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;

            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(git_repo.ancestor_of(
                &oid_to_sha1(&ahead_2_oid),
                &oid_to_sha1(&from_main_in_feature_history)
            )?);
            Ok(())
        }

        #[test]
        fn commit_parent_returns_true() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;

            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(git_repo.ancestor_of(&oid_to_sha1(&ahead_2_oid), &oid_to_sha1(&ahead_1_oid))?);
            Ok(())
        }

        #[test]
        fn same_commit_returns_false() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;

            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(!git_repo.ancestor_of(&oid_to_sha1(&ahead_2_oid), &oid_to_sha1(&ahead_2_oid))?);
            Ok(())
        }

        #[test]
        fn commit_not_in_history_returns_false() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            // create feature branch and add 2 commits
            test_repo.create_branch("feature")?;

            // create commit not in feature history
            std::fs::write(test_repo.dir.join("notfeature.md"), "some content")?;
            let on_main_after_feature = test_repo.stage_and_commit("add notfeature.md")?;

            test_repo.checkout("feature")?;
            std::fs::write(test_repo.dir.join("t3.md"), "some content")?;
            test_repo.stage_and_commit("add t3.md")?;
            std::fs::write(test_repo.dir.join("t4.md"), "some content")?;
            let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?;

            let git_repo = Repo::from_path(&test_repo.dir)?;

            assert!(!git_repo.ancestor_of(
                &oid_to_sha1(&ahead_2_oid),
                &oid_to_sha1(&on_main_after_feature)
            )?);
            Ok(())
        }
    }

    mod worktree {
        use super::*;

        #[test]
        fn get_path_returns_worktree_working_dir() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-branch")?;
            let git_repo = Repo::from_path(&worktree_repo.dir)?;

            let path = git_repo.get_path()?;
            // get_path() should return the worktree's working directory, not
            // somewhere inside the main repo's .git/worktrees/
            assert_eq!(path.canonicalize()?, worktree_repo.dir.canonicalize()?,);
            Ok(())
        }

        #[test]
        fn get_path_returns_normal_repo_working_dir() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let git_repo = Repo::from_path(&test_repo.dir)?;
            let path = git_repo.get_path()?;
            assert_eq!(path.canonicalize()?, test_repo.dir.canonicalize()?,);
            Ok(())
        }

        #[test]
        fn from_path_works_with_worktree_dir() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-open")?;
            // Opening from the worktree's working directory should succeed
            let git_repo = Repo::from_path(&worktree_repo.dir)?;
            // And get_path() should return the worktree dir
            assert_eq!(
                git_repo.get_path()?.canonicalize()?,
                worktree_repo.dir.canonicalize()?,
            );
            Ok(())
        }

        #[test]
        fn worktree_can_read_branches() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-branches")?;
            let git_repo = Repo::from_path(&worktree_repo.dir)?;

            let branches = git_repo.get_local_branch_names()?;
            assert!(branches.contains(&"main".to_string()));
            assert!(branches.contains(&"wt-branches".to_string()));
            Ok(())
        }

        #[test]
        fn worktree_can_read_git_config() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-config")?;
            let git_repo = Repo::from_path(&worktree_repo.dir)?;

            // nostr.repo is set by GitTestRepo::default() on the main repo
            // and should be readable from the worktree since config is shared
            let nostr_repo = git_repo.get_git_config_item("nostr.repo", None)?;
            assert!(nostr_repo.is_some());
            Ok(())
        }

        #[test]
        fn worktree_get_head_commit_works() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-head")?;
            let git_repo = Repo::from_path(&worktree_repo.dir)?;

            // Should not error - worktree has its own HEAD
            let _head = git_repo.get_head_commit()?;
            Ok(())
        }

        #[test]
        fn worktree_files_accessible_from_get_path() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-files")?;
            let git_repo = Repo::from_path(&worktree_repo.dir)?;

            // Create a file in the worktree
            let test_file = worktree_repo.dir.join("worktree-test.txt");
            fs::write(&test_file, "hello from worktree")?;

            // get_path() should point to the worktree dir where the file lives
            let path = git_repo.get_path()?;
            assert!(path.join("worktree-test.txt").exists());
            Ok(())
        }

        #[test]
        fn worktree_opened_via_git_dir_env_works() -> Result<()> {
            let test_repo = GitTestRepo::default();
            test_repo.populate()?;

            let worktree_repo = test_repo.create_worktree("wt-gitdir")?;

            // In a worktree, GIT_DIR points to the worktree-specific git dir
            // (e.g., .git/worktrees/<name>). Simulate what git does when
            // calling a remote helper.
            let git_dir = worktree_repo.git_repo.path().to_path_buf();
            let git_repo = Repo::from_path(&git_dir)?;

            // get_path() should still return the worktree working directory
            assert_eq!(
                git_repo.get_path()?.canonicalize()?,
                worktree_repo.dir.canonicalize()?,
            );
            Ok(())
        }
    }
}