This file is indexed.

/usr/lib/python2.7/dist-packages/hgext/mq.py is in mercurial-common 4.5.3-1ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# mq.py - patch queues for mercurial
#
# Copyright 2005, 2006 Chris Mason <mason@suse.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

'''manage a stack of patches

This extension lets you work with a stack of patches in a Mercurial
repository. It manages two stacks of patches - all known patches, and
applied patches (subset of known patches).

Known patches are represented as patch files in the .hg/patches
directory. Applied patches are both patch files and changesets.

Common tasks (use :hg:`help COMMAND` for more details)::

  create new patch                          qnew
  import existing patch                     qimport

  print patch series                        qseries
  print applied patches                     qapplied

  add known patch to applied stack          qpush
  remove patch from applied stack           qpop
  refresh contents of top applied patch     qrefresh

By default, mq will automatically use git patches when required to
avoid losing file mode changes, copy records, binary files or empty
files creations or deletions. This behavior can be configured with::

  [mq]
  git = auto/keep/yes/no

If set to 'keep', mq will obey the [diff] section configuration while
preserving existing git patches upon qrefresh. If set to 'yes' or
'no', mq will override the [diff] section and always generate git or
regular patches, possibly losing data in the second case.

It may be desirable for mq changesets to be kept in the secret phase (see
:hg:`help phases`), which can be enabled with the following setting::

  [mq]
  secret = True

You will by default be managing a patch queue named "patches". You can
create other, independent patch queues with the :hg:`qqueue` command.

If the working directory contains uncommitted files, qpush, qpop and
qgoto abort immediately. If -f/--force is used, the changes are
discarded. Setting::

  [mq]
  keepchanges = True

make them behave as if --keep-changes were passed, and non-conflicting
local changes will be tolerated and preserved. If incompatible options
such as -f/--force or --exact are passed, this setting is ignored.

This extension used to provide a strip command. This command now lives
in the strip extension.
'''

from __future__ import absolute_import, print_function

import errno
import os
import re
import shutil
from mercurial.i18n import _
from mercurial.node import (
    bin,
    hex,
    nullid,
    nullrev,
    short,
)
from mercurial import (
    cmdutil,
    commands,
    dirstateguard,
    encoding,
    error,
    extensions,
    hg,
    localrepo,
    lock as lockmod,
    patch as patchmod,
    phases,
    pycompat,
    registrar,
    revsetlang,
    scmutil,
    smartset,
    subrepo,
    util,
    vfs as vfsmod,
)

release = lockmod.release
seriesopts = [('s', 'summary', None, _('print first line of patch header'))]

cmdtable = {}
command = registrar.command(cmdtable)
# Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
# leave the attribute unspecified.
testedwith = 'ships-with-hg-core'

configtable = {}
configitem = registrar.configitem(configtable)

configitem('mq', 'git',
    default='auto',
)
configitem('mq', 'keepchanges',
    default=False,
)
configitem('mq', 'plain',
    default=False,
)
configitem('mq', 'secret',
    default=False,
)

# force load strip extension formerly included in mq and import some utility
try:
    stripext = extensions.find('strip')
except KeyError:
    # note: load is lazy so we could avoid the try-except,
    # but I (marmoute) prefer this explicit code.
    class dummyui(object):
        def debug(self, msg):
            pass
    stripext = extensions.load(dummyui(), 'strip', '')

strip = stripext.strip
checksubstate = stripext.checksubstate
checklocalchanges = stripext.checklocalchanges


# Patch names looks like unix-file names.
# They must be joinable with queue directory and result in the patch path.
normname = util.normpath

class statusentry(object):
    def __init__(self, node, name):
        self.node, self.name = node, name
    def __repr__(self):
        return hex(self.node) + ':' + self.name

# The order of the headers in 'hg export' HG patches:
HGHEADERS = [
#   '# HG changeset patch',
    '# User ',
    '# Date ',
    '#      ',
    '# Branch ',
    '# Node ID ',
    '# Parent  ', # can occur twice for merges - but that is not relevant for mq
    ]
# The order of headers in plain 'mail style' patches:
PLAINHEADERS = {
    'from': 0,
    'date': 1,
    'subject': 2,
    }

def inserthgheader(lines, header, value):
    """Assuming lines contains a HG patch header, add a header line with value.
    >>> try: inserthgheader([], b'# Date ', b'z')
    ... except ValueError as inst: print("oops")
    oops
    >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
    ['# HG changeset patch', '# Date z']
    >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
    ['# HG changeset patch', '# Date z', '']
    >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
    ['# HG changeset patch', '# User y', '# Date z']
    >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
    ...                b'# User ', b'z')
    ['# HG changeset patch', '# Date x', '# User z']
    >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
    ['# HG changeset patch', '# Date z']
    >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
    ...                b'# Date ', b'z')
    ['# HG changeset patch', '# Date z', '', '# Date y']
    >>> inserthgheader([b'# HG changeset patch', b'# Parent  y'],
    ...                b'# Date ', b'z')
    ['# HG changeset patch', '# Date z', '# Parent  y']
    """
    start = lines.index('# HG changeset patch') + 1
    newindex = HGHEADERS.index(header)
    bestpos = len(lines)
    for i in range(start, len(lines)):
        line = lines[i]
        if not line.startswith('# '):
            bestpos = min(bestpos, i)
            break
        for lineindex, h in enumerate(HGHEADERS):
            if line.startswith(h):
                if lineindex == newindex:
                    lines[i] = header + value
                    return lines
                if lineindex > newindex:
                    bestpos = min(bestpos, i)
                break # next line
    lines.insert(bestpos, header + value)
    return lines

def insertplainheader(lines, header, value):
    """For lines containing a plain patch header, add a header line with value.
    >>> insertplainheader([], b'Date', b'z')
    ['Date: z']
    >>> insertplainheader([b''], b'Date', b'z')
    ['Date: z', '']
    >>> insertplainheader([b'x'], b'Date', b'z')
    ['Date: z', '', 'x']
    >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
    ['From: y', 'Date: z', '', 'x']
    >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
    [' date : x', 'From: z', '']
    >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
    ['Date: z', '', 'Date: y']
    >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
    ['From: y', 'foo: bar', 'DATE: z', '', 'x']
    """
    newprio = PLAINHEADERS[header.lower()]
    bestpos = len(lines)
    for i, line in enumerate(lines):
        if ':' in line:
            lheader = line.split(':', 1)[0].strip().lower()
            lprio = PLAINHEADERS.get(lheader, newprio + 1)
            if lprio == newprio:
                lines[i] = '%s: %s' % (header, value)
                return lines
            if lprio > newprio and i < bestpos:
                bestpos = i
        else:
            if line:
                lines.insert(i, '')
            if i < bestpos:
                bestpos = i
            break
    lines.insert(bestpos, '%s: %s' % (header, value))
    return lines

class patchheader(object):
    def __init__(self, pf, plainmode=False):
        def eatdiff(lines):
            while lines:
                l = lines[-1]
                if (l.startswith("diff -") or
                    l.startswith("Index:") or
                    l.startswith("===========")):
                    del lines[-1]
                else:
                    break
        def eatempty(lines):
            while lines:
                if not lines[-1].strip():
                    del lines[-1]
                else:
                    break

        message = []
        comments = []
        user = None
        date = None
        parent = None
        format = None
        subject = None
        branch = None
        nodeid = None
        diffstart = 0

        for line in file(pf):
            line = line.rstrip()
            if (line.startswith('diff --git')
                or (diffstart and line.startswith('+++ '))):
                diffstart = 2
                break
            diffstart = 0 # reset
            if line.startswith("--- "):
                diffstart = 1
                continue
            elif format == "hgpatch":
                # parse values when importing the result of an hg export
                if line.startswith("# User "):
                    user = line[7:]
                elif line.startswith("# Date "):
                    date = line[7:]
                elif line.startswith("# Parent "):
                    parent = line[9:].lstrip() # handle double trailing space
                elif line.startswith("# Branch "):
                    branch = line[9:]
                elif line.startswith("# Node ID "):
                    nodeid = line[10:]
                elif not line.startswith("# ") and line:
                    message.append(line)
                    format = None
            elif line == '# HG changeset patch':
                message = []
                format = "hgpatch"
            elif (format != "tagdone" and (line.startswith("Subject: ") or
                                           line.startswith("subject: "))):
                subject = line[9:]
                format = "tag"
            elif (format != "tagdone" and (line.startswith("From: ") or
                                           line.startswith("from: "))):
                user = line[6:]
                format = "tag"
            elif (format != "tagdone" and (line.startswith("Date: ") or
                                           line.startswith("date: "))):
                date = line[6:]
                format = "tag"
            elif format == "tag" and line == "":
                # when looking for tags (subject: from: etc) they
                # end once you find a blank line in the source
                format = "tagdone"
            elif message or line:
                message.append(line)
            comments.append(line)

        eatdiff(message)
        eatdiff(comments)
        # Remember the exact starting line of the patch diffs before consuming
        # empty lines, for external use by TortoiseHg and others
        self.diffstartline = len(comments)
        eatempty(message)
        eatempty(comments)

        # make sure message isn't empty
        if format and format.startswith("tag") and subject:
            message.insert(0, subject)

        self.message = message
        self.comments = comments
        self.user = user
        self.date = date
        self.parent = parent
        # nodeid and branch are for external use by TortoiseHg and others
        self.nodeid = nodeid
        self.branch = branch
        self.haspatch = diffstart > 1
        self.plainmode = (plainmode or
                          '# HG changeset patch' not in self.comments and
                          any(c.startswith('Date: ') or
                                   c.startswith('From: ')
                                   for c in self.comments))

    def setuser(self, user):
        try:
            inserthgheader(self.comments, '# User ', user)
        except ValueError:
            if self.plainmode:
                insertplainheader(self.comments, 'From', user)
            else:
                tmp = ['# HG changeset patch', '# User ' + user]
                self.comments = tmp + self.comments
        self.user = user

    def setdate(self, date):
        try:
            inserthgheader(self.comments, '# Date ', date)
        except ValueError:
            if self.plainmode:
                insertplainheader(self.comments, 'Date', date)
            else:
                tmp = ['# HG changeset patch', '# Date ' + date]
                self.comments = tmp + self.comments
        self.date = date

    def setparent(self, parent):
        try:
            inserthgheader(self.comments, '# Parent  ', parent)
        except ValueError:
            if not self.plainmode:
                tmp = ['# HG changeset patch', '# Parent  ' + parent]
                self.comments = tmp + self.comments
        self.parent = parent

    def setmessage(self, message):
        if self.comments:
            self._delmsg()
        self.message = [message]
        if message:
            if self.plainmode and self.comments and self.comments[-1]:
                self.comments.append('')
            self.comments.append(message)

    def __str__(self):
        s = '\n'.join(self.comments).rstrip()
        if not s:
            return ''
        return s + '\n\n'

    def _delmsg(self):
        '''Remove existing message, keeping the rest of the comments fields.
        If comments contains 'subject: ', message will prepend
        the field and a blank line.'''
        if self.message:
            subj = 'subject: ' + self.message[0].lower()
            for i in xrange(len(self.comments)):
                if subj == self.comments[i].lower():
                    del self.comments[i]
                    self.message = self.message[2:]
                    break
        ci = 0
        for mi in self.message:
            while mi != self.comments[ci]:
                ci += 1
            del self.comments[ci]

def newcommit(repo, phase, *args, **kwargs):
    """helper dedicated to ensure a commit respect mq.secret setting

    It should be used instead of repo.commit inside the mq source for operation
    creating new changeset.
    """
    repo = repo.unfiltered()
    if phase is None:
        if repo.ui.configbool('mq', 'secret'):
            phase = phases.secret
    overrides = {('ui', 'allowemptycommit'): True}
    if phase is not None:
        overrides[('phases', 'new-commit')] = phase
    with repo.ui.configoverride(overrides, 'mq'):
        repo.ui.setconfig('ui', 'allowemptycommit', True)
        return repo.commit(*args, **kwargs)

class AbortNoCleanup(error.Abort):
    pass

class queue(object):
    def __init__(self, ui, baseui, path, patchdir=None):
        self.basepath = path
        try:
            fh = open(os.path.join(path, 'patches.queue'))
            cur = fh.read().rstrip()
            fh.close()
            if not cur:
                curpath = os.path.join(path, 'patches')
            else:
                curpath = os.path.join(path, 'patches-' + cur)
        except IOError:
            curpath = os.path.join(path, 'patches')
        self.path = patchdir or curpath
        self.opener = vfsmod.vfs(self.path)
        self.ui = ui
        self.baseui = baseui
        self.applieddirty = False
        self.seriesdirty = False
        self.added = []
        self.seriespath = "series"
        self.statuspath = "status"
        self.guardspath = "guards"
        self.activeguards = None
        self.guardsdirty = False
        # Handle mq.git as a bool with extended values
        gitmode = ui.config('mq', 'git').lower()
        boolmode = util.parsebool(gitmode)
        if boolmode is not None:
            if boolmode:
                gitmode = 'yes'
            else:
                gitmode = 'no'
        self.gitmode = gitmode
        # deprecated config: mq.plain
        self.plainmode = ui.configbool('mq', 'plain')
        self.checkapplied = True

    @util.propertycache
    def applied(self):
        def parselines(lines):
            for l in lines:
                entry = l.split(':', 1)
                if len(entry) > 1:
                    n, name = entry
                    yield statusentry(bin(n), name)
                elif l.strip():
                    self.ui.warn(_('malformated mq status line: %s\n') % entry)
                # else we ignore empty lines
        try:
            lines = self.opener.read(self.statuspath).splitlines()
            return list(parselines(lines))
        except IOError as e:
            if e.errno == errno.ENOENT:
                return []
            raise

    @util.propertycache
    def fullseries(self):
        try:
            return self.opener.read(self.seriespath).splitlines()
        except IOError as e:
            if e.errno == errno.ENOENT:
                return []
            raise

    @util.propertycache
    def series(self):
        self.parseseries()
        return self.series

    @util.propertycache
    def seriesguards(self):
        self.parseseries()
        return self.seriesguards

    def invalidate(self):
        for a in 'applied fullseries series seriesguards'.split():
            if a in self.__dict__:
                delattr(self, a)
        self.applieddirty = False
        self.seriesdirty = False
        self.guardsdirty = False
        self.activeguards = None

    def diffopts(self, opts=None, patchfn=None, plain=False):
        """Return diff options tweaked for this mq use, possibly upgrading to
        git format, and possibly plain and without lossy options."""
        diffopts = patchmod.difffeatureopts(self.ui, opts,
            git=True, whitespace=not plain, formatchanging=not plain)
        if self.gitmode == 'auto':
            diffopts.upgrade = True
        elif self.gitmode == 'keep':
            pass
        elif self.gitmode in ('yes', 'no'):
            diffopts.git = self.gitmode == 'yes'
        else:
            raise error.Abort(_('mq.git option can be auto/keep/yes/no'
                               ' got %s') % self.gitmode)
        if patchfn:
            diffopts = self.patchopts(diffopts, patchfn)
        return diffopts

    def patchopts(self, diffopts, *patches):
        """Return a copy of input diff options with git set to true if
        referenced patch is a git patch and should be preserved as such.
        """
        diffopts = diffopts.copy()
        if not diffopts.git and self.gitmode == 'keep':
            for patchfn in patches:
                patchf = self.opener(patchfn, 'r')
                # if the patch was a git patch, refresh it as a git patch
                for line in patchf:
                    if line.startswith('diff --git'):
                        diffopts.git = True
                        break
                patchf.close()
        return diffopts

    def join(self, *p):
        return os.path.join(self.path, *p)

    def findseries(self, patch):
        def matchpatch(l):
            l = l.split('#', 1)[0]
            return l.strip() == patch
        for index, l in enumerate(self.fullseries):
            if matchpatch(l):
                return index
        return None

    guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')

    def parseseries(self):
        self.series = []
        self.seriesguards = []
        for l in self.fullseries:
            h = l.find('#')
            if h == -1:
                patch = l
                comment = ''
            elif h == 0:
                continue
            else:
                patch = l[:h]
                comment = l[h:]
            patch = patch.strip()
            if patch:
                if patch in self.series:
                    raise error.Abort(_('%s appears more than once in %s') %
                                     (patch, self.join(self.seriespath)))
                self.series.append(patch)
                self.seriesguards.append(self.guard_re.findall(comment))

    def checkguard(self, guard):
        if not guard:
            return _('guard cannot be an empty string')
        bad_chars = '# \t\r\n\f'
        first = guard[0]
        if first in '-+':
            return (_('guard %r starts with invalid character: %r') %
                      (guard, first))
        for c in bad_chars:
            if c in guard:
                return _('invalid character in guard %r: %r') % (guard, c)

    def setactive(self, guards):
        for guard in guards:
            bad = self.checkguard(guard)
            if bad:
                raise error.Abort(bad)
        guards = sorted(set(guards))
        self.ui.debug('active guards: %s\n' % ' '.join(guards))
        self.activeguards = guards
        self.guardsdirty = True

    def active(self):
        if self.activeguards is None:
            self.activeguards = []
            try:
                guards = self.opener.read(self.guardspath).split()
            except IOError as err:
                if err.errno != errno.ENOENT:
                    raise
                guards = []
            for i, guard in enumerate(guards):
                bad = self.checkguard(guard)
                if bad:
                    self.ui.warn('%s:%d: %s\n' %
                                 (self.join(self.guardspath), i + 1, bad))
                else:
                    self.activeguards.append(guard)
        return self.activeguards

    def setguards(self, idx, guards):
        for g in guards:
            if len(g) < 2:
                raise error.Abort(_('guard %r too short') % g)
            if g[0] not in '-+':
                raise error.Abort(_('guard %r starts with invalid char') % g)
            bad = self.checkguard(g[1:])
            if bad:
                raise error.Abort(bad)
        drop = self.guard_re.sub('', self.fullseries[idx])
        self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
        self.parseseries()
        self.seriesdirty = True

    def pushable(self, idx):
        if isinstance(idx, str):
            idx = self.series.index(idx)
        patchguards = self.seriesguards[idx]
        if not patchguards:
            return True, None
        guards = self.active()
        exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
        if exactneg:
            return False, repr(exactneg[0])
        pos = [g for g in patchguards if g[0] == '+']
        exactpos = [g for g in pos if g[1:] in guards]
        if pos:
            if exactpos:
                return True, repr(exactpos[0])
            return False, ' '.join(map(repr, pos))
        return True, ''

    def explainpushable(self, idx, all_patches=False):
        if all_patches:
            write = self.ui.write
        else:
            write = self.ui.warn

        if all_patches or self.ui.verbose:
            if isinstance(idx, str):
                idx = self.series.index(idx)
            pushable, why = self.pushable(idx)
            if all_patches and pushable:
                if why is None:
                    write(_('allowing %s - no guards in effect\n') %
                          self.series[idx])
                else:
                    if not why:
                        write(_('allowing %s - no matching negative guards\n') %
                              self.series[idx])
                    else:
                        write(_('allowing %s - guarded by %s\n') %
                              (self.series[idx], why))
            if not pushable:
                if why:
                    write(_('skipping %s - guarded by %s\n') %
                          (self.series[idx], why))
                else:
                    write(_('skipping %s - no matching guards\n') %
                          self.series[idx])

    def savedirty(self):
        def writelist(items, path):
            fp = self.opener(path, 'w')
            for i in items:
                fp.write("%s\n" % i)
            fp.close()
        if self.applieddirty:
            writelist(map(str, self.applied), self.statuspath)
            self.applieddirty = False
        if self.seriesdirty:
            writelist(self.fullseries, self.seriespath)
            self.seriesdirty = False
        if self.guardsdirty:
            writelist(self.activeguards, self.guardspath)
            self.guardsdirty = False
        if self.added:
            qrepo = self.qrepo()
            if qrepo:
                qrepo[None].add(f for f in self.added if f not in qrepo[None])
            self.added = []

    def removeundo(self, repo):
        undo = repo.sjoin('undo')
        if not os.path.exists(undo):
            return
        try:
            os.unlink(undo)
        except OSError as inst:
            self.ui.warn(_('error removing undo: %s\n') % str(inst))

    def backup(self, repo, files, copy=False):
        # backup local changes in --force case
        for f in sorted(files):
            absf = repo.wjoin(f)
            if os.path.lexists(absf):
                self.ui.note(_('saving current version of %s as %s\n') %
                             (f, scmutil.origpath(self.ui, repo, f)))

                absorig = scmutil.origpath(self.ui, repo, absf)
                if copy:
                    util.copyfile(absf, absorig)
                else:
                    util.rename(absf, absorig)

    def printdiff(self, repo, diffopts, node1, node2=None, files=None,
                  fp=None, changes=None, opts=None):
        if opts is None:
            opts = {}
        stat = opts.get('stat')
        m = scmutil.match(repo[node1], files, opts)
        cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2,  m,
                               changes, stat, fp)

    def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
        # first try just applying the patch
        (err, n) = self.apply(repo, [patch], update_status=False,
                              strict=True, merge=rev)

        if err == 0:
            return (err, n)

        if n is None:
            raise error.Abort(_("apply failed for patch %s") % patch)

        self.ui.warn(_("patch didn't work out, merging %s\n") % patch)

        # apply failed, strip away that rev and merge.
        hg.clean(repo, head)
        strip(self.ui, repo, [n], update=False, backup=False)

        ctx = repo[rev]
        ret = hg.merge(repo, rev)
        if ret:
            raise error.Abort(_("update returned %d") % ret)
        n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
        if n is None:
            raise error.Abort(_("repo commit failed"))
        try:
            ph = patchheader(mergeq.join(patch), self.plainmode)
        except Exception:
            raise error.Abort(_("unable to read %s") % patch)

        diffopts = self.patchopts(diffopts, patch)
        patchf = self.opener(patch, "w")
        comments = str(ph)
        if comments:
            patchf.write(comments)
        self.printdiff(repo, diffopts, head, n, fp=patchf)
        patchf.close()
        self.removeundo(repo)
        return (0, n)

    def qparents(self, repo, rev=None):
        """return the mq handled parent or p1

        In some case where mq get himself in being the parent of a merge the
        appropriate parent may be p2.
        (eg: an in progress merge started with mq disabled)

        If no parent are managed by mq, p1 is returned.
        """
        if rev is None:
            (p1, p2) = repo.dirstate.parents()
            if p2 == nullid:
                return p1
            if not self.applied:
                return None
            return self.applied[-1].node
        p1, p2 = repo.changelog.parents(rev)
        if p2 != nullid and p2 in [x.node for x in self.applied]:
            return p2
        return p1

    def mergepatch(self, repo, mergeq, series, diffopts):
        if not self.applied:
            # each of the patches merged in will have two parents.  This
            # can confuse the qrefresh, qdiff, and strip code because it
            # needs to know which parent is actually in the patch queue.
            # so, we insert a merge marker with only one parent.  This way
            # the first patch in the queue is never a merge patch
            #
            pname = ".hg.patches.merge.marker"
            n = newcommit(repo, None, '[mq]: merge marker', force=True)
            self.removeundo(repo)
            self.applied.append(statusentry(n, pname))
            self.applieddirty = True

        head = self.qparents(repo)

        for patch in series:
            patch = mergeq.lookup(patch, strict=True)
            if not patch:
                self.ui.warn(_("patch %s does not exist\n") % patch)
                return (1, None)
            pushable, reason = self.pushable(patch)
            if not pushable:
                self.explainpushable(patch, all_patches=True)
                continue
            info = mergeq.isapplied(patch)
            if not info:
                self.ui.warn(_("patch %s is not applied\n") % patch)
                return (1, None)
            rev = info[1]
            err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
            if head:
                self.applied.append(statusentry(head, patch))
                self.applieddirty = True
            if err:
                return (err, head)
        self.savedirty()
        return (0, head)

    def patch(self, repo, patchfile):
        '''Apply patchfile  to the working directory.
        patchfile: name of patch file'''
        files = set()
        try:
            fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
                                  files=files, eolmode=None)
            return (True, list(files), fuzz)
        except Exception as inst:
            self.ui.note(str(inst) + '\n')
            if not self.ui.verbose:
                self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
            self.ui.traceback()
            return (False, list(files), False)

    def apply(self, repo, series, list=False, update_status=True,
              strict=False, patchdir=None, merge=None, all_files=None,
              tobackup=None, keepchanges=False):
        wlock = lock = tr = None
        try:
            wlock = repo.wlock()
            lock = repo.lock()
            tr = repo.transaction("qpush")
            try:
                ret = self._apply(repo, series, list, update_status,
                                  strict, patchdir, merge, all_files=all_files,
                                  tobackup=tobackup, keepchanges=keepchanges)
                tr.close()
                self.savedirty()
                return ret
            except AbortNoCleanup:
                tr.close()
                self.savedirty()
                raise
            except: # re-raises
                try:
                    tr.abort()
                finally:
                    self.invalidate()
                raise
        finally:
            release(tr, lock, wlock)
            self.removeundo(repo)

    def _apply(self, repo, series, list=False, update_status=True,
               strict=False, patchdir=None, merge=None, all_files=None,
               tobackup=None, keepchanges=False):
        """returns (error, hash)

        error = 1 for unable to read, 2 for patch failed, 3 for patch
        fuzz. tobackup is None or a set of files to backup before they
        are modified by a patch.
        """
        # TODO unify with commands.py
        if not patchdir:
            patchdir = self.path
        err = 0
        n = None
        for patchname in series:
            pushable, reason = self.pushable(patchname)
            if not pushable:
                self.explainpushable(patchname, all_patches=True)
                continue
            self.ui.status(_("applying %s\n") % patchname)
            pf = os.path.join(patchdir, patchname)

            try:
                ph = patchheader(self.join(patchname), self.plainmode)
            except IOError:
                self.ui.warn(_("unable to read %s\n") % patchname)
                err = 1
                break

            message = ph.message
            if not message:
                # The commit message should not be translated
                message = "imported patch %s\n" % patchname
            else:
                if list:
                    # The commit message should not be translated
                    message.append("\nimported patch %s" % patchname)
                message = '\n'.join(message)

            if ph.haspatch:
                if tobackup:
                    touched = patchmod.changedfiles(self.ui, repo, pf)
                    touched = set(touched) & tobackup
                    if touched and keepchanges:
                        raise AbortNoCleanup(
                            _("conflicting local changes found"),
                            hint=_("did you forget to qrefresh?"))
                    self.backup(repo, touched, copy=True)
                    tobackup = tobackup - touched
                (patcherr, files, fuzz) = self.patch(repo, pf)
                if all_files is not None:
                    all_files.update(files)
                patcherr = not patcherr
            else:
                self.ui.warn(_("patch %s is empty\n") % patchname)
                patcherr, files, fuzz = 0, [], 0

            if merge and files:
                # Mark as removed/merged and update dirstate parent info
                removed = []
                merged = []
                for f in files:
                    if os.path.lexists(repo.wjoin(f)):
                        merged.append(f)
                    else:
                        removed.append(f)
                with repo.dirstate.parentchange():
                    for f in removed:
                        repo.dirstate.remove(f)
                    for f in merged:
                        repo.dirstate.merge(f)
                    p1, p2 = repo.dirstate.parents()
                    repo.setparents(p1, merge)

            if all_files and '.hgsubstate' in all_files:
                wctx = repo[None]
                pctx = repo['.']
                overwrite = False
                mergedsubstate = subrepo.submerge(repo, pctx, wctx, wctx,
                    overwrite)
                files += mergedsubstate.keys()

            match = scmutil.matchfiles(repo, files or [])
            oldtip = repo['tip']
            n = newcommit(repo, None, message, ph.user, ph.date, match=match,
                          force=True)
            if repo['tip'] == oldtip:
                raise error.Abort(_("qpush exactly duplicates child changeset"))
            if n is None:
                raise error.Abort(_("repository commit failed"))

            if update_status:
                self.applied.append(statusentry(n, patchname))

            if patcherr:
                self.ui.warn(_("patch failed, rejects left in working "
                               "directory\n"))
                err = 2
                break

            if fuzz and strict:
                self.ui.warn(_("fuzz found when applying patch, stopping\n"))
                err = 3
                break
        return (err, n)

    def _cleanup(self, patches, numrevs, keep=False):
        if not keep:
            r = self.qrepo()
            if r:
                r[None].forget(patches)
            for p in patches:
                try:
                    os.unlink(self.join(p))
                except OSError as inst:
                    if inst.errno != errno.ENOENT:
                        raise

        qfinished = []
        if numrevs:
            qfinished = self.applied[:numrevs]
            del self.applied[:numrevs]
            self.applieddirty = True

        unknown = []

        for (i, p) in sorted([(self.findseries(p), p) for p in patches],
                             reverse=True):
            if i is not None:
                del self.fullseries[i]
            else:
                unknown.append(p)

        if unknown:
            if numrevs:
                rev  = dict((entry.name, entry.node) for entry in qfinished)
                for p in unknown:
                    msg = _('revision %s refers to unknown patches: %s\n')
                    self.ui.warn(msg % (short(rev[p]), p))
            else:
                msg = _('unknown patches: %s\n')
                raise error.Abort(''.join(msg % p for p in unknown))

        self.parseseries()
        self.seriesdirty = True
        return [entry.node for entry in qfinished]

    def _revpatches(self, repo, revs):
        firstrev = repo[self.applied[0].node].rev()
        patches = []
        for i, rev in enumerate(revs):

            if rev < firstrev:
                raise error.Abort(_('revision %d is not managed') % rev)

            ctx = repo[rev]
            base = self.applied[i].node
            if ctx.node() != base:
                msg = _('cannot delete revision %d above applied patches')
                raise error.Abort(msg % rev)

            patch = self.applied[i].name
            for fmt in ('[mq]: %s', 'imported patch %s'):
                if ctx.description() == fmt % patch:
                    msg = _('patch %s finalized without changeset message\n')
                    repo.ui.status(msg % patch)
                    break

            patches.append(patch)
        return patches

    def finish(self, repo, revs):
        # Manually trigger phase computation to ensure phasedefaults is
        # executed before we remove the patches.
        repo._phasecache
        patches = self._revpatches(repo, sorted(revs))
        qfinished = self._cleanup(patches, len(patches))
        if qfinished and repo.ui.configbool('mq', 'secret'):
            # only use this logic when the secret option is added
            oldqbase = repo[qfinished[0]]
            tphase = phases.newcommitphase(repo.ui)
            if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
                with repo.transaction('qfinish') as tr:
                    phases.advanceboundary(repo, tr, tphase, qfinished)

    def delete(self, repo, patches, opts):
        if not patches and not opts.get('rev'):
            raise error.Abort(_('qdelete requires at least one revision or '
                               'patch name'))

        realpatches = []
        for patch in patches:
            patch = self.lookup(patch, strict=True)
            info = self.isapplied(patch)
            if info:
                raise error.Abort(_("cannot delete applied patch %s") % patch)
            if patch not in self.series:
                raise error.Abort(_("patch %s not in series file") % patch)
            if patch not in realpatches:
                realpatches.append(patch)

        numrevs = 0
        if opts.get('rev'):
            if not self.applied:
                raise error.Abort(_('no patches applied'))
            revs = scmutil.revrange(repo, opts.get('rev'))
            revs.sort()
            revpatches = self._revpatches(repo, revs)
            realpatches += revpatches
            numrevs = len(revpatches)

        self._cleanup(realpatches, numrevs, opts.get('keep'))

    def checktoppatch(self, repo):
        '''check that working directory is at qtip'''
        if self.applied:
            top = self.applied[-1].node
            patch = self.applied[-1].name
            if repo.dirstate.p1() != top:
                raise error.Abort(_("working directory revision is not qtip"))
            return top, patch
        return None, None

    def putsubstate2changes(self, substatestate, changes):
        for files in changes[:3]:
            if '.hgsubstate' in files:
                return # already listed up
        # not yet listed up
        if substatestate in 'a?':
            changes[1].append('.hgsubstate')
        elif substatestate in 'r':
            changes[2].append('.hgsubstate')
        else: # modified
            changes[0].append('.hgsubstate')

    def checklocalchanges(self, repo, force=False, refresh=True):
        excsuffix = ''
        if refresh:
            excsuffix = ', qrefresh first'
            # plain versions for i18n tool to detect them
            _("local changes found, qrefresh first")
            _("local changed subrepos found, qrefresh first")
        return checklocalchanges(repo, force, excsuffix)

    _reserved = ('series', 'status', 'guards', '.', '..')
    def checkreservedname(self, name):
        if name in self._reserved:
            raise error.Abort(_('"%s" cannot be used as the name of a patch')
                             % name)
        if name != name.strip():
            # whitespace is stripped by parseseries()
            raise error.Abort(_('patch name cannot begin or end with '
                                'whitespace'))
        for prefix in ('.hg', '.mq'):
            if name.startswith(prefix):
                raise error.Abort(_('patch name cannot begin with "%s"')
                                 % prefix)
        for c in ('#', ':', '\r', '\n'):
            if c in name:
                raise error.Abort(_('%r cannot be used in the name of a patch')
                                 % c)

    def checkpatchname(self, name, force=False):
        self.checkreservedname(name)
        if not force and os.path.exists(self.join(name)):
            if os.path.isdir(self.join(name)):
                raise error.Abort(_('"%s" already exists as a directory')
                                 % name)
            else:
                raise error.Abort(_('patch "%s" already exists') % name)

    def makepatchname(self, title, fallbackname):
        """Return a suitable filename for title, adding a suffix to make
        it unique in the existing list"""
        namebase = re.sub('[\s\W_]+', '_', title.lower()).strip('_')
        namebase = namebase[:75] # avoid too long name (issue5117)
        if namebase:
            try:
                self.checkreservedname(namebase)
            except error.Abort:
                namebase = fallbackname
        else:
            namebase = fallbackname
        name = namebase
        i = 0
        while True:
            if name not in self.fullseries:
                try:
                    self.checkpatchname(name)
                    break
                except error.Abort:
                    pass
            i += 1
            name = '%s__%s' % (namebase, i)
        return name

    def checkkeepchanges(self, keepchanges, force):
        if force and keepchanges:
            raise error.Abort(_('cannot use both --force and --keep-changes'))

    def new(self, repo, patchfn, *pats, **opts):
        """options:
           msg: a string or a no-argument function returning a string
        """
        msg = opts.get('msg')
        edit = opts.get('edit')
        editform = opts.get('editform', 'mq.qnew')
        user = opts.get('user')
        date = opts.get('date')
        if date:
            date = util.parsedate(date)
        diffopts = self.diffopts({'git': opts.get('git')}, plain=True)
        if opts.get('checkname', True):
            self.checkpatchname(patchfn)
        inclsubs = checksubstate(repo)
        if inclsubs:
            substatestate = repo.dirstate['.hgsubstate']
        if opts.get('include') or opts.get('exclude') or pats:
            # detect missing files in pats
            def badfn(f, msg):
                if f != '.hgsubstate': # .hgsubstate is auto-created
                    raise error.Abort('%s: %s' % (f, msg))
            match = scmutil.match(repo[None], pats, opts, badfn=badfn)
            changes = repo.status(match=match)
        else:
            changes = self.checklocalchanges(repo, force=True)
        commitfiles = list(inclsubs)
        for files in changes[:3]:
            commitfiles.extend(files)
        match = scmutil.matchfiles(repo, commitfiles)
        if len(repo[None].parents()) > 1:
            raise error.Abort(_('cannot manage merge changesets'))
        self.checktoppatch(repo)
        insert = self.fullseriesend()
        with repo.wlock():
            try:
                # if patch file write fails, abort early
                p = self.opener(patchfn, "w")
            except IOError as e:
                raise error.Abort(_('cannot write patch "%s": %s')
                                 % (patchfn, encoding.strtolocal(e.strerror)))
            try:
                defaultmsg = "[mq]: %s" % patchfn
                editor = cmdutil.getcommiteditor(editform=editform)
                if edit:
                    def finishdesc(desc):
                        if desc.rstrip():
                            return desc
                        else:
                            return defaultmsg
                    # i18n: this message is shown in editor with "HG: " prefix
                    extramsg = _('Leave message empty to use default message.')
                    editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
                                                     extramsg=extramsg,
                                                     editform=editform)
                    commitmsg = msg
                else:
                    commitmsg = msg or defaultmsg

                n = newcommit(repo, None, commitmsg, user, date, match=match,
                              force=True, editor=editor)
                if n is None:
                    raise error.Abort(_("repo commit failed"))
                try:
                    self.fullseries[insert:insert] = [patchfn]
                    self.applied.append(statusentry(n, patchfn))
                    self.parseseries()
                    self.seriesdirty = True
                    self.applieddirty = True
                    nctx = repo[n]
                    ph = patchheader(self.join(patchfn), self.plainmode)
                    if user:
                        ph.setuser(user)
                    if date:
                        ph.setdate('%s %s' % date)
                    ph.setparent(hex(nctx.p1().node()))
                    msg = nctx.description().strip()
                    if msg == defaultmsg.strip():
                        msg = ''
                    ph.setmessage(msg)
                    p.write(str(ph))
                    if commitfiles:
                        parent = self.qparents(repo, n)
                        if inclsubs:
                            self.putsubstate2changes(substatestate, changes)
                        chunks = patchmod.diff(repo, node1=parent, node2=n,
                                               changes=changes, opts=diffopts)
                        for chunk in chunks:
                            p.write(chunk)
                    p.close()
                    r = self.qrepo()
                    if r:
                        r[None].add([patchfn])
                except: # re-raises
                    repo.rollback()
                    raise
            except Exception:
                patchpath = self.join(patchfn)
                try:
                    os.unlink(patchpath)
                except OSError:
                    self.ui.warn(_('error unlinking %s\n') % patchpath)
                raise
            self.removeundo(repo)

    def isapplied(self, patch):
        """returns (index, rev, patch)"""
        for i, a in enumerate(self.applied):
            if a.name == patch:
                return (i, a.node, a.name)
        return None

    # if the exact patch name does not exist, we try a few
    # variations.  If strict is passed, we try only #1
    #
    # 1) a number (as string) to indicate an offset in the series file
    # 2) a unique substring of the patch name was given
    # 3) patchname[-+]num to indicate an offset in the series file
    def lookup(self, patch, strict=False):
        def partialname(s):
            if s in self.series:
                return s
            matches = [x for x in self.series if s in x]
            if len(matches) > 1:
                self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
                for m in matches:
                    self.ui.warn('  %s\n' % m)
                return None
            if matches:
                return matches[0]
            if self.series and self.applied:
                if s == 'qtip':
                    return self.series[self.seriesend(True) - 1]
                if s == 'qbase':
                    return self.series[0]
            return None

        if patch in self.series:
            return patch

        if not os.path.isfile(self.join(patch)):
            try:
                sno = int(patch)
            except (ValueError, OverflowError):
                pass
            else:
                if -len(self.series) <= sno < len(self.series):
                    return self.series[sno]

            if not strict:
                res = partialname(patch)
                if res:
                    return res
                minus = patch.rfind('-')
                if minus >= 0:
                    res = partialname(patch[:minus])
                    if res:
                        i = self.series.index(res)
                        try:
                            off = int(patch[minus + 1:] or 1)
                        except (ValueError, OverflowError):
                            pass
                        else:
                            if i - off >= 0:
                                return self.series[i - off]
                plus = patch.rfind('+')
                if plus >= 0:
                    res = partialname(patch[:plus])
                    if res:
                        i = self.series.index(res)
                        try:
                            off = int(patch[plus + 1:] or 1)
                        except (ValueError, OverflowError):
                            pass
                        else:
                            if i + off < len(self.series):
                                return self.series[i + off]
        raise error.Abort(_("patch %s not in series") % patch)

    def push(self, repo, patch=None, force=False, list=False, mergeq=None,
             all=False, move=False, exact=False, nobackup=False,
             keepchanges=False):
        self.checkkeepchanges(keepchanges, force)
        diffopts = self.diffopts()
        with repo.wlock():
            heads = []
            for hs in repo.branchmap().itervalues():
                heads.extend(hs)
            if not heads:
                heads = [nullid]
            if repo.dirstate.p1() not in heads and not exact:
                self.ui.status(_("(working directory not at a head)\n"))

            if not self.series:
                self.ui.warn(_('no patches in series\n'))
                return 0

            # Suppose our series file is: A B C and the current 'top'
            # patch is B. qpush C should be performed (moving forward)
            # qpush B is a NOP (no change) qpush A is an error (can't
            # go backwards with qpush)
            if patch:
                patch = self.lookup(patch)
                info = self.isapplied(patch)
                if info and info[0] >= len(self.applied) - 1:
                    self.ui.warn(
                        _('qpush: %s is already at the top\n') % patch)
                    return 0

                pushable, reason = self.pushable(patch)
                if pushable:
                    if self.series.index(patch) < self.seriesend():
                        raise error.Abort(
                            _("cannot push to a previous patch: %s") % patch)
                else:
                    if reason:
                        reason = _('guarded by %s') % reason
                    else:
                        reason = _('no matching guards')
                    self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
                    return 1
            elif all:
                patch = self.series[-1]
                if self.isapplied(patch):
                    self.ui.warn(_('all patches are currently applied\n'))
                    return 0

            # Following the above example, starting at 'top' of B:
            # qpush should be performed (pushes C), but a subsequent
            # qpush without an argument is an error (nothing to
            # apply). This allows a loop of "...while hg qpush..." to
            # work as it detects an error when done
            start = self.seriesend()
            if start == len(self.series):
                self.ui.warn(_('patch series already fully applied\n'))
                return 1
            if not force and not keepchanges:
                self.checklocalchanges(repo, refresh=self.applied)

            if exact:
                if keepchanges:
                    raise error.Abort(
                        _("cannot use --exact and --keep-changes together"))
                if move:
                    raise error.Abort(_('cannot use --exact and --move '
                                       'together'))
                if self.applied:
                    raise error.Abort(_('cannot push --exact with applied '
                                       'patches'))
                root = self.series[start]
                target = patchheader(self.join(root), self.plainmode).parent
                if not target:
                    raise error.Abort(
                        _("%s does not have a parent recorded") % root)
                if not repo[target] == repo['.']:
                    hg.update(repo, target)

            if move:
                if not patch:
                    raise error.Abort(_("please specify the patch to move"))
                for fullstart, rpn in enumerate(self.fullseries):
                    # strip markers for patch guards
                    if self.guard_re.split(rpn, 1)[0] == self.series[start]:
                        break
                for i, rpn in enumerate(self.fullseries[fullstart:]):
                    # strip markers for patch guards
                    if self.guard_re.split(rpn, 1)[0] == patch:
                        break
                index = fullstart + i
                assert index < len(self.fullseries)
                fullpatch = self.fullseries[index]
                del self.fullseries[index]
                self.fullseries.insert(fullstart, fullpatch)
                self.parseseries()
                self.seriesdirty = True

            self.applieddirty = True
            if start > 0:
                self.checktoppatch(repo)
            if not patch:
                patch = self.series[start]
                end = start + 1
            else:
                end = self.series.index(patch, start) + 1

            tobackup = set()
            if (not nobackup and force) or keepchanges:
                status = self.checklocalchanges(repo, force=True)
                if keepchanges:
                    tobackup.update(status.modified + status.added +
                                    status.removed + status.deleted)
                else:
                    tobackup.update(status.modified + status.added)

            s = self.series[start:end]
            all_files = set()
            try:
                if mergeq:
                    ret = self.mergepatch(repo, mergeq, s, diffopts)
                else:
                    ret = self.apply(repo, s, list, all_files=all_files,
                                     tobackup=tobackup, keepchanges=keepchanges)
            except AbortNoCleanup:
                raise
            except: # re-raises
                self.ui.warn(_('cleaning up working directory...\n'))
                cmdutil.revert(self.ui, repo, repo['.'],
                               repo.dirstate.parents(), no_backup=True)
                # only remove unknown files that we know we touched or
                # created while patching
                for f in all_files:
                    if f not in repo.dirstate:
                        repo.wvfs.unlinkpath(f, ignoremissing=True)
                self.ui.warn(_('done\n'))
                raise

            if not self.applied:
                return ret[0]
            top = self.applied[-1].name
            if ret[0] and ret[0] > 1:
                msg = _("errors during apply, please fix and qrefresh %s\n")
                self.ui.write(msg % top)
            else:
                self.ui.write(_("now at: %s\n") % top)
            return ret[0]

    def pop(self, repo, patch=None, force=False, update=True, all=False,
            nobackup=False, keepchanges=False):
        self.checkkeepchanges(keepchanges, force)
        with repo.wlock():
            if patch:
                # index, rev, patch
                info = self.isapplied(patch)
                if not info:
                    patch = self.lookup(patch)
                info = self.isapplied(patch)
                if not info:
                    raise error.Abort(_("patch %s is not applied") % patch)

            if not self.applied:
                # Allow qpop -a to work repeatedly,
                # but not qpop without an argument
                self.ui.warn(_("no patches applied\n"))
                return not all

            if all:
                start = 0
            elif patch:
                start = info[0] + 1
            else:
                start = len(self.applied) - 1

            if start >= len(self.applied):
                self.ui.warn(_("qpop: %s is already at the top\n") % patch)
                return

            if not update:
                parents = repo.dirstate.parents()
                rr = [x.node for x in self.applied]
                for p in parents:
                    if p in rr:
                        self.ui.warn(_("qpop: forcing dirstate update\n"))
                        update = True
            else:
                parents = [p.node() for p in repo[None].parents()]
                needupdate = False
                for entry in self.applied[start:]:
                    if entry.node in parents:
                        needupdate = True
                        break
                update = needupdate

            tobackup = set()
            if update:
                s = self.checklocalchanges(repo, force=force or keepchanges)
                if force:
                    if not nobackup:
                        tobackup.update(s.modified + s.added)
                elif keepchanges:
                    tobackup.update(s.modified + s.added +
                                    s.removed + s.deleted)

            self.applieddirty = True
            end = len(self.applied)
            rev = self.applied[start].node

            try:
                heads = repo.changelog.heads(rev)
            except error.LookupError:
                node = short(rev)
                raise error.Abort(_('trying to pop unknown node %s') % node)

            if heads != [self.applied[-1].node]:
                raise error.Abort(_("popping would remove a revision not "
                                   "managed by this patch queue"))
            if not repo[self.applied[-1].node].mutable():
                raise error.Abort(
                    _("popping would remove a public revision"),
                    hint=_("see 'hg help phases' for details"))

            # we know there are no local changes, so we can make a simplified
            # form of hg.update.
            if update:
                qp = self.qparents(repo, rev)
                ctx = repo[qp]
                m, a, r, d = repo.status(qp, '.')[:4]
                if d:
                    raise error.Abort(_("deletions found between repo revs"))

                tobackup = set(a + m + r) & tobackup
                if keepchanges and tobackup:
                    raise error.Abort(_("local changes found, qrefresh first"))
                self.backup(repo, tobackup)
                with repo.dirstate.parentchange():
                    for f in a:
                        repo.wvfs.unlinkpath(f, ignoremissing=True)
                        repo.dirstate.drop(f)
                    for f in m + r:
                        fctx = ctx[f]
                        repo.wwrite(f, fctx.data(), fctx.flags())
                        repo.dirstate.normal(f)
                    repo.setparents(qp, nullid)
            for patch in reversed(self.applied[start:end]):
                self.ui.status(_("popping %s\n") % patch.name)
            del self.applied[start:end]
            strip(self.ui, repo, [rev], update=False, backup=False)
            for s, state in repo['.'].substate.items():
                repo['.'].sub(s).get(state)
            if self.applied:
                self.ui.write(_("now at: %s\n") % self.applied[-1].name)
            else:
                self.ui.write(_("patch queue now empty\n"))

    def diff(self, repo, pats, opts):
        top, patch = self.checktoppatch(repo)
        if not top:
            self.ui.write(_("no patches applied\n"))
            return
        qp = self.qparents(repo, top)
        if opts.get('reverse'):
            node1, node2 = None, qp
        else:
            node1, node2 = qp, None
        diffopts = self.diffopts(opts, patch)
        self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)

    def refresh(self, repo, pats=None, **opts):
        if not self.applied:
            self.ui.write(_("no patches applied\n"))
            return 1
        msg = opts.get('msg', '').rstrip()
        edit = opts.get('edit')
        editform = opts.get('editform', 'mq.qrefresh')
        newuser = opts.get('user')
        newdate = opts.get('date')
        if newdate:
            newdate = '%d %d' % util.parsedate(newdate)
        wlock = repo.wlock()

        try:
            self.checktoppatch(repo)
            (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
            if repo.changelog.heads(top) != [top]:
                raise error.Abort(_("cannot qrefresh a revision with children"))
            if not repo[top].mutable():
                raise error.Abort(_("cannot qrefresh public revision"),
                                 hint=_("see 'hg help phases' for details"))

            cparents = repo.changelog.parents(top)
            patchparent = self.qparents(repo, top)

            inclsubs = checksubstate(repo, hex(patchparent))
            if inclsubs:
                substatestate = repo.dirstate['.hgsubstate']

            ph = patchheader(self.join(patchfn), self.plainmode)
            diffopts = self.diffopts({'git': opts.get('git')}, patchfn,
                                     plain=True)
            if newuser:
                ph.setuser(newuser)
            if newdate:
                ph.setdate(newdate)
            ph.setparent(hex(patchparent))

            # only commit new patch when write is complete
            patchf = self.opener(patchfn, 'w', atomictemp=True)

            # update the dirstate in place, strip off the qtip commit
            # and then commit.
            #
            # this should really read:
            #   mm, dd, aa = repo.status(top, patchparent)[:3]
            # but we do it backwards to take advantage of manifest/changelog
            # caching against the next repo.status call
            mm, aa, dd = repo.status(patchparent, top)[:3]
            changes = repo.changelog.read(top)
            man = repo.manifestlog[changes[0]].read()
            aaa = aa[:]
            match1 = scmutil.match(repo[None], pats, opts)
            # in short mode, we only diff the files included in the
            # patch already plus specified files
            if opts.get('short'):
                # if amending a patch, we start with existing
                # files plus specified files - unfiltered
                match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
                # filter with include/exclude options
                match1 = scmutil.match(repo[None], opts=opts)
            else:
                match = scmutil.matchall(repo)
            m, a, r, d = repo.status(match=match)[:4]
            mm = set(mm)
            aa = set(aa)
            dd = set(dd)

            # we might end up with files that were added between
            # qtip and the dirstate parent, but then changed in the
            # local dirstate. in this case, we want them to only
            # show up in the added section
            for x in m:
                if x not in aa:
                    mm.add(x)
            # we might end up with files added by the local dirstate that
            # were deleted by the patch.  In this case, they should only
            # show up in the changed section.
            for x in a:
                if x in dd:
                    dd.remove(x)
                    mm.add(x)
                else:
                    aa.add(x)
            # make sure any files deleted in the local dirstate
            # are not in the add or change column of the patch
            forget = []
            for x in d + r:
                if x in aa:
                    aa.remove(x)
                    forget.append(x)
                    continue
                else:
                    mm.discard(x)
                dd.add(x)

            m = list(mm)
            r = list(dd)
            a = list(aa)

            # create 'match' that includes the files to be recommitted.
            # apply match1 via repo.status to ensure correct case handling.
            cm, ca, cr, cd = repo.status(patchparent, match=match1)[:4]
            allmatches = set(cm + ca + cr + cd)
            refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]

            files = set(inclsubs)
            for x in refreshchanges:
                files.update(x)
            match = scmutil.matchfiles(repo, files)

            bmlist = repo[top].bookmarks()

            dsguard = None
            try:
                dsguard = dirstateguard.dirstateguard(repo, 'mq.refresh')
                if diffopts.git or diffopts.upgrade:
                    copies = {}
                    for dst in a:
                        src = repo.dirstate.copied(dst)
                        # during qfold, the source file for copies may
                        # be removed. Treat this as a simple add.
                        if src is not None and src in repo.dirstate:
                            copies.setdefault(src, []).append(dst)
                        repo.dirstate.add(dst)
                    # remember the copies between patchparent and qtip
                    for dst in aaa:
                        f = repo.file(dst)
                        src = f.renamed(man[dst])
                        if src:
                            copies.setdefault(src[0], []).extend(
                                copies.get(dst, []))
                            if dst in a:
                                copies[src[0]].append(dst)
                        # we can't copy a file created by the patch itself
                        if dst in copies:
                            del copies[dst]
                    for src, dsts in copies.iteritems():
                        for dst in dsts:
                            repo.dirstate.copy(src, dst)
                else:
                    for dst in a:
                        repo.dirstate.add(dst)
                    # Drop useless copy information
                    for f in list(repo.dirstate.copies()):
                        repo.dirstate.copy(None, f)
                for f in r:
                    repo.dirstate.remove(f)
                # if the patch excludes a modified file, mark that
                # file with mtime=0 so status can see it.
                mm = []
                for i in xrange(len(m) - 1, -1, -1):
                    if not match1(m[i]):
                        mm.append(m[i])
                        del m[i]
                for f in m:
                    repo.dirstate.normal(f)
                for f in mm:
                    repo.dirstate.normallookup(f)
                for f in forget:
                    repo.dirstate.drop(f)

                user = ph.user or changes[1]

                oldphase = repo[top].phase()

                # assumes strip can roll itself back if interrupted
                repo.setparents(*cparents)
                self.applied.pop()
                self.applieddirty = True
                strip(self.ui, repo, [top], update=False, backup=False)
                dsguard.close()
            finally:
                release(dsguard)

            try:
                # might be nice to attempt to roll back strip after this

                defaultmsg = "[mq]: %s" % patchfn
                editor = cmdutil.getcommiteditor(editform=editform)
                if edit:
                    def finishdesc(desc):
                        if desc.rstrip():
                            ph.setmessage(desc)
                            return desc
                        return defaultmsg
                    # i18n: this message is shown in editor with "HG: " prefix
                    extramsg = _('Leave message empty to use default message.')
                    editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
                                                     extramsg=extramsg,
                                                     editform=editform)
                    message = msg or "\n".join(ph.message)
                elif not msg:
                    if not ph.message:
                        message = defaultmsg
                    else:
                        message = "\n".join(ph.message)
                else:
                    message = msg
                    ph.setmessage(msg)

                # Ensure we create a new changeset in the same phase than
                # the old one.
                lock = tr = None
                try:
                    lock = repo.lock()
                    tr = repo.transaction('mq')
                    n = newcommit(repo, oldphase, message, user, ph.date,
                              match=match, force=True, editor=editor)
                    # only write patch after a successful commit
                    c = [list(x) for x in refreshchanges]
                    if inclsubs:
                        self.putsubstate2changes(substatestate, c)
                    chunks = patchmod.diff(repo, patchparent,
                                           changes=c, opts=diffopts)
                    comments = str(ph)
                    if comments:
                        patchf.write(comments)
                    for chunk in chunks:
                        patchf.write(chunk)
                    patchf.close()

                    marks = repo._bookmarks
                    marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
                    tr.close()

                    self.applied.append(statusentry(n, patchfn))
                finally:
                    lockmod.release(tr, lock)
            except: # re-raises
                ctx = repo[cparents[0]]
                repo.dirstate.rebuild(ctx.node(), ctx.manifest())
                self.savedirty()
                self.ui.warn(_('qrefresh interrupted while patch was popped! '
                               '(revert --all, qpush to recover)\n'))
                raise
        finally:
            wlock.release()
            self.removeundo(repo)

    def init(self, repo, create=False):
        if not create and os.path.isdir(self.path):
            raise error.Abort(_("patch queue directory already exists"))
        try:
            os.mkdir(self.path)
        except OSError as inst:
            if inst.errno != errno.EEXIST or not create:
                raise
        if create:
            return self.qrepo(create=True)

    def unapplied(self, repo, patch=None):
        if patch and patch not in self.series:
            raise error.Abort(_("patch %s is not in series file") % patch)
        if not patch:
            start = self.seriesend()
        else:
            start = self.series.index(patch) + 1
        unapplied = []
        for i in xrange(start, len(self.series)):
            pushable, reason = self.pushable(i)
            if pushable:
                unapplied.append((i, self.series[i]))
            self.explainpushable(i)
        return unapplied

    def qseries(self, repo, missing=None, start=0, length=None, status=None,
                summary=False):
        def displayname(pfx, patchname, state):
            if pfx:
                self.ui.write(pfx)
            if summary:
                ph = patchheader(self.join(patchname), self.plainmode)
                if ph.message:
                    msg = ph.message[0]
                else:
                    msg = ''

                if self.ui.formatted():
                    width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
                    if width > 0:
                        msg = util.ellipsis(msg, width)
                    else:
                        msg = ''
                self.ui.write(patchname, label='qseries.' + state)
                self.ui.write(': ')
                self.ui.write(msg, label='qseries.message.' + state)
            else:
                self.ui.write(patchname, label='qseries.' + state)
            self.ui.write('\n')

        applied = set([p.name for p in self.applied])
        if length is None:
            length = len(self.series) - start
        if not missing:
            if self.ui.verbose:
                idxwidth = len(str(start + length - 1))
            for i in xrange(start, start + length):
                patch = self.series[i]
                if patch in applied:
                    char, state = 'A', 'applied'
                elif self.pushable(i)[0]:
                    char, state = 'U', 'unapplied'
                else:
                    char, state = 'G', 'guarded'
                pfx = ''
                if self.ui.verbose:
                    pfx = '%*d %s ' % (idxwidth, i, char)
                elif status and status != char:
                    continue
                displayname(pfx, patch, state)
        else:
            msng_list = []
            for root, dirs, files in os.walk(self.path):
                d = root[len(self.path) + 1:]
                for f in files:
                    fl = os.path.join(d, f)
                    if (fl not in self.series and
                        fl not in (self.statuspath, self.seriespath,
                                   self.guardspath)
                        and not fl.startswith('.')):
                        msng_list.append(fl)
            for x in sorted(msng_list):
                pfx = self.ui.verbose and ('D ') or ''
                displayname(pfx, x, 'missing')

    def issaveline(self, l):
        if l.name == '.hg.patches.save.line':
            return True

    def qrepo(self, create=False):
        ui = self.baseui.copy()
        # copy back attributes set by ui.pager()
        if self.ui.pageractive and not ui.pageractive:
            ui.pageractive = self.ui.pageractive
            # internal config: ui.formatted
            ui.setconfig('ui', 'formatted',
                         self.ui.config('ui', 'formatted'), 'mqpager')
            ui.setconfig('ui', 'interactive',
                         self.ui.config('ui', 'interactive'), 'mqpager')
        if create or os.path.isdir(self.join(".hg")):
            return hg.repository(ui, path=self.path, create=create)

    def restore(self, repo, rev, delete=None, qupdate=None):
        desc = repo[rev].description().strip()
        lines = desc.splitlines()
        i = 0
        datastart = None
        series = []
        applied = []
        qpp = None
        for i, line in enumerate(lines):
            if line == 'Patch Data:':
                datastart = i + 1
            elif line.startswith('Dirstate:'):
                l = line.rstrip()
                l = l[10:].split(' ')
                qpp = [bin(x) for x in l]
            elif datastart is not None:
                l = line.rstrip()
                n, name = l.split(':', 1)
                if n:
                    applied.append(statusentry(bin(n), name))
                else:
                    series.append(l)
        if datastart is None:
            self.ui.warn(_("no saved patch data found\n"))
            return 1
        self.ui.warn(_("restoring status: %s\n") % lines[0])
        self.fullseries = series
        self.applied = applied
        self.parseseries()
        self.seriesdirty = True
        self.applieddirty = True
        heads = repo.changelog.heads()
        if delete:
            if rev not in heads:
                self.ui.warn(_("save entry has children, leaving it alone\n"))
            else:
                self.ui.warn(_("removing save entry %s\n") % short(rev))
                pp = repo.dirstate.parents()
                if rev in pp:
                    update = True
                else:
                    update = False
                strip(self.ui, repo, [rev], update=update, backup=False)
        if qpp:
            self.ui.warn(_("saved queue repository parents: %s %s\n") %
                         (short(qpp[0]), short(qpp[1])))
            if qupdate:
                self.ui.status(_("updating queue directory\n"))
                r = self.qrepo()
                if not r:
                    self.ui.warn(_("unable to load queue repository\n"))
                    return 1
                hg.clean(r, qpp[0])

    def save(self, repo, msg=None):
        if not self.applied:
            self.ui.warn(_("save: no patches applied, exiting\n"))
            return 1
        if self.issaveline(self.applied[-1]):
            self.ui.warn(_("status is already saved\n"))
            return 1

        if not msg:
            msg = _("hg patches saved state")
        else:
            msg = "hg patches: " + msg.rstrip('\r\n')
        r = self.qrepo()
        if r:
            pp = r.dirstate.parents()
            msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
        msg += "\n\nPatch Data:\n"
        msg += ''.join('%s\n' % x for x in self.applied)
        msg += ''.join(':%s\n' % x for x in self.fullseries)
        n = repo.commit(msg, force=True)
        if not n:
            self.ui.warn(_("repo commit failed\n"))
            return 1
        self.applied.append(statusentry(n, '.hg.patches.save.line'))
        self.applieddirty = True
        self.removeundo(repo)

    def fullseriesend(self):
        if self.applied:
            p = self.applied[-1].name
            end = self.findseries(p)
            if end is None:
                return len(self.fullseries)
            return end + 1
        return 0

    def seriesend(self, all_patches=False):
        """If all_patches is False, return the index of the next pushable patch
        in the series, or the series length. If all_patches is True, return the
        index of the first patch past the last applied one.
        """
        end = 0
        def nextpatch(start):
            if all_patches or start >= len(self.series):
                return start
            for i in xrange(start, len(self.series)):
                p, reason = self.pushable(i)
                if p:
                    return i
                self.explainpushable(i)
            return len(self.series)
        if self.applied:
            p = self.applied[-1].name
            try:
                end = self.series.index(p)
            except ValueError:
                return 0
            return nextpatch(end + 1)
        return nextpatch(end)

    def appliedname(self, index):
        pname = self.applied[index].name
        if not self.ui.verbose:
            p = pname
        else:
            p = str(self.series.index(pname)) + " " + pname
        return p

    def qimport(self, repo, files, patchname=None, rev=None, existing=None,
                force=None, git=False):
        def checkseries(patchname):
            if patchname in self.series:
                raise error.Abort(_('patch %s is already in the series file')
                                 % patchname)

        if rev:
            if files:
                raise error.Abort(_('option "-r" not valid when importing '
                                   'files'))
            rev = scmutil.revrange(repo, rev)
            rev.sort(reverse=True)
        elif not files:
            raise error.Abort(_('no files or revisions specified'))
        if (len(files) > 1 or len(rev) > 1) and patchname:
            raise error.Abort(_('option "-n" not valid when importing multiple '
                               'patches'))
        imported = []
        if rev:
            # If mq patches are applied, we can only import revisions
            # that form a linear path to qbase.
            # Otherwise, they should form a linear path to a head.
            heads = repo.changelog.heads(repo.changelog.node(rev.first()))
            if len(heads) > 1:
                raise error.Abort(_('revision %d is the root of more than one '
                                   'branch') % rev.last())
            if self.applied:
                base = repo.changelog.node(rev.first())
                if base in [n.node for n in self.applied]:
                    raise error.Abort(_('revision %d is already managed')
                                     % rev.first())
                if heads != [self.applied[-1].node]:
                    raise error.Abort(_('revision %d is not the parent of '
                                       'the queue') % rev.first())
                base = repo.changelog.rev(self.applied[0].node)
                lastparent = repo.changelog.parentrevs(base)[0]
            else:
                if heads != [repo.changelog.node(rev.first())]:
                    raise error.Abort(_('revision %d has unmanaged children')
                                     % rev.first())
                lastparent = None

            diffopts = self.diffopts({'git': git})
            with repo.transaction('qimport') as tr:
                for r in rev:
                    if not repo[r].mutable():
                        raise error.Abort(_('revision %d is not mutable') % r,
                                         hint=_("see 'hg help phases' "
                                                'for details'))
                    p1, p2 = repo.changelog.parentrevs(r)
                    n = repo.changelog.node(r)
                    if p2 != nullrev:
                        raise error.Abort(_('cannot import merge revision %d')
                                         % r)
                    if lastparent and lastparent != r:
                        raise error.Abort(_('revision %d is not the parent of '
                                           '%d')
                                         % (r, lastparent))
                    lastparent = p1

                    if not patchname:
                        patchname = self.makepatchname(
                            repo[r].description().split('\n', 1)[0],
                            '%d.diff' % r)
                    checkseries(patchname)
                    self.checkpatchname(patchname, force)
                    self.fullseries.insert(0, patchname)

                    patchf = self.opener(patchname, "w")
                    cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
                    patchf.close()

                    se = statusentry(n, patchname)
                    self.applied.insert(0, se)

                    self.added.append(patchname)
                    imported.append(patchname)
                    patchname = None
                    if rev and repo.ui.configbool('mq', 'secret'):
                        # if we added anything with --rev, move the secret root
                        phases.retractboundary(repo, tr, phases.secret, [n])
                    self.parseseries()
                    self.applieddirty = True
                    self.seriesdirty = True

        for i, filename in enumerate(files):
            if existing:
                if filename == '-':
                    raise error.Abort(_('-e is incompatible with import from -')
                                     )
                filename = normname(filename)
                self.checkreservedname(filename)
                if util.url(filename).islocal():
                    originpath = self.join(filename)
                    if not os.path.isfile(originpath):
                        raise error.Abort(
                            _("patch %s does not exist") % filename)

                if patchname:
                    self.checkpatchname(patchname, force)

                    self.ui.write(_('renaming %s to %s\n')
                                        % (filename, patchname))
                    util.rename(originpath, self.join(patchname))
                else:
                    patchname = filename

            else:
                if filename == '-' and not patchname:
                    raise error.Abort(_('need --name to import a patch from -'))
                elif not patchname:
                    patchname = normname(os.path.basename(filename.rstrip('/')))
                self.checkpatchname(patchname, force)
                try:
                    if filename == '-':
                        text = self.ui.fin.read()
                    else:
                        fp = hg.openpath(self.ui, filename)
                        text = fp.read()
                        fp.close()
                except (OSError, IOError):
                    raise error.Abort(_("unable to read file %s") % filename)
                patchf = self.opener(patchname, "w")
                patchf.write(text)
                patchf.close()
            if not force:
                checkseries(patchname)
            if patchname not in self.series:
                index = self.fullseriesend() + i
                self.fullseries[index:index] = [patchname]
            self.parseseries()
            self.seriesdirty = True
            self.ui.warn(_("adding %s to series file\n") % patchname)
            self.added.append(patchname)
            imported.append(patchname)
            patchname = None

        self.removeundo(repo)
        return imported

def fixkeepchangesopts(ui, opts):
    if (not ui.configbool('mq', 'keepchanges') or opts.get('force')
        or opts.get('exact')):
        return opts
    opts = dict(opts)
    opts['keep_changes'] = True
    return opts

@command("qdelete|qremove|qrm",
         [('k', 'keep', None, _('keep patch file')),
          ('r', 'rev', [],
           _('stop managing a revision (DEPRECATED)'), _('REV'))],
         _('hg qdelete [-k] [PATCH]...'))
def delete(ui, repo, *patches, **opts):
    """remove patches from queue

    The patches must not be applied, and at least one patch is required. Exact
    patch identifiers must be given. With -k/--keep, the patch files are
    preserved in the patch directory.

    To stop managing a patch and move it into permanent history,
    use the :hg:`qfinish` command."""
    q = repo.mq
    q.delete(repo, patches, opts)
    q.savedirty()
    return 0

@command("qapplied",
         [('1', 'last', None, _('show only the preceding applied patch'))
          ] + seriesopts,
         _('hg qapplied [-1] [-s] [PATCH]'))
def applied(ui, repo, patch=None, **opts):
    """print the patches already applied

    Returns 0 on success."""

    q = repo.mq
    opts = pycompat.byteskwargs(opts)

    if patch:
        if patch not in q.series:
            raise error.Abort(_("patch %s is not in series file") % patch)
        end = q.series.index(patch) + 1
    else:
        end = q.seriesend(True)

    if opts.get('last') and not end:
        ui.write(_("no patches applied\n"))
        return 1
    elif opts.get('last') and end == 1:
        ui.write(_("only one patch applied\n"))
        return 1
    elif opts.get('last'):
        start = end - 2
        end = 1
    else:
        start = 0

    q.qseries(repo, length=end, start=start, status='A',
              summary=opts.get('summary'))


@command("qunapplied",
         [('1', 'first', None, _('show only the first patch'))] + seriesopts,
         _('hg qunapplied [-1] [-s] [PATCH]'))
def unapplied(ui, repo, patch=None, **opts):
    """print the patches not yet applied

    Returns 0 on success."""

    q = repo.mq
    opts = pycompat.byteskwargs(opts)
    if patch:
        if patch not in q.series:
            raise error.Abort(_("patch %s is not in series file") % patch)
        start = q.series.index(patch) + 1
    else:
        start = q.seriesend(True)

    if start == len(q.series) and opts.get('first'):
        ui.write(_("all patches applied\n"))
        return 1

    if opts.get('first'):
        length = 1
    else:
        length = None
    q.qseries(repo, start=start, length=length, status='U',
              summary=opts.get('summary'))

@command("qimport",
         [('e', 'existing', None, _('import file in patch directory')),
          ('n', 'name', '',
           _('name of patch file'), _('NAME')),
          ('f', 'force', None, _('overwrite existing files')),
          ('r', 'rev', [],
           _('place existing revisions under mq control'), _('REV')),
          ('g', 'git', None, _('use git extended diff format')),
          ('P', 'push', None, _('qpush after importing'))],
         _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'))
def qimport(ui, repo, *filename, **opts):
    """import a patch or existing changeset

    The patch is inserted into the series after the last applied
    patch. If no patches have been applied, qimport prepends the patch
    to the series.

    The patch will have the same name as its source file unless you
    give it a new one with -n/--name.

    You can register an existing patch inside the patch directory with
    the -e/--existing flag.

    With -f/--force, an existing patch of the same name will be
    overwritten.

    An existing changeset may be placed under mq control with -r/--rev
    (e.g. qimport --rev . -n patch will place the current revision
    under mq control). With -g/--git, patches imported with --rev will
    use the git diff format. See the diffs help topic for information
    on why this is important for preserving rename/copy information
    and permission changes. Use :hg:`qfinish` to remove changesets
    from mq control.

    To import a patch from standard input, pass - as the patch file.
    When importing from standard input, a patch name must be specified
    using the --name flag.

    To import an existing patch while renaming it::

      hg qimport -e existing-patch -n new-name

    Returns 0 if import succeeded.
    """
    opts = pycompat.byteskwargs(opts)
    with repo.lock(): # cause this may move phase
        q = repo.mq
        try:
            imported = q.qimport(
                repo, filename, patchname=opts.get('name'),
                existing=opts.get('existing'), force=opts.get('force'),
                rev=opts.get('rev'), git=opts.get('git'))
        finally:
            q.savedirty()

    if imported and opts.get('push') and not opts.get('rev'):
        return q.push(repo, imported[-1])
    return 0

def qinit(ui, repo, create):
    """initialize a new queue repository

    This command also creates a series file for ordering patches, and
    an mq-specific .hgignore file in the queue repository, to exclude
    the status and guards files (these contain mostly transient state).

    Returns 0 if initialization succeeded."""
    q = repo.mq
    r = q.init(repo, create)
    q.savedirty()
    if r:
        if not os.path.exists(r.wjoin('.hgignore')):
            fp = r.wvfs('.hgignore', 'w')
            fp.write('^\\.hg\n')
            fp.write('^\\.mq\n')
            fp.write('syntax: glob\n')
            fp.write('status\n')
            fp.write('guards\n')
            fp.close()
        if not os.path.exists(r.wjoin('series')):
            r.wvfs('series', 'w').close()
        r[None].add(['.hgignore', 'series'])
        commands.add(ui, r)
    return 0

@command("^qinit",
         [('c', 'create-repo', None, _('create queue repository'))],
         _('hg qinit [-c]'))
def init(ui, repo, **opts):
    """init a new queue repository (DEPRECATED)

    The queue repository is unversioned by default. If
    -c/--create-repo is specified, qinit will create a separate nested
    repository for patches (qinit -c may also be run later to convert
    an unversioned patch repository into a versioned one). You can use
    qcommit to commit changes to this queue repository.

    This command is deprecated. Without -c, it's implied by other relevant
    commands. With -c, use :hg:`init --mq` instead."""
    return qinit(ui, repo, create=opts.get(r'create_repo'))

@command("qclone",
         [('', 'pull', None, _('use pull protocol to copy metadata')),
          ('U', 'noupdate', None,
           _('do not update the new working directories')),
          ('', 'uncompressed', None,
           _('use uncompressed transfer (fast over LAN)')),
          ('p', 'patches', '',
           _('location of source patch repository'), _('REPO')),
         ] + cmdutil.remoteopts,
         _('hg qclone [OPTION]... SOURCE [DEST]'),
         norepo=True)
def clone(ui, source, dest=None, **opts):
    '''clone main and patch repository at same time

    If source is local, destination will have no patches applied. If
    source is remote, this command can not check if patches are
    applied in source, so cannot guarantee that patches are not
    applied in destination. If you clone remote repository, be sure
    before that it has no patches applied.

    Source patch repository is looked for in <src>/.hg/patches by
    default. Use -p <url> to change.

    The patch directory must be a nested Mercurial repository, as
    would be created by :hg:`init --mq`.

    Return 0 on success.
    '''
    opts = pycompat.byteskwargs(opts)
    def patchdir(repo):
        """compute a patch repo url from a repo object"""
        url = repo.url()
        if url.endswith('/'):
            url = url[:-1]
        return url + '/.hg/patches'

    # main repo (destination and sources)
    if dest is None:
        dest = hg.defaultdest(source)
    sr = hg.peer(ui, opts, ui.expandpath(source))

    # patches repo (source only)
    if opts.get('patches'):
        patchespath = ui.expandpath(opts.get('patches'))
    else:
        patchespath = patchdir(sr)
    try:
        hg.peer(ui, opts, patchespath)
    except error.RepoError:
        raise error.Abort(_('versioned patch repository not found'
                           ' (see init --mq)'))
    qbase, destrev = None, None
    if sr.local():
        repo = sr.local()
        if repo.mq.applied and repo[qbase].phase() != phases.secret:
            qbase = repo.mq.applied[0].node
            if not hg.islocal(dest):
                heads = set(repo.heads())
                destrev = list(heads.difference(repo.heads(qbase)))
                destrev.append(repo.changelog.parents(qbase)[0])
    elif sr.capable('lookup'):
        try:
            qbase = sr.lookup('qbase')
        except error.RepoError:
            pass

    ui.note(_('cloning main repository\n'))
    sr, dr = hg.clone(ui, opts, sr.url(), dest,
                      pull=opts.get('pull'),
                      rev=destrev,
                      update=False,
                      stream=opts.get('uncompressed'))

    ui.note(_('cloning patch repository\n'))
    hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
             pull=opts.get('pull'), update=not opts.get('noupdate'),
             stream=opts.get('uncompressed'))

    if dr.local():
        repo = dr.local()
        if qbase:
            ui.note(_('stripping applied patches from destination '
                      'repository\n'))
            strip(ui, repo, [qbase], update=False, backup=None)
        if not opts.get('noupdate'):
            ui.note(_('updating destination repository\n'))
            hg.update(repo, repo.changelog.tip())

@command("qcommit|qci",
         commands.table["^commit|ci"][1],
         _('hg qcommit [OPTION]... [FILE]...'),
         inferrepo=True)
def commit(ui, repo, *pats, **opts):
    """commit changes in the queue repository (DEPRECATED)

    This command is deprecated; use :hg:`commit --mq` instead."""
    q = repo.mq
    r = q.qrepo()
    if not r:
        raise error.Abort('no queue repository')
    commands.commit(r.ui, r, *pats, **opts)

@command("qseries",
         [('m', 'missing', None, _('print patches not in series')),
         ] + seriesopts,
          _('hg qseries [-ms]'))
def series(ui, repo, **opts):
    """print the entire series file

    Returns 0 on success."""
    repo.mq.qseries(repo, missing=opts.get(r'missing'),
                    summary=opts.get(r'summary'))
    return 0

@command("qtop", seriesopts, _('hg qtop [-s]'))
def top(ui, repo, **opts):
    """print the name of the current patch

    Returns 0 on success."""
    q = repo.mq
    if q.applied:
        t = q.seriesend(True)
    else:
        t = 0

    if t:
        q.qseries(repo, start=t - 1, length=1, status='A',
                  summary=opts.get(r'summary'))
    else:
        ui.write(_("no patches applied\n"))
        return 1

@command("qnext", seriesopts, _('hg qnext [-s]'))
def next(ui, repo, **opts):
    """print the name of the next pushable patch

    Returns 0 on success."""
    q = repo.mq
    end = q.seriesend()
    if end == len(q.series):
        ui.write(_("all patches applied\n"))
        return 1
    q.qseries(repo, start=end, length=1, summary=opts.get(r'summary'))

@command("qprev", seriesopts, _('hg qprev [-s]'))
def prev(ui, repo, **opts):
    """print the name of the preceding applied patch

    Returns 0 on success."""
    q = repo.mq
    l = len(q.applied)
    if l == 1:
        ui.write(_("only one patch applied\n"))
        return 1
    if not l:
        ui.write(_("no patches applied\n"))
        return 1
    idx = q.series.index(q.applied[-2].name)
    q.qseries(repo, start=idx, length=1, status='A',
              summary=opts.get(r'summary'))

def setupheaderopts(ui, opts):
    if not opts.get('user') and opts.get('currentuser'):
        opts['user'] = ui.username()
    if not opts.get('date') and opts.get('currentdate'):
        opts['date'] = "%d %d" % util.makedate()

@command("^qnew",
         [('e', 'edit', None, _('invoke editor on commit messages')),
          ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
          ('g', 'git', None, _('use git extended diff format')),
          ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
          ('u', 'user', '',
           _('add "From: <USER>" to patch'), _('USER')),
          ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
          ('d', 'date', '',
           _('add "Date: <DATE>" to patch'), _('DATE'))
          ] + cmdutil.walkopts + cmdutil.commitopts,
         _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
         inferrepo=True)
def new(ui, repo, patch, *args, **opts):
    """create a new patch

    qnew creates a new patch on top of the currently-applied patch (if
    any). The patch will be initialized with any outstanding changes
    in the working directory. You may also use -I/--include,
    -X/--exclude, and/or a list of files after the patch name to add
    only changes to matching files to the new patch, leaving the rest
    as uncommitted modifications.

    -u/--user and -d/--date can be used to set the (given) user and
    date, respectively. -U/--currentuser and -D/--currentdate set user
    to current user and date to current date.

    -e/--edit, -m/--message or -l/--logfile set the patch header as
    well as the commit message. If none is specified, the header is
    empty and the commit message is '[mq]: PATCH'.

    Use the -g/--git option to keep the patch in the git extended diff
    format. Read the diffs help topic for more information on why this
    is important for preserving permission changes and copy/rename
    information.

    Returns 0 on successful creation of a new patch.
    """
    opts = pycompat.byteskwargs(opts)
    msg = cmdutil.logmessage(ui, opts)
    q = repo.mq
    opts['msg'] = msg
    setupheaderopts(ui, opts)
    q.new(repo, patch, *args, **pycompat.strkwargs(opts))
    q.savedirty()
    return 0

@command("^qrefresh",
         [('e', 'edit', None, _('invoke editor on commit messages')),
          ('g', 'git', None, _('use git extended diff format')),
          ('s', 'short', None,
           _('refresh only files already in the patch and specified files')),
          ('U', 'currentuser', None,
           _('add/update author field in patch with current user')),
          ('u', 'user', '',
           _('add/update author field in patch with given user'), _('USER')),
          ('D', 'currentdate', None,
           _('add/update date field in patch with current date')),
          ('d', 'date', '',
           _('add/update date field in patch with given date'), _('DATE'))
          ] + cmdutil.walkopts + cmdutil.commitopts,
         _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
         inferrepo=True)
def refresh(ui, repo, *pats, **opts):
    """update the current patch

    If any file patterns are provided, the refreshed patch will
    contain only the modifications that match those patterns; the
    remaining modifications will remain in the working directory.

    If -s/--short is specified, files currently included in the patch
    will be refreshed just like matched files and remain in the patch.

    If -e/--edit is specified, Mercurial will start your configured editor for
    you to enter a message. In case qrefresh fails, you will find a backup of
    your message in ``.hg/last-message.txt``.

    hg add/remove/copy/rename work as usual, though you might want to
    use git-style patches (-g/--git or [diff] git=1) to track copies
    and renames. See the diffs help topic for more information on the
    git diff format.

    Returns 0 on success.
    """
    opts = pycompat.byteskwargs(opts)
    q = repo.mq
    message = cmdutil.logmessage(ui, opts)
    setupheaderopts(ui, opts)
    with repo.wlock():
        ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
        q.savedirty()
        return ret

@command("^qdiff",
         cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
         _('hg qdiff [OPTION]... [FILE]...'),
         inferrepo=True)
def diff(ui, repo, *pats, **opts):
    """diff of the current patch and subsequent modifications

    Shows a diff which includes the current patch as well as any
    changes which have been made in the working directory since the
    last refresh (thus showing what the current patch would become
    after a qrefresh).

    Use :hg:`diff` if you only want to see the changes made since the
    last qrefresh, or :hg:`export qtip` if you want to see changes
    made by the current patch without including changes made since the
    qrefresh.

    Returns 0 on success.
    """
    ui.pager('qdiff')
    repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
    return 0

@command('qfold',
         [('e', 'edit', None, _('invoke editor on commit messages')),
          ('k', 'keep', None, _('keep folded patch files')),
         ] + cmdutil.commitopts,
         _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
def fold(ui, repo, *files, **opts):
    """fold the named patches into the current patch

    Patches must not yet be applied. Each patch will be successively
    applied to the current patch in the order given. If all the
    patches apply successfully, the current patch will be refreshed
    with the new cumulative patch, and the folded patches will be
    deleted. With -k/--keep, the folded patch files will not be
    removed afterwards.

    The header for each folded patch will be concatenated with the
    current patch header, separated by a line of ``* * *``.

    Returns 0 on success."""
    opts = pycompat.byteskwargs(opts)
    q = repo.mq
    if not files:
        raise error.Abort(_('qfold requires at least one patch name'))
    if not q.checktoppatch(repo)[0]:
        raise error.Abort(_('no patches applied'))
    q.checklocalchanges(repo)

    message = cmdutil.logmessage(ui, opts)

    parent = q.lookup('qtip')
    patches = []
    messages = []
    for f in files:
        p = q.lookup(f)
        if p in patches or p == parent:
            ui.warn(_('skipping already folded patch %s\n') % p)
        if q.isapplied(p):
            raise error.Abort(_('qfold cannot fold already applied patch %s')
                             % p)
        patches.append(p)

    for p in patches:
        if not message:
            ph = patchheader(q.join(p), q.plainmode)
            if ph.message:
                messages.append(ph.message)
        pf = q.join(p)
        (patchsuccess, files, fuzz) = q.patch(repo, pf)
        if not patchsuccess:
            raise error.Abort(_('error folding patch %s') % p)

    if not message:
        ph = patchheader(q.join(parent), q.plainmode)
        message = ph.message
        for msg in messages:
            if msg:
                if message:
                    message.append('* * *')
                message.extend(msg)
        message = '\n'.join(message)

    diffopts = q.patchopts(q.diffopts(), *patches)
    with repo.wlock():
        q.refresh(repo, msg=message, git=diffopts.git, edit=opts.get('edit'),
                  editform='mq.qfold')
        q.delete(repo, patches, opts)
        q.savedirty()

@command("qgoto",
         [('', 'keep-changes', None,
           _('tolerate non-conflicting local changes')),
          ('f', 'force', None, _('overwrite any local changes')),
          ('', 'no-backup', None, _('do not save backup copies of files'))],
         _('hg qgoto [OPTION]... PATCH'))
def goto(ui, repo, patch, **opts):
    '''push or pop patches until named patch is at top of stack

    Returns 0 on success.'''
    opts = pycompat.byteskwargs(opts)
    opts = fixkeepchangesopts(ui, opts)
    q = repo.mq
    patch = q.lookup(patch)
    nobackup = opts.get('no_backup')
    keepchanges = opts.get('keep_changes')
    if q.isapplied(patch):
        ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
                    keepchanges=keepchanges)
    else:
        ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
                     keepchanges=keepchanges)
    q.savedirty()
    return ret

@command("qguard",
         [('l', 'list', None, _('list all patches and guards')),
          ('n', 'none', None, _('drop all guards'))],
         _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
def guard(ui, repo, *args, **opts):
    '''set or print guards for a patch

    Guards control whether a patch can be pushed. A patch with no
    guards is always pushed. A patch with a positive guard ("+foo") is
    pushed only if the :hg:`qselect` command has activated it. A patch with
    a negative guard ("-foo") is never pushed if the :hg:`qselect` command
    has activated it.

    With no arguments, print the currently active guards.
    With arguments, set guards for the named patch.

    .. note::

       Specifying negative guards now requires '--'.

    To set guards on another patch::

      hg qguard other.patch -- +2.6.17 -stable

    Returns 0 on success.
    '''
    def status(idx):
        guards = q.seriesguards[idx] or ['unguarded']
        if q.series[idx] in applied:
            state = 'applied'
        elif q.pushable(idx)[0]:
            state = 'unapplied'
        else:
            state = 'guarded'
        label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
        ui.write('%s: ' % ui.label(q.series[idx], label))

        for i, guard in enumerate(guards):
            if guard.startswith('+'):
                ui.write(guard, label='qguard.positive')
            elif guard.startswith('-'):
                ui.write(guard, label='qguard.negative')
            else:
                ui.write(guard, label='qguard.unguarded')
            if i != len(guards) - 1:
                ui.write(' ')
        ui.write('\n')
    q = repo.mq
    applied = set(p.name for p in q.applied)
    patch = None
    args = list(args)
    if opts.get(r'list'):
        if args or opts.get('none'):
            raise error.Abort(_('cannot mix -l/--list with options or '
                               'arguments'))
        for i in xrange(len(q.series)):
            status(i)
        return
    if not args or args[0][0:1] in '-+':
        if not q.applied:
            raise error.Abort(_('no patches applied'))
        patch = q.applied[-1].name
    if patch is None and args[0][0:1] not in '-+':
        patch = args.pop(0)
    if patch is None:
        raise error.Abort(_('no patch to work with'))
    if args or opts.get('none'):
        idx = q.findseries(patch)
        if idx is None:
            raise error.Abort(_('no patch named %s') % patch)
        q.setguards(idx, args)
        q.savedirty()
    else:
        status(q.series.index(q.lookup(patch)))

@command("qheader", [], _('hg qheader [PATCH]'))
def header(ui, repo, patch=None):
    """print the header of the topmost or specified patch

    Returns 0 on success."""
    q = repo.mq

    if patch:
        patch = q.lookup(patch)
    else:
        if not q.applied:
            ui.write(_('no patches applied\n'))
            return 1
        patch = q.lookup('qtip')
    ph = patchheader(q.join(patch), q.plainmode)

    ui.write('\n'.join(ph.message) + '\n')

def lastsavename(path):
    (directory, base) = os.path.split(path)
    names = os.listdir(directory)
    namere = re.compile("%s.([0-9]+)" % base)
    maxindex = None
    maxname = None
    for f in names:
        m = namere.match(f)
        if m:
            index = int(m.group(1))
            if maxindex is None or index > maxindex:
                maxindex = index
                maxname = f
    if maxname:
        return (os.path.join(directory, maxname), maxindex)
    return (None, None)

def savename(path):
    (last, index) = lastsavename(path)
    if last is None:
        index = 0
    newpath = path + ".%d" % (index + 1)
    return newpath

@command("^qpush",
         [('', 'keep-changes', None,
           _('tolerate non-conflicting local changes')),
          ('f', 'force', None, _('apply on top of local changes')),
          ('e', 'exact', None,
           _('apply the target patch to its recorded parent')),
          ('l', 'list', None, _('list patch name in commit text')),
          ('a', 'all', None, _('apply all patches')),
          ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
          ('n', 'name', '',
           _('merge queue name (DEPRECATED)'), _('NAME')),
          ('', 'move', None,
           _('reorder patch series and apply only the patch')),
          ('', 'no-backup', None, _('do not save backup copies of files'))],
         _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
def push(ui, repo, patch=None, **opts):
    """push the next patch onto the stack

    By default, abort if the working directory contains uncommitted
    changes. With --keep-changes, abort only if the uncommitted files
    overlap with patched files. With -f/--force, backup and patch over
    uncommitted changes.

    Return 0 on success.
    """
    q = repo.mq
    mergeq = None

    opts = pycompat.byteskwargs(opts)
    opts = fixkeepchangesopts(ui, opts)
    if opts.get('merge'):
        if opts.get('name'):
            newpath = repo.vfs.join(opts.get('name'))
        else:
            newpath, i = lastsavename(q.path)
        if not newpath:
            ui.warn(_("no saved queues found, please use -n\n"))
            return 1
        mergeq = queue(ui, repo.baseui, repo.path, newpath)
        ui.warn(_("merging with queue at: %s\n") % mergeq.path)
    ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
                 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
                 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
                 keepchanges=opts.get('keep_changes'))
    return ret

@command("^qpop",
         [('a', 'all', None, _('pop all patches')),
          ('n', 'name', '',
           _('queue name to pop (DEPRECATED)'), _('NAME')),
          ('', 'keep-changes', None,
           _('tolerate non-conflicting local changes')),
          ('f', 'force', None, _('forget any local changes to patched files')),
          ('', 'no-backup', None, _('do not save backup copies of files'))],
         _('hg qpop [-a] [-f] [PATCH | INDEX]'))
def pop(ui, repo, patch=None, **opts):
    """pop the current patch off the stack

    Without argument, pops off the top of the patch stack. If given a
    patch name, keeps popping off patches until the named patch is at
    the top of the stack.

    By default, abort if the working directory contains uncommitted
    changes. With --keep-changes, abort only if the uncommitted files
    overlap with patched files. With -f/--force, backup and discard
    changes made to such files.

    Return 0 on success.
    """
    opts = pycompat.byteskwargs(opts)
    opts = fixkeepchangesopts(ui, opts)
    localupdate = True
    if opts.get('name'):
        q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get('name')))
        ui.warn(_('using patch queue: %s\n') % q.path)
        localupdate = False
    else:
        q = repo.mq
    ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
                all=opts.get('all'), nobackup=opts.get('no_backup'),
                keepchanges=opts.get('keep_changes'))
    q.savedirty()
    return ret

@command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
def rename(ui, repo, patch, name=None, **opts):
    """rename a patch

    With one argument, renames the current patch to PATCH1.
    With two arguments, renames PATCH1 to PATCH2.

    Returns 0 on success."""
    q = repo.mq
    if not name:
        name = patch
        patch = None

    if patch:
        patch = q.lookup(patch)
    else:
        if not q.applied:
            ui.write(_('no patches applied\n'))
            return
        patch = q.lookup('qtip')
    absdest = q.join(name)
    if os.path.isdir(absdest):
        name = normname(os.path.join(name, os.path.basename(patch)))
        absdest = q.join(name)
    q.checkpatchname(name)

    ui.note(_('renaming %s to %s\n') % (patch, name))
    i = q.findseries(patch)
    guards = q.guard_re.findall(q.fullseries[i])
    q.fullseries[i] = name + ''.join([' #' + g for g in guards])
    q.parseseries()
    q.seriesdirty = True

    info = q.isapplied(patch)
    if info:
        q.applied[info[0]] = statusentry(info[1], name)
    q.applieddirty = True

    destdir = os.path.dirname(absdest)
    if not os.path.isdir(destdir):
        os.makedirs(destdir)
    util.rename(q.join(patch), absdest)
    r = q.qrepo()
    if r and patch in r.dirstate:
        wctx = r[None]
        with r.wlock():
            if r.dirstate[patch] == 'a':
                r.dirstate.drop(patch)
                r.dirstate.add(name)
            else:
                wctx.copy(patch, name)
                wctx.forget([patch])

    q.savedirty()

@command("qrestore",
         [('d', 'delete', None, _('delete save entry')),
          ('u', 'update', None, _('update queue working directory'))],
         _('hg qrestore [-d] [-u] REV'))
def restore(ui, repo, rev, **opts):
    """restore the queue state saved by a revision (DEPRECATED)

    This command is deprecated, use :hg:`rebase` instead."""
    rev = repo.lookup(rev)
    q = repo.mq
    q.restore(repo, rev, delete=opts.get(r'delete'),
              qupdate=opts.get(r'update'))
    q.savedirty()
    return 0

@command("qsave",
         [('c', 'copy', None, _('copy patch directory')),
          ('n', 'name', '',
           _('copy directory name'), _('NAME')),
          ('e', 'empty', None, _('clear queue status file')),
          ('f', 'force', None, _('force copy'))] + cmdutil.commitopts,
         _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
def save(ui, repo, **opts):
    """save current queue state (DEPRECATED)

    This command is deprecated, use :hg:`rebase` instead."""
    q = repo.mq
    opts = pycompat.byteskwargs(opts)
    message = cmdutil.logmessage(ui, opts)
    ret = q.save(repo, msg=message)
    if ret:
        return ret
    q.savedirty() # save to .hg/patches before copying
    if opts.get('copy'):
        path = q.path
        if opts.get('name'):
            newpath = os.path.join(q.basepath, opts.get('name'))
            if os.path.exists(newpath):
                if not os.path.isdir(newpath):
                    raise error.Abort(_('destination %s exists and is not '
                                       'a directory') % newpath)
                if not opts.get('force'):
                    raise error.Abort(_('destination %s exists, '
                                       'use -f to force') % newpath)
        else:
            newpath = savename(path)
        ui.warn(_("copy %s to %s\n") % (path, newpath))
        util.copyfiles(path, newpath)
    if opts.get('empty'):
        del q.applied[:]
        q.applieddirty = True
        q.savedirty()
    return 0


@command("qselect",
         [('n', 'none', None, _('disable all guards')),
          ('s', 'series', None, _('list all guards in series file')),
          ('', 'pop', None, _('pop to before first guarded applied patch')),
          ('', 'reapply', None, _('pop, then reapply patches'))],
         _('hg qselect [OPTION]... [GUARD]...'))
def select(ui, repo, *args, **opts):
    '''set or print guarded patches to push

    Use the :hg:`qguard` command to set or print guards on patch, then use
    qselect to tell mq which guards to use. A patch will be pushed if
    it has no guards or any positive guards match the currently
    selected guard, but will not be pushed if any negative guards
    match the current guard. For example::

        qguard foo.patch -- -stable    (negative guard)
        qguard bar.patch    +stable    (positive guard)
        qselect stable

    This activates the "stable" guard. mq will skip foo.patch (because
    it has a negative match) but push bar.patch (because it has a
    positive match).

    With no arguments, prints the currently active guards.
    With one argument, sets the active guard.

    Use -n/--none to deactivate guards (no other arguments needed).
    When no guards are active, patches with positive guards are
    skipped and patches with negative guards are pushed.

    qselect can change the guards on applied patches. It does not pop
    guarded patches by default. Use --pop to pop back to the last
    applied patch that is not guarded. Use --reapply (which implies
    --pop) to push back to the current patch afterwards, but skip
    guarded patches.

    Use -s/--series to print a list of all guards in the series file
    (no other arguments needed). Use -v for more information.

    Returns 0 on success.'''

    q = repo.mq
    opts = pycompat.byteskwargs(opts)
    guards = q.active()
    pushable = lambda i: q.pushable(q.applied[i].name)[0]
    if args or opts.get('none'):
        old_unapplied = q.unapplied(repo)
        old_guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
        q.setactive(args)
        q.savedirty()
        if not args:
            ui.status(_('guards deactivated\n'))
        if not opts.get('pop') and not opts.get('reapply'):
            unapplied = q.unapplied(repo)
            guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
            if len(unapplied) != len(old_unapplied):
                ui.status(_('number of unguarded, unapplied patches has '
                            'changed from %d to %d\n') %
                          (len(old_unapplied), len(unapplied)))
            if len(guarded) != len(old_guarded):
                ui.status(_('number of guarded, applied patches has changed '
                            'from %d to %d\n') %
                          (len(old_guarded), len(guarded)))
    elif opts.get('series'):
        guards = {}
        noguards = 0
        for gs in q.seriesguards:
            if not gs:
                noguards += 1
            for g in gs:
                guards.setdefault(g, 0)
                guards[g] += 1
        if ui.verbose:
            guards['NONE'] = noguards
        guards = guards.items()
        guards.sort(key=lambda x: x[0][1:])
        if guards:
            ui.note(_('guards in series file:\n'))
            for guard, count in guards:
                ui.note('%2d  ' % count)
                ui.write(guard, '\n')
        else:
            ui.note(_('no guards in series file\n'))
    else:
        if guards:
            ui.note(_('active guards:\n'))
            for g in guards:
                ui.write(g, '\n')
        else:
            ui.write(_('no active guards\n'))
    reapply = opts.get('reapply') and q.applied and q.applied[-1].name
    popped = False
    if opts.get('pop') or opts.get('reapply'):
        for i in xrange(len(q.applied)):
            if not pushable(i):
                ui.status(_('popping guarded patches\n'))
                popped = True
                if i == 0:
                    q.pop(repo, all=True)
                else:
                    q.pop(repo, q.applied[i - 1].name)
                break
    if popped:
        try:
            if reapply:
                ui.status(_('reapplying unguarded patches\n'))
                q.push(repo, reapply)
        finally:
            q.savedirty()

@command("qfinish",
         [('a', 'applied', None, _('finish all applied changesets'))],
         _('hg qfinish [-a] [REV]...'))
def finish(ui, repo, *revrange, **opts):
    """move applied patches into repository history

    Finishes the specified revisions (corresponding to applied
    patches) by moving them out of mq control into regular repository
    history.

    Accepts a revision range or the -a/--applied option. If --applied
    is specified, all applied mq revisions are removed from mq
    control. Otherwise, the given revisions must be at the base of the
    stack of applied patches.

    This can be especially useful if your changes have been applied to
    an upstream repository, or if you are about to push your changes
    to upstream.

    Returns 0 on success.
    """
    if not opts.get(r'applied') and not revrange:
        raise error.Abort(_('no revisions specified'))
    elif opts.get(r'applied'):
        revrange = ('qbase::qtip',) + revrange

    q = repo.mq
    if not q.applied:
        ui.status(_('no patches applied\n'))
        return 0

    revs = scmutil.revrange(repo, revrange)
    if repo['.'].rev() in revs and repo[None].files():
        ui.warn(_('warning: uncommitted changes in the working directory\n'))
    # queue.finish may changes phases but leave the responsibility to lock the
    # repo to the caller to avoid deadlock with wlock. This command code is
    # responsibility for this locking.
    with repo.lock():
        q.finish(repo, revs)
        q.savedirty()
    return 0

@command("qqueue",
         [('l', 'list', False, _('list all available queues')),
          ('', 'active', False, _('print name of active queue')),
          ('c', 'create', False, _('create new queue')),
          ('', 'rename', False, _('rename active queue')),
          ('', 'delete', False, _('delete reference to queue')),
          ('', 'purge', False, _('delete queue, and remove patch dir')),
         ],
         _('[OPTION] [QUEUE]'))
def qqueue(ui, repo, name=None, **opts):
    '''manage multiple patch queues

    Supports switching between different patch queues, as well as creating
    new patch queues and deleting existing ones.

    Omitting a queue name or specifying -l/--list will show you the registered
    queues - by default the "normal" patches queue is registered. The currently
    active queue will be marked with "(active)". Specifying --active will print
    only the name of the active queue.

    To create a new queue, use -c/--create. The queue is automatically made
    active, except in the case where there are applied patches from the
    currently active queue in the repository. Then the queue will only be
    created and switching will fail.

    To delete an existing queue, use --delete. You cannot delete the currently
    active queue.

    Returns 0 on success.
    '''
    q = repo.mq
    _defaultqueue = 'patches'
    _allqueues = 'patches.queues'
    _activequeue = 'patches.queue'

    def _getcurrent():
        cur = os.path.basename(q.path)
        if cur.startswith('patches-'):
            cur = cur[8:]
        return cur

    def _noqueues():
        try:
            fh = repo.vfs(_allqueues, 'r')
            fh.close()
        except IOError:
            return True

        return False

    def _getqueues():
        current = _getcurrent()

        try:
            fh = repo.vfs(_allqueues, 'r')
            queues = [queue.strip() for queue in fh if queue.strip()]
            fh.close()
            if current not in queues:
                queues.append(current)
        except IOError:
            queues = [_defaultqueue]

        return sorted(queues)

    def _setactive(name):
        if q.applied:
            raise error.Abort(_('new queue created, but cannot make active '
                               'as patches are applied'))
        _setactivenocheck(name)

    def _setactivenocheck(name):
        fh = repo.vfs(_activequeue, 'w')
        if name != 'patches':
            fh.write(name)
        fh.close()

    def _addqueue(name):
        fh = repo.vfs(_allqueues, 'a')
        fh.write('%s\n' % (name,))
        fh.close()

    def _queuedir(name):
        if name == 'patches':
            return repo.vfs.join('patches')
        else:
            return repo.vfs.join('patches-' + name)

    def _validname(name):
        for n in name:
            if n in ':\\/.':
                return False
        return True

    def _delete(name):
        if name not in existing:
            raise error.Abort(_('cannot delete queue that does not exist'))

        current = _getcurrent()

        if name == current:
            raise error.Abort(_('cannot delete currently active queue'))

        fh = repo.vfs('patches.queues.new', 'w')
        for queue in existing:
            if queue == name:
                continue
            fh.write('%s\n' % (queue,))
        fh.close()
        repo.vfs.rename('patches.queues.new', _allqueues)

    opts = pycompat.byteskwargs(opts)
    if not name or opts.get('list') or opts.get('active'):
        current = _getcurrent()
        if opts.get('active'):
            ui.write('%s\n' % (current,))
            return
        for queue in _getqueues():
            ui.write('%s' % (queue,))
            if queue == current and not ui.quiet:
                ui.write(_(' (active)\n'))
            else:
                ui.write('\n')
        return

    if not _validname(name):
        raise error.Abort(
                _('invalid queue name, may not contain the characters ":\\/."'))

    with repo.wlock():
        existing = _getqueues()

        if opts.get('create'):
            if name in existing:
                raise error.Abort(_('queue "%s" already exists') % name)
            if _noqueues():
                _addqueue(_defaultqueue)
            _addqueue(name)
            _setactive(name)
        elif opts.get('rename'):
            current = _getcurrent()
            if name == current:
                raise error.Abort(_('can\'t rename "%s" to its current name')
                                  % name)
            if name in existing:
                raise error.Abort(_('queue "%s" already exists') % name)

            olddir = _queuedir(current)
            newdir = _queuedir(name)

            if os.path.exists(newdir):
                raise error.Abort(_('non-queue directory "%s" already exists') %
                        newdir)

            fh = repo.vfs('patches.queues.new', 'w')
            for queue in existing:
                if queue == current:
                    fh.write('%s\n' % (name,))
                    if os.path.exists(olddir):
                        util.rename(olddir, newdir)
                else:
                    fh.write('%s\n' % (queue,))
            fh.close()
            repo.vfs.rename('patches.queues.new', _allqueues)
            _setactivenocheck(name)
        elif opts.get('delete'):
            _delete(name)
        elif opts.get('purge'):
            if name in existing:
                _delete(name)
            qdir = _queuedir(name)
            if os.path.exists(qdir):
                shutil.rmtree(qdir)
        else:
            if name not in existing:
                raise error.Abort(_('use --create to create a new queue'))
            _setactive(name)

def mqphasedefaults(repo, roots):
    """callback used to set mq changeset as secret when no phase data exists"""
    if repo.mq.applied:
        if repo.ui.configbool('mq', 'secret'):
            mqphase = phases.secret
        else:
            mqphase = phases.draft
        qbase = repo[repo.mq.applied[0].node]
        roots[mqphase].add(qbase.node())
    return roots

def reposetup(ui, repo):
    class mqrepo(repo.__class__):
        @localrepo.unfilteredpropertycache
        def mq(self):
            return queue(self.ui, self.baseui, self.path)

        def invalidateall(self):
            super(mqrepo, self).invalidateall()
            if localrepo.hasunfilteredcache(self, 'mq'):
                # recreate mq in case queue path was changed
                delattr(self.unfiltered(), 'mq')

        def abortifwdirpatched(self, errmsg, force=False):
            if self.mq.applied and self.mq.checkapplied and not force:
                parents = self.dirstate.parents()
                patches = [s.node for s in self.mq.applied]
                if parents[0] in patches or parents[1] in patches:
                    raise error.Abort(errmsg)

        def commit(self, text="", user=None, date=None, match=None,
                   force=False, editor=False, extra=None):
            if extra is None:
                extra = {}
            self.abortifwdirpatched(
                _('cannot commit over an applied mq patch'),
                force)

            return super(mqrepo, self).commit(text, user, date, match, force,
                                              editor, extra)

        def checkpush(self, pushop):
            if self.mq.applied and self.mq.checkapplied and not pushop.force:
                outapplied = [e.node for e in self.mq.applied]
                if pushop.revs:
                    # Assume applied patches have no non-patch descendants and
                    # are not on remote already. Filtering any changeset not
                    # pushed.
                    heads = set(pushop.revs)
                    for node in reversed(outapplied):
                        if node in heads:
                            break
                        else:
                            outapplied.pop()
                # looking for pushed and shared changeset
                for node in outapplied:
                    if self[node].phase() < phases.secret:
                        raise error.Abort(_('source has mq patches applied'))
                # no non-secret patches pushed
            super(mqrepo, self).checkpush(pushop)

        def _findtags(self):
            '''augment tags from base class with patch tags'''
            result = super(mqrepo, self)._findtags()

            q = self.mq
            if not q.applied:
                return result

            mqtags = [(patch.node, patch.name) for patch in q.applied]

            try:
                # for now ignore filtering business
                self.unfiltered().changelog.rev(mqtags[-1][0])
            except error.LookupError:
                self.ui.warn(_('mq status file refers to unknown node %s\n')
                             % short(mqtags[-1][0]))
                return result

            # do not add fake tags for filtered revisions
            included = self.changelog.hasnode
            mqtags = [mqt for mqt in mqtags if included(mqt[0])]
            if not mqtags:
                return result

            mqtags.append((mqtags[-1][0], 'qtip'))
            mqtags.append((mqtags[0][0], 'qbase'))
            mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
            tags = result[0]
            for patch in mqtags:
                if patch[1] in tags:
                    self.ui.warn(_('tag %s overrides mq patch of the same '
                                   'name\n') % patch[1])
                else:
                    tags[patch[1]] = patch[0]

            return result

    if repo.local():
        repo.__class__ = mqrepo

        repo._phasedefaults.append(mqphasedefaults)

def mqimport(orig, ui, repo, *args, **kwargs):
    if (util.safehasattr(repo, 'abortifwdirpatched')
        and not kwargs.get(r'no_commit', False)):
        repo.abortifwdirpatched(_('cannot import over an applied patch'),
                                   kwargs.get(r'force'))
    return orig(ui, repo, *args, **kwargs)

def mqinit(orig, ui, *args, **kwargs):
    mq = kwargs.pop(r'mq', None)

    if not mq:
        return orig(ui, *args, **kwargs)

    if args:
        repopath = args[0]
        if not hg.islocal(repopath):
            raise error.Abort(_('only a local queue repository '
                               'may be initialized'))
    else:
        repopath = cmdutil.findrepo(pycompat.getcwd())
        if not repopath:
            raise error.Abort(_('there is no Mercurial repository here '
                               '(.hg not found)'))
    repo = hg.repository(ui, repopath)
    return qinit(ui, repo, True)

def mqcommand(orig, ui, repo, *args, **kwargs):
    """Add --mq option to operate on patch repository instead of main"""

    # some commands do not like getting unknown options
    mq = kwargs.pop(r'mq', None)

    if not mq:
        return orig(ui, repo, *args, **kwargs)

    q = repo.mq
    r = q.qrepo()
    if not r:
        raise error.Abort(_('no queue repository'))
    return orig(r.ui, r, *args, **kwargs)

def summaryhook(ui, repo):
    q = repo.mq
    m = []
    a, u = len(q.applied), len(q.unapplied(repo))
    if a:
        m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
    if u:
        m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
    if m:
        # i18n: column positioning for "hg summary"
        ui.write(_("mq:     %s\n") % ', '.join(m))
    else:
        # i18n: column positioning for "hg summary"
        ui.note(_("mq:     (empty queue)\n"))

revsetpredicate = registrar.revsetpredicate()

@revsetpredicate('mq()')
def revsetmq(repo, subset, x):
    """Changesets managed by MQ.
    """
    revsetlang.getargs(x, 0, 0, _("mq takes no arguments"))
    applied = set([repo[r.node].rev() for r in repo.mq.applied])
    return smartset.baseset([r for r in subset if r in applied])

# tell hggettext to extract docstrings from these functions:
i18nfunctions = [revsetmq]

def extsetup(ui):
    # Ensure mq wrappers are called first, regardless of extension load order by
    # NOT wrapping in uisetup() and instead deferring to init stage two here.
    mqopt = [('', 'mq', None, _("operate on patch repository"))]

    extensions.wrapcommand(commands.table, 'import', mqimport)
    cmdutil.summaryhooks.add('mq', summaryhook)

    entry = extensions.wrapcommand(commands.table, 'init', mqinit)
    entry[1].extend(mqopt)

    def dotable(cmdtable):
        for cmd, entry in cmdtable.iteritems():
            cmd = cmdutil.parsealiases(cmd)[0]
            func = entry[0]
            if func.norepo:
                continue
            entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
            entry[1].extend(mqopt)

    dotable(commands.table)

    for extname, extmodule in extensions.extensions():
        if extmodule.__file__ != __file__:
            dotable(getattr(extmodule, 'cmdtable', {}))

colortable = {'qguard.negative': 'red',
              'qguard.positive': 'yellow',
              'qguard.unguarded': 'green',
              'qseries.applied': 'blue bold underline',
              'qseries.guarded': 'black bold',
              'qseries.missing': 'red bold',
              'qseries.unapplied': 'black bold'}