summaryrefslogtreecommitdiffstats
path: root/bin/git/git-imerge
blob: b903539093ee3f56fef47fa3c8075cfe5c37567e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2012-2013 Michael Haggerty <mhagger@alum.mit.edu>
#
# This file is part of git-imerge.
#
# git-imerge is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see
# <http://www.gnu.org/licenses/>.

r"""Git incremental merge

Perform the merge between two branches incrementally.  If conflicts
are encountered, figure out exactly which pairs of commits conflict,
and present the user with one pairwise conflict at a time for
resolution.

Multiple incremental merges can be in progress at the same time.  Each
incremental merge has a name, and its progress is recorded in the Git
repository as references under 'refs/imerge/NAME'.

An incremental merge can be interrupted and resumed arbitrarily, or
even pushed to a server to allow somebody else to work on it.


Instructions:

To start an incremental merge or rebase, use one of the following
commands:

    git-imerge merge BRANCH
        Analogous to "git merge BRANCH"

    git-imerge rebase BRANCH
        Analogous to "git rebase BRANCH"

    git-imerge drop [commit | commit1..commit2]
        Drop the specified commit(s) from the current branch

    git-imerge revert [commit | commit1..commit2]
        Revert the specified commits by adding new commits that
        reverse their effects

    git-imerge start --name=NAME --goal=GOAL BRANCH
        Start a general imerge

Then the tool will present conflicts to you one at a time, similar to
"git rebase --incremental".  Resolve each conflict, and then

    git add FILE...
    git-imerge continue

You can view your progress at any time with

    git-imerge diagram

When you have resolved all of the conflicts, simplify and record the
result by typing

    git-imerge finish

To get more help about any git-imerge subcommand, type

    git-imerge SUBCOMMAND --help

"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import locale
import sys
import re
import subprocess
from subprocess import CalledProcessError
from subprocess import check_call
import itertools
import argparse
from io import StringIO
import json
import os


PREFERRED_ENCODING = locale.getpreferredencoding()


# Define check_output() for ourselves, including decoding of the
# output into PREFERRED_ENCODING:
def check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
    output = communicate(process)[0]
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        # We don't store output in the CalledProcessError because
        # the "output" keyword parameter was not supported in
        # Python 2.6:
        raise CalledProcessError(retcode, cmd)
    return output


STATE_VERSION = (1, 3, 0)

ZEROS = '0' * 40

ALLOWED_GOALS = [
    'full',
    'rebase',
    'rebase-with-history',
    'border',
    'border-with-history',
    'border-with-history2',
    'merge',
    'drop',
    'revert',
    ]
DEFAULT_GOAL = 'merge'


class Failure(Exception):
    """An exception that indicates a normal failure of the script.

    Failures are reported at top level via sys.exit(str(e)) rather
    than via a Python stack dump."""

    pass


class AnsiColor:
    BLACK = '\033[0;30m'
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    YELLOW = '\033[0;33m'
    BLUE = '\033[0;34m'
    MAGENTA = '\033[0;35m'
    CYAN = '\033[0;36m'
    B_GRAY = '\033[0;37m'
    D_GRAY = '\033[1;30m'
    B_RED = '\033[1;31m'
    B_GREEN = '\033[1;32m'
    B_YELLOW = '\033[1;33m'
    B_BLUE = '\033[1;34m'
    B_MAGENTA = '\033[1;35m'
    B_CYAN = '\033[1;36m'
    WHITE = '\033[1;37m'
    END = '\033[0m'

    @classmethod
    def disable(cls):
        cls.BLACK = ''
        cls.RED = ''
        cls.GREEN = ''
        cls.YELLOW = ''
        cls.BLUE = ''
        cls.MAGENTA = ''
        cls.CYAN = ''
        cls.B_GRAY = ''
        cls.D_GRAY = ''
        cls.B_RED = ''
        cls.B_GREEN = ''
        cls.B_YELLOW = ''
        cls.B_BLUE = ''
        cls.B_MAGENTA = ''
        cls.B_CYAN = ''
        cls.WHITE = ''
        cls.END = ''


def iter_neighbors(iterable):
    """For an iterable (x0, x1, x2, ...) generate [(x0,x1), (x1,x2), ...]."""

    i = iter(iterable)

    try:
        last = next(i)
    except StopIteration:
        return

    for x in i:
        yield (last, x)
        last = x


def find_first_false(f, lo, hi):
    """Return the smallest i in lo <= i < hi for which f(i) returns False using bisection.

    If there is no such i, return hi.

    """

    # Loop invariant: f(i) returns True for i < lo; f(i) returns False
    # for i >= hi.

    while lo < hi:
        mid = (lo + hi) // 2
        if f(mid):
            lo = mid + 1
        else:
            hi = mid

    return lo


def call_silently(cmd):
    try:
        NULL = open(os.devnull, 'w')
    except (IOError, AttributeError):
        NULL = subprocess.PIPE

    p = subprocess.Popen(cmd, stdout=NULL, stderr=NULL)
    p.communicate()
    retcode = p.wait()
    if retcode:
        raise CalledProcessError(retcode, cmd)


def communicate(process, input=None):
    """Return decoded output from process."""
    if input is not None:
        input = input.encode(PREFERRED_ENCODING)

    output, error = process.communicate(input)

    output = None if output is None else output.decode(PREFERRED_ENCODING)
    error = None if error is None else error.decode(PREFERRED_ENCODING)

    return (output, error)


if sys.hexversion < 0x03000000:
    # In Python 2.x, os.environ keys and values must be byte
    # strings:
    def env_encode(s):
        """Encode unicode keys or values for use in os.environ."""

        return s.encode(PREFERRED_ENCODING)

else:
    # In Python 3.x, os.environ keys and values must be unicode
    # strings:
    def env_encode(s):
        """Use unicode keys or values unchanged in os.environ."""

        return s


class UncleanWorkTreeError(Failure):
    pass


class AutomaticMergeFailed(Exception):
    def __init__(self, commit1, commit2):
        Exception.__init__(
            self, 'Automatic merge of %s and %s failed' % (commit1, commit2,)
            )
        self.commit1, self.commit2 = commit1, commit2


class InvalidBranchNameError(Failure):
    pass


class NotFirstParentAncestorError(Failure):
    def __init__(self, commit1, commit2):
        Failure.__init__(
            self,
            'Commit "%s" is not a first-parent ancestor of "%s"'
            % (commit1, commit2),
            )


class NonlinearAncestryError(Failure):
    def __init__(self, commit1, commit2):
        Failure.__init__(
            self,
            'The history "%s..%s" is not linear'
            % (commit1, commit2),
            )


class NothingToDoError(Failure):
    def __init__(self, src_tip, dst_tip):
        Failure.__init__(
            self,
            'There are no commits on "%s" that are not already in "%s"'
            % (src_tip, dst_tip),
            )


class GitTemporaryHead(object):
    """A context manager that records the current HEAD state then restores it.

    This should only be used when the working copy is clean. message
    is used for the reflog.

    """

    def __init__(self, git, message):
        self.git = git
        self.message = message

    def __enter__(self):
        self.head_name = self.git.get_head_refname()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.head_name:
            try:
                self.git.restore_head(self.head_name, self.message)
            except CalledProcessError as e:
                raise Failure(
                    'Could not restore HEAD to %r!:    %s\n'
                    % (self.head_name, e.message,)
                    )

        return False


class GitRepository(object):
    BRANCH_PREFIX = 'refs/heads/'

    MERGE_STATE_REFNAME_RE = re.compile(
        r"""
        ^
        refs\/imerge\/
        (?P<name>.+)
        \/state
        $
        """,
        re.VERBOSE,
        )

    def __init__(self):
        self.git_dir_cache = None

    def git_dir(self):
        if self.git_dir_cache is None:
            self.git_dir_cache = check_output(
                ['git', 'rev-parse', '--git-dir']
                ).rstrip('\n')

        return self.git_dir_cache

    def check_imerge_name_format(self, name):
        """Check that name is a valid imerge name."""

        try:
            call_silently(
                ['git', 'check-ref-format', 'refs/imerge/%s' % (name,)]
                )
        except CalledProcessError:
            raise Failure('Name %r is not a valid refname component!' % (name,))

    def check_branch_name_format(self, name):
        """Check that name is a valid branch name."""

        try:
            call_silently(
                ['git', 'check-ref-format', 'refs/heads/%s' % (name,)]
                )
        except CalledProcessError:
            raise InvalidBranchNameError('Name %r is not a valid branch name!' % (name,))

    def iter_existing_imerge_names(self):
        """Iterate over the names of existing MergeStates in this repo."""

        for line in check_output(['git', 'for-each-ref', 'refs/imerge']).splitlines():
            (sha1, type, refname) = line.split()
            if type == 'blob':
                m = GitRepository.MERGE_STATE_REFNAME_RE.match(refname)
                if m:
                    yield m.group('name')

    def set_default_imerge_name(self, name):
        """Set the default merge to the specified one.

        name can be None to cause the default to be cleared."""

        if name is None:
            try:
                check_call(['git', 'config', '--unset', 'imerge.default'])
            except CalledProcessError as e:
                if e.returncode == 5:
                    # Value was not set
                    pass
                else:
                    raise
        else:
            check_call(['git', 'config', 'imerge.default', name])

    def get_default_imerge_name(self):
        """Get the name of the default merge, or None if it is currently unset."""

        try:
            return check_output(['git', 'config', 'imerge.default']).rstrip()
        except CalledProcessError:
            return None

    def get_default_edit(self):
        """Should '--edit' be used when committing intermediate user merges?

        When 'git imerge continue' or 'git imerge record' finds a user
        merge that can be committed, should it (by default) ask the user
        to edit the commit message? This behavior can be configured via
        'imerge.editmergemessages'. If it is not configured, return False.

        Please note that this function is only used to choose the default
        value. It can be overridden on the command line using '--edit' or
        '--no-edit'.

        """

        try:
            return {'true' : True, 'false' : False}[
                check_output(
                    ['git', 'config', '--bool', 'imerge.editmergemessages']
                    ).rstrip()
                ]
        except CalledProcessError:
            return False

    def unstaged_changes(self):
        """Return True iff there are unstaged changes in the working copy"""

        try:
            check_call(['git', 'diff-files', '--quiet', '--ignore-submodules'])
            return False
        except CalledProcessError:
            return True

    def uncommitted_changes(self):
        """Return True iff the index contains uncommitted changes."""

        try:
            check_call([
                'git', 'diff-index', '--cached', '--quiet',
                '--ignore-submodules', 'HEAD', '--',
                ])
            return False
        except CalledProcessError:
            return True

    def get_commit_sha1(self, arg):
        """Convert arg into a SHA1 and verify that it refers to a commit.

        If not, raise ValueError."""

        try:
            return self.rev_parse('%s^{commit}' % (arg,))
        except CalledProcessError:
            raise ValueError('%r does not refer to a valid git commit' % (arg,))

    def refresh_index(self):
        process = subprocess.Popen(
            ['git', 'update-index', '-q', '--ignore-submodules', '--refresh'],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            )
        out, err = communicate(process)
        retcode = process.poll()
        if retcode:
            raise UncleanWorkTreeError(err.rstrip() or out.rstrip())

    def verify_imerge_name_available(self, name):
        self.check_imerge_name_format(name)
        if check_output(['git', 'for-each-ref', 'refs/imerge/%s' % (name,)]):
            raise Failure('Name %r is already in use!' % (name,))

    def check_imerge_exists(self, name):
        """Verify that a MergeState with the given name exists.

        Just check for the existence, readability, and compatible
        version of the 'state' reference.  If the reference doesn't
        exist, just return False.  If it exists but is unusable for
        some other reason, raise an exception."""

        self.check_imerge_name_format(name)
        state_refname = 'refs/imerge/%s/state' % (name,)
        for line in check_output(['git', 'for-each-ref', state_refname]).splitlines():
            (sha1, type, refname) = line.split()
            if refname == state_refname and type == 'blob':
                self.read_imerge_state_dict(name)
                # If that didn't throw an exception:
                return True
        else:
            return False

    def read_imerge_state_dict(self, name):
        state_string = check_output(
            ['git', 'cat-file', 'blob', 'refs/imerge/%s/state' % (name,)],
            )
        state = json.loads(state_string)

        # Convert state['version'] to a tuple of integers, and verify
        # that it is compatible with this version of the script:
        version = tuple(int(i) for i in state['version'].split('.'))
        if version[0] != STATE_VERSION[0] or version[1] > STATE_VERSION[1]:
            raise Failure(
                'The format of imerge %s (%s) is not compatible with this script version.'
                % (name, state['version'],)
                )
        state['version'] = version

        return state

    def read_imerge_state(self, name):
        """Read the state associated with the specified imerge.

        Return the tuple

            (state_dict, {(i1, i2) : (sha1, source), ...})

        , where source is 'auto' or 'manual'. Validity is checked only
        lightly.

        """

        merge_ref_re = re.compile(
            r"""
            ^
            refs\/imerge\/
            """ + re.escape(name) + r"""
            \/(?P<source>auto|manual)\/
            (?P<i1>0|[1-9][0-9]*)
            \-
            (?P<i2>0|[1-9][0-9]*)
            $
            """,
            re.VERBOSE,
            )

        state_ref_re = re.compile(
            r"""
            ^
            refs\/imerge\/
            """ + re.escape(name) + r"""
            \/state
            $
            """,
            re.VERBOSE,
            )

        state = None

        # A map {(i1, i2) : (sha1, source)}:
        merges = {}

        # refnames that were found but not understood:
        unexpected = []

        for line in check_output([
                'git', 'for-each-ref', 'refs/imerge/%s' % (name,)
                ]).splitlines():
            (sha1, type, refname) = line.split()
            m = merge_ref_re.match(refname)
            if m:
                if type != 'commit':
                    raise Failure('Reference %r is not a commit!' % (refname,))
                i1, i2 = int(m.group('i1')), int(m.group('i2'))
                source = m.group('source')
                merges[i1, i2] = (sha1, source)
                continue

            m = state_ref_re.match(refname)
            if m:
                if type != 'blob':
                    raise Failure('Reference %r is not a blob!' % (refname,))
                state = self.read_imerge_state_dict(name)
                continue

            unexpected.append(refname)

        if state is None:
            raise Failure(
                'No state found; it should have been a blob reference at '
                '"refs/imerge/%s/state"' % (name,)
                )

        if unexpected:
            raise Failure(
                'Unexpected reference(s) found in "refs/imerge/%s" namespace:\n    %s\n'
                % (name, '\n    '.join(unexpected),)
                )

        return (state, merges)

    def write_imerge_state_dict(self, name, state):
        state_string = json.dumps(state, sort_keys=True) + '\n'

        cmd = ['git', 'hash-object', '-t', 'blob', '-w', '--stdin']
        p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        out = communicate(p, input=state_string)[0]
        retcode = p.poll()
        if retcode:
            raise CalledProcessError(retcode, cmd)
        sha1 = out.strip()
        check_call([
            'git', 'update-ref',
            '-m', 'imerge %r: Record state' % (name,),
            'refs/imerge/%s/state' % (name,),
            sha1,
            ])

    def is_ancestor(self, commit1, commit2):
        """Return True iff commit1 is an ancestor (or equal to) commit2."""

        if commit1 == commit2:
            return True
        else:
            return int(
                check_output([
                    'git', 'rev-list', '--count', '--ancestry-path',
                    '%s..%s' % (commit1, commit2,),
                    ]).strip()
                ) != 0

    def is_ff(self, refname, commit):
        """Would updating refname to commit be a fast-forward update?

        Return True iff refname is not currently set or it points to an
        ancestor of commit.

        """

        try:
            ref_oldval = self.get_commit_sha1(refname)
        except ValueError:
            # refname doesn't already exist; no problem.
            return True
        else:
            return self.is_ancestor(ref_oldval, commit)

    def automerge(self, commit1, commit2, msg=None):
        """Attempt an automatic merge of commit1 and commit2.

        Return the SHA1 of the resulting commit, or raise
        AutomaticMergeFailed on error.  This must be called with a clean
        worktree."""

        call_silently(['git', 'checkout', '-f', commit1])
        cmd = ['git', '-c', 'rerere.enabled=false', 'merge']
        if msg is not None:
            cmd += ['-m', msg]
        cmd += [commit2]
        try:
            call_silently(cmd)
        except CalledProcessError:
            self.abort_merge()
            raise AutomaticMergeFailed(commit1, commit2)
        else:
            return self.get_commit_sha1('HEAD')

    def manualmerge(self, commit, msg):
        """Initiate a merge of commit into the current HEAD."""

        check_call(['git', 'merge', '--no-commit', '-m', msg, commit,])

    def require_clean_work_tree(self, action):
        """Verify that the current tree is clean.

        The code is a Python translation of the git-sh-setup(1) function
        of the same name."""

        process = subprocess.Popen(
            ['git', 'rev-parse', '--verify', 'HEAD'],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            )
        err = communicate(process)[1]
        retcode = process.poll()
        if retcode:
            raise UncleanWorkTreeError(err.rstrip())

        self.refresh_index()

        error = []
        if self.unstaged_changes():
            error.append('Cannot %s: You have unstaged changes.' % (action,))

        if self.uncommitted_changes():
            if not error:
                error.append('Cannot %s: Your index contains uncommitted changes.' % (action,))
            else:
                error.append('Additionally, your index contains uncommitted changes.')

        if error:
            raise UncleanWorkTreeError('\n'.join(error))

    def simple_merge_in_progress(self):
        """Return True iff a merge (of a single branch) is in progress."""

        try:
            with open(os.path.join(self.git_dir(), 'MERGE_HEAD')) as f:
                heads = [line.rstrip() for line in f]
        except IOError:
            return False

        return len(heads) == 1

    def commit_user_merge(self, edit_log_msg=None):
        """If a merge is in progress and ready to be committed, commit it.

        If a simple merge is in progress and any changes in the working
        tree are staged, commit the merge commit and return True.
        Otherwise, return False.

        """

        if not self.simple_merge_in_progress():
            return False

        # Check if all conflicts are resolved and everything in the
        # working tree is staged:
        self.refresh_index()
        if self.unstaged_changes():
            raise UncleanWorkTreeError(
                'Cannot proceed: You have unstaged changes.'
                )

        # A merge is in progress, and either all changes have been staged
        # or no changes are necessary. Create a merge commit.
        cmd = ['git', 'commit', '--no-verify']

        if edit_log_msg is None:
            edit_log_msg = self.get_default_edit()

        if edit_log_msg:
            cmd += ['--edit']
        else:
            cmd += ['--no-edit']

        try:
            check_call(cmd)
        except CalledProcessError:
            raise Failure('Could not commit staged changes.')

        return True

    def create_commit_chain(self, base, path):
        """Point refname at the chain of commits indicated by path.

        path is a list [(commit, metadata), ...]. Create a series of
        commits corresponding to the entries in path. Each commit's tree
        is taken from the corresponding old commit, and each commit's
        metadata is taken from the corresponding metadata commit. Use base
        as the parent of the first commit, or make the first commit a root
        commit if base is None. Reuse existing commits from the list
        whenever possible.

        Return a commit object corresponding to the last commit in the
        chain.

        """

        reusing = True
        if base is None:
            if not path:
                raise ValueError('neither base nor path specified')
            parents = []
        else:
            parents = [base]

        for (commit, metadata) in path:
            if reusing:
                if commit == metadata and self.get_commit_parents(commit) == parents:
                    # We can reuse this commit, too.
                    parents = [commit]
                    continue
                else:
                    reusing = False

            # Create a commit, copying the old log message and author info
            # from the metadata commit:
            tree = self.get_tree(commit)
            new_commit = self.commit_tree(
                tree, parents,
                msg=self.get_log_message(metadata),
                metadata=self.get_author_info(metadata),
                )
            parents = [new_commit]

        [commit] = parents
        return commit

    def rev_parse(self, arg):
        return check_output(['git', 'rev-parse', '--verify', '--quiet', arg]).strip()

    def rev_list(self, *args):
        cmd = ['git', 'rev-list'] + list(args)
        return [
            l.strip()
            for l in check_output(cmd).splitlines()
            ]

    def rev_list_with_parents(self, *args):
        """Iterate over (commit, [parent,...])."""

        cmd = ['git', 'log', '--format=%H %P'] + list(args)
        for line in check_output(cmd).splitlines():
            commits = line.strip().split()
            yield (commits[0], commits[1:])

    def summarize_commit(self, commit):
        """Summarize `commit` to stdout."""

        check_call(['git', '--no-pager', 'log', '--no-walk', commit])

    def get_author_info(self, commit):
        """Return environment settings to set author metadata.

        Return a map {str : str}."""

        # We use newlines as separators here because msysgit has problems
        # with NUL characters; see
        #
        #     https://github.com/mhagger/git-imerge/pull/71
        a = check_output([
            'git', '--no-pager', 'log', '-n1',
            '--format=%an%n%ae%n%ai', commit
            ]).strip().splitlines()

        return {
            'GIT_AUTHOR_NAME': env_encode(a[0]),
            'GIT_AUTHOR_EMAIL': env_encode(a[1]),
            'GIT_AUTHOR_DATE': env_encode(a[2]),
            }

    def get_log_message(self, commit):
        contents = check_output([
            'git', 'cat-file', 'commit', commit,
            ]).splitlines(True)
        contents = contents[contents.index('\n') + 1:]
        if contents and contents[-1][-1:] != '\n':
            contents.append('\n')
        return ''.join(contents)

    def get_commit_parents(self, commit):
        """Return a list containing the parents of commit."""

        return check_output(
            ['git', '--no-pager', 'log', '--no-walk', '--pretty=format:%P', commit]
            ).strip().split()

    def get_tree(self, arg):
        return self.rev_parse('%s^{tree}' % (arg,))

    def update_ref(self, refname, value, msg, deref=True):
        if deref:
            opt = []
        else:
            opt = ['--no-deref']

        check_call(['git', 'update-ref'] + opt + ['-m', msg, refname, value])

    def delete_ref(self, refname, msg, deref=True):
        if deref:
            opt = []
        else:
            opt = ['--no-deref']

        check_call(['git', 'update-ref'] + opt + ['-m', msg, '-d', refname])

    def delete_imerge_refs(self, name):
        stdin = ''.join(
            'delete %s\n' % (refname,)
            for refname in check_output([
                    'git', 'for-each-ref',
                    '--format=%(refname)',
                    'refs/imerge/%s' % (name,)
                    ]).splitlines()
            )

        process = subprocess.Popen(
            [
                'git', 'update-ref',
                '-m', 'imerge: remove merge %r' % (name,),
                '--stdin',
                ],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
            )
        out = communicate(process, input=stdin)[0]
        retcode = process.poll()
        if retcode:
            sys.stderr.write(
                'Warning: error removing references:\n%s' % (out,)
                )

    def detach(self, msg):
        """Detach HEAD. msg is used for the reflog."""

        self.update_ref('HEAD', 'HEAD^0', msg, deref=False)

    def reset_hard(self, commit):
        check_call(['git', 'reset', '--hard', commit])

    def amend(self):
        check_call(['git', 'commit', '--amend'])

    def abort_merge(self):
        # We don't use "git merge --abort" here because it was
        # only added in git version 1.7.4.
        check_call(['git', 'reset', '--merge'])

    def compute_best_merge_base(self, tip1, tip2):
        try:
            merge_bases = check_output(['git', 'merge-base', '--all', tip1, tip2]).splitlines()
        except CalledProcessError:
            raise Failure('Cannot compute merge base for %r and %r' % (tip1, tip2))
        if not merge_bases:
            raise Failure('%r and %r do not have a common merge base' % (tip1, tip2))
        if len(merge_bases) == 1:
            return merge_bases[0]

        # There are multiple merge bases. The "best" one is the one that
        # is the "closest" to the tips, which we define to be the one with
        # the fewest non-merge commits in "merge_base..tip". (It can be
        # shown that the result is independent of which tip is used in the
        # computation.)
        best_base = best_count = None
        for merge_base in merge_bases:
            cmd = ['git', 'rev-list', '--no-merges', '--count', '%s..%s' % (merge_base, tip1)]
            count = int(check_output(cmd).strip())
            if best_base is None or count < best_count:
                best_base = merge_base
                best_count = count

        return best_base

    def linear_ancestry(self, commit1, commit2, first_parent):
        """Compute a linear ancestry between commit1 and commit2.

        Our goal is to find a linear series of commits connecting
        `commit1` and `commit2`. We do so as follows:

        * If all of the commits in

              git rev-list --ancestry-path commit1..commit2

          are on a linear chain, return that.

        * If there are multiple paths between `commit1` and `commit2` in
          that list of commits, then

          * If `first_parent` is not set, then raise an
            `NonlinearAncestryError` exception.

          * If `first_parent` is set, then, at each merge commit, follow
            the first parent that is in that list of commits.

        Return a list of SHA-1s in 'chronological' order.

        Raise NotFirstParentAncestorError if commit1 is not an ancestor of
        commit2.

        """

        oid1 = self.rev_parse(commit1)
        oid2 = self.rev_parse(commit2)

        parentage = {oid1 : []}
        for (commit, parents) in self.rev_list_with_parents(
                '--ancestry-path', '--topo-order', '%s..%s' % (oid1, oid2)
                ):
            parentage[commit] = parents

        commits = []

        commit = oid2
        while commit != oid1:
            parents = parentage.get(commit, [])

            # Only consider parents that are in the ancestry path:
            included_parents = [
                parent
                for parent in parents
                if parent in parentage
            ]

            if not included_parents:
                raise NotFirstParentAncestorError(commit1, commit2)
            elif len(included_parents) == 1 or first_parent:
                parent = included_parents[0]
            else:
                raise NonlinearAncestryError(commit1, commit2)

            commits.append(commit)
            commit = parent

        commits.reverse()

        return commits

    def get_boundaries(self, tip1, tip2, first_parent):
        """Get the boundaries of an incremental merge.

        Given the tips of two branches that should be merged, return
        (merge_base, commits1, commits2) describing the edges of the
        imerge.  Raise Failure if there are any problems."""

        merge_base = self.compute_best_merge_base(tip1, tip2)

        commits1 = self.linear_ancestry(merge_base, tip1, first_parent)
        if not commits1:
            raise NothingToDoError(tip1, tip2)

        commits2 = self.linear_ancestry(merge_base, tip2, first_parent)
        if not commits2:
            raise NothingToDoError(tip2, tip1)

        return (merge_base, commits1, commits2)

    def get_head_refname(self, short=False):
        """Return the name of the reference that is currently checked out.

        If `short` is set, return it as a branch name. If HEAD is
        currently detached, return None."""

        cmd = ['git', 'symbolic-ref', '--quiet']
        if short:
            cmd += ['--short']
        cmd += ['HEAD']
        try:
            return check_output(cmd).strip()
        except CalledProcessError:
            return None

    def restore_head(self, refname, message):
        check_call(['git', 'symbolic-ref', '-m', message, 'HEAD', refname])
        check_call(['git', 'reset', '--hard'])

    def checkout(self, refname, quiet=False):
        cmd = ['git', 'checkout']
        if quiet:
            cmd += ['--quiet']
        if refname.startswith(GitRepository.BRANCH_PREFIX):
            target = refname[len(GitRepository.BRANCH_PREFIX):]
        else:
            target = '%s^0' % (refname,)
        cmd += [target]
        check_call(cmd)

    def commit_tree(self, tree, parents, msg, metadata=None):
        """Create a commit containing the specified tree.

        metadata can be author or committer information to be added to the
        environment, as str objects; e.g., {'GIT_AUTHOR_NAME' : 'me'}.

        Return the SHA-1 of the new commit object."""

        cmd = ['git', 'commit-tree', tree]
        for parent in parents:
            cmd += ['-p', parent]

        if metadata is not None:
            env = os.environ.copy()
            env.update(metadata)
        else:
            env = os.environ

        process = subprocess.Popen(
            cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            )
        out = communicate(process, input=msg)[0]
        retcode = process.poll()

        if retcode:
            # We don't store the output in the CalledProcessError because
            # the "output" keyword parameter was not supported in Python
            # 2.6:
            raise CalledProcessError(retcode, cmd)

        return out.strip()

    def revert(self, commit):
        """Apply the inverse of commit^..commit to HEAD and commit."""

        cmd = ['git', 'revert', '--no-edit']
        if len(self.get_commit_parents(commit)) > 1:
            cmd += ['-m', '1']
        cmd += [commit]
        check_call(cmd)

    def reparent(self, commit, parent_sha1s, msg=None):
        """Create a new commit object like commit, but with the specified parents.

        commit is the SHA1 of an existing commit and parent_sha1s is a
        list of SHA1s.  Create a new commit exactly like that one, except
        that it has the specified parent commits.  Return the SHA1 of the
        resulting commit object, which is already stored in the object
        database but is not yet referenced by anything.

        If msg is set, then use it as the commit message for the new
        commit."""

        old_commit = check_output(['git', 'cat-file', 'commit', commit])
        separator = old_commit.index('\n\n')
        headers = old_commit[:separator + 1].splitlines(True)
        rest = old_commit[separator + 2:]

        new_commit = StringIO()
        for i in range(len(headers)):
            line = headers[i]
            if line.startswith('tree '):
                new_commit.write(line)
                for parent_sha1 in parent_sha1s:
                    new_commit.write('parent %s\n' % (parent_sha1,))
            elif line.startswith('parent '):
                # Discard old parents:
                pass
            else:
                new_commit.write(line)

        new_commit.write('\n')
        if msg is None:
            new_commit.write(rest)
        else:
            new_commit.write(msg)
            if not msg.endswith('\n'):
                new_commit.write('\n')

        process = subprocess.Popen(
            ['git', 'hash-object', '-t', 'commit', '-w', '--stdin'],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            )
        out = communicate(process, input=new_commit.getvalue())[0]
        retcode = process.poll()
        if retcode:
            raise Failure('Could not reparent commit %s' % (commit,))
        return out.strip()

    def temporary_head(self, message):
        """Return a context manager to manage a temporary HEAD.

        On entry, record the current HEAD state. On exit, restore it.
        message is used for the reflog.

        """

        return GitTemporaryHead(self, message)


class MergeRecord(object):
    # Bits for the flags field:

    # There is a saved successful auto merge:
    SAVED_AUTO = 0x01

    # An auto merge (which may have been unsuccessful) has been done:
    NEW_AUTO = 0x02

    # There is a saved successful manual merge:
    SAVED_MANUAL = 0x04

    # A manual merge (which may have been unsuccessful) has been done:
    NEW_MANUAL = 0x08

    # A merge that is currently blocking the merge frontier:
    BLOCKED = 0x10

    # Some useful bit combinations:
    SAVED = SAVED_AUTO | SAVED_MANUAL
    NEW = NEW_AUTO | NEW_MANUAL

    AUTO = SAVED_AUTO | NEW_AUTO
    MANUAL = SAVED_MANUAL | NEW_MANUAL

    ALLOWED_INITIAL_FLAGS = [
        SAVED_AUTO,
        SAVED_MANUAL,
        NEW_AUTO,
        NEW_MANUAL,
        ]

    def __init__(self, sha1=None, flags=0):
        # The currently believed correct merge, or None if it is
        # unknown or the best attempt was unsuccessful.
        self.sha1 = sha1

        if self.sha1 is None:
            if flags != 0:
                raise ValueError('Initial flags (%s) for sha1=None should be 0' % (flags,))
        elif flags not in self.ALLOWED_INITIAL_FLAGS:
            raise ValueError('Initial flags (%s) is invalid' % (flags,))

        # See bits above.
        self.flags = flags

    def record_merge(self, sha1, source):
        """Record a merge at this position.

        source must be SAVED_AUTO, SAVED_MANUAL, NEW_AUTO, or NEW_MANUAL."""

        if source == self.SAVED_AUTO:
            # SAVED_AUTO is recorded in any case, but only used if it
            # is the only info available.
            if self.flags & (self.MANUAL | self.NEW) == 0:
                self.sha1 = sha1
            self.flags |= source
        elif source == self.NEW_AUTO:
            # NEW_AUTO is silently ignored if any MANUAL value is
            # already recorded.
            if self.flags & self.MANUAL == 0:
                self.sha1 = sha1
                self.flags |= source
        elif source == self.SAVED_MANUAL:
            # SAVED_MANUAL is recorded in any case, but only used if
            # no NEW_MANUAL is available.
            if self.flags & self.NEW_MANUAL == 0:
                self.sha1 = sha1
            self.flags |= source
        elif source == self.NEW_MANUAL:
            # NEW_MANUAL is always used, and also causes NEW_AUTO to
            # be forgotten if present.
            self.sha1 = sha1
            self.flags = (self.flags | source) & ~self.NEW_AUTO
        else:
            raise ValueError('Undefined source: %s' % (source,))

    def record_blocked(self, blocked):
        if blocked:
            self.flags |= self.BLOCKED
        else:
            self.flags &= ~self.BLOCKED

    def is_known(self):
        return self.sha1 is not None

    def is_blocked(self):
        return self.flags & self.BLOCKED != 0

    def is_manual(self):
        return self.flags & self.MANUAL != 0

    def save(self, git, name, i1, i2):
        """If this record has changed, save it."""

        def set_ref(source):
            git.update_ref(
                'refs/imerge/%s/%s/%d-%d' % (name, source, i1, i2),
                self.sha1,
                'imerge %r: Record %s merge' % (name, source,),
                )

        def clear_ref(source):
            git.delete_ref(
                'refs/imerge/%s/%s/%d-%d' % (name, source, i1, i2),
                'imerge %r: Remove obsolete %s merge' % (name, source,),
                )

        if self.flags & self.MANUAL:
            if self.flags & self.AUTO:
                # Any MANUAL obsoletes any AUTO:
                if self.flags & self.SAVED_AUTO:
                    clear_ref('auto')

                self.flags &= ~self.AUTO

            if self.flags & self.NEW_MANUAL:
                # Convert NEW_MANUAL to SAVED_MANUAL.
                if self.sha1:
                    set_ref('manual')
                    self.flags |= self.SAVED_MANUAL
                elif self.flags & self.SAVED_MANUAL:
                    # Delete any existing SAVED_MANUAL:
                    clear_ref('manual')
                    self.flags &= ~self.SAVED_MANUAL
                self.flags &= ~self.NEW_MANUAL

        elif self.flags & self.NEW_AUTO:
            # Convert NEW_AUTO to SAVED_AUTO.
            if self.sha1:
                set_ref('auto')
                self.flags |= self.SAVED_AUTO
            elif self.flags & self.SAVED_AUTO:
                # Delete any existing SAVED_AUTO:
                clear_ref('auto')
                self.flags &= ~self.SAVED_AUTO
            self.flags &= ~self.NEW_AUTO


class UnexpectedMergeFailure(Exception):
    def __init__(self, msg, i1, i2):
        Exception.__init__(self, msg)
        self.i1, self.i2 = i1, i2


class BlockCompleteError(Exception):
    pass


class FrontierBlockedError(Exception):
    def __init__(self, msg, i1, i2):
        Exception.__init__(self, msg)
        self.i1 = i1
        self.i2 = i2


class NotABlockingCommitError(Exception):
    pass


def find_frontier_blocks(block):
    """Iterate over the frontier blocks for the specified block.

    Use bisection to find the blocks. Iterate over the blocks starting
    in the bottom left and ending at the top right. Record in block
    any blockers that we find.

    We make the following assumptions (using Python subscript
    notation):

    0. All of the merges in block[1:,0] and block[0,1:] are
       already known.  (This is an invariant of the Block class.)

    1. If a direct merge can be done between block[i1-1,0] and
       block[0,i2-1], then all of the pairwise merges in
       block[1:i1, 1:i2] can also be done.

    2. If a direct merge fails between block[i1-1,0] and
       block[0,i2-1], then all of the pairwise merges in
       block[i1-1:,i2-1:] would also fail.

    Under these assumptions, the merge frontier is a stepstair
    pattern going from the bottom-left to the top-right, and
    bisection can be used to find the transition between mergeable
    and conflicting in any row or column.

    Of course these assumptions are not rigorously true, so the
    MergeFrontier returned by this function is only an
    approximation of the real merge diagram.  We check for and
    correct such inconsistencies later.

    """

    # Given that these diagrams typically have few blocks, check
    # the end of a range first to see if the whole range can be
    # determined, and fall back to bisection otherwise.  We
    # determine the frontier block by block, starting in the lower
    # left.

    if block.len1 <= 1 or block.len2 <= 1 or block.is_blocked(1, 1):
        return

    if block.is_mergeable(block.len1 - 1, block.len2 - 1):
        # The whole block is mergable!
        yield block
        return

    if not block.is_mergeable(1, 1):
        # There are no mergeable blocks in block; therefore,
        # block[1,1] must itself be unmergeable.  Record that
        # fact:
        block[1, 1].record_blocked(True)
        return

    # At this point, we know that there is at least one mergeable
    # commit in the first column.  Find the height of the success
    # block in column 1:
    i1 = 1
    i2 = find_first_false(
        lambda i: block.is_mergeable(i1, i),
        2, block.len2,
        )

    # Now we know that (1,i2-1) is mergeable but (1,i2) is not;
    # e.g., (i1, i2) is like 'A' (or maybe 'B') in the following
    # diagram (where '*' means mergeable, 'x' means not mergeable,
    # and '?' means indeterminate) and that the merge under 'A' is
    # not mergeable:
    #
    #          i1
    #
    #        0123456
    #      0 *******
    #      1 **?????
    #  i2  2 **?????
    #      3 **?????
    #      4 *Axxxxx
    #      5 *xxxxxx
    #         B

    while True:
        if i2 == 1:
            break

        # At this point in the loop, we know that any blocks to
        # the left of 'A' have already been recorded, (i1, i2-1)
        # is mergeable but (i1, i2) is not; e.g., we are at a
        # place like 'A' in the following diagram:
        #
        #          i1
        #
        #        0123456
        #      0 **|****
        #      1 **|*???
        #  i2  2 **|*???
        #      3 **|Axxx
        #      4 --+xxxx
        #      5 *xxxxxx
        #
        # This implies that (i1, i2) is the first unmergeable
        # commit in a blocker block (though blocker blocks are not
        # recorded explicitly).  It also implies that a mergeable
        # block has its last mergeable commit somewhere in row
        # i2-1; find its width.
        if (
                i1 == block.len1 - 1
                or block.is_mergeable(block.len1 - 1, i2 - 1)
                ):
            yield block[:block.len1, :i2]
            break
        else:
            i1 = find_first_false(
                lambda i: block.is_mergeable(i, i2 - 1),
                i1 + 1, block.len1 - 1,
                )
            yield block[:i1, :i2]

        # At this point in the loop, (i1-1, i2-1) is mergeable but
        # (i1, i2-1) is not; e.g., 'A' in the following diagram:
        #
        #          i1
        #
        #        0123456
        #      0 **|*|**
        #      1 **|*|??
        #  i2  2 --+-+xx
        #      3 **|xxAx
        #      4 --+xxxx
        #      5 *xxxxxx
        #
        # The block ending at (i1-1,i2-1) has just been recorded.
        # Now find the height of the conflict rectangle at column
        # i1 and fill it in:
        if i2 - 1 == 1 or not block.is_mergeable(i1, 1):
            break
        else:
            i2 = find_first_false(
                lambda i: block.is_mergeable(i1, i),
                2, i2 - 1,
                )


class MergeFrontier(object):
    """Represents the merge frontier within a Block.

    A MergeFrontier is represented by a list of SubBlocks, each of
    which is thought to be completely mergeable.  The list is kept in
    normalized form:

    * Only non-empty blocks are retained

    * Blocks are sorted from bottom left to upper right

    * No redundant blocks

    """

    @staticmethod
    def map_known_frontier(block):
        """Return the MergeFrontier describing existing successful merges in block.

        The return value only includes the part that is fully outlined
        and whose outline consists of rectangles reaching back to
        (0,0).

        A blocked commit is *not* considered to be within the
        frontier, even if a merge is registered for it.  Such merges
        must be explicitly unblocked."""

        # FIXME: This algorithm can take combinatorial time, for
        # example if there is a big block of merges that is a dead
        # end:
        #
        #     +++++++
        #     +?+++++
        #     +?+++++
        #     +?+++++
        #     +?*++++
        #
        # The problem is that the algorithm will explore all of the
        # ways of getting to commit *, and the number of paths grows
        # like a binomial coefficient.  The solution would be to
        # remember dead-ends and reject any curves that visit a point
        # to the right of a dead-end.
        #
        # For now we don't intend to allow a situation like this to be
        # created, so we ignore the problem.

        # A list (i1, i2, down) of points in the path so far.  down is
        # True iff the attempted step following this one was
        # downwards.
        path = []

        def create_frontier(path):
            blocks = []
            for ((i1old, i2old, downold), (i1new, i2new, downnew)) in iter_neighbors(path):
                if downold is True and downnew is False:
                    blocks.append(block[:i1new + 1, :i2new + 1])
            return MergeFrontier(block, blocks)

        # Loop invariants:
        #
        # * path is a valid path
        #
        # * (i1, i2) is in block but it not yet added to path
        #
        # * down is True if a step downwards from (i1, i2) has not yet
        #   been attempted
        (i1, i2) = (block.len1 - 1, 0)
        down = True
        while True:
            if down:
                if i2 == block.len2 - 1:
                    # Hit edge of block; can't move down:
                    down = False
                elif (i1, i2 + 1) in block and not block.is_blocked(i1, i2 + 1):
                    # Can move down
                    path.append((i1, i2, True))
                    i2 += 1
                else:
                    # Can't move down.
                    down = False
            else:
                if i1 == 0:
                    # Success!
                    path.append((i1, i2, False))
                    return create_frontier(path)
                elif (i1 - 1, i2) in block and not block.is_blocked(i1 - 1, i2):
                    # Can move left
                    path.append((i1, i2, False))
                    down = True
                    i1 -= 1
                else:
                    # There's no way to go forward; backtrack until we
                    # find a place where we can still try going left:
                    while True:
                        try:
                            (i1, i2, down) = path.pop()
                        except IndexError:
                            # This shouldn't happen because, in the
                            # worst case, there is a valid path across
                            # the top edge of the merge diagram.
                            raise RuntimeError('Block is improperly formed!')
                        if down:
                            down = False
                            break

    @staticmethod
    def compute_by_bisection(block):
        """Return a MergeFrontier instance for block.

        Compute the blocks making up the boundary using bisection. See
        find_frontier_blocks() for more information.

        """

        return MergeFrontier(block, list(find_frontier_blocks(block)))

    def __init__(self, block, blocks=None):
        self.block = block
        self.blocks = self._normalized_blocks(blocks or [])

    def __iter__(self):
        """Iterate over blocks from bottom left to upper right."""

        return iter(self.blocks)

    def __bool__(self):
        """Return True iff this frontier has no completed parts."""

        return bool(self.blocks)

    def __nonzero__(self):
        """Return True iff this frontier has no completed parts."""

        return bool(self.blocks)

    def is_complete(self):
        """Return True iff the frontier covers the whole block."""

        return (
            len(self.blocks) == 1
            and self.blocks[0].len1 == self.block.len1
            and self.blocks[0].len2 == self.block.len2
            )

    # Additional codes used in the 2D array returned from create_diagram()
    FRONTIER_WITHIN = 0x10
    FRONTIER_RIGHT_EDGE = 0x20
    FRONTIER_BOTTOM_EDGE = 0x40
    FRONTIER_MASK = 0x70

    @classmethod
    def default_formatter(cls, node, legend=None):
        def color(node, within):
            if within:
                return AnsiColor.B_GREEN + node + AnsiColor.END
            else:
                return AnsiColor.B_RED + node + AnsiColor.END

        if legend is None:
            legend = ['?', '*', '.', '#', '@', '-', '|', '+']
        merge = node & Block.MERGE_MASK
        within = merge == Block.MERGE_MANUAL or (node & cls.FRONTIER_WITHIN)
        skip = [Block.MERGE_MANUAL, Block.MERGE_BLOCKED, Block.MERGE_UNBLOCKED]
        if merge not in skip:
            vertex = (cls.FRONTIER_BOTTOM_EDGE | cls.FRONTIER_RIGHT_EDGE)
            edge_status = node & vertex
            if edge_status == vertex:
                return color(legend[-1], within)
            elif edge_status == cls.FRONTIER_RIGHT_EDGE:
                return color(legend[-2], within)
            elif edge_status == cls.FRONTIER_BOTTOM_EDGE:
                return color(legend[-3], within)
        return color(legend[merge], within)

    def create_diagram(self):
        """Generate a diagram of this frontier.

        The returned diagram is a nested list of integers forming a 2D array,
        representing the merge frontier embedded in the diagram of commits
        returned from Block.create_diagram().

        At each node in the returned diagram is an integer whose value is a
        bitwise-or of existing MERGE_* constant from Block.create_diagram()
        and zero or more of the FRONTIER_* constants defined in this class."""

        diagram = self.block.create_diagram()

        try:
            next_block = self.blocks[0]
        except IndexError:
            next_block = None

        diagram[0][-1] |= self.FRONTIER_BOTTOM_EDGE
        for i2 in range(1, self.block.len2):
            if next_block is None or i2 >= next_block.len2:
                diagram[0][i2] |= self.FRONTIER_RIGHT_EDGE

        prev_block = None
        for n in range(len(self.blocks)):
            block = self.blocks[n]
            try:
                next_block = self.blocks[n + 1]
            except IndexError:
                next_block = None

            for i1 in range(block.len1):
                for i2 in range(block.len2):
                    v = self.FRONTIER_WITHIN
                    if i1 == block.len1 - 1 and (
                            next_block is None or i2 >= next_block.len2
                            ):
                        v |= self.FRONTIER_RIGHT_EDGE
                    if i2 == block.len2 - 1 and (
                            prev_block is None or i1 >= prev_block.len1
                            ):
                        v |= self.FRONTIER_BOTTOM_EDGE
                    diagram[i1][i2] |= v
            prev_block = block

        try:
            prev_block = self.blocks[-1]
        except IndexError:
            prev_block = None

        for i1 in range(1, self.block.len1):
            if prev_block is None or i1 >= prev_block.len1:
                diagram[i1][0] |= self.FRONTIER_BOTTOM_EDGE
        diagram[-1][0] |= self.FRONTIER_RIGHT_EDGE

        return diagram

    def format_diagram(self, formatter=None, diagram=None):
        if formatter is None:
            formatter = self.default_formatter
        if diagram is None:
            diagram = self.create_diagram()
        return [
            [formatter(diagram[i1][i2]) for i2 in range(self.block.len2)]
            for i1 in range(self.block.len1)]

    def write(self, f):
        """Write this frontier to file-like object f."""
        diagram = self.format_diagram()
        for i2 in range(self.block.len2):
            for i1 in range(self.block.len1):
                f.write(diagram[i1][i2])
            f.write('\n')

    def write_html(self, f, name, cssfile='imerge.css', abbrev_sha1=7):
        class_map = {
            Block.MERGE_UNKNOWN: 'merge_unknown',
            Block.MERGE_MANUAL: 'merge_manual',
            Block.MERGE_AUTOMATIC: 'merge_automatic',
            Block.MERGE_BLOCKED: 'merge_blocked',
            Block.MERGE_UNBLOCKED: 'merge_unblocked',
            self.FRONTIER_WITHIN: 'frontier_within',
            self.FRONTIER_RIGHT_EDGE: 'frontier_right_edge',
            self.FRONTIER_BOTTOM_EDGE: 'frontier_bottom_edge',
            }

        def map_to_classes(i1, i2, node):
            merge = node & Block.MERGE_MASK
            ret = [class_map[merge]]
            for bit in [self.FRONTIER_WITHIN, self.FRONTIER_RIGHT_EDGE,
                        self.FRONTIER_BOTTOM_EDGE]:
                if node & bit:
                    ret.append(class_map[bit])
            if not (node & self.FRONTIER_WITHIN):
                ret.append('frontier_without')
            elif (node & Block.MERGE_MASK) == Block.MERGE_UNKNOWN:
                ret.append('merge_skipped')
            if i1 == 0 or i2 == 0:
                ret.append('merge_initial')
            if i1 == 0:
                ret.append('col_left')
            if i1 == self.block.len1 - 1:
                ret.append('col_right')
            if i2 == 0:
                ret.append('row_top')
            if i2 == self.block.len2 - 1:
                ret.append('row_bottom')
            return ret

        f.write("""\
<html>
<head>
<title>git-imerge: %s</title>
<link rel="stylesheet" href="%s" type="text/css" />
</head>
<body>
<table id="imerge">
""" % (name, cssfile))

        diagram = self.create_diagram()

        f.write('  <tr>\n')
        f.write('    <th class="indexes">&nbsp;</td>\n')
        for i1 in range(self.block.len1):
            f.write('    <th class="indexes">%d-*</td>\n' % (i1,))
        f.write('  </tr>\n')

        for i2 in range(self.block.len2):
            f.write('  <tr>\n')
            f.write('    <th class="indexes">*-%d</td>\n' % (i2,))
            for i1 in range(self.block.len1):
                classes = map_to_classes(i1, i2, diagram[i1][i2])
                record = self.block.get_value(i1, i2)
                sha1 = record.sha1 or ''
                td_id = record.sha1 and ' id="%s"' % (record.sha1) or ''
                td_class = classes and ' class="' + ' '.join(classes) + '"' or ''
                f.write('    <td%s%s>%.*s</td>\n' % (
                        td_id, td_class, abbrev_sha1, sha1))
            f.write('  </tr>\n')
        f.write('</table>\n</body>\n</html>\n')

    @staticmethod
    def _normalized_blocks(blocks):
        """Return a normalized list of blocks from the argument.

        * Remove empty blocks.

        * Remove redundant blocks.

        * Sort the blocks according to their len1 members.

        """

        def contains(block1, block2):
            """Return true if block1 contains block2."""

            return block1.len1 >= block2.len1 and block1.len2 >= block2.len2

        blocks = sorted(blocks, key=lambda block: block.len1)
        ret = []

        for block in blocks:
            if block.len1 == 0 or block.len2 == 0:
                continue
            while True:
                if not ret:
                    ret.append(block)
                    break

                last = ret[-1]
                if contains(last, block):
                    break
                elif contains(block, last):
                    ret.pop()
                else:
                    ret.append(block)
                    break

        return ret

    def remove_failure(self, i1, i2):
        """Refine the merge frontier given that the specified merge fails."""

        newblocks = []
        shrunk_block = False

        for block in self.blocks:
            if i1 < block.len1 and i2 < block.len2:
                if i1 > 1:
                    newblocks.append(block[:i1, :])
                if i2 > 1:
                    newblocks.append(block[:, :i2])
                shrunk_block = True
            else:
                newblocks.append(block)

        if shrunk_block:
            self.blocks = self._normalized_blocks(newblocks)

    def partition(self, block):
        """Return two MergeFrontier instances partitioned by block.

        Return (frontier1, frontier2), where each frontier is limited
        to each side of the argument.

        block must be contained in this MergeFrontier and already be
        outlined."""

        # Remember that the new blocks have to include the outlined
        # edge of the partitioning block to satisfy the invariant that
        # the left and upper edge of a block has to be known.

        left = []
        right = []
        for b in self.blocks:
            if b.len1 == block.len1 and b.len2 == block.len2:
                # That's the block we're partitioning on; just skip it.
                pass
            elif b.len1 < block.len1 and b.len2 > block.len2:
                left.append(b[:, block.len2 - 1:])
            elif b.len1 > block.len1 and b.len2 < block.len2:
                right.append(b[block.len1 - 1:, :])
            else:
                raise ValueError(
                    'MergeFrontier partitioned with inappropriate block'
                    )
        return (
            MergeFrontier(self.block[:block.len1, block.len2 - 1:], left),
            MergeFrontier(self.block[block.len1 - 1:, :block.len2], right),
            )

    def iter_blocker_blocks(self):
        """Iterate over the blocks on the far side of this frontier.

        This must only be called for an outlined frontier."""

        if not self:
            yield self.block
            return

        blockruns = []
        if self.blocks[0].len2 < self.block.len2:
            blockruns.append([self.block[0, :]])
        blockruns.append(self)
        if self.blocks[-1].len1 < self.block.len1:
            blockruns.append([self.block[:, 0]])

        for block1, block2 in iter_neighbors(itertools.chain(*blockruns)):
            yield self.block[block1.len1 - 1:block2.len1, block2.len2 - 1: block1.len2]

    def get_affected_blocker_block(self, i1, i2):
        """Return the blocker block that a successful merge (i1,i2) would unblock.

        If there is no such block, raise NotABlockingCommitError."""

        for block in self.iter_blocker_blocks():
            try:
                (block_i1, block_i2) = block.convert_original_indexes(i1, i2)
            except IndexError:
                pass
            else:
                if (block_i1, block_i2) == (1, 1):
                    # That's the one we need to improve this block:
                    return block
                else:
                    # An index pair can only be in a single blocker
                    # block, which we've already found:
                    raise NotABlockingCommitError(
                        'Commit %d-%d was not blocking the frontier.'
                        % self.block.get_original_indexes(i1, i2)
                        )
        else:
            raise NotABlockingCommitError(
                'Commit %d-%d was not on the frontier.'
                % self.block.get_original_indexes(i1, i2)
                )

    def auto_expand(self):
        """Try pushing out one of the blocks on this frontier.

        Raise BlockCompleteError if the whole block has already been
        solved.  Raise FrontierBlockedError if the frontier is blocked
        everywhere.  This method does *not* update self; if it returns
        successfully you should recompute the frontier from
        scratch."""

        blocks = list(self.iter_blocker_blocks())
        if not blocks:
            raise BlockCompleteError('The block is already complete')

        # Try blocks from left to right:
        blocks.sort(key=lambda block: block.get_original_indexes(0, 0))

        for block in blocks:
            if block.auto_expand_frontier():
                return
        else:
            # None of the blocks could be expanded.  Suggest that the
            # caller do a manual merge of the commit that is blocking
            # the leftmost blocker block.
            i1, i2 = blocks[0].get_original_indexes(1, 1)
            raise FrontierBlockedError(
                'Conflict; suggest manual merge of %d-%d' % (i1, i2),
                i1, i2
                )


class NoManualMergeError(Exception):
    pass


class ManualMergeUnusableError(Exception):
    def __init__(self, msg, commit):
        Exception.__init__(self, 'Commit %s is not usable; %s' % (commit, msg))
        self.commit = commit


class CommitNotFoundError(Exception):
    def __init__(self, commit):
        Exception.__init__(
            self,
            'Commit %s was not found among the known merge commits' % (commit,),
            )
        self.commit = commit


class Block(object):
    """A rectangular range of commits, indexed by (i1,i2).

    The commits block[0,1:] and block[1:,0] are always all known.
    block[0,0] may or may not be known; it is usually unneeded (except
    maybe implicitly).

    Members:

        name -- the name of the imerge of which this block is part.

        len1, len2 -- the dimensions of the block.

    """

    def __init__(self, git, name, len1, len2):
        self.git = git
        self.name = name
        self.len1 = len1
        self.len2 = len2

    def get_merge_state(self):
        """Return the MergeState instance containing this Block."""

        raise NotImplementedError()

    def get_area(self):
        """Return the area of this block, ignoring the known edges."""

        return (self.len1 - 1) * (self.len2 - 1)

    def _check_indexes(self, i1, i2):
        if not (0 <= i1 < self.len1):
            raise IndexError('first index (%s) is out of range 0:%d' % (i1, self.len1,))
        if not (0 <= i2 < self.len2):
            raise IndexError('second index (%s) is out of range 0:%d' % (i2, self.len2,))

    def _normalize_indexes(self, index):
        """Return a pair of non-negative integers (i1, i2)."""

        try:
            (i1, i2) = index
        except TypeError:
            raise IndexError('Block indexing requires exactly two indexes')

        if i1 < 0:
            i1 += self.len1
        if i2 < 0:
            i2 += self.len2

        self._check_indexes(i1, i2)
        return (i1, i2)

    def get_original_indexes(self, i1, i2):
        """Return the original indexes corresponding to (i1,i2) in this block.

        This function supports negative indexes."""

        return self._normalize_indexes((i1, i2))

    def convert_original_indexes(self, i1, i2):
        """Return the indexes in this block corresponding to original indexes (i1,i2).

        raise IndexError if they are not within this block.  This
        method does not support negative indices."""

        return (i1, i2)

    def _set_value(self, i1, i2, value):
        """Set the MergeRecord for integer indexes (i1, i2).

        i1 and i2 must be non-negative."""

        raise NotImplementedError()

    def get_value(self, i1, i2):
        """Return the MergeRecord for integer indexes (i1, i2).

        i1 and i2 must be non-negative."""

        raise NotImplementedError()

    def __getitem__(self, index):
        """Return the MergeRecord at (i1, i2) (requires two indexes).

        If i1 and i2 are integers but the merge is unknown, return
        None.  If either index is a slice, return a SubBlock."""

        try:
            (i1, i2) = index
        except TypeError:
            raise IndexError('Block indexing requires exactly two indexes')
        if isinstance(i1, slice) or isinstance(i2, slice):
            return SubBlock(self, i1, i2)
        else:
            return self.get_value(*self._normalize_indexes((i1, i2)))

    def __contains__(self, index):
        return self[index].is_known()

    def is_blocked(self, i1, i2):
        """Return True iff the specified commit is blocked."""

        (i1, i2) = self._normalize_indexes((i1, i2))
        return self[i1, i2].is_blocked()

    def is_mergeable(self, i1, i2):
        """Determine whether (i1,i2) can be merged automatically.

        If we already have a merge record for (i1,i2), return True.
        Otherwise, attempt a merge (discarding the result)."""

        (i1, i2) = self._normalize_indexes((i1, i2))
        if (i1, i2) in self:
            return True
        else:
            sys.stderr.write(
                'Attempting automerge of %d-%d...' % self.get_original_indexes(i1, i2)
                )
            try:
                self.git.automerge(self[i1, 0].sha1, self[0, i2].sha1)
                sys.stderr.write('success.\n')
                return True
            except AutomaticMergeFailed:
                sys.stderr.write('failure.\n')
                return False

    def auto_outline(self):
        """Complete the outline of this Block.

        raise UnexpectedMergeFailure if automerging fails."""

        # Check that all of the merges go through before recording any
        # of them permanently.
        merges = []

        def do_merge(i1, commit1, i2, commit2, msg='Autofilling %d-%d...', record=True):
            if (i1, i2) in self:
                return self[i1, i2].sha1
            (i1orig, i2orig) = self.get_original_indexes(i1, i2)
            sys.stderr.write(msg % (i1orig, i2orig))
            logmsg = 'imerge \'%s\': automatic merge %d-%d' % (self.name, i1orig, i2orig)
            try:
                merge = self.git.automerge(commit1, commit2, msg=logmsg)
                sys.stderr.write('success.\n')
            except AutomaticMergeFailed as e:
                sys.stderr.write('unexpected conflict.  Backtracking...\n')
                raise UnexpectedMergeFailure(str(e), i1, i2)
            if record:
                merges.append((i1, i2, merge))
            return merge

        i2 = self.len2 - 1
        left = self[0, i2].sha1
        for i1 in range(1, self.len1 - 1):
            left = do_merge(i1, self[i1, 0].sha1, i2, left)

        i1 = self.len1 - 1
        above = self[i1, 0].sha1
        for i2 in range(1, self.len2 - 1):
            above = do_merge(i1, above, i2, self[0, i2].sha1)

        i1, i2 = self.len1 - 1, self.len2 - 1
        if i1 > 1 and i2 > 1:
            # We will compare two ways of doing the final "vertex" merge:
            # as a continuation of the bottom edge, or as a continuation
            # of the right edge.  We only accept it if both approaches
            # succeed and give identical trees.
            vertex_v1 = do_merge(
                i1, self[i1, 0].sha1, i2, left,
                msg='Autofilling %d-%d (first way)...',
                record=False,
                )
            vertex_v2 = do_merge(
                i1, above, i2, self[0, i2].sha1,
                msg='Autofilling %d-%d (second way)...',
                record=False,
                )
            if self.git.get_tree(vertex_v1) == self.git.get_tree(vertex_v2):
                sys.stderr.write(
                    'The two ways of autofilling %d-%d agree.\n'
                    % self.get_original_indexes(i1, i2)
                    )
                # Everything is OK.  Now reparent the actual vertex merge to
                # have above and left as its parents:
                merges.append(
                    (i1, i2, self.git.reparent(vertex_v1, [above, left]))
                    )
            else:
                sys.stderr.write(
                    'The two ways of autofilling %d-%d do not agree.  Backtracking...\n'
                    % self.get_original_indexes(i1, i2)
                    )
                raise UnexpectedMergeFailure('Inconsistent vertex merges', i1, i2)
        else:
            do_merge(
                i1, above, i2, left,
                msg='Autofilling %d-%d...',
                )

        # Done!  Now we can record the results:
        sys.stderr.write('Recording autofilled block %s.\n' % (self,))
        for (i1, i2, merge) in merges:
            self[i1, i2].record_merge(merge, MergeRecord.NEW_AUTO)

    def auto_fill_micromerge(self):
        """Try to fill the very first micromerge in this block.

        Return True iff the attempt was successful."""

        assert (1, 1) not in self
        if self.len1 <= 1 or self.len2 <= 1 or self.is_blocked(1, 1):
            return False

        i1, i2 = 1, 1
        (i1orig, i2orig) = self.get_original_indexes(i1, i2)
        sys.stderr.write('Attempting to merge %d-%d...' % (i1orig, i2orig))
        logmsg = 'imerge \'%s\': automatic merge %d-%d' % (self.name, i1orig, i2orig)
        try:
            merge = self.git.automerge(
                self[i1, i2 - 1].sha1,
                self[i1 - 1, i2].sha1,
                msg=logmsg,
                )
            sys.stderr.write('success.\n')
        except AutomaticMergeFailed:
            sys.stderr.write('conflict.\n')
            self[i1, i2].record_blocked(True)
            return False
        else:
            self[i1, i2].record_merge(merge, MergeRecord.NEW_AUTO)
            return True

    def auto_outline_frontier(self, merge_frontier=None):
        """Try to outline the merge frontier of this block.

        Return True iff some progress was made."""

        if merge_frontier is None:
            merge_frontier = MergeFrontier.compute_by_bisection(self)

        if not merge_frontier:
            # Nothing to do.
            return False

        best_block = max(merge_frontier, key=lambda block: block.get_original_indexes(0, 0))

        try:
            best_block.auto_outline()
        except UnexpectedMergeFailure as e:
            # One of the merges that we expected to succeed in
            # fact failed.
            merge_frontier.remove_failure(e.i1, e.i2)
            return self.auto_outline_frontier(merge_frontier)
        else:
            f1, f2 = merge_frontier.partition(best_block)
            if f1:
                f1.block.auto_outline_frontier(f1)
            if f2:
                f2.block.auto_outline_frontier(f2)
            return True

    def auto_expand_frontier(self):
        merge_state = self.get_merge_state()
        if merge_state.manual:
            return False
        elif merge_state.goal == 'full':
            return self.auto_fill_micromerge()
        else:
            return self.auto_outline_frontier()

    # The codes in the 2D array returned from create_diagram()
    MERGE_UNKNOWN = 0
    MERGE_MANUAL = 1
    MERGE_AUTOMATIC = 2
    MERGE_BLOCKED = 3
    MERGE_UNBLOCKED = 4
    MERGE_MASK = 7

    # A map {(is_known(), manual, is_blocked()) : integer constant}
    MergeState = {
        (False, False, False): MERGE_UNKNOWN,
        (False, False, True): MERGE_BLOCKED,
        (True, False, True): MERGE_UNBLOCKED,
        (True, True, True): MERGE_UNBLOCKED,
        (True, False, False): MERGE_AUTOMATIC,
        (True, True, False): MERGE_MANUAL,
        }

    def create_diagram(self):
        """Generate a diagram of this Block.

        The returned diagram, is a nested list of integers forming a 2D array,
        where the integer at diagram[i1][i2] is one of MERGE_UNKNOWN,
        MERGE_MANUAL, MERGE_AUTOMATIC, MERGE_BLOCKED, or MERGE_UNBLOCKED,
        representing the state of the commit at (i1, i2)."""

        diagram = [[None for i2 in range(self.len2)] for i1 in range(self.len1)]

        for i2 in range(self.len2):
            for i1 in range(self.len1):
                rec = self.get_value(i1, i2)
                c = self.MergeState[
                    rec.is_known(), rec.is_manual(), rec.is_blocked()]
                diagram[i1][i2] = c

        return diagram

    def format_diagram(self, legend=None, diagram=None):
        if legend is None:
            legend = [
                AnsiColor.D_GRAY + '?' + AnsiColor.END,
                AnsiColor.B_GREEN + '*' + AnsiColor.END,
                AnsiColor.B_GREEN + '.' + AnsiColor.END,
                AnsiColor.B_RED + '#' + AnsiColor.END,
                AnsiColor.B_YELLOW + '@' + AnsiColor.END,
                ]
        if diagram is None:
            diagram = self.create_diagram()
        return [
            [legend[diagram[i1][i2]] for i2 in range(self.len2)]
            for i1 in range(self.len1)]

    def write(self, f, legend=None, sep='', linesep='\n'):
        diagram = self.format_diagram(legend)
        for i2 in range(self.len2):
            f.write(sep.join(diagram[i1][i2] for i1 in range(self.len1)) + linesep)

    def writeppm(self, f):
        f.write('P3\n')
        f.write('%d %d 255\n' % (self.len1, self.len2,))
        legend = ['127 127 0', '0 255 0', '0 127 0', '255 0 0', '127 0 0']
        self.write(f, legend, sep='  ')


class SubBlock(Block):
    @staticmethod
    def _convert_to_slice(i, len):
        """Return (start, len) for the specified index.

        i may be an integer or a slice with step equal to 1."""

        if isinstance(i, int):
            if i < 0:
                i += len
            i = slice(i, i + 1)
        elif isinstance(i, slice):
            if i.step is not None and i.step != 1:
                raise ValueError('Index has a non-zero step size')
        else:
            raise ValueError('Index cannot be converted to a slice')

        (start, stop, step) = i.indices(len)
        return (start, stop - start)

    def __init__(self, block, slice1, slice2):
        (start1, len1) = self._convert_to_slice(slice1, block.len1)
        (start2, len2) = self._convert_to_slice(slice2, block.len2)
        Block.__init__(self, block.git, block.name, len1, len2)
        if isinstance(block, SubBlock):
            # Peel away one level of indirection:
            self._merge_state = block._merge_state
            self._start1 = start1 + block._start1
            self._start2 = start2 + block._start2
        else:
            assert(isinstance(block, MergeState))
            self._merge_state = block
            self._start1 = start1
            self._start2 = start2

    def get_merge_state(self):
        return self._merge_state

    def get_original_indexes(self, i1, i2):
        i1, i2 = self._normalize_indexes((i1, i2))
        return self._merge_state.get_original_indexes(
            i1 + self._start1,
            i2 + self._start2,
            )

    def convert_original_indexes(self, i1, i2):
        (i1, i2) = self._merge_state.convert_original_indexes(i1, i2)
        if not (
                self._start1 <= i1 < self._start1 + self.len1
                and self._start2 <= i2 < self._start2 + self.len2
                ):
            raise IndexError('Indexes are not within block')
        return (i1 - self._start1, i2 - self._start2)

    def _set_value(self, i1, i2, sha1, flags):
        self._check_indexes(i1, i2)
        self._merge_state._set_value(
            i1 + self._start1,
            i2 + self._start2,
            sha1, flags,
            )

    def get_value(self, i1, i2):
        self._check_indexes(i1, i2)
        return self._merge_state.get_value(i1 + self._start1, i2 + self._start2)

    def __str__(self):
        return '%s[%d:%d,%d:%d]' % (
            self._merge_state,
            self._start1, self._start1 + self.len1,
            self._start2, self._start2 + self.len2,
            )


class MissingMergeFailure(Failure):
    def __init__(self, i1, i2):
        Failure.__init__(self, 'Merge %d-%d is not yet done' % (i1, i2))
        self.i1 = i1
        self.i2 = i2


class MergeState(Block):
    SOURCE_TABLE = {
        'auto': MergeRecord.SAVED_AUTO,
        'manual': MergeRecord.SAVED_MANUAL,
        }

    @staticmethod
    def get_scratch_refname(name):
        return 'refs/heads/imerge/%s' % (name,)

    @staticmethod
    def _check_no_merges(git, commits):
        multiparent_commits = [
            commit
            for commit in commits
            if len(git.get_commit_parents(commit)) > 1
            ]
        if multiparent_commits:
            raise Failure(
                'The following commits on the to-be-merged branch are merge commits:\n'
                '    %s\n'
                '--goal=\'rebase\' is not yet supported for branches that include merges.\n'
                % ('\n    '.join(multiparent_commits),)
                )

    @staticmethod
    def initialize(
            git, name, merge_base,
            tip1, commits1,
            tip2, commits2,
            goal=DEFAULT_GOAL, goalopts=None,
            manual=False, branch=None,
            ):
        """Create and return a new MergeState object."""

        git.verify_imerge_name_available(name)
        if branch:
            git.check_branch_name_format(branch)
        else:
            branch = name

        if goal == 'rebase':
            MergeState._check_no_merges(git, commits2)

        return MergeState(
            git, name, merge_base,
            tip1, commits1,
            tip2, commits2,
            MergeRecord.NEW_MANUAL,
            goal=goal, goalopts=goalopts,
            manual=manual,
            branch=branch,
            )

    @staticmethod
    def read(git, name):
        (state, merges) = git.read_imerge_state(name)

        # Translate sources from strings into MergeRecord constants
        # SAVED_AUTO or SAVED_MANUAL:
        merges = dict((
            ((i1, i2), (sha1, MergeState.SOURCE_TABLE[source]))
            for ((i1, i2), (sha1, source)) in merges.items()
            ))

        blockers = state.get('blockers', [])

        # Find merge_base, commits1, and commits2:
        (merge_base, source) = merges.pop((0, 0))
        if source != MergeRecord.SAVED_MANUAL:
            raise Failure('Merge base should be manual!')
        commits1 = []
        for i1 in itertools.count(1):
            try:
                (sha1, source) = merges.pop((i1, 0))
                if source != MergeRecord.SAVED_MANUAL:
                    raise Failure('Merge %d-0 should be manual!' % (i1,))
                commits1.append(sha1)
            except KeyError:
                break

        commits2 = []
        for i2 in itertools.count(1):
            try:
                (sha1, source) = merges.pop((0, i2))
                if source != MergeRecord.SAVED_MANUAL:
                    raise Failure('Merge (0,%d) should be manual!' % (i2,))
                commits2.append(sha1)
            except KeyError:
                break

        tip1 = state.get('tip1', commits1[-1])
        tip2 = state.get('tip2', commits2[-1])

        goal = state['goal']
        if goal not in ALLOWED_GOALS:
            raise Failure('Goal %r, read from state, is not recognized.' % (goal,))

        goalopts = state['goalopts']

        manual = state['manual']
        branch = state.get('branch', name)

        state = MergeState(
            git, name, merge_base,
            tip1, commits1,
            tip2, commits2,
            MergeRecord.SAVED_MANUAL,
            goal=goal, goalopts=goalopts,
            manual=manual,
            branch=branch,
            )

        # Now write the rest of the merges to state:
        for ((i1, i2), (sha1, source)) in merges.items():
            if i1 == 0 and i2 >= state.len2:
                raise Failure('Merge 0-%d is missing!' % (state.len2,))
            if i1 >= state.len1 and i2 == 0:
                raise Failure('Merge %d-0 is missing!' % (state.len1,))
            if i1 >= state.len1 or i2 >= state.len2:
                raise Failure(
                    'Merge %d-%d is out of range [0:%d,0:%d]'
                    % (i1, i2, state.len1, state.len2)
                    )
            state[i1, i2].record_merge(sha1, source)

        # Record any blockers:
        for (i1, i2) in blockers:
            state[i1, i2].record_blocked(True)

        return state

    @staticmethod
    def remove(git, name):
        # If HEAD is the scratch refname, abort any in-progress
        # commits and detach HEAD:
        scratch_refname = MergeState.get_scratch_refname(name)
        if git.get_head_refname() == scratch_refname:
            try:
                git.abort_merge()
            except CalledProcessError:
                pass
            # Detach head so that we can delete scratch_refname:
            git.detach('Detach HEAD from %s' % (scratch_refname,))

        # Delete the scratch refname:
        git.delete_ref(
            scratch_refname, 'imerge %s: remove scratch reference' % (name,),
            )

        # Remove any references referring to intermediate merges:
        git.delete_imerge_refs(name)

        # If this merge was the default, unset the default:
        if git.get_default_imerge_name() == name:
            git.set_default_imerge_name(None)

    def __init__(
            self, git, name, merge_base,
            tip1, commits1,
            tip2, commits2,
            source,
            goal=DEFAULT_GOAL, goalopts=None,
            manual=False,
            branch=None,
            ):
        Block.__init__(self, git, name, len(commits1) + 1, len(commits2) + 1)
        self.tip1 = tip1
        self.tip2 = tip2
        self.goal = goal
        self.goalopts = goalopts
        self.manual = bool(manual)
        self.branch = branch or name

        # A simulated 2D array.  Values are None or MergeRecord instances.
        self._data = [[None] * self.len2 for i1 in range(self.len1)]

        self.get_value(0, 0).record_merge(merge_base, source)
        for (i1, commit) in enumerate(commits1, 1):
            self.get_value(i1, 0).record_merge(commit, source)
        for (i2, commit) in enumerate(commits2, 1):
            self.get_value(0, i2).record_merge(commit, source)

    def get_merge_state(self):
        return self

    def set_goal(self, goal):
        if goal not in ALLOWED_GOALS:
            raise ValueError('%r is not an allowed goal' % (goal,))

        if goal == 'rebase':
            self._check_no_merges(
                self.git,
                [self[0, i2].sha1 for i2 in range(1, self.len2)],
                )

        self.goal = goal

    def _set_value(self, i1, i2, value):
        self._data[i1][i2] = value

    def get_value(self, i1, i2):
        value = self._data[i1][i2]
        # Missing values spring to life on first access:
        if value is None:
            value = MergeRecord()
            self._data[i1][i2] = value
        return value

    def __contains__(self, index):
        # Avoid creating new MergeRecord objects here.
        (i1, i2) = self._normalize_indexes(index)
        value = self._data[i1][i2]
        return (value is not None) and value.is_known()

    def auto_complete_frontier(self):
        """Complete the frontier using automerges.

        If progress is blocked before the frontier is complete, raise
        a FrontierBlockedError.  Save the state as progress is
        made."""

        progress_made = False
        try:
            while True:
                frontier = MergeFrontier.map_known_frontier(self)
                frontier.auto_expand()
                self.save()
                progress_made = True
        except BlockCompleteError:
            return
        except FrontierBlockedError as e:
            self.save()
            if not progress_made:
                # Adjust the error message:
                raise FrontierBlockedError(
                    'No progress was possible; suggest manual merge of %d-%d'
                    % (e.i1, e.i2),
                    e.i1, e.i2,
                    )
            else:
                raise

    def find_index(self, commit):
        """Return (i1,i2) for the specified commit.

        Raise CommitNotFoundError if it is not known."""

        for i2 in range(0, self.len2):
            for i1 in range(0, self.len1):
                if (i1, i2) in self:
                    record = self[i1, i2]
                    if record.sha1 == commit:
                        return (i1, i2)
        raise CommitNotFoundError(commit)

    def request_user_merge(self, i1, i2):
        """Prepare the working tree for the user to do a manual merge.

        It is assumed that the merges above and to the left of (i1, i2)
        are already done."""

        above = self[i1, i2 - 1]
        left = self[i1 - 1, i2]
        if not above.is_known() or not left.is_known():
            raise RuntimeError('The parents of merge %d-%d are not ready' % (i1, i2))
        refname = MergeState.get_scratch_refname(self.name)
        self.git.update_ref(
            refname, above.sha1,
            'imerge %r: Prepare merge %d-%d' % (self.name, i1, i2,),
            )
        self.git.checkout(refname)
        logmsg = 'imerge \'%s\': manual merge %d-%d' % (self.name, i1, i2)
        try:
            self.git.manualmerge(left.sha1, logmsg)
        except CalledProcessError:
            # We expect an error (otherwise we would have automerged!)
            pass
        sys.stderr.write(
            '\n'
            'Original first commit:\n'
            )
        self.git.summarize_commit(self[i1, 0].sha1)
        sys.stderr.write(
            '\n'
            'Original second commit:\n'
            )
        self.git.summarize_commit(self[0, i2].sha1)
        sys.stderr.write(
            '\n'
            'There was a conflict merging commit %d-%d, shown above.\n'
            'Please resolve the conflict, commit the result, then type\n'
            '\n'
            '    git-imerge continue\n'
            % (i1, i2)
            )

    def incorporate_manual_merge(self, commit):
        """Record commit as a manual merge of its parents.

        Return the indexes (i1,i2) where it was recorded.  If the
        commit is not usable for some reason, raise
        ManualMergeUnusableError."""

        parents = self.git.get_commit_parents(commit)
        if len(parents) < 2:
            raise ManualMergeUnusableError('it is not a merge', commit)
        if len(parents) > 2:
            raise ManualMergeUnusableError('it is an octopus merge', commit)
        # Find the parents among our contents...
        try:
            (i1first, i2first) = self.find_index(parents[0])
            (i1second, i2second) = self.find_index(parents[1])
        except CommitNotFoundError:
            raise ManualMergeUnusableError(
                'its parents are not known merge commits', commit,
                )
        swapped = False
        if i1first < i1second:
            # Swap parents to make the parent from above the first parent:
            (i1first, i2first, i1second, i2second) = (i1second, i2second, i1first, i2first)
            swapped = True
        if i1first != i1second + 1 or i2first != i2second - 1:
            raise ManualMergeUnusableError(
                'it is not a pairwise merge of adjacent parents', commit,
                )
        if swapped:
            # Create a new merge with the parents in the conventional order:
            commit = self.git.reparent(commit, [parents[1], parents[0]])

        i1, i2 = i1first, i2second
        self[i1, i2].record_merge(commit, MergeRecord.NEW_MANUAL)
        return (i1, i2)

    def incorporate_user_merge(self, edit_log_msg=None):
        """If the user has done a merge for us, incorporate the results.

        If the scratch reference refs/heads/imerge/NAME exists and is
        checked out, first check if there are staged changes that can
        be committed. Then try to incorporate the current commit into
        this MergeState, delete the reference, and return (i1,i2)
        corresponding to the merge. If the scratch reference does not
        exist, raise NoManualMergeError(). If the scratch reference
        exists but cannot be used, raise a ManualMergeUnusableError.
        If there are unstaged changes in the working tree, emit an
        error message and raise UncleanWorkTreeError.

        """

        refname = MergeState.get_scratch_refname(self.name)

        try:
            commit = self.git.get_commit_sha1(refname)
        except ValueError:
            raise NoManualMergeError('Reference %s does not exist.' % (refname,))

        head_name = self.git.get_head_refname()
        if head_name is None:
            raise NoManualMergeError('HEAD is currently detached.')
        elif head_name != refname:
            # This should not usually happen.  The scratch reference
            # exists, but it is not current.  Perhaps the user gave up on
            # an attempted merge then switched to another branch.  We want
            # to delete refname, but only if it doesn't contain any
            # content that we don't already know.
            try:
                self.find_index(commit)
            except CommitNotFoundError:
                # It points to a commit that we don't have in our records.
                raise Failure(
                    'The scratch reference, %(refname)s, already exists but is not\n'
                    'checked out.  If it points to a merge commit that you would like\n'
                    'to use, please check it out using\n'
                    '\n'
                    '    git checkout %(refname)s\n'
                    '\n'
                    'and then try to continue again.  If it points to a commit that is\n'
                    'unneeded, then please delete the reference using\n'
                    '\n'
                    '    git update-ref -d %(refname)s\n'
                    '\n'
                    'and then continue.'
                    % dict(refname=refname)
                    )
            else:
                # It points to a commit that is already recorded.  We can
                # delete it without losing any information.
                self.git.delete_ref(
                    refname,
                    'imerge %r: Remove obsolete scratch reference' % (self.name,),
                    )
                sys.stderr.write(
                    '%s did not point to a new merge; it has been deleted.\n'
                    % (refname,)
                    )
                raise NoManualMergeError(
                    'Reference %s was not checked out.' % (refname,)
                    )

        # If we reach this point, then the scratch reference exists and is
        # checked out.  Now check whether there is staged content that
        # can be committed:
        if self.git.commit_user_merge(edit_log_msg=edit_log_msg):
            commit = self.git.get_commit_sha1('HEAD')

        self.git.require_clean_work_tree('proceed')

        merge_frontier = MergeFrontier.map_known_frontier(self)

        # This might throw ManualMergeUnusableError:
        (i1, i2) = self.incorporate_manual_merge(commit)

        # Now detach head so that we can delete refname.
        self.git.detach('Detach HEAD from %s' % (refname,))

        self.git.delete_ref(
            refname, 'imerge %s: remove scratch reference' % (self.name,),
            )

        try:
            # This might throw NotABlockingCommitError:
            unblocked_block = merge_frontier.get_affected_blocker_block(i1, i2)
            unblocked_block[1, 1].record_blocked(False)
            sys.stderr.write(
                'Merge has been recorded for merge %d-%d.\n'
                % unblocked_block.get_original_indexes(1, 1)
                )
        except NotABlockingCommitError:
            raise
        finally:
            self.save()

    def _set_refname(self, refname, commit, force=False):
        try:
            ref_oldval = self.git.get_commit_sha1(refname)
        except ValueError:
            # refname doesn't already exist; simply point it at commit:
            self.git.update_ref(refname, commit, 'imerge: recording final merge')
            self.git.checkout(refname, quiet=True)
        else:
            # refname already exists.  This has two ramifications:
            # 1. HEAD might point at it
            # 2. We may only fast-forward it (unless force is set)
            head_refname = self.git.get_head_refname()

            if not force and not self.git.is_ancestor(ref_oldval, commit):
                raise Failure(
                    '%s cannot be fast-forwarded to %s!' % (refname, commit)
                    )

            if head_refname == refname:
                self.git.reset_hard(commit)
            else:
                self.git.update_ref(
                    refname, commit, 'imerge: recording final merge',
                    )
                self.git.checkout(refname, quiet=True)

    def simplify_to_full(self, refname, force=False):
        for i1 in range(1, self.len1):
            for i2 in range(1, self.len2):
                if not (i1, i2) in self:
                    raise Failure(
                        'Cannot simplify to "full" because '
                        'merge %d-%d is not yet done'
                        % (i1, i2)
                        )

        self._set_refname(refname, self[-1, -1].sha1, force=force)

    def simplify_to_rebase_with_history(self, refname, force=False):
        i1 = self.len1 - 1
        for i2 in range(1, self.len2):
            if not (i1, i2) in self:
                raise Failure(
                    'Cannot simplify to rebase-with-history because '
                    'merge %d-%d is not yet done'
                    % (i1, i2)
                    )

        commit = self[i1, 0].sha1
        for i2 in range(1, self.len2):
            orig = self[0, i2].sha1
            tree = self.git.get_tree(self[i1, i2].sha1)

            # Create a commit, copying the old log message:
            msg = (
                self.git.get_log_message(orig).rstrip('\n')
                + '\n\n(rebased-with-history from commit %s)\n' % orig
                )
            commit = self.git.commit_tree(tree, [commit, orig], msg=msg)

        self._set_refname(refname, commit, force=force)

    def simplify_to_border(
            self, refname,
            with_history1=False, with_history2=False, force=False,
            ):
        i1 = self.len1 - 1
        for i2 in range(1, self.len2):
            if not (i1, i2) in self:
                raise Failure(
                    'Cannot simplify to border because '
                    'merge %d-%d is not yet done'
                    % (i1, i2)
                    )

        i2 = self.len2 - 1
        for i1 in range(1, self.len1):
            if not (i1, i2) in self:
                raise Failure(
                    'Cannot simplify to border because '
                    'merge %d-%d is not yet done'
                    % (i1, i2)
                    )

        i1 = self.len1 - 1
        commit = self[i1, 0].sha1
        for i2 in range(1, self.len2 - 1):
            orig = self[0, i2].sha1
            tree = self.git.get_tree(self[i1, i2].sha1)

            # Create a commit, copying the old log message:
            if with_history2:
                parents = [commit, orig]
                msg = (
                    self.git.get_log_message(orig).rstrip('\n')
                    + '\n\n(rebased-with-history from commit %s)\n' % (orig,)
                    )
            else:
                parents = [commit]
                msg = (
                    self.git.get_log_message(orig).rstrip('\n')
                    + '\n\n(rebased from commit %s)\n' % (orig,)
                    )

            commit = self.git.commit_tree(tree, parents, msg=msg)
        commit1 = commit

        i2 = self.len2 - 1
        commit = self[0, i2].sha1
        for i1 in range(1, self.len1 - 1):
            orig = self[i1, 0].sha1
            tree = self.git.get_tree(self[i1, i2].sha1)

            # Create a commit, copying the old log message:
            if with_history1:
                parents = [orig, commit]
                msg = (
                    self.git.get_log_message(orig).rstrip('\n')
                    + '\n\n(rebased-with-history from commit %s)\n' % (orig,)
                    )
            else:
                parents = [commit]
                msg = (
                    self.git.get_log_message(orig).rstrip('\n')
                    + '\n\n(rebased from commit %s)\n' % (orig,)
                    )

            commit = self.git.commit_tree(tree, parents, msg=msg)
        commit2 = commit

        # Construct the apex commit:
        tree = self.git.get_tree(self[-1, -1].sha1)
        msg = (
            'Merge %s into %s (using imerge border)'
            % (self.tip2, self.tip1)
            )

        commit = self.git.commit_tree(tree, [commit1, commit2], msg=msg)

        # Update the reference:
        self._set_refname(refname, commit, force=force)

    def _simplify_to_path(self, refname, base, path, force=False):
        """Simplify based on path and set refname to the result.

        The base and path arguments are defined similarly to
        create_commit_chain(), except that instead of SHA-1s they may
        optionally represent commits via (i1, i2) tuples.

        """

        def to_sha1(arg):
            if type(arg) is tuple:
                commit_record = self[arg]
                if not commit_record.is_known():
                    raise MissingMergeFailure(*arg)
                return commit_record.sha1
            else:
                return arg

        base_sha1 = to_sha1(base)
        path_sha1 = []
        for (commit, metadata) in path:
            commit_sha1 = to_sha1(commit)
            metadata_sha1 = to_sha1(metadata)
            path_sha1.append((commit_sha1, metadata_sha1))

        # A path simplification is allowed to discard history, as long
        # as the *pre-simplification* apex commit is a descendant of
        # the branch to be moved.
        if path:
            apex = path_sha1[-1][0]
        else:
            apex = base_sha1

        if not force and not self.git.is_ff(refname, apex):
            raise Failure(
                '%s cannot be updated to %s without discarding history.\n'
                'Use --force if you are sure, or choose a different reference'
                % (refname, apex,)
                )

        # The update is OK, so here we can set force=True:
        self._set_refname(
            refname,
            self.git.create_commit_chain(base_sha1, path_sha1),
            force=True,
            )

    def simplify_to_rebase(self, refname, force=False):
        i1 = self.len1 - 1
        path = [
            ((i1, i2), (0, i2))
            for i2 in range(1, self.len2)
            ]

        try:
            self._simplify_to_path(refname, (i1, 0), path, force=force)
        except MissingMergeFailure as e:
            raise Failure(
                'Cannot simplify to %s because merge %d-%d is not yet done'
                % (self.goal, e.i1, e.i2)
                )

    def simplify_to_drop(self, refname, force=False):
        try:
            base = self.goalopts['base']
        except KeyError:
            raise Failure('Goal "drop" was not initialized correctly')

        i2 = self.len2 - 1
        path = [
            ((i1, i2), (i1, 0))
            for i1 in range(1, self.len1)
            ]

        try:
            self._simplify_to_path(refname, base, path, force=force)
        except MissingMergeFailure as e:
            raise Failure(
                'Cannot simplify to rebase because merge %d-%d is not yet done'
                % (e.i1, e.i2)
                )

    def simplify_to_revert(self, refname, force=False):
        self.simplify_to_rebase(refname, force=force)

    def simplify_to_merge(self, refname, force=False):
        if not (-1, -1) in self:
            raise Failure(
                'Cannot simplify to merge because merge %d-%d is not yet done'
                % (self.len1 - 1, self.len2 - 1)
                )
        tree = self.git.get_tree(self[-1, -1].sha1)
        parents = [self[-1, 0].sha1, self[0, -1].sha1]

        # Create a preliminary commit with a generic commit message:
        sha1 = self.git.commit_tree(
            tree, parents,
            msg='Merge %s into %s (using imerge)' % (self.tip2, self.tip1),
            )

        self._set_refname(refname, sha1, force=force)

        # Now let the user edit the commit log message:
        self.git.amend()

    def simplify(self, refname, force=False):
        """Simplify this MergeState and save the result to refname.

        The merge must be complete before calling this method."""

        if self.goal == 'full':
            self.simplify_to_full(refname, force=force)
        elif self.goal == 'rebase':
            self.simplify_to_rebase(refname, force=force)
        elif self.goal == 'rebase-with-history':
            self.simplify_to_rebase_with_history(refname, force=force)
        elif self.goal == 'border':
            self.simplify_to_border(refname, force=force)
        elif self.goal == 'border-with-history':
            self.simplify_to_border(refname, with_history2=True, force=force)
        elif self.goal == 'border-with-history2':
            self.simplify_to_border(
                refname, with_history1=True, with_history2=True, force=force,
                )
        elif self.goal == 'drop':
            self.simplify_to_drop(refname, force=force)
        elif self.goal == 'revert':
            self.simplify_to_revert(refname, force=force)
        elif self.goal == 'merge':
            self.simplify_to_merge(refname, force=force)
        else:
            raise ValueError('Invalid value for goal (%r)' % (self.goal,))

    def save(self):
        """Write the current MergeState to the repository."""

        blockers = []
        for i2 in range(0, self.len2):
            for i1 in range(0, self.len1):
                record = self[i1, i2]
                if record.is_known():
                    record.save(self.git, self.name, i1, i2)
                if record.is_blocked():
                    blockers.append((i1, i2))

        state = dict(
            version='.'.join(str(i) for i in STATE_VERSION),
            blockers=blockers,
            tip1=self.tip1, tip2=self.tip2,
            goal=self.goal,
            goalopts=self.goalopts,
            manual=self.manual,
            branch=self.branch,
            )
        self.git.write_imerge_state_dict(self.name, state)

    def __str__(self):
        return 'MergeState(\'%s\', tip1=\'%s\', tip2=\'%s\', goal=\'%s\')' % (
            self.name, self.tip1, self.tip2, self.goal,
            )


def choose_merge_name(git, name):
    names = list(git.iter_existing_imerge_names())

    # If a name was specified, try to use it and fail if not possible:
    if name is not None:
        if name not in names:
            raise Failure('There is no incremental merge called \'%s\'!' % (name,))
        if len(names) > 1:
            # Record this as the new default:
            git.set_default_imerge_name(name)
        return name

    # A name was not specified.  Try to use the default name:
    default_name = git.get_default_imerge_name()
    if default_name:
        if git.check_imerge_exists(default_name):
            return default_name
        else:
            # There's no reason to keep the invalid default around:
            git.set_default_imerge_name(None)
            raise Failure(
                'Warning: The default incremental merge \'%s\' has disappeared.\n'
                '(The setting imerge.default has been cleared.)\n'
                'Please try again.'
                % (default_name,)
                )

    # If there is exactly one imerge, set it to be the default and use it.
    if len(names) == 1 and git.check_imerge_exists(names[0]):
        return names[0]

    raise Failure('Please select an incremental merge using --name')


def read_merge_state(git, name=None):
    return MergeState.read(git, choose_merge_name(git, name))


def cmd_list(parser, options):
    git = GitRepository()
    names = list(git.iter_existing_imerge_names())
    default_merge = git.get_default_imerge_name()
    if not default_merge and len(names) == 1:
        default_merge = names[0]
    for name in names:
        if name == default_merge:
            sys.stdout.write('* %s\n' % (name,))
        else:
            sys.stdout.write('  %s\n' % (name,))


def cmd_init(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    if not options.name:
        parser.error(
            'Please specify the --name to be used for this incremental merge'
            )
    tip1 = git.get_head_refname(short=True) or 'HEAD'
    tip2 = options.tip2
    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))

    merge_state = MergeState.initialize(
        git, options.name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal=options.goal, manual=options.manual,
        branch=(options.branch or options.name),
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(options.name)


def cmd_start(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    if not options.name:
        parser.error(
            'Please specify the --name to be used for this incremental merge'
            )
    tip1 = git.get_head_refname(short=True) or 'HEAD'
    tip2 = options.tip2

    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))

    merge_state = MergeState.initialize(
        git, options.name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal=options.goal, manual=options.manual,
        branch=(options.branch or options.name),
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(options.name)

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_merge(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    tip2 = options.tip2

    if options.name:
        name = options.name
    else:
        # By default, name the imerge after the branch being merged:
        name = tip2
        git.check_imerge_name_format(name)

    tip1 = git.get_head_refname(short=True)
    if tip1:
        if not options.branch:
            # See if we can store the result to the checked-out branch:
            try:
                git.check_branch_name_format(tip1)
            except InvalidBranchNameError:
                pass
            else:
                options.branch = tip1
    else:
        tip1 = 'HEAD'

    if not options.branch:
        if options.name:
            options.branch = options.name
        else:
            parser.error(
                'HEAD is not a simple branch.  '
                'Please specify --branch for storing results.'
                )

    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))
    except NothingToDoError as e:
        sys.stdout.write('Already up-to-date.\n')
        sys.exit(0)

    merge_state = MergeState.initialize(
        git, name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal=options.goal, manual=options.manual,
        branch=options.branch,
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(name)

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_rebase(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    tip1 = options.tip1

    tip2 = git.get_head_refname(short=True)
    if tip2:
        if not options.branch:
            # See if we can store the result to the current branch:
            try:
                git.check_branch_name_format(tip2)
            except InvalidBranchNameError:
                pass
            else:
                options.branch = tip2
        if not options.name:
            # By default, name the imerge after the branch being rebased:
            options.name = tip2
    else:
        tip2 = git.rev_parse('HEAD')

    if not options.name:
        parser.error(
            'The checked-out branch could not be used as the imerge name.\n'
            'Please use the --name option.'
            )

    if not options.branch:
        if options.name:
            options.branch = options.name
        else:
            parser.error(
                'HEAD is not a simple branch.  '
                'Please specify --branch for storing results.'
                )

    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))
    except NothingToDoError as e:
        sys.stdout.write('Already up-to-date.\n')
        sys.exit(0)

    merge_state = MergeState.initialize(
        git, options.name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal=options.goal, manual=options.manual,
        branch=options.branch,
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(options.name)

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_drop(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    m = re.match(r'^(?P<start>.*[^\.])(?P<sep>\.{2,})(?P<end>[^\.].*)$', options.range)
    if m:
        if m.group('sep') != '..':
            parser.error(
                'Range must either be a single commit '
                'or in the form "commit..commit"'
                )
        start = git.rev_parse(m.group('start'))
        end = git.rev_parse(m.group('end'))
    else:
        end = git.rev_parse(options.range)
        start = git.rev_parse('%s^' % (end,))

    try:
        to_drop = git.linear_ancestry(start, end, options.first_parent)
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))

    # Suppose we want to drop commits 2 and 3 in the branch below.
    # Then we set up an imerge as follows:
    #
    #     o - 0 - 1 - 2 - 3 - 4 - 5 - 6    ← tip1
    #                     |
    #                     3⁻¹
    #                     |
    #                     2⁻¹
    #
    #                     ↑
    #                    tip2
    #
    # We first use imerge to rebase tip1 onto tip2, then we simplify
    # by discarding the sequence (2, 3, 3⁻¹, 2⁻¹) (which together are
    # a NOOP). In this case, goalopts would have the following
    # contents:
    #
    #     goalopts['base'] = rev_parse(commit1)

    tip1 = git.get_head_refname(short=True)
    if tip1:
        if not options.branch:
            # See if we can store the result to the current branch:
            try:
                git.check_branch_name_format(tip1)
            except InvalidBranchNameError:
                pass
            else:
                options.branch = tip1
        if not options.name:
            # By default, name the imerge after the branch being rebased:
            options.name = tip1
    else:
        tip1 = git.rev_parse('HEAD')

    if not options.name:
        parser.error(
            'The checked-out branch could not be used as the imerge name.\n'
            'Please use the --name option.'
            )

    if not options.branch:
        if options.name:
            options.branch = options.name
        else:
            parser.error(
                'HEAD is not a simple branch.  '
                'Please specify --branch for storing results.'
                )

    # Create a branch based on end that contains the inverse of the
    # commits that we want to drop. This will be tip2:

    git.checkout(end)
    for commit in reversed(to_drop):
        git.revert(commit)

    tip2 = git.rev_parse('HEAD')

    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))
    except NothingToDoError as e:
        sys.stdout.write('Already up-to-date.\n')
        sys.exit(0)

    merge_state = MergeState.initialize(
        git, options.name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal='drop', goalopts={'base' : start},
        manual=options.manual,
        branch=options.branch,
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(options.name)

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_revert(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')

    m = re.match(r'^(?P<start>.*[^\.])(?P<sep>\.{2,})(?P<end>[^\.].*)$', options.range)
    if m:
        if m.group('sep') != '..':
            parser.error(
                'Range must either be a single commit '
                'or in the form "commit..commit"'
                )
        start = git.rev_parse(m.group('start'))
        end = git.rev_parse(m.group('end'))
    else:
        end = git.rev_parse(options.range)
        start = git.rev_parse('%s^' % (end,))

    try:
        to_revert = git.linear_ancestry(start, end, options.first_parent)
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))

    # Suppose we want to revert commits 2 and 3 in the branch below.
    # Then we set up an imerge as follows:
    #
    #     o - 0 - 1 - 2 - 3 - 4 - 5 - 6    ← tip1
    #                     |
    #                     3⁻¹
    #                     |
    #                     2⁻¹
    #
    #                     ↑
    #                    tip2
    #
    # Then we use imerge to rebase tip2 onto tip1.

    tip1 = git.get_head_refname(short=True)
    if tip1:
        if not options.branch:
            # See if we can store the result to the current branch:
            try:
                git.check_branch_name_format(tip1)
            except InvalidBranchNameError:
                pass
            else:
                options.branch = tip1
        if not options.name:
            # By default, name the imerge after the branch being rebased:
            options.name = tip1
    else:
        tip1 = git.rev_parse('HEAD')

    if not options.name:
        parser.error(
            'The checked-out branch could not be used as the imerge name.\n'
            'Please use the --name option.'
            )

    if not options.branch:
        if options.name:
            options.branch = options.name
        else:
            parser.error(
                'HEAD is not a simple branch.  '
                'Please specify --branch for storing results.'
                )

    # Create a branch based on end that contains the inverse of the
    # commits that we want to drop. This will be tip2:

    git.checkout(end)
    for commit in reversed(to_revert):
        git.revert(commit)

    tip2 = git.rev_parse('HEAD')

    try:
        (merge_base, commits1, commits2) = git.get_boundaries(
            tip1, tip2, options.first_parent,
            )
    except NonlinearAncestryError as e:
        if options.first_parent:
            parser.error(str(e))
        else:
            parser.error('%s\nPerhaps use "--first-parent"?' % (e,))
    except NothingToDoError as e:
        sys.stdout.write('Already up-to-date.\n')
        sys.exit(0)

    merge_state = MergeState.initialize(
        git, options.name, merge_base,
        tip1, commits1,
        tip2, commits2,
        goal='revert',
        manual=options.manual,
        branch=options.branch,
        )
    merge_state.save()
    if len(list(git.iter_existing_imerge_names())) > 1:
        git.set_default_imerge_name(options.name)

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_remove(parser, options):
    git = GitRepository()
    MergeState.remove(git, choose_merge_name(git, options.name))


def cmd_continue(parser, options):
    git = GitRepository()
    merge_state = read_merge_state(git, options.name)
    try:
        merge_state.incorporate_user_merge(edit_log_msg=options.edit)
    except NoManualMergeError:
        pass
    except NotABlockingCommitError as e:
        raise Failure(str(e))
    except ManualMergeUnusableError as e:
        raise Failure(str(e))

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        merge_state.request_user_merge(e.i1, e.i2)
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_record(parser, options):
    git = GitRepository()
    merge_state = read_merge_state(git, options.name)
    try:
        merge_state.incorporate_user_merge(edit_log_msg=options.edit)
    except NoManualMergeError as e:
        raise Failure(str(e))
    except NotABlockingCommitError:
        raise Failure(str(e))
    except ManualMergeUnusableError as e:
        raise Failure(str(e))

    try:
        merge_state.auto_complete_frontier()
    except FrontierBlockedError as e:
        pass
    else:
        sys.stderr.write('Merge is complete!\n')


def cmd_autofill(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')
    merge_state = read_merge_state(git, options.name)
    with git.temporary_head(message='imerge: restoring'):
        try:
            merge_state.auto_complete_frontier()
        except FrontierBlockedError as e:
            raise Failure(str(e))


def cmd_simplify(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')
    merge_state = read_merge_state(git, options.name)
    merge_frontier = MergeFrontier.map_known_frontier(merge_state)
    if not merge_frontier.is_complete():
        raise Failure('Merge %s is not yet complete!' % (merge_state.name,))
    refname = 'refs/heads/%s' % ((options.branch or merge_state.branch),)
    if options.goal is not None:
        merge_state.set_goal(options.goal)
        merge_state.save()
    merge_state.simplify(refname, force=options.force)


def cmd_finish(parser, options):
    git = GitRepository()
    git.require_clean_work_tree('proceed')
    merge_state = read_merge_state(git, options.name)
    merge_frontier = MergeFrontier.map_known_frontier(merge_state)
    if not merge_frontier.is_complete():
        raise Failure('Merge %s is not yet complete!' % (merge_state.name,))
    refname = 'refs/heads/%s' % ((options.branch or merge_state.branch),)
    if options.goal is not None:
        merge_state.set_goal(options.goal)
        merge_state.save()
    merge_state.simplify(refname, force=options.force)
    MergeState.remove(git, merge_state.name)


def cmd_diagram(parser, options):
    git = GitRepository()
    if not (options.commits or options.frontier):
        options.frontier = True
    if not (options.color or (options.color is None and sys.stdout.isatty())):
        AnsiColor.disable()

    merge_state = read_merge_state(git, options.name)
    if options.commits:
        merge_state.write(sys.stdout)
        sys.stdout.write('\n')
    if options.frontier:
        merge_frontier = MergeFrontier.map_known_frontier(merge_state)
        merge_frontier.write(sys.stdout)
        sys.stdout.write('\n')
    if options.html:
        merge_frontier = MergeFrontier.map_known_frontier(merge_state)
        html = open(options.html, 'w')
        merge_frontier.write_html(html, merge_state.name)
        html.close()
    sys.stdout.write(
        'Key:\n'
        )
    if options.frontier:
        sys.stdout.write(
            '  |,-,+ = rectangles forming current merge frontier\n'
            )
    sys.stdout.write(
        '  * = merge done manually\n'
        '  . = merge done automatically\n'
        '  # = conflict that is currently blocking progress\n'
        '  @ = merge was blocked but has been resolved\n'
        '  ? = no merge recorded\n'
        '\n'
        )


def reparent_recursively(git, start_commit, parents, end_commit):
    """Change the parents of start_commit and its descendants.

    Change start_commit to have the specified parents, and reparent
    all commits on the ancestry path between start_commit and
    end_commit accordingly. Return the replacement end_commit.
    start_commit, parents, and end_commit must all be resolved OIDs.

    """

    # A map {old_oid : new_oid} keeping track of which replacements
    # have to be made:
    replacements = {}

    # Reparent start_commit:
    replacements[start_commit] = git.reparent(start_commit, parents)

    for (commit, parents) in git.rev_list_with_parents(
            '--ancestry-path', '--topo-order', '--reverse',
            '%s..%s' % (start_commit, end_commit)
            ):
        parents = [replacements.get(p, p) for p in parents]
        replacements[commit] = git.reparent(commit, parents)

    try:
        return replacements[end_commit]
    except KeyError:
        raise ValueError(
            "%s is not an ancestor of %s" % (start_commit, end_commit),
        )


def cmd_reparent(parser, options):
    git = GitRepository()
    try:
        commit = git.get_commit_sha1(options.commit)
    except ValueError:
        sys.exit('%s is not a valid commit', options.commit)

    try:
        head = git.get_commit_sha1('HEAD')
    except ValueError:
        sys.exit('HEAD is not a valid commit')

    try:
        parents = [git.get_commit_sha1(p) for p in options.parents]
    except ValueError as e:
        sys.exit(e.message)

    sys.stderr.write('Reparenting %s..HEAD\n' % (options.commit,))

    try:
        new_head = reparent_recursively(git, commit, parents, head)
    except ValueError as e:
        sys.exit(e.message)

    sys.stdout.write('%s\n' % (new_head,))


def main(args):
    NAME_INIT_HELP = 'name to use for this incremental merge'

    def add_name_argument(subparser, help=None):
        if help is None:
            subcommand = subparser.prog.split()[1]
            help = 'name of incremental merge to {0}'.format(subcommand)

        subparser.add_argument(
            '--name', action='store', default=None, help=help,
            )

    def add_goal_argument(subparser, default=DEFAULT_GOAL):
        help = 'the goal of the incremental merge'
        if default is None:
            help = (
                'the type of simplification to be made '
                '(default is the value provided to "init" or "start")'
                )
        subparser.add_argument(
            '--goal',
            action='store', default=default,
            choices=ALLOWED_GOALS,
            help=help,
            )

    def add_branch_argument(subparser):
        subcommand = subparser.prog.split()[1]
        help = 'the name of the branch to which the result will be stored'
        if subcommand in ['simplify', 'finish']:
            help = (
                'the name of the branch to which to store the result '
                '(default is the value provided to "init" or "start" if any; '
                'otherwise the name of the merge).   '
                'If BRANCH already exists then it must be able to be '
                'fast-forwarded to the result unless the --force option is '
                'specified.'
                )
        subparser.add_argument(
            '--branch',
            action='store', default=None,
            help=help,
            )

    def add_manual_argument(subparser):
        subparser.add_argument(
            '--manual',
            action='store_true', default=False,
            help=(
                'ask the user to complete all merges manually, even when they '
                'appear conflict-free.  This option disables the usual bisection '
                'algorithm and causes the full incremental merge diagram to be '
                'completed.'
                ),
            )

    def add_first_parent_argument(subparser, default=None):
        subcommand = subparser.prog.split()[1]
        help = (
            'handle only the first parent commits '
            '(this option is currently required if the history is nonlinear)'
            )
        if subcommand in ['merge', 'rebase']:
            help = argparse.SUPPRESS
        subparser.add_argument(
            '--first-parent', action='store_true', default=default, help=help,
            )

    def add_tip2_argument(subparser):
        subparser.add_argument(
            'tip2', action='store', metavar='branch',
            help='the tip of the branch to be merged into HEAD',
        )

    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        )
    subparsers = parser.add_subparsers(dest='subcommand', help='sub-command')

    subparser = subparsers.add_parser(
        'start',
        help=(
            'start a new incremental merge '
            '(equivalent to "init" followed by "continue")'
            ),
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_goal_argument(subparser)
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser)
    add_tip2_argument(subparser)

    subparser = subparsers.add_parser(
        'merge',
        help='start a simple merge via incremental merge',
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_goal_argument(subparser, default='merge')
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser, default=True)
    add_tip2_argument(subparser)

    subparser = subparsers.add_parser(
        'rebase',
        help='start a simple rebase via incremental merge',
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_goal_argument(subparser, default='rebase')
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser, default=True)
    subparser.add_argument(
        'tip1', action='store', metavar='branch',
        help=(
            'the tip of the branch onto which the current branch should '
            'be rebased'
            ),
        )

    subparser = subparsers.add_parser(
        'drop',
        help='drop one or more commits via incremental merge',
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser, default=True)
    subparser.add_argument(
        'range', action='store', metavar='[commit | commit..commit]',
        help=(
            'the commit or range of commits that should be dropped'
            ),
        )

    subparser = subparsers.add_parser(
        'revert',
        help='revert one or more commits via incremental merge',
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser, default=True)
    subparser.add_argument(
        'range', action='store', metavar='[commit | commit..commit]',
        help=(
            'the commit or range of commits that should be reverted'
            ),
        )

    subparser = subparsers.add_parser(
        'continue',
        help=(
            'record the merge at branch imerge/NAME '
            'and start the next step of the merge '
            '(equivalent to "record" followed by "autofill" '
            'and then sets up the working copy with the next '
            'conflict that has to be resolved manually)'
            ),
        )
    add_name_argument(subparser)
    subparser.set_defaults(edit=None)
    subparser.add_argument(
        '--edit', '-e', dest='edit', action='store_true',
        help='commit staged changes with the --edit option',
        )
    subparser.add_argument(
        '--no-edit', dest='edit', action='store_false',
        help='commit staged changes with the --no-edit option',
        )

    subparser = subparsers.add_parser(
        'finish',
        help=(
            'simplify then remove a completed incremental merge '
            '(equivalent to "simplify" followed by "remove")'
            ),
        )
    add_name_argument(subparser)
    add_goal_argument(subparser, default=None)
    add_branch_argument(subparser)
    subparser.add_argument(
        '--force',
        action='store_true', default=False,
        help='allow the target branch to be updated in a non-fast-forward manner',
        )

    subparser = subparsers.add_parser(
        'diagram',
        help='display a diagram of the current state of a merge',
        )
    add_name_argument(subparser)
    subparser.add_argument(
        '--commits', action='store_true', default=False,
        help='show the merges that have been made so far',
        )
    subparser.add_argument(
        '--frontier', action='store_true', default=False,
        help='show the current merge frontier',
        )
    subparser.add_argument(
        '--html', action='store', default=None,
        help='generate HTML diagram showing the current merge frontier',
        )
    subparser.add_argument(
        '--color', dest='color', action='store_true', default=None,
        help='draw diagram with colors',
        )
    subparser.add_argument(
        '--no-color', dest='color', action='store_false',
        help='draw diagram without colors',
        )

    subparser = subparsers.add_parser(
        'list',
        help=(
            'list the names of incremental merges that are currently in progress.  '
            'The active merge is shown with an asterisk next to it.'
            ),
        )

    subparser = subparsers.add_parser(
        'init',
        help='initialize a new incremental merge',
        )
    add_name_argument(subparser, help=NAME_INIT_HELP)
    add_goal_argument(subparser)
    add_branch_argument(subparser)
    add_manual_argument(subparser)
    add_first_parent_argument(subparser)
    add_tip2_argument(subparser)

    subparser = subparsers.add_parser(
        'record',
        help='record the merge at branch imerge/NAME',
        )
    # record:
    add_name_argument(
        subparser,
        help='name of merge to which the merge should be added',
        )
    subparser.set_defaults(edit=None)
    subparser.add_argument(
        '--edit', '-e', dest='edit', action='store_true',
        help='commit staged changes with the --edit option',
        )
    subparser.add_argument(
        '--no-edit', dest='edit', action='store_false',
        help='commit staged changes with the --no-edit option',
        )

    subparser = subparsers.add_parser(
        'autofill',
        help='autofill non-conflicting merges',
        )
    add_name_argument(subparser)

    subparser = subparsers.add_parser(
        'simplify',
        help=(
            'simplify a completed incremental merge by discarding unneeded '
            'intermediate merges and cleaning up the ancestry of the commits '
            'that are retained'
            ),
        )
    add_name_argument(subparser)
    add_goal_argument(subparser, default=None)
    add_branch_argument(subparser)
    subparser.add_argument(
        '--force',
        action='store_true', default=False,
        help='allow the target branch to be updated in a non-fast-forward manner',
        )

    subparser = subparsers.add_parser(
        'remove',
        help='irrevocably remove an incremental merge',
        )
    add_name_argument(subparser)

    subparser = subparsers.add_parser(
        'reparent',
        help=(
            'change the parents of the specified commit and propagate the '
            'change to HEAD'
            ),
        )
    subparser.add_argument(
        '--commit', metavar='COMMIT', default='HEAD',
        help=(
            'target commit to reparent. Create a new commit identical to '
            'this one, but having the specified parents. Then create '
            'new versions of all descendants of this commit all the way to '
            'HEAD, incorporating the modified commit. Output the SHA-1 of '
            'the replacement HEAD commit.'
        ),
    )
    subparser.add_argument(
        'parents', nargs='*', metavar='PARENT',
        help='a list of commits',
        )

    options = parser.parse_args(args)

    # Set an environment variable GIT_IMERGE=1 while we are running.
    # This makes it possible for hook scripts etc. to know that they
    # are being run within git-imerge, and should perhaps behave
    # differently.  In the future we might make the value more
    # informative, like GIT_IMERGE=[automerge|autofill|...].
    os.environ[str('GIT_IMERGE')] = str('1')

    if options.subcommand == 'list':
        cmd_list(parser, options)
    elif options.subcommand == 'init':
        cmd_init(parser, options)
    elif options.subcommand == 'start':
        cmd_start(parser, options)
    elif options.subcommand == 'merge':
        cmd_merge(parser, options)
    elif options.subcommand == 'rebase':
        cmd_rebase(parser, options)
    elif options.subcommand == 'drop':
        cmd_drop(parser, options)
    elif options.subcommand == 'revert':
        cmd_revert(parser, options)
    elif options.subcommand == 'remove':
        cmd_remove(parser, options)
    elif options.subcommand == 'continue':
        cmd_continue(parser, options)
    elif options.subcommand == 'record':
        cmd_record(parser, options)
    elif options.subcommand == 'autofill':
        cmd_autofill(parser, options)
    elif options.subcommand == 'simplify':
        cmd_simplify(parser, options)
    elif options.subcommand == 'finish':
        cmd_finish(parser, options)
    elif options.subcommand == 'diagram':
        cmd_diagram(parser, options)
    elif options.subcommand == 'reparent':
        cmd_reparent(parser, options)
    else:
        parser.error('Unrecognized subcommand')


if __name__ == '__main__':
    try:
        main(sys.argv[1:])
    except Failure as e:
        sys.exit(str(e))


# vim: set expandtab ft=python: