Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Proxy.cs « Core « LibGit2Sharp - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e78c56e040be85840a794823e32b21e346b7e683 (plain)
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using LibGit2Sharp.Core.Compat;
using LibGit2Sharp.Core.Handles;

// ReSharper disable InconsistentNaming
namespace LibGit2Sharp.Core
{
    internal class Proxy
    {
        #region giterr_

        public static void giterr_set_str(GitErrorCategory error_class, Exception exception)
        {
            if (exception is OutOfMemoryException)
            {
                NativeMethods.giterr_set_oom();
            }
            else
            {
                NativeMethods.giterr_set_str(error_class, exception.Message);
            }
        }

        public static void giterr_set_str(GitErrorCategory error_class, String errorString)
        {
            NativeMethods.giterr_set_str(error_class, errorString);
        }

        #endregion

        #region git_blame_

        public static BlameSafeHandle git_blame_file(
            RepositorySafeHandle repo,
            FilePath path,
            GitBlameOptions options)
        {
            using (ThreadAffinity())
            {
                BlameSafeHandle handle;
                int res = NativeMethods.git_blame_file(out handle, repo, path, options);
                Ensure.ZeroResult(res);
                return handle;
            }
        }

        public static GitBlameHunk git_blame_get_hunk_byindex(BlameSafeHandle blame, uint idx)
        {
            return NativeMethods.git_blame_get_hunk_byindex(blame, idx).MarshalAs<GitBlameHunk>(false);
        }

        public static void git_blame_free(IntPtr blame)
        {
            NativeMethods.git_blame_free(blame);
        }

        #endregion

        #region git_blob_

        public static ObjectId git_blob_create_fromchunks(RepositorySafeHandle repo, FilePath hintpath, NativeMethods.source_callback fileCallback)
        {
            using (ThreadAffinity())
            {
                var oid = new GitOid();
                int res = NativeMethods.git_blob_create_fromchunks(ref oid, repo, hintpath, fileCallback, IntPtr.Zero);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static ObjectId git_blob_create_fromdisk(RepositorySafeHandle repo, FilePath path)
        {
            using (ThreadAffinity())
            {
                var oid = new GitOid();
                int res = NativeMethods.git_blob_create_fromdisk(ref oid, repo, path);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static ObjectId git_blob_create_fromfile(RepositorySafeHandle repo, FilePath path)
        {
            using (ThreadAffinity())
            {
                var oid = new GitOid();
                int res = NativeMethods.git_blob_create_fromworkdir(ref oid, repo, path);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static UnmanagedMemoryStream git_blob_filtered_content_stream(RepositorySafeHandle repo, ObjectId id, FilePath path, bool check_for_binary_data)
        {
            var buf = new GitBuf();
            var handle = new ObjectSafeWrapper(id, repo).ObjectPtr;

            return new RawContentStream(handle, h =>
            {
                Ensure.ZeroResult(NativeMethods.git_blob_filtered_content(buf, h, path, check_for_binary_data));
                return buf.ptr;
            },
            h => (long)buf.size,
            new[] { buf });
        }

        public static byte[] git_blob_rawcontent(RepositorySafeHandle repo, ObjectId id, int size)
        {
            using (var obj = new ObjectSafeWrapper(id, repo))
            {
                var arr = new byte[size];
                Marshal.Copy(NativeMethods.git_blob_rawcontent(obj.ObjectPtr), arr, 0, size);
                return arr;
            }
        }

        public static UnmanagedMemoryStream git_blob_rawcontent_stream(RepositorySafeHandle repo, ObjectId id, Int64 size)
        {
            var handle = new ObjectSafeWrapper(id, repo).ObjectPtr;
            return new RawContentStream(handle, NativeMethods.git_blob_rawcontent, h => size);
        }

        public static Int64 git_blob_rawsize(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_blob_rawsize(obj);
        }

        public static bool git_blob_is_binary(GitObjectSafeHandle obj)
        {
            int res = NativeMethods.git_blob_is_binary(obj);
            Ensure.BooleanResult(res);

            return (res == 1);
        }

        #endregion

        #region git_branch_

        public static ReferenceSafeHandle git_branch_create(RepositorySafeHandle repo, string branch_name, ObjectId targetId, bool force)
        {
            using (ThreadAffinity())
            using (var osw = new ObjectSafeWrapper(targetId, repo))
            {
                ReferenceSafeHandle reference;
                int res = NativeMethods.git_branch_create(out reference, repo, branch_name, osw.ObjectPtr, force);
                Ensure.ZeroResult(res);
                return reference;
            }
        }

        public static void git_branch_delete(ReferenceSafeHandle reference)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_branch_delete(reference);
                reference.SetHandleAsInvalid();
                Ensure.ZeroResult(res);
            }
        }

        public static IEnumerable<Branch> git_branch_iterator(Repository repo, GitBranchType branchType)
        {
            return git_iterator(
                (out BranchIteratorSafeHandle iter_out) =>
                NativeMethods.git_branch_iterator_new(out iter_out, repo.Handle, branchType),
                (BranchIteratorSafeHandle iter, out ReferenceSafeHandle ref_out, out int res) =>
                    {
                        GitBranchType type_out;
                        res = NativeMethods.git_branch_next(out ref_out, out type_out, iter);
                        return new { BranchType = type_out };
                    },
                (handle, payload) =>
                    {
                        var reference = Reference.BuildFromPtr<Reference>(handle, repo);
                        return new Branch(repo, reference, reference.CanonicalName);
                    }
                );
        }

        public static void git_branch_iterator_free(IntPtr iter)
        {
            NativeMethods.git_branch_iterator_free(iter);
        }

        public static ReferenceSafeHandle git_branch_move(ReferenceSafeHandle reference, string new_branch_name, bool force)
        {
            using (ThreadAffinity())
            {
                ReferenceSafeHandle ref_out;
                int res = NativeMethods.git_branch_move(out ref_out, reference, new_branch_name, force);
                Ensure.ZeroResult(res);
                return ref_out;
            }
        }

        public static string git_branch_remote_name(RepositorySafeHandle repo, string canonical_branch_name)
        {
            using (ThreadAffinity())
            {
                int bufSize = NativeMethods.git_branch_remote_name(null, UIntPtr.Zero, repo, canonical_branch_name);
                Ensure.Int32Result(bufSize);

                var buffer = new byte[bufSize];

                int res = NativeMethods.git_branch_remote_name(buffer, (UIntPtr)buffer.Length, repo, canonical_branch_name);
                Ensure.Int32Result(res);

                return LaxUtf8Marshaler.FromBuffer(buffer) ?? string.Empty;
            }
        }

        public static string git_branch_upstream_name(RepositorySafeHandle handle, string canonicalReferenceName)
        {
            using (ThreadAffinity())
            {
                int bufSize = NativeMethods.git_branch_upstream_name(
                    null, UIntPtr.Zero, handle, canonicalReferenceName);

                if (bufSize == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.Int32Result(bufSize);

                var buffer = new byte[bufSize];

                int res = NativeMethods.git_branch_upstream_name(
                    buffer, (UIntPtr)buffer.Length, handle, canonicalReferenceName);
                Ensure.Int32Result(res);

                return LaxUtf8Marshaler.FromBuffer(buffer);
            }
        }

        #endregion

        #region git_buf_

        public static void git_buf_free(GitBuf buf)
        {
            NativeMethods.git_buf_free(buf);
        }

        #endregion

        #region git_checkout_

        public static void git_checkout_tree(
            RepositorySafeHandle repo,
            ObjectId treeId,
            ref GitCheckoutOpts opts)
        {
            using (ThreadAffinity())
            using (var osw = new ObjectSafeWrapper(treeId, repo))
            {
                int res = NativeMethods.git_checkout_tree(repo, osw.ObjectPtr, ref opts);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_checkout_index(RepositorySafeHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_checkout_index(repo, treeish, ref opts);
                Ensure.ZeroResult(res);
            }
        }

        #endregion

        #region git_clone_

        public static RepositorySafeHandle git_clone(
            string url,
            string workdir,
            GitCloneOptions opts)
        {
            using (ThreadAffinity())
            {
                RepositorySafeHandle repo;
                int res = NativeMethods.git_clone(out repo, url, workdir, opts);
                Ensure.ZeroResult(res);
                return repo;
            }
        }

        #endregion

        #region git_commit_

        public static Signature git_commit_author(GitObjectSafeHandle obj)
        {
            return new Signature(NativeMethods.git_commit_author(obj));
        }

        public static Signature git_commit_committer(GitObjectSafeHandle obj)
        {
            return new Signature(NativeMethods.git_commit_committer(obj));
        }

        public static ObjectId git_commit_create(
            RepositorySafeHandle repo,
            string referenceName,
            Signature author,
            Signature committer,
            string message,
            Tree tree,
            GitOid[] parentIds)
        {
            using (ThreadAffinity())
            using (SignatureSafeHandle authorHandle = author.BuildHandle())
            using (SignatureSafeHandle committerHandle = committer.BuildHandle())
            using (var parentPtrs = new ArrayMarshaler<GitOid>(parentIds))
            {
                GitOid commitOid;

                var treeOid = tree.Id.Oid;

                int res = NativeMethods.git_commit_create_from_oids(
                    out commitOid, repo, referenceName, authorHandle,
                    committerHandle, null, message,
                    ref treeOid, parentPtrs.Count, parentPtrs.ToArray());

                Ensure.ZeroResult(res);

                return commitOid;
            }
        }

        public static string git_commit_message(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_commit_message(obj);
        }

        public static string git_commit_summary(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_commit_summary(obj);
        }

        public static string git_commit_message_encoding(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_commit_message_encoding(obj);
        }

        public static ObjectId git_commit_parent_oid(GitObjectSafeHandle obj, uint i)
        {
            return NativeMethods.git_commit_parent_id(obj, i).MarshalAsObjectId();
        }

        public static int git_commit_parentcount(RepositorySafeHandle repo, ObjectId id)
        {
            using (var obj = new ObjectSafeWrapper(id, repo))
            {
                return git_commit_parentcount(obj);
            }
        }

        public static int git_commit_parentcount(ObjectSafeWrapper obj)
        {
            return (int)NativeMethods.git_commit_parentcount(obj.ObjectPtr);
        }

        public static ObjectId git_commit_tree_oid(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_commit_tree_id(obj).MarshalAsObjectId();
        }

        #endregion

        #region git_config_

        public static void git_config_add_file_ondisk(ConfigurationSafeHandle config, FilePath path, ConfigurationLevel level)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_add_file_ondisk(config, path, (uint)level, true);
                Ensure.ZeroResult(res);
            }
        }

        public static bool git_config_delete(ConfigurationSafeHandle config, string name)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_delete_entry(config, name);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return false;
                }

                Ensure.ZeroResult(res);
                return true;
            }
        }

        public static FilePath git_config_find_global()
        {
            return ConvertPath(NativeMethods.git_config_find_global);
        }

        public static FilePath git_config_find_system()
        {
            return ConvertPath(NativeMethods.git_config_find_system);
        }

        public static FilePath git_config_find_xdg()
        {
            return ConvertPath(NativeMethods.git_config_find_xdg);
        }

        public static void git_config_free(IntPtr config)
        {
            NativeMethods.git_config_free(config);
        }

        public static ConfigurationEntry<T> git_config_get_entry<T>(ConfigurationSafeHandle config, string key)
        {
            GitConfigEntryHandle handle;

            if (!configurationParser.ContainsKey(typeof(T)))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName));
            }

            using (ThreadAffinity())
            {
                var res = NativeMethods.git_config_get_entry(out handle, config, key);
                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);
            }

            GitConfigEntry entry = handle.MarshalAsGitConfigEntry();

            return new ConfigurationEntry<T>(LaxUtf8Marshaler.FromNative(entry.namePtr),
                (T)configurationParser[typeof(T)](LaxUtf8Marshaler.FromNative(entry.valuePtr)),
                (ConfigurationLevel)entry.level);
        }

        public static ConfigurationSafeHandle git_config_new()
        {
            using (ThreadAffinity())
            {
                ConfigurationSafeHandle handle;
                int res = NativeMethods.git_config_new(out handle);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static ConfigurationSafeHandle git_config_open_level(ConfigurationSafeHandle parent, ConfigurationLevel level)
        {
            using (ThreadAffinity())
            {
                ConfigurationSafeHandle handle;
                int res = NativeMethods.git_config_open_level(out handle, parent, (uint)level);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static bool git_config_parse_bool(string value)
        {
            using (ThreadAffinity())
            {
                bool outVal;
                var res = NativeMethods.git_config_parse_bool(out outVal, value);

                Ensure.ZeroResult(res);
                return outVal;
            }
        }

        public static int git_config_parse_int32(string value)
        {
            using (ThreadAffinity())
            {
                int outVal;
                var res = NativeMethods.git_config_parse_int32(out outVal, value);

                Ensure.ZeroResult(res);
                return outVal;
            }
        }

        public static long git_config_parse_int64(string value)
        {
            using (ThreadAffinity())
            {
                long outVal;
                var res = NativeMethods.git_config_parse_int64(out outVal, value);

                Ensure.ZeroResult(res);
                return outVal;
            }
        }

        public static void git_config_set_bool(ConfigurationSafeHandle config, string name, bool value)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_set_bool(config, name, value);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_config_set_int32(ConfigurationSafeHandle config, string name, int value)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_set_int32(config, name, value);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_config_set_int64(ConfigurationSafeHandle config, string name, long value)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_set_int64(config, name, value);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_config_set_string(ConfigurationSafeHandle config, string name, string value)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_config_set_string(config, name, value);
                Ensure.ZeroResult(res);
            }
        }

        public static ICollection<TResult> git_config_foreach<TResult>(
            ConfigurationSafeHandle config,
            Func<IntPtr, TResult> resultSelector)
        {
            return git_foreach(resultSelector, c => NativeMethods.git_config_foreach(config, (e, p) => c(e, p), IntPtr.Zero));
        }

        public static IEnumerable<ConfigurationEntry<string>> git_config_iterator_glob(
            ConfigurationSafeHandle config,
            string regexp,
            Func<IntPtr, ConfigurationEntry<string>> resultSelector)
        {
            return git_iterator(
                (out ConfigurationIteratorSafeHandle iter) =>
                NativeMethods.git_config_iterator_glob_new(out iter, config, regexp),
                (ConfigurationIteratorSafeHandle iter, out SafeHandleBase handle, out int res) =>
                    {
                        handle = null;

                        IntPtr entry;
                        res = NativeMethods.git_config_next(out entry, iter);
                        return new { EntryPtr = entry };
                    },
                (handle, payload) => resultSelector(payload.EntryPtr)
                );
        }

        public static void git_config_iterator_free(IntPtr iter)
        {
            NativeMethods.git_config_iterator_free(iter);
        }

        #endregion

        #region git_diff_

        public static void git_diff_blobs(
            RepositorySafeHandle repo,
            ObjectId oldBlob,
            ObjectId newBlob,
            GitDiffOptions options,
            NativeMethods.git_diff_file_cb fileCallback,
            NativeMethods.git_diff_hunk_cb hunkCallback,
            NativeMethods.git_diff_line_cb lineCallback)
        {
            using (ThreadAffinity())
            using (var osw1 = new ObjectSafeWrapper(oldBlob, repo, true))
            using (var osw2 = new ObjectSafeWrapper(newBlob, repo, true))
            {
                int res = NativeMethods.git_diff_blobs(
                    osw1.ObjectPtr, null, osw2.ObjectPtr, null,
                    options, fileCallback, hunkCallback, lineCallback, IntPtr.Zero);

                Ensure.ZeroResult(res);
            }
        }

        public static void git_diff_foreach(
            DiffSafeHandle diff,
            NativeMethods.git_diff_file_cb fileCallback,
            NativeMethods.git_diff_hunk_cb hunkCallback,
            NativeMethods.git_diff_line_cb lineCallback)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_diff_foreach(diff, fileCallback, hunkCallback, lineCallback, IntPtr.Zero);
                Ensure.ZeroResult(res);
            }
        }

        public static DiffSafeHandle git_diff_tree_to_index(
            RepositorySafeHandle repo,
            IndexSafeHandle index,
            ObjectId oldTree,
            GitDiffOptions options)
        {
            using (ThreadAffinity())
            using (var osw = new ObjectSafeWrapper(oldTree, repo, true))
            {
                DiffSafeHandle diff;
                int res = NativeMethods.git_diff_tree_to_index(out diff, repo, osw.ObjectPtr, index, options);
                Ensure.ZeroResult(res);

                return diff;
            }
        }

        public static void git_diff_free(IntPtr diff)
        {
            NativeMethods.git_diff_free(diff);
        }

        public static void git_diff_merge(DiffSafeHandle onto, DiffSafeHandle from)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_diff_merge(onto, from);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_diff_print(DiffSafeHandle diff, NativeMethods.git_diff_line_cb printCallback)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_diff_print(diff, GitDiffFormat.GIT_DIFF_FORMAT_PATCH,
                    printCallback, IntPtr.Zero);
                Ensure.ZeroResult(res);
            }
        }

        public static DiffSafeHandle git_diff_tree_to_tree(
            RepositorySafeHandle repo,
            ObjectId oldTree,
            ObjectId newTree,
            GitDiffOptions options)
        {
            using (ThreadAffinity())
            using (var osw1 = new ObjectSafeWrapper(oldTree, repo, true))
            using (var osw2 = new ObjectSafeWrapper(newTree, repo, true))
            {
                DiffSafeHandle diff;
                int res = NativeMethods.git_diff_tree_to_tree(out diff, repo, osw1.ObjectPtr, osw2.ObjectPtr, options);
                Ensure.ZeroResult(res);

                return diff;
            }
        }

        public static DiffSafeHandle git_diff_index_to_workdir(
            RepositorySafeHandle repo,
            IndexSafeHandle index,
            GitDiffOptions options)
        {
            using (ThreadAffinity())
            {
                DiffSafeHandle diff;
                int res = NativeMethods.git_diff_index_to_workdir(out diff, repo, index, options);
                Ensure.ZeroResult(res);

                return diff;
            }
        }

        public static DiffSafeHandle git_diff_tree_to_workdir(
           RepositorySafeHandle repo,
           ObjectId oldTree,
           GitDiffOptions options)
        {
            using (ThreadAffinity())
            using (var osw = new ObjectSafeWrapper(oldTree, repo, true))
            {
                DiffSafeHandle diff;
                int res = NativeMethods.git_diff_tree_to_workdir(out diff, repo, osw.ObjectPtr, options);
                Ensure.ZeroResult(res);

                return diff;
            }
        }

        public static void git_diff_find_similar(DiffSafeHandle diff, GitDiffFindOptions options)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_diff_find_similar(diff, options);
                Ensure.ZeroResult(res);
            }
        }

        public static int git_diff_num_deltas(DiffSafeHandle diff)
        {
            return (int)NativeMethods.git_diff_num_deltas(diff);
        }

        public static GitDiffDelta git_diff_get_delta(DiffSafeHandle diff, int idx)
        {
            return NativeMethods.git_diff_get_delta(diff, (UIntPtr) idx).MarshalAs<GitDiffDelta>(false);
        }

        #endregion

        #region git_graph_

        public static Tuple<int?, int?> git_graph_ahead_behind(RepositorySafeHandle repo, Commit first, Commit second)
        {
            if (first == null || second == null)
            {
                return new Tuple<int?, int?>(null, null);
            }

            GitOid oid1 = first.Id.Oid;
            GitOid oid2 = second.Id.Oid;

            using (ThreadAffinity())
            {
                UIntPtr ahead;
                UIntPtr behind;

                int res = NativeMethods.git_graph_ahead_behind(out ahead, out behind, repo, ref oid1, ref oid2);

                Ensure.ZeroResult(res);

                return new Tuple<int?, int?>((int)ahead, (int)behind);
            }
        }

        #endregion

        #region git_ignore_

        public static void git_ignore_add_rule(RepositorySafeHandle repo, string rules)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_ignore_add_rule(repo, rules);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_ignore_clear_internal_rules(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_ignore_clear_internal_rules(repo);
                Ensure.ZeroResult(res);
            }
        }

        public static bool git_ignore_path_is_ignored(RepositorySafeHandle repo, string path)
        {
            using (ThreadAffinity())
            {
                int ignored;
                int res = NativeMethods.git_ignore_path_is_ignored(out ignored, repo, path);
                Ensure.ZeroResult(res);

                return (ignored != 0);
            }
        }

        #endregion

        #region git_index_

        public static void git_index_add(IndexSafeHandle index, GitIndexEntry entry)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_index_add(index, entry);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_index_add_bypath(IndexSafeHandle index, FilePath path)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_index_add_bypath(index, path);
                Ensure.ZeroResult(res);
            }
        }

        public static Conflict git_index_conflict_get(
            IndexSafeHandle index,
            Repository repo,
            FilePath path)
        {
            IndexEntrySafeHandle ancestor, ours, theirs;

            int res = NativeMethods.git_index_conflict_get(
                out ancestor, out ours, out theirs, index, path);

            if (res == (int)GitErrorCode.NotFound)
            {
                return null;
            }

            Ensure.ZeroResult(res);

            return new Conflict(
                IndexEntry.BuildFromPtr(ancestor),
                IndexEntry.BuildFromPtr(ours),
                IndexEntry.BuildFromPtr(theirs));
        }

        public static int git_index_entrycount(IndexSafeHandle index)
        {
            UIntPtr count = NativeMethods.git_index_entrycount(index);
            if ((long)count > int.MaxValue)
            {
                throw new LibGit2SharpException("Index entry count exceeds size of int");
            }
            return (int)count;
        }

        public static StageLevel git_index_entry_stage(IndexEntrySafeHandle index)
        {
            return (StageLevel)NativeMethods.git_index_entry_stage(index);
        }

        public static void git_index_free(IntPtr index)
        {
            NativeMethods.git_index_free(index);
        }

        public static IndexEntrySafeHandle git_index_get_byindex(IndexSafeHandle index, UIntPtr n)
        {
            return NativeMethods.git_index_get_byindex(index, n);
        }

        public static IndexEntrySafeHandle git_index_get_bypath(IndexSafeHandle index, FilePath path, int stage)
        {
            IndexEntrySafeHandle handle = NativeMethods.git_index_get_bypath(index, path, stage);

            return handle.IsZero ? null : handle;
        }

        public static bool git_index_has_conflicts(IndexSafeHandle index)
        {
            int res = NativeMethods.git_index_has_conflicts(index);
            Ensure.BooleanResult(res);

            return res != 0;
        }

        public static IndexSafeHandle git_index_open(FilePath indexpath)
        {
            using (ThreadAffinity())
            {
                IndexSafeHandle handle;
                int res = NativeMethods.git_index_open(out handle, indexpath);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static void git_index_read(IndexSafeHandle index)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_index_read(index, false);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_index_remove_bypath(IndexSafeHandle index, FilePath path)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_index_remove_bypath(index, path);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_index_write(IndexSafeHandle index)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_index_write(index);
                Ensure.ZeroResult(res);
            }
        }

        public static ObjectId git_tree_create_fromindex(Index index)
        {
            using (ThreadAffinity())
            {
                GitOid treeOid;
                int res = NativeMethods.git_index_write_tree(out treeOid, index.Handle);
                Ensure.ZeroResult(res);

                return treeOid;
            }
        }

        #endregion

        #region git_merge_

        public static ObjectId git_merge_base(RepositorySafeHandle repo, Commit first, Commit second)
        {
            using (ThreadAffinity())
            using (var osw1 = new ObjectSafeWrapper(first.Id, repo))
            using (var osw2 = new ObjectSafeWrapper(second.Id, repo))
            {
                GitOid ret;
                int res = NativeMethods.git_merge_base(out ret, repo, osw1.ObjectPtr, osw2.ObjectPtr);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return ret;
            }
        }

        public static GitMergeHeadHandle git_merge_head_from_oid(RepositorySafeHandle repo, GitOid oid)
        {
            using (ThreadAffinity())
            {
                GitMergeHeadHandle their_head;

                int res = NativeMethods.git_merge_head_from_oid(out their_head, repo, ref oid);

                Ensure.ZeroResult(res);

                return their_head;
            }
        }

        public static GitMergeResultHandle git_merge(RepositorySafeHandle repo, GitMergeHeadHandle[] heads, GitMergeOpts options)
        {
            using (ThreadAffinity())
            {
                GitMergeResultHandle ret;

                IntPtr[] their_heads = new IntPtr[heads.Length];
                for (int i = 0; i < heads.Length; i++)
                {
                    their_heads[i] = heads[i].DangerousGetHandle();
                }

                int res = NativeMethods.git_merge(
                    out ret,
                    repo,
                    their_heads,
                    (UIntPtr)their_heads.Length,
                    ref options);

                Ensure.ZeroResult(res);

                return ret;
            }
        }

        public static bool git_merge_result_is_uptodate(GitMergeResultHandle handle)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_merge_result_is_uptodate(handle);
                Ensure.BooleanResult(res);

                return (res == 1);
            }
        }

        public static bool git_merge_result_is_fastforward(GitMergeResultHandle handle)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_merge_result_is_fastforward(handle);
                Ensure.BooleanResult(res);

                return (res == 1);
            }
        }

        public static GitOid git_merge_result_fastforward_oid(GitMergeResultHandle handle)
        {
            using (ThreadAffinity())
            {
                GitOid oid;
                int res = NativeMethods.git_merge_result_fastforward_oid(out oid, handle);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static void git_merge_result_free(IntPtr handle)
        {
            NativeMethods.git_merge_result_free(handle);
        }

        public static void git_merge_head_free(IntPtr handle)
        {
            NativeMethods.git_merge_head_free(handle);
        }

        #endregion

        #region git_message_

        public static string git_message_prettify(string message)
        {
            using (ThreadAffinity())
            {
                int bufSize = NativeMethods.git_message_prettify(null, UIntPtr.Zero, message, false);
                Ensure.Int32Result(bufSize);

                var buffer = new byte[bufSize];

                int res = NativeMethods.git_message_prettify(buffer, (UIntPtr)buffer.Length, message, false);
                Ensure.Int32Result(res);

                return LaxUtf8Marshaler.FromBuffer(buffer) ?? string.Empty;
            }
        }

        #endregion

        #region git_note_

        public static ObjectId git_note_create(
            RepositorySafeHandle repo,
            Signature author,
            Signature committer,
            string notes_ref,
            ObjectId targetId,
            string note,
            bool force)
        {
            using (ThreadAffinity())
            using (SignatureSafeHandle authorHandle = author.BuildHandle())
            using (SignatureSafeHandle committerHandle = committer.BuildHandle())
            {
                GitOid noteOid;
                GitOid oid = targetId.Oid;

                int res = NativeMethods.git_note_create(out noteOid, repo, authorHandle, committerHandle, notes_ref, ref oid, note, force ? 1 : 0);
                Ensure.ZeroResult(res);

                return noteOid;
            }
        }

        public static string git_note_default_ref(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                string notes_ref;
                int res = NativeMethods.git_note_default_ref(out notes_ref, repo);
                Ensure.ZeroResult(res);

                return notes_ref;
            }
        }

        public static ICollection<TResult> git_note_foreach<TResult>(RepositorySafeHandle repo, string notes_ref, Func<GitOid, GitOid, TResult> resultSelector)
        {
            return git_foreach(resultSelector, c => NativeMethods.git_note_foreach(repo, notes_ref,
                (ref GitOid x, ref GitOid y, IntPtr p) => c(x, y, p), IntPtr.Zero));
        }

        public static void git_note_free(IntPtr note)
        {
            NativeMethods.git_note_free(note);
        }

        public static string git_note_message(NoteSafeHandle note)
        {
            return NativeMethods.git_note_message(note);
        }

        public static ObjectId git_note_oid(NoteSafeHandle note)
        {
            return NativeMethods.git_note_oid(note).MarshalAsObjectId();
        }

        public static NoteSafeHandle git_note_read(RepositorySafeHandle repo, string notes_ref, ObjectId id)
        {
            using (ThreadAffinity())
            {
                GitOid oid = id.Oid;
                NoteSafeHandle note;

                int res = NativeMethods.git_note_read(out note, repo, notes_ref, ref oid);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return note;
            }
        }

        public static void git_note_remove(RepositorySafeHandle repo, string notes_ref, Signature author, Signature committer, ObjectId targetId)
        {
            using (ThreadAffinity())
            using (SignatureSafeHandle authorHandle = author.BuildHandle())
            using (SignatureSafeHandle committerHandle = committer.BuildHandle())
            {
                GitOid oid = targetId.Oid;

                int res = NativeMethods.git_note_remove(repo, notes_ref, authorHandle, committerHandle, ref oid);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return;
                }

                Ensure.ZeroResult(res);
            }
        }

        #endregion

        #region git_object_

        public static ObjectId git_object_id(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_object_id(obj).MarshalAsObjectId();
        }

        public static void git_object_free(IntPtr obj)
        {
            NativeMethods.git_object_free(obj);
        }

        public static GitObjectSafeHandle git_object_lookup(RepositorySafeHandle repo, ObjectId id, GitObjectType type)
        {
            using (ThreadAffinity())
            {
                GitObjectSafeHandle handle;
                GitOid oid = id.Oid;

                int res = NativeMethods.git_object_lookup(out handle, repo, ref oid, type);
                switch (res)
                {
                    case (int)GitErrorCode.NotFound:
                        return null;

                    default:
                        Ensure.ZeroResult(res);
                        break;
                }

                return handle;
            }
        }

        public static GitObjectSafeHandle git_object_peel(RepositorySafeHandle repo, ObjectId id, GitObjectType type, bool throwsIfCanNotPeel)
        {
            using (ThreadAffinity())
            {
                GitObjectSafeHandle peeled;
                int res;

                using (var obj = new ObjectSafeWrapper(id, repo))
                {
                    res = NativeMethods.git_object_peel(out peeled, obj.ObjectPtr, type);
                }

                if (!throwsIfCanNotPeel &&
                    (res == (int)GitErrorCode.NotFound || res == (int)GitErrorCode.Ambiguous))
                {
                    return null;
                }

                Ensure.ZeroResult(res);
                return peeled;
            }
        }

        public static GitObjectType git_object_type(GitObjectSafeHandle obj)
        {
            return NativeMethods.git_object_type(obj);
        }

        #endregion

        #region git_odb_

        public static void git_odb_add_backend(ObjectDatabaseSafeHandle odb, IntPtr backend, int priority)
        {
            Ensure.ZeroResult(NativeMethods.git_odb_add_backend(odb, backend, priority));
        }

        public static IntPtr git_odb_backend_malloc(IntPtr backend, UIntPtr len)
        {
            IntPtr toReturn = NativeMethods.git_odb_backend_malloc(backend, len);

            if (IntPtr.Zero == toReturn)
            {
                throw new LibGit2SharpException(String.Format(CultureInfo.InvariantCulture,
                                                              "Unable to allocate {0} bytes; out of memory",
                                                              len),
                                                GitErrorCode.Error, GitErrorCategory.NoMemory);
            }

            return toReturn;
        }

        public static bool git_odb_exists(ObjectDatabaseSafeHandle odb, ObjectId id)
        {
            GitOid oid = id.Oid;

            int res = NativeMethods.git_odb_exists(odb, ref oid);
            Ensure.BooleanResult(res);

            return (res == 1);
        }

        public static ICollection<TResult> git_odb_foreach<TResult>(
            ObjectDatabaseSafeHandle odb,
            Func<IntPtr, TResult> resultSelector)
        {
            return git_foreach(
                resultSelector,
                c => NativeMethods.git_odb_foreach(
                    odb,
                    (x, p) => c(x, p),
                    IntPtr.Zero));
        }

        public static void git_odb_free(IntPtr odb)
        {
            NativeMethods.git_odb_free(odb);
        }

        #endregion

        #region git_patch_

        public static void git_patch_free(IntPtr patch)
        {
            NativeMethods.git_patch_free(patch);
        }

        public static PatchSafeHandle git_patch_from_diff(DiffSafeHandle diff, int idx)
        {
            using (ThreadAffinity())
            {
                PatchSafeHandle handle;
                int res = NativeMethods.git_patch_from_diff(out handle, diff, (UIntPtr) idx);
                Ensure.ZeroResult(res);
                return handle;
            }
        }

        public static void git_patch_print(PatchSafeHandle patch, NativeMethods.git_diff_line_cb printCallback)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_patch_print(patch, printCallback, IntPtr.Zero);
                Ensure.ZeroResult(res);
            }
        }

        public static Tuple<int, int> git_patch_line_stats(PatchSafeHandle patch)
        {
            using (ThreadAffinity())
            {
                UIntPtr ctx, add, del;
                int res = NativeMethods.git_patch_line_stats(out ctx, out add, out del, patch);
                Ensure.ZeroResult(res);
                return new Tuple<int, int>((int)add, (int)del);
            }
        } 

        #endregion

        #region git_push_

        public static void git_push_add_refspec(PushSafeHandle push, string pushRefSpec)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_add_refspec(push, pushRefSpec);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_push_finish(PushSafeHandle push)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_finish(push);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_push_free(IntPtr push)
        {
            NativeMethods.git_push_free(push);
        }

        public static PushSafeHandle git_push_new(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                PushSafeHandle handle;
                int res = NativeMethods.git_push_new(out handle, remote);
                Ensure.ZeroResult(res);
                return handle;
            }
        }

        public static void git_push_set_callbacks(
            PushSafeHandle push,
            NativeMethods.git_push_transfer_progress pushTransferProgress,
            NativeMethods.git_packbuilder_progress packBuilderProgress)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_set_callbacks(push, packBuilderProgress, IntPtr.Zero, pushTransferProgress, IntPtr.Zero);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_push_set_options(PushSafeHandle push, GitPushOptions options)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_set_options(push, options);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_push_status_foreach(PushSafeHandle push, NativeMethods.push_status_foreach_cb status_cb)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_status_foreach(push, status_cb, IntPtr.Zero);
                Ensure.ZeroResult(res);
            }
        }

        public static bool git_push_unpack_ok(PushSafeHandle push)
        {
            int res = NativeMethods.git_push_unpack_ok(push);
            return res == 1;
        }

        public static void git_push_update_tips(PushSafeHandle push)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_push_update_tips(push);
                Ensure.ZeroResult(res);
            }
        }

        #endregion

        #region git_reference_

        public static ReferenceSafeHandle git_reference_create(RepositorySafeHandle repo, string name, ObjectId targetId, bool allowOverwrite)
        {
            using (ThreadAffinity())
            {
                GitOid oid = targetId.Oid;
                ReferenceSafeHandle handle;

                int res = NativeMethods.git_reference_create(out handle, repo, name, ref oid, allowOverwrite);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static ReferenceSafeHandle git_reference_symbolic_create(RepositorySafeHandle repo, string name, string target, bool allowOverwrite)
        {
            using (ThreadAffinity())
            {
                ReferenceSafeHandle handle;
                int res = NativeMethods.git_reference_symbolic_create(out handle, repo, name, target, allowOverwrite);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static void git_reference_delete(ReferenceSafeHandle reference)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_reference_delete(reference);
                Ensure.ZeroResult(res);
            }
        }

        public static ICollection<TResult> git_reference_foreach_glob<TResult>(
            RepositorySafeHandle repo,
            string glob,
            Func<IntPtr, TResult> resultSelector)
        {
            return git_foreach(resultSelector, c => NativeMethods.git_reference_foreach_glob(repo, glob, (x, p) => c(x, p), IntPtr.Zero));
        }

        public static void git_reference_free(IntPtr reference)
        {
            NativeMethods.git_reference_free(reference);
        }

        public static bool git_reference_is_valid_name(string refname)
        {
            int res = NativeMethods.git_reference_is_valid_name(refname);
            Ensure.BooleanResult(res);

            return (res == 1);
        }

        public static IList<string> git_reference_list(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                UnSafeNativeMethods.git_strarray arr;
                int res = UnSafeNativeMethods.git_reference_list(out arr, repo);
                Ensure.ZeroResult(res);

                return Libgit2UnsafeHelper.BuildListOf(arr);
            }
        }

        public static ReferenceSafeHandle git_reference_lookup(RepositorySafeHandle repo, string name, bool shouldThrowIfNotFound)
        {
            using (ThreadAffinity())
            {
                ReferenceSafeHandle handle;
                int res = NativeMethods.git_reference_lookup(out handle, repo, name);

                if (!shouldThrowIfNotFound && res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static string git_reference_name(ReferenceSafeHandle reference)
        {
            return NativeMethods.git_reference_name(reference);
        }

        public static ObjectId git_reference_target(ReferenceSafeHandle reference)
        {
            return NativeMethods.git_reference_target(reference).MarshalAsObjectId();
        }

        public static ReferenceSafeHandle git_reference_rename(ReferenceSafeHandle reference, string newName, bool allowOverwrite)
        {
            using (ThreadAffinity())
            {
                ReferenceSafeHandle ref_out;

                int res = NativeMethods.git_reference_rename(out ref_out, reference, newName, allowOverwrite);
                Ensure.ZeroResult(res);

                return ref_out;
            }
        }

        public static ReferenceSafeHandle git_reference_set_target(ReferenceSafeHandle reference, ObjectId id)
        {
            using (ThreadAffinity())
            {
                GitOid oid = id.Oid;
                ReferenceSafeHandle ref_out;

                int res = NativeMethods.git_reference_set_target(out ref_out, reference, ref oid);
                Ensure.ZeroResult(res);

                return ref_out;
            }
        }

        public static ReferenceSafeHandle git_reference_symbolic_set_target(ReferenceSafeHandle reference, string target)
        {
            using (ThreadAffinity())
            {
                ReferenceSafeHandle ref_out;

                int res = NativeMethods.git_reference_symbolic_set_target(out ref_out, reference, target);
                Ensure.ZeroResult(res);

                return ref_out;
            }
        }

        public static string git_reference_symbolic_target(ReferenceSafeHandle reference)
        {
            return NativeMethods.git_reference_symbolic_target(reference);
        }

        public static GitReferenceType git_reference_type(ReferenceSafeHandle reference)
        {
            return NativeMethods.git_reference_type(reference);
        }

        #endregion

        #region git_reflog_

        public static void git_reflog_free(IntPtr reflog)
        {
            NativeMethods.git_reflog_free(reflog);
        }

        public static ReflogSafeHandle git_reflog_read(RepositorySafeHandle repo, string canonicalName)
        {
            using (ThreadAffinity())
            {
                ReflogSafeHandle reflog_out;

                int res = NativeMethods.git_reflog_read(out reflog_out, repo, canonicalName);
                Ensure.ZeroResult(res);

                return reflog_out;
            }
        }

        public static int git_reflog_entrycount(ReflogSafeHandle reflog)
        {
            return (int)NativeMethods.git_reflog_entrycount(reflog);
        }

        public static ReflogEntrySafeHandle git_reflog_entry_byindex(ReflogSafeHandle reflog, int idx)
        {
            return NativeMethods.git_reflog_entry_byindex(reflog, (UIntPtr)idx);
        }

        public static ObjectId git_reflog_entry_id_old(SafeHandle entry)
        {
            return NativeMethods.git_reflog_entry_id_old(entry).MarshalAsObjectId();
        }

        public static ObjectId git_reflog_entry_id_new(SafeHandle entry)
        {
            return NativeMethods.git_reflog_entry_id_new(entry).MarshalAsObjectId();
        }

        public static Signature git_reflog_entry_committer(SafeHandle entry)
        {
            return new Signature(NativeMethods.git_reflog_entry_committer(entry));
        }

        public static string git_reflog_entry_message(SafeHandle entry)
        {
            return NativeMethods.git_reflog_entry_message(entry);
        }

        public static void git_reflog_append(ReflogSafeHandle reflog, ObjectId commit_id, Signature committer, string message)
        {
            using (ThreadAffinity())
            using (SignatureSafeHandle committerHandle = committer.BuildHandle())
            {
                var oid = commit_id.Oid;

                int res = NativeMethods.git_reflog_append(reflog, ref oid, committerHandle, message);
                Ensure.ZeroResult(res);

                res = NativeMethods.git_reflog_write(reflog);
                Ensure.ZeroResult(res);
            }
        }

        #endregion

        #region git_refspec

        public static string git_refspec_rtransform(GitRefSpecHandle refSpecPtr, string name)
        {
            using (ThreadAffinity())
            {
                // libgit2 API does not support querying for required buffer size.
                // Use a sufficiently large buffer until it does.
                var buffer = new byte[1024];

                // TODO: Use code pattern similar to Proxy.git_message_prettify() when available
                int res = NativeMethods.git_refspec_rtransform(buffer, (UIntPtr)buffer.Length, refSpecPtr, name);
                Ensure.ZeroResult(res);

                return LaxUtf8Marshaler.FromBuffer(buffer) ?? string.Empty;
            }
        }

        public static string git_refspec_string(GitRefSpecHandle refSpec)
        {
            return NativeMethods.git_refspec_string(refSpec);
        }

        public static string git_refspec_src(GitRefSpecHandle refSpec)
        {
            return NativeMethods.git_refspec_src(refSpec);
        }

        public static string git_refspec_dst(GitRefSpecHandle refSpec)
        {
            return NativeMethods.git_refspec_dst(refSpec);
        }

        public static RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec)
        {
            return NativeMethods.git_refspec_direction(refSpec);
        }

        public static bool git_refspec_force(GitRefSpecHandle refSpec)
        {
            return NativeMethods.git_refspec_force(refSpec);
        }

        #endregion

        #region git_remote_

        public static TagFetchMode git_remote_autotag(RemoteSafeHandle remote)
        {
            return (TagFetchMode) NativeMethods.git_remote_autotag(remote);
        }

        public static RemoteSafeHandle git_remote_create(RepositorySafeHandle repo, string name, string url)
        {
            using (ThreadAffinity())
            {
                RemoteSafeHandle handle;
                int res = NativeMethods.git_remote_create(out handle, repo, name, url);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static RemoteSafeHandle git_remote_create_with_fetchspec(RepositorySafeHandle repo, string name, string url, string refspec)
        {
            using (ThreadAffinity())
            {
                RemoteSafeHandle handle;
                int res = NativeMethods.git_remote_create_with_fetchspec(out handle, repo, name, url, refspec);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static RemoteSafeHandle git_remote_create_inmemory(RepositorySafeHandle repo, string url, string refspec)
        {
            using (ThreadAffinity())
            {
                RemoteSafeHandle handle;
                int res = NativeMethods.git_remote_create_inmemory(out handle, repo, url, refspec);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static void git_remote_connect(RemoteSafeHandle remote, GitDirection direction)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_connect(remote, direction);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_disconnect(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                NativeMethods.git_remote_disconnect(remote);
            }
        }

        public static GitRefSpecHandle git_remote_get_refspec(RemoteSafeHandle remote, int n)
        {
            return NativeMethods.git_remote_get_refspec(remote, (UIntPtr)n);
        }

        public static int git_remote_refspec_count(RemoteSafeHandle remote)
        {
            return (int)NativeMethods.git_remote_refspec_count(remote);
        }

        public static IList<string> git_remote_get_fetch_refspecs(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                UnSafeNativeMethods.git_strarray arr;
                int res = UnSafeNativeMethods.git_remote_get_fetch_refspecs(out arr, remote);
                Ensure.ZeroResult(res);

                return Libgit2UnsafeHelper.BuildListOf(arr);
            }
        }

        public static IList<string> git_remote_get_push_refspecs(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                UnSafeNativeMethods.git_strarray arr;
                int res = UnSafeNativeMethods.git_remote_get_push_refspecs(out arr, remote);
                Ensure.ZeroResult(res);

                return Libgit2UnsafeHelper.BuildListOf(arr);
            }
        }

        public static void git_remote_set_fetch_refspecs(RemoteSafeHandle remote, IEnumerable<string> refSpecs)
        {
            using (ThreadAffinity())
            using (GitStrArrayIn array = GitStrArrayIn.BuildFrom(refSpecs.ToArray()))
            {
                int res = NativeMethods.git_remote_set_fetch_refspecs(remote, array);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_set_push_refspecs(RemoteSafeHandle remote, IEnumerable<string> refSpecs)
        {
            using (ThreadAffinity())
            using (GitStrArrayIn array = GitStrArrayIn.BuildFrom(refSpecs.ToArray()))
            {
                int res = NativeMethods.git_remote_set_push_refspecs(remote, array);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_download(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_download(remote);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_free(IntPtr remote)
        {
            NativeMethods.git_remote_free(remote);
        }

        public static bool git_remote_is_valid_name(string refname)
        {
            int res = NativeMethods.git_remote_is_valid_name(refname);
            Ensure.BooleanResult(res);

            return (res == 1);
        }

        public static IList<string> git_remote_list(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                UnSafeNativeMethods.git_strarray arr;
                int res = UnSafeNativeMethods.git_remote_list(out arr, repo);
                Ensure.ZeroResult(res);

                return Libgit2UnsafeHelper.BuildListOf(arr);
            }
        }

        public static IEnumerable<DirectReference> git_remote_ls(Repository repository, RemoteSafeHandle remote)
        {
            var refs = new List<DirectReference>();
            IntPtr heads;
            UIntPtr size;

            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_ls(out heads, out size, remote);
                Ensure.ZeroResult(res);
            }

            var grheads = Libgit2UnsafeHelper.RemoteLsHelper(heads, size);

            foreach (var remoteHead in grheads)
            {
                // The name pointer should never be null - if it is,
                // this indicates a bug somewhere (libgit2, server, etc).
                if (remoteHead.NamePtr == IntPtr.Zero)
                {
                    throw new InvalidOperationException("Not expecting null value for reference name.");
                }

                string name = LaxUtf8Marshaler.FromNative(remoteHead.NamePtr);
                refs.Add(new DirectReference(name, repository, remoteHead.Oid));
            }

            return refs;
        }

        public static RemoteSafeHandle git_remote_load(RepositorySafeHandle repo, string name, bool throwsIfNotFound)
        {
            using (ThreadAffinity())
            {
                RemoteSafeHandle handle;
                int res = NativeMethods.git_remote_load(out handle, repo, name);

                if (res == (int)GitErrorCode.NotFound && !throwsIfNotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);
                return handle;
            }
        }

        public static string git_remote_name(RemoteSafeHandle remote)
        {
            return NativeMethods.git_remote_name(remote);
        }

        public static void git_remote_save(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_save(remote);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_set_autotag(RemoteSafeHandle remote, TagFetchMode value)
        {
            NativeMethods.git_remote_set_autotag(remote, value);
        }

        public static void git_remote_set_callbacks(RemoteSafeHandle remote, ref GitRemoteCallbacks callbacks)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_set_callbacks(remote, ref callbacks);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_remote_update_tips(RemoteSafeHandle remote)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_remote_update_tips(remote);
                Ensure.ZeroResult(res);
            }
        }

        public static string git_remote_url(RemoteSafeHandle remote)
        {
            return NativeMethods.git_remote_url(remote);
        }

        #endregion

        #region git_repository_

        public static FilePath git_repository_discover(FilePath start_path)
        {
            return ConvertPath((buffer, bufSize) => NativeMethods.git_repository_discover(buffer, bufSize, start_path, false, null));
        }

        public static bool git_repository_head_detached(RepositorySafeHandle repo)
        {
            return RepositoryStateChecker(repo, NativeMethods.git_repository_head_detached);
        }

        public static ICollection<TResult> git_repository_fetchhead_foreach<TResult>(
            RepositorySafeHandle repo,
            Func<string, string, GitOid, bool, TResult> resultSelector)
        {
            return git_foreach(
                resultSelector,
                c => NativeMethods.git_repository_fetchhead_foreach(
                    repo,
                    (IntPtr w, IntPtr x, ref GitOid y, bool z, IntPtr p)
                        => c(LaxUtf8Marshaler.FromNative(w), LaxUtf8Marshaler.FromNative(x), y, z, p), IntPtr.Zero),
                    GitErrorCode.NotFound);
        }

        public static void git_repository_free(IntPtr repo)
        {
            NativeMethods.git_repository_free(repo);
        }

        public static bool git_repository_head_unborn(RepositorySafeHandle repo)
        {
            return RepositoryStateChecker(repo, NativeMethods.git_repository_head_unborn);
        }

        public static IndexSafeHandle git_repository_index(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                IndexSafeHandle handle;
                int res = NativeMethods.git_repository_index(out handle, repo);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static RepositorySafeHandle git_repository_init_ext(
            FilePath workdirPath,
            FilePath gitdirPath,
            bool isBare)
        {
            using (ThreadAffinity())
            using (var opts = GitRepositoryInitOptions.BuildFrom(workdirPath, isBare))
            {
                RepositorySafeHandle repo;
                int res = NativeMethods.git_repository_init_ext(out repo, gitdirPath, opts);
                Ensure.ZeroResult(res);

                return repo;
            }
        }

        public static bool git_repository_is_bare(RepositorySafeHandle repo)
        {
            return RepositoryStateChecker(repo, NativeMethods.git_repository_is_bare);
        }

        public static bool git_repository_is_empty(RepositorySafeHandle repo)
        {
            return RepositoryStateChecker(repo, NativeMethods.git_repository_is_empty);
        }

        public static bool git_repository_is_shallow(RepositorySafeHandle repo)
        {
            return RepositoryStateChecker(repo, NativeMethods.git_repository_is_shallow);
        }

        public static void git_repository_state_cleanup(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_repository_state_cleanup(repo);
                Ensure.ZeroResult(res);
            }
        }

        public static ICollection<TResult> git_repository_mergehead_foreach<TResult>(
            RepositorySafeHandle repo,
            Func<GitOid, TResult> resultSelector)
        {
            return git_foreach(
                resultSelector,
                c => NativeMethods.git_repository_mergehead_foreach(
                    repo, (ref GitOid x, IntPtr p) => c(x, p), IntPtr.Zero),
                GitErrorCode.NotFound);
        }

        public static string git_repository_message(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                int bufSize = NativeMethods.git_repository_message(null, (UIntPtr)0, repo);

                if (bufSize == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.Int32Result(bufSize);

                byte[] buf = new byte[bufSize];
                int len = NativeMethods.git_repository_message(buf, (UIntPtr)bufSize, repo);

                if (len != bufSize)
                {
                    throw new LibGit2SharpException("Repository message file changed as we were reading it");
                }

                return LaxUtf8Marshaler.FromBuffer(buf);
            }
        }

        public static ObjectDatabaseSafeHandle git_repository_odb(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                ObjectDatabaseSafeHandle handle;
                int res = NativeMethods.git_repository_odb(out handle, repo);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static RepositorySafeHandle git_repository_open(string path)
        {
            using (ThreadAffinity())
            {
                RepositorySafeHandle repo;
                int res = NativeMethods.git_repository_open(out repo, path);

                if (res == (int)GitErrorCode.NotFound)
                {
                    throw new RepositoryNotFoundException(String.Format(CultureInfo.InvariantCulture, "Path '{0}' doesn't point at a valid Git repository or workdir.", path));
                }

                Ensure.ZeroResult(res);

                return repo;
            }
        }

        public static void git_repository_open_ext(string path, RepositoryOpenFlags flags, string ceilingDirs)
        {
            using (ThreadAffinity())
            {
                int res;

                using (var repo = new NullRepositorySafeHandle())
                {
                    res = NativeMethods.git_repository_open_ext(repo, path, flags, ceilingDirs);
                }

                if (res == (int)GitErrorCode.NotFound)
                {
                    throw new RepositoryNotFoundException(String.Format(CultureInfo.InvariantCulture, "Path '{0}' doesn't point at a valid Git repository or workdir.", path));
                }

                Ensure.ZeroResult(res);
            }
        }

        public static FilePath git_repository_path(RepositorySafeHandle repo)
        {
            return NativeMethods.git_repository_path(repo);
        }

        public static void git_repository_set_config(RepositorySafeHandle repo, ConfigurationSafeHandle config)
        {
            NativeMethods.git_repository_set_config(repo, config);
        }

        public static void git_repository_set_index(RepositorySafeHandle repo, IndexSafeHandle index)
        {
            NativeMethods.git_repository_set_index(repo, index);
        }

        public static void git_repository_set_workdir(RepositorySafeHandle repo, FilePath workdir)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_repository_set_workdir(repo, workdir, false);
                Ensure.ZeroResult(res);
            }
        }

        public static CurrentOperation git_repository_state(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_repository_state(repo);
                Ensure.Int32Result(res);
                return (CurrentOperation)res;
            }
        }

        public static FilePath git_repository_workdir(RepositorySafeHandle repo)
        {
            return NativeMethods.git_repository_workdir(repo);
        }

        #endregion

        #region git_reset_

        public static void git_reset(
            RepositorySafeHandle repo,
            ObjectId committishId,
            ResetMode resetKind)
        {
            using (ThreadAffinity())
            using (var osw = new ObjectSafeWrapper(committishId, repo))
            {
                int res = NativeMethods.git_reset(repo, osw.ObjectPtr, resetKind);
                Ensure.ZeroResult(res);
            }
        }

        #endregion

        #region git_revparse_

        public static Tuple<GitObjectSafeHandle, ReferenceSafeHandle> git_revparse_ext(RepositorySafeHandle repo, string objectish)
        {
            using (ThreadAffinity())
            {
                GitObjectSafeHandle obj;
                ReferenceSafeHandle reference;
                int res = NativeMethods.git_revparse_ext(out obj, out reference, repo, objectish);

                switch (res)
                {
                    case (int)GitErrorCode.NotFound:
                        return null;

                    case (int)GitErrorCode.Ambiguous:
                        throw new AmbiguousSpecificationException(string.Format(CultureInfo.InvariantCulture, "Provided abbreviated ObjectId '{0}' is too short.", objectish));

                    default:
                        Ensure.ZeroResult(res);
                        break;
                }

                return new Tuple<GitObjectSafeHandle, ReferenceSafeHandle>(obj, reference);
            }
        }

        public static GitObjectSafeHandle git_revparse_single(RepositorySafeHandle repo, string objectish)
        {
            var handles = git_revparse_ext(repo, objectish);

            if (handles == null)
            {
                return null;
            }

            handles.Item2.Dispose();

            return handles.Item1;
        }

        #endregion

        #region git_revwalk_

        public static void git_revwalk_free(IntPtr walker)
        {
            NativeMethods.git_revwalk_free(walker);
        }

        public static void git_revwalk_hide(RevWalkerSafeHandle walker, ObjectId commit_id)
        {
            using (ThreadAffinity())
            {
                GitOid oid = commit_id.Oid;
                int res = NativeMethods.git_revwalk_hide(walker, ref oid);
                Ensure.ZeroResult(res);
            }
        }

        public static RevWalkerSafeHandle git_revwalk_new(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                RevWalkerSafeHandle handle;
                int res = NativeMethods.git_revwalk_new(out handle, repo);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        public static ObjectId git_revwalk_next(RevWalkerSafeHandle walker)
        {
            using (ThreadAffinity())
            {
                GitOid ret;
                int res = NativeMethods.git_revwalk_next(out ret, walker);

                if (res == (int)GitErrorCode.IterOver)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return ret;
            }
        }

        public static void git_revwalk_push(RevWalkerSafeHandle walker, ObjectId id)
        {
            using (ThreadAffinity())
            {
                GitOid oid = id.Oid;
                int res = NativeMethods.git_revwalk_push(walker, ref oid);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_revwalk_reset(RevWalkerSafeHandle walker)
        {
            NativeMethods.git_revwalk_reset(walker);
        }

        public static void git_revwalk_sorting(RevWalkerSafeHandle walker, CommitSortStrategies options)
        {
            NativeMethods.git_revwalk_sorting(walker, options);
        }

        public static void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walker)
        {
            NativeMethods.git_revwalk_simplify_first_parent(walker);
        }

        #endregion

        #region git_signature_

        public static void git_signature_free(IntPtr signature)
        {
            NativeMethods.git_signature_free(signature);
        }

        public static SignatureSafeHandle git_signature_new(string name, string email, DateTimeOffset when)
        {
            using (ThreadAffinity())
            {
                SignatureSafeHandle handle;
                int res = NativeMethods.git_signature_new(out handle, name, email, when.ToSecondsSinceEpoch(),
                                                          (int)when.Offset.TotalMinutes);
                Ensure.ZeroResult(res);

                return handle;
            }
        }

        #endregion

        #region git_stash_

        public static ObjectId git_stash_save(
            RepositorySafeHandle repo,
            Signature stasher,
            string prettifiedMessage,
            StashModifiers options)
        {
            using (ThreadAffinity())
            using (SignatureSafeHandle stasherHandle = stasher.BuildHandle())
            {
                GitOid stashOid;

                int res = NativeMethods.git_stash_save(out stashOid, repo, stasherHandle, prettifiedMessage, options);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.Int32Result(res);

                return new ObjectId(stashOid);
            }
        }

        public static ICollection<TResult> git_stash_foreach<TResult>(
            RepositorySafeHandle repo,
            Func<int, IntPtr, GitOid, TResult> resultSelector)
        {
            return git_foreach(
                resultSelector,
                c => NativeMethods.git_stash_foreach(
                    repo, (UIntPtr i, IntPtr m, ref GitOid x, IntPtr p) => c((int)i, m, x, p), IntPtr.Zero),
                GitErrorCode.NotFound);
        }

        public static void git_stash_drop(RepositorySafeHandle repo, int index)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_stash_drop(repo, (UIntPtr) index);
                Ensure.BooleanResult(res);
            }
        }

        #endregion

        #region git_status_

        public static FileStatus git_status_file(RepositorySafeHandle repo, FilePath path)
        {
            using (ThreadAffinity())
            {
                FileStatus status;
                int res = NativeMethods.git_status_file(out status, repo, path);

                switch (res)
                {
                    case (int)GitErrorCode.NotFound:
                        return FileStatus.Nonexistent;

                    case (int)GitErrorCode.Ambiguous:
                        throw new AmbiguousSpecificationException(string.Format(CultureInfo.InvariantCulture, "More than one file matches the pathspec '{0}'. You can either force a literal path evaluation (GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH), or use git_status_foreach().", path));

                    default:
                        Ensure.ZeroResult(res);
                        break;
                }

                return status;
            }
        }

        public static StatusListSafeHandle git_status_list_new(RepositorySafeHandle repo, GitStatusOptions options)
        {
            using (ThreadAffinity())
            {
                StatusListSafeHandle handle;
                int res = NativeMethods.git_status_list_new(out handle, repo, options);
                Ensure.ZeroResult(res);
                return handle;
            }
        }

        public static int git_status_list_entrycount(StatusListSafeHandle list)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_status_list_entrycount(list);
                Ensure.Int32Result(res);
                return res;
            }
        }

        public static StatusEntrySafeHandle git_status_byindex(StatusListSafeHandle list, long idx)
        {
            return NativeMethods.git_status_byindex(list, (UIntPtr)idx);
        }

        public static void git_status_list_free(IntPtr statusList)
        {
            NativeMethods.git_status_list_free(statusList);
        }

        #endregion

        #region git_submodule_

        /// <summary>
        /// Returns a handle to the corresponding submodule,
        /// or an invalid handle if a submodule is not found.
        /// </summary>
        public static SubmoduleSafeHandle git_submodule_lookup(RepositorySafeHandle repo, FilePath name)
        {
            using (ThreadAffinity())
            {
                SubmoduleSafeHandle reference;
                var res = NativeMethods.git_submodule_lookup(out reference, repo, name);

                switch (res)
                {
                    case (int)GitErrorCode.NotFound:
                    case (int)GitErrorCode.Exists:
                    case (int)GitErrorCode.OrphanedHead:
                        return null;

                    default:
                        Ensure.ZeroResult(res);
                        return reference;
                }
            }
        }

        public static ICollection<TResult> git_submodule_foreach<TResult>(RepositorySafeHandle repo, Func<IntPtr, IntPtr, TResult> resultSelector)
        {
            return git_foreach(resultSelector, c => NativeMethods.git_submodule_foreach(repo, (x, y, p) => c(x, y, p), IntPtr.Zero));
        }

        public static void git_submodule_add_to_index(SubmoduleSafeHandle submodule, bool write_index)
        {
            using (ThreadAffinity())
            {
                var res = NativeMethods.git_submodule_add_to_index(submodule, write_index);
                Ensure.ZeroResult(res);
            }
        }

        public static void git_submodule_save(SubmoduleSafeHandle submodule)
        {
            using (ThreadAffinity())
            {
                var res = NativeMethods.git_submodule_save(submodule);
                Ensure.ZeroResult(res);
            }
        }

        public static string git_submodule_path(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_path(submodule);
        }

        public static string git_submodule_url(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_url(submodule);
        }

        public static ObjectId git_submodule_index_id(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_index_id(submodule).MarshalAsObjectId();
        }

        public static ObjectId git_submodule_head_id(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_head_id(submodule).MarshalAsObjectId();
        }

        public static ObjectId git_submodule_wd_id(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_wd_id(submodule).MarshalAsObjectId();
        }

        public static SubmoduleIgnore git_submodule_ignore(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_ignore(submodule);
        }

        public static SubmoduleUpdate git_submodule_update(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_update(submodule);
        }

        public static bool git_submodule_fetch_recurse_submodules(SubmoduleSafeHandle submodule)
        {
            return NativeMethods.git_submodule_fetch_recurse_submodules(submodule);
        }

        public static void git_submodule_reload(SubmoduleSafeHandle submodule)
        {
            using (ThreadAffinity())
            {
                var res = NativeMethods.git_submodule_reload(submodule);
                Ensure.ZeroResult(res);
            }
        }

        public static SubmoduleStatus git_submodule_status(SubmoduleSafeHandle submodule)
        {
            using (ThreadAffinity())
            {
                SubmoduleStatus status;
                var res = NativeMethods.git_submodule_status(out status, submodule);
                Ensure.ZeroResult(res);
                return status;
            }
        }

        #endregion

        #region git_tag_

        public static ObjectId git_tag_annotation_create(
            RepositorySafeHandle repo,
            string name,
            GitObject target,
            Signature tagger,
            string message)
        {
            using (ThreadAffinity())
            using (var objectPtr = new ObjectSafeWrapper(target.Id, repo))
            using (SignatureSafeHandle taggerHandle = tagger.BuildHandle())
            {
                GitOid oid;
                int res = NativeMethods.git_tag_annotation_create(out oid, repo, name, objectPtr.ObjectPtr, taggerHandle, message);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static ObjectId git_tag_create(
            RepositorySafeHandle repo,
            string name,
            GitObject target,
            Signature tagger,
            string message,
            bool allowOverwrite)
        {
            using (ThreadAffinity())
            using (var objectPtr = new ObjectSafeWrapper(target.Id, repo))
            using (SignatureSafeHandle taggerHandle = tagger.BuildHandle())
            {
                GitOid oid;
                int res = NativeMethods.git_tag_create(out oid, repo, name, objectPtr.ObjectPtr, taggerHandle, message, allowOverwrite);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static ObjectId git_tag_create_lightweight(RepositorySafeHandle repo, string name, GitObject target, bool allowOverwrite)
        {
            using (ThreadAffinity())
            using (var objectPtr = new ObjectSafeWrapper(target.Id, repo))
            {
                GitOid oid;
                int res = NativeMethods.git_tag_create_lightweight(out oid, repo, name, objectPtr.ObjectPtr, allowOverwrite);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        public static void git_tag_delete(RepositorySafeHandle repo, string name)
        {
            using (ThreadAffinity())
            {
                int res = NativeMethods.git_tag_delete(repo, name);
                Ensure.ZeroResult(res);
            }
        }

        public static IList<string> git_tag_list(RepositorySafeHandle repo)
        {
            using (ThreadAffinity())
            {
                UnSafeNativeMethods.git_strarray arr;
                int res = UnSafeNativeMethods.git_tag_list(out arr, repo);
                Ensure.ZeroResult(res);

                return Libgit2UnsafeHelper.BuildListOf(arr);
            }
        }

        public static string git_tag_message(GitObjectSafeHandle tag)
        {
            return NativeMethods.git_tag_message(tag);
        }

        public static string git_tag_name(GitObjectSafeHandle tag)
        {
            return NativeMethods.git_tag_name(tag);
        }

        public static Signature git_tag_tagger(GitObjectSafeHandle tag)
        {
            return new Signature(NativeMethods.git_tag_tagger(tag));
        }

        public static ObjectId git_tag_target_oid(GitObjectSafeHandle tag)
        {
            return NativeMethods.git_tag_target_id(tag).MarshalAsObjectId();
        }

        public static GitObjectType git_tag_target_type(GitObjectSafeHandle tag)
        {
            return NativeMethods.git_tag_target_type(tag);
        }

        #endregion

        #region git_tree_

        public static Mode git_tree_entry_attributes(SafeHandle entry)
        {
            return (Mode)NativeMethods.git_tree_entry_filemode(entry);
        }

        public static TreeEntrySafeHandle git_tree_entry_byindex(GitObjectSafeHandle tree, long idx)
        {
            return NativeMethods.git_tree_entry_byindex(tree, (UIntPtr)idx);
        }

        public static TreeEntrySafeHandle_Owned git_tree_entry_bypath(RepositorySafeHandle repo, ObjectId id, FilePath treeentry_path)
        {
            using (ThreadAffinity())
            using (var obj = new ObjectSafeWrapper(id, repo))
            {
                TreeEntrySafeHandle_Owned treeEntryPtr;
                int res = NativeMethods.git_tree_entry_bypath(out treeEntryPtr, obj.ObjectPtr, treeentry_path);

                if (res == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(res);

                return treeEntryPtr;
            }
        }

        public static void git_tree_entry_free(IntPtr treeEntry)
        {
            NativeMethods.git_tree_entry_free(treeEntry);
        }

        public static ObjectId git_tree_entry_id(SafeHandle entry)
        {
            return NativeMethods.git_tree_entry_id(entry).MarshalAsObjectId();
        }

        public static string git_tree_entry_name(SafeHandle entry)
        {
            return NativeMethods.git_tree_entry_name(entry);
        }

        public static GitObjectType git_tree_entry_type(SafeHandle entry)
        {
            return NativeMethods.git_tree_entry_type(entry);
        }

        public static int git_tree_entrycount(GitObjectSafeHandle tree)
        {
            return (int)NativeMethods.git_tree_entrycount(tree);
        }

        #endregion

        #region git_treebuilder_

        public static TreeBuilderSafeHandle git_treebuilder_create()
        {
            using (ThreadAffinity())
            {
                TreeBuilderSafeHandle builder;
                int res = NativeMethods.git_treebuilder_create(out builder, IntPtr.Zero);
                Ensure.ZeroResult(res);

                return builder;
            }
        }

        public static void git_treebuilder_free(IntPtr bld)
        {
            NativeMethods.git_treebuilder_free(bld);
        }

        public static void git_treebuilder_insert(TreeBuilderSafeHandle builder, string treeentry_name, TreeEntryDefinition treeEntryDefinition)
        {
            using (ThreadAffinity())
            {
                GitOid oid = treeEntryDefinition.TargetId.Oid;
                int res = NativeMethods.git_treebuilder_insert(IntPtr.Zero, builder, treeentry_name, ref oid, (uint)treeEntryDefinition.Mode);
                Ensure.ZeroResult(res);
            }
        }

        public static ObjectId git_treebuilder_write(RepositorySafeHandle repo, TreeBuilderSafeHandle bld)
        {
            using (ThreadAffinity())
            {
                GitOid oid;
                int res = NativeMethods.git_treebuilder_write(out oid, repo, bld);
                Ensure.ZeroResult(res);

                return oid;
            }
        }

        #endregion

        private static ICollection<TResult> git_foreach<T, TResult>(
            Func<T, TResult> resultSelector,
            Func<Func<T, IntPtr, int>, int> iterator,
            params GitErrorCode[] ignoredErrorCodes)
        {
            using (ThreadAffinity())
            {
                var result = new List<TResult>();
                var res = iterator((x, payload) =>
                                       {
                                           result.Add(resultSelector(x));
                                           return 0;
                                       });

                if (ignoredErrorCodes != null && ignoredErrorCodes.Contains((GitErrorCode)res))
                {
                    return new TResult[0];
                }

                Ensure.ZeroResult(res);
                return result;
            }
        }

        private static ICollection<TResult> git_foreach<T1, T2, TResult>(
            Func<T1, T2, TResult> resultSelector,
            Func<Func<T1, T2, IntPtr, int>, int> iterator,
            params GitErrorCode[] ignoredErrorCodes)
        {
            using (ThreadAffinity())
            {
                var result = new List<TResult>();
                var res = iterator((x, y, payload) =>
                                       {
                                           result.Add(resultSelector(x, y));
                                           return 0;
                                       });

                if (ignoredErrorCodes != null && ignoredErrorCodes.Contains((GitErrorCode)res))
                {
                    return new TResult[0];
                }

                Ensure.ZeroResult(res);
                return result;
            }
        }

        private static ICollection<TResult> git_foreach<T1, T2, T3, TResult>(
            Func<T1, T2, T3, TResult> resultSelector,
            Func<Func<T1, T2, T3, IntPtr, int>, int> iterator,
            params GitErrorCode[] ignoredErrorCodes)
        {
            using (ThreadAffinity())
            {
                var result = new List<TResult>();
                var res = iterator((w, x, y, payload) =>
                {
                    result.Add(resultSelector(w, x, y));
                    return 0;
                });

                if (ignoredErrorCodes != null && ignoredErrorCodes.Contains((GitErrorCode)res))
                {
                    return new TResult[0];
                }

                Ensure.ZeroResult(res);
                return result;
            }
        }

        public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);

        private static ICollection<TResult> git_foreach<T1, T2, T3, T4, TResult>(
            Func<T1, T2, T3, T4, TResult> resultSelector,
            Func<Func<T1, T2, T3, T4, IntPtr, int>, int> iterator,
            params GitErrorCode[] ignoredErrorCodes)
        {
            using (ThreadAffinity())
            {
                var result = new List<TResult>();
                var res = iterator((w, x, y, z, payload) =>
                {
                    result.Add(resultSelector(w, x, y, z));
                    return 0;
                });

                if (ignoredErrorCodes != null && ignoredErrorCodes.Contains((GitErrorCode)res))
                {
                    return new TResult[0];
                }

                Ensure.ZeroResult(res);
                return result;
            }
        }

        private delegate int IteratorNew<THandle>(out THandle iter);

        private delegate TPayload IteratorNext<in TIterator, THandle, out TPayload>(TIterator iter, out THandle next, out int res);

        private static THandle git_iterator_new<THandle>(IteratorNew<THandle> newFunc)
            where THandle : SafeHandleBase
        {
            THandle iter;
            Ensure.ZeroResult(newFunc(out iter));
            return iter;
        }

        private static IEnumerable<TResult> git_iterator_next<TIterator, THandle, TPayload, TResult>(
            TIterator iter,
            IteratorNext<TIterator, THandle, TPayload> nextFunc,
            Func<THandle, TPayload, TResult> resultSelector)
            where THandle : SafeHandleBase
        {
            while (true)
            {
                var next = default(THandle);
                try
                {
                    int res;
                    var payload = nextFunc(iter, out next, out res);

                    if (res == (int)GitErrorCode.IterOver)
                    {
                        yield break;
                    }

                    Ensure.ZeroResult(res);
                    yield return resultSelector(next, payload);
                }
                finally
                {
                    if (next != null)
                        next.SafeDispose();
                }
            }
        }

        private static IEnumerable<TResult> git_iterator<TIterator, THandle, TPayload, TResult>(
            IteratorNew<TIterator> newFunc,
            IteratorNext<TIterator, THandle, TPayload> nextFunc,
            Func<THandle, TPayload, TResult> resultSelector
            )
            where TIterator : SafeHandleBase
            where THandle : SafeHandleBase
        {
            using (ThreadAffinity())
            {
                using (var iter = git_iterator_new(newFunc))
                {
                    foreach (var next in git_iterator_next(iter, nextFunc, resultSelector))
                    {
                        yield return next;
                    }
                }
            }
        }

        private static unsafe class Libgit2UnsafeHelper
        {
            public static IList<string> BuildListOf(UnSafeNativeMethods.git_strarray strArray)
            {

                try
                {
                    UnSafeNativeMethods.git_strarray* gitStrArray = &strArray;

                    var numberOfEntries = (int)gitStrArray->size;
                    var list = new List<string>(numberOfEntries);
                    for (uint i = 0; i < numberOfEntries; i++)
                    {
                        var name = LaxUtf8Marshaler.FromNative((IntPtr)gitStrArray->strings[i]);
                        list.Add(name);
                    }

                    return list;
                }
                finally
                {
                    UnSafeNativeMethods.git_strarray_free(ref strArray);
                }
            }

            public static IList<GitRemoteHead> RemoteLsHelper(IntPtr heads, UIntPtr size)
            {
                var rawHeads = (IntPtr*) heads;
                var count = (int) size;

                var list = new List<GitRemoteHead>(count);
                for (int i = 0; i < count; i++)
                {
                    list.Add(rawHeads[i].MarshalAs<GitRemoteHead>());
                }
                return list;
            }
        }

        private static bool RepositoryStateChecker(RepositorySafeHandle repo, Func<RepositorySafeHandle, int> checker)
        {
            using (ThreadAffinity())
            {
                int res = checker(repo);
                Ensure.BooleanResult(res);

                return (res == 1);
            }
        }

        private static FilePath ConvertPath(Func<byte[], UIntPtr, int> pathRetriever)
        {
            using (ThreadAffinity())
            {
                var buffer = new byte[NativeMethods.GIT_PATH_MAX];

                int result = pathRetriever(buffer, (UIntPtr)NativeMethods.GIT_PATH_MAX);

                if (result == (int)GitErrorCode.NotFound)
                {
                    return null;
                }

                Ensure.ZeroResult(result);

                return LaxFilePathMarshaler.FromBuffer(buffer);
            }
        }

        private static Func<IDisposable> ThreadAffinity = WithoutThreadAffinity;

        internal static void EnableThreadAffinity()
        {
            ThreadAffinity = WithThreadAffinity;
        }

        private static IDisposable WithoutThreadAffinity()
        {
            return null;
        }

        private static IDisposable WithThreadAffinity()
        {
            return new DisposableThreadAffinityWrapper();
        }

        private class DisposableThreadAffinityWrapper : IDisposable
        {
            public DisposableThreadAffinityWrapper()
            {
                Thread.BeginThreadAffinity();
            }

            public void Dispose()
            {
                Thread.EndThreadAffinity();
            }
        }

        private static readonly IDictionary<Type, Func<string, object>> configurationParser = new Dictionary<Type, Func<string, object>>
        {
            { typeof(int), value => git_config_parse_int32(value) },
            { typeof(long), value => git_config_parse_int64(value) },
            { typeof(bool), value => git_config_parse_bool(value) },
            { typeof(string), value => value },
        };

        /// <summary>
        /// Helper method for consistent conversion of return value on
        /// Callbacks that support cancellation from bool to native type.
        /// True indicates that function should continue, false indicates
        /// user wants to cancel.
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        internal static int ConvertResultToCancelFlag(bool result)
        {
            return result ? 0 : -1;
        }
    }
}
// ReSharper restore InconsistentNaming