mutable-history / hgext / evolve.py

   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
# Copyright 2011 Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
#                Logilab SA        <contact@logilab.fr>
#                Pierre-Yves David <pierre-yves.david@ens-lyon.org>
#                Patrick Mezard <patrick@mezard.eu>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

'''Extends Mercurial feature related to Changeset Evolution

This extension provides several commands to mutate history and deal with
issues it may raise.

It also:

    - enables the "Changeset Obsolescence" feature of mercurial,
    - alters core commands and extensions that rewrite history to use
      this feature,
    - improves some aspect of the early implementation in 2.3
'''

testedwith = '2.5'
buglink = 'https://bitbucket.org/marmoute/mutable-history/issues'

import sys
import random

import mercurial
from mercurial import util

try:
    from mercurial import obsolete
    if not obsolete._enabled:
        obsolete._enabled = True
    from mercurial import bookmarks
    bookmarks.bmstore
except (ImportError, AttributeError):
    raise util.Abort('Your Mercurial is too old for this version of Evolve',
                     hint='requires version >> 2.4.x')



from mercurial import bookmarks
from mercurial import cmdutil
from mercurial import commands
from mercurial import context
from mercurial import copies
from mercurial import error
from mercurial import extensions
from mercurial import hg
from mercurial import lock as lockmod
from mercurial import merge
from mercurial import node
from mercurial import phases
from mercurial import revset
from mercurial import scmutil
from mercurial import templatekw
from mercurial.i18n import _
from mercurial.commands import walkopts, commitopts, commitopts2
from mercurial.node import nullid



# This extension contains the following code
#
# - Extension Helper code
# - Obsolescence cache
# - ...
# - Older format compat



#####################################################################
### Extension helper                                              ###
#####################################################################

class exthelper(object):
    """Helper for modular extension setup

    A single helper should be instanciated for each extension. Helper
    methods are then used as decorator for various purpose.

    All decorators return the original function and may be chained.
    """

    def __init__(self):
        self._uicallables = []
        self._extcallables = []
        self._repocallables = []
        self._revsetsymbols = []
        self._templatekws = []
        self._commandwrappers = []
        self._extcommandwrappers = []
        self._functionwrappers = []
        self._duckpunchers = []

    def final_uisetup(self, ui):
        """Method to be used as the extension uisetup

        The following operations belong here:

        - Changes to ui.__class__ . The ui object that will be used to run the
          command has not yet been created. Changes made here will affect ui
          objects created after this, and in particular the ui that will be
          passed to runcommand
        - Command wraps (extensions.wrapcommand)
        - Changes that need to be visible to other extensions: because
          initialization occurs in phases (all extensions run uisetup, then all
          run extsetup), a change made here will be visible to other extensions
          during extsetup
        - Monkeypatch or wrap function (extensions.wrapfunction) of dispatch
          module members
        - Setup of pre-* and post-* hooks
        - pushkey setup
        """
        for cont, funcname, func in self._duckpunchers:
            setattr(cont, funcname, func)
        for command, wrapper in self._commandwrappers:
            extensions.wrapcommand(commands.table, command, wrapper)
        for cont, funcname, wrapper in self._functionwrappers:
            extensions.wrapfunction(cont, funcname, wrapper)
        for c in self._uicallables:
            c(ui)

    def final_extsetup(self, ui):
        """Method to be used as a the extension extsetup

        The following operations belong here:

        - Changes depending on the status of other extensions. (if
          extensions.find('mq'))
        - Add a global option to all commands
        - Register revset functions
        """
        knownexts = {}
        for name, symbol in self._revsetsymbols:
            revset.symbols[name] = symbol
        for name, kw in self._templatekws:
            templatekw.keywords[name] = kw
        for ext, command, wrapper in self._extcommandwrappers:
            if ext not in knownexts:
                e = extensions.find(ext)
                if e is None:
                    raise util.Abort('extension %s not found' % ext)
                knownexts[ext] = e.cmdtable
            extensions.wrapcommand(knownexts[ext], commands, wrapper)
        for c in self._extcallables:
            c(ui)

    def final_reposetup(self, ui, repo):
        """Method to be used as a the extension reposetup

        The following operations belong here:

        - All hooks but pre-* and post-*
        - Modify configuration variables
        - Changes to repo.__class__, repo.dirstate.__class__
        """
        for c in self._repocallables:
            c(ui, repo)

    def uisetup(self, call):
        """Decorated function will be executed during uisetup

        example::

            @eh.uisetup
            def setupbabar(ui):
                print 'this is uisetup!'
        """
        self._uicallables.append(call)
        return call

    def extsetup(self, call):
        """Decorated function will be executed during extsetup

        example::

            @eh.extsetup
            def setupcelestine(ui):
                print 'this is extsetup!'
        """
        self._extcallables.append(call)
        return call

    def reposetup(self, call):
        """Decorated function will be executed during reposetup

        example::

            @eh.reposetup
            def setupzephir(ui, repo):
                print 'this is reposetup!'
        """
        self._repocallables.append(call)
        return call

    def revset(self, symbolname):
        """Decorated function is a revset symbol

        The name of the symbol must be given as the decorator argument.
        The symbol is added during `extsetup`.

        example::

            @eh.revset('hidden')
            def revsetbabar(repo, subset, x):
                args = revset.getargs(x, 0, 0, 'babar accept no argument')
                return [r for r in subset if 'babar' in repo[r].description()]
        """
        def dec(symbol):
            self._revsetsymbols.append((symbolname, symbol))
            return symbol
        return dec


    def templatekw(self, keywordname):
        """Decorated function is a revset keyword

        The name of the keyword must be given as the decorator argument.
        The symbol is added during `extsetup`.

        example::

            @eh.templatekw('babar')
            def kwbabar(ctx):
                return 'babar'
        """
        def dec(keyword):
            self._templatekws.append((keywordname, keyword))
            return keyword
        return dec

    def wrapcommand(self, command, extension=None):
        """Decorated function is a command wrapper

        The name of the command must be given as the decorator argument.
        The wrapping is installed during `uisetup`.

        If the second option `extension` argument is provided, the wrapping
        will be applied in the extension commandtable. This argument must be a
        string that will be searched using `extension.find` if not found and
        Abort error is raised. If the wrapping applies to an extension, it is
        installed during `extsetup`

        example::

            @eh.wrapcommand('summary')
            def wrapsummary(orig, ui, repo, *args, **kwargs):
                ui.note('Barry!')
                return orig(ui, repo, *args, **kwargs)

        """
        def dec(wrapper):
            if extension is None:
                self._commandwrappers.append((command, wrapper))
            else:
                self._extcommandwrappers.append((extension, command, wrapper))
            return wrapper
        return dec

    def wrapfunction(self, container, funcname):
        """Decorated function is a function wrapper

        This function takes two arguments, the container and the name of the
        function to wrap. The wrapping is performed during `uisetup`.
        (there is no extension support)

        example::

            @eh.function(discovery, 'checkheads')
            def wrapfunction(orig, *args, **kwargs):
                ui.note('His head smashed in and his heart cut out')
                return orig(*args, **kwargs)
        """
        def dec(wrapper):
            self._functionwrappers.append((container, funcname, wrapper))
            return wrapper
        return dec

    def addattr(self, container, funcname):
        """Decorated function is to be added to the container

        This function takes two arguments, the container and the name of the
        function to wrap. The wrapping is performed during `uisetup`.

        example::

            @eh.function(context.changectx, 'babar')
            def babar(ctx):
                return 'babar' in ctx.description
        """
        def dec(func):
            self._duckpunchers.append((container, funcname, func))
            return func
        return dec

eh = exthelper()
uisetup = eh.final_uisetup
extsetup = eh.final_extsetup
reposetup = eh.final_reposetup

#####################################################################
### Critical fix                                                  ###
#####################################################################

@eh.wrapfunction(mercurial.obsolete, '_readmarkers')
def safereadmarkers(orig, data):
    """safe maker wrapper to remove nullid succesors

    Nullid successors was created by older version of evolve.
    """
    nb = 0
    for marker in orig(data):
        if nullid in marker[1]:
            marker = (marker[0],
                      tuple(s for s in marker[1] if s != nullid),
                      marker[2],
                      marker[3])
            nb += 1
        yield marker
    if nb:
        e = sys.stderr
        print >> e, 'repo contains %i invalid obsolescence markers' % nb

getrevs = obsolete.getrevs

#####################################################################
### Complete troubles computation logic                           ###
#####################################################################


### Cache computation
latediff = 1  # flag to prevent taking late comer fix into account

### changectx method

@eh.addattr(context.changectx, 'latecomer')
def latecomer(ctx):
    """is the changeset bumped (Try to succeed to public change)"""
    return ctx.bumped()

@eh.addattr(context.changectx, 'conflicting')
def conflicting(ctx):
    """is the changeset divergent (Try to succeed to public change)"""
    return ctx.divergent()

### revset symbol

eh.revset('latecomer')(revset.symbols['bumped'])
eh.revset('conflicting')(revset.symbols['divergent'])




#####################################################################
### Additional Utilities                                          ###
#####################################################################

# This section contains a lot of small utility function and method

# - Function to create markers
# - useful alias pstatus and pdiff (should probably go in evolve)
# - "troubles" method on changectx
# - function to travel throught the obsolescence graph
# - function to find useful changeset to stabilize

createmarkers = obsolete.createmarkers


### Useful alias

@eh.uisetup
def _installalias(ui):
    if ui.config('alias', 'pstatus', None) is None:
        ui.setconfig('alias', 'pstatus', 'status --rev .^')
    if ui.config('alias', 'pdiff', None) is None:
        ui.setconfig('alias', 'pdiff', 'diff --rev .^')
    if ui.config('alias', 'olog', None) is None:
        ui.setconfig('alias', 'olog', "log -r 'precursors(.)' --hidden")
    if ui.config('alias', 'odiff', None) is None:
        ui.setconfig('alias', 'odiff', "diff --hidden --rev 'limit(precursors(.),1)' --rev .")
    if ui.config('alias', 'grab', None) is None:
        ui.setconfig('alias', 'grab', "rebase --dest . --rev $1")


### Troubled revset symbol

@eh.revset('troubled')
def revsettroubled(repo, subset, x):
    """``troubled()``
    Changesets with troubles.
    """
    _ = revset.getargs(x, 0, 0, 'troubled takes no arguments')
    return repo.revs('%ld and (unstable() + bumped() + divergent())',
                     subset)


### Obsolescence graph

# XXX SOME MAJOR CLEAN UP TO DO HERE XXX

def _precursors(repo, s):
    """Precursor of a changeset"""
    cs = set()
    nm = repo.changelog.nodemap
    markerbysubj = repo.obsstore.precursors
    for r in s:
        for p in markerbysubj.get(repo[r].node(), ()):
            pr = nm.get(p[0])
            if pr is not None:
                cs.add(pr)
    return cs

def _allprecursors(repo, s):  # XXX we need a better naming
    """transitive precursors of a subset"""
    toproceed = [repo[r].node() for r in s]
    seen = set()
    allsubjects = repo.obsstore.precursors
    while toproceed:
        nc = toproceed.pop()
        for mark in allsubjects.get(nc, ()):
            np = mark[0]
            if np not in seen:
                seen.add(np)
                toproceed.append(np)
    nm = repo.changelog.nodemap
    cs = set()
    for p in seen:
        pr = nm.get(p)
        if pr is not None:
            cs.add(pr)
    return cs

def _successors(repo, s):
    """Successors of a changeset"""
    cs = set()
    nm = repo.changelog.nodemap
    markerbyobj = repo.obsstore.successors
    for r in s:
        for p in markerbyobj.get(repo[r].node(), ()):
            for sub in p[1]:
                sr = nm.get(sub)
                if sr is not None:
                    cs.add(sr)
    return cs

def _allsuccessors(repo, s, haltonflags=0):  # XXX we need a better naming
    """transitive successors of a subset

    haltonflags allows to provide flags which prevent the evaluation of a
    marker.  """
    toproceed = [repo[r].node() for r in s]
    seen = set()
    allobjects = repo.obsstore.successors
    while toproceed:
        nc = toproceed.pop()
        for mark in allobjects.get(nc, ()):
            if mark[2] & haltonflags:
                continue
            for sub in mark[1]:
                if sub == nullid:
                    continue # should not be here!
                if sub not in seen:
                    seen.add(sub)
                    toproceed.append(sub)
    nm = repo.changelog.nodemap
    cs = set()
    for s in seen:
        sr = nm.get(s)
        if sr is not None:
            cs.add(sr)
    return cs




#####################################################################
### Extending revset and template                                 ###
#####################################################################

# this section add several useful revset symbol not yet in core.
# they are subject to changes


### XXX I'm not sure this revset is useful
@eh.revset('suspended')
def revsetsuspended(repo, subset, x):
    """``suspended()``
    Obsolete changesets with non-obsolete descendants.
    """
    args = revset.getargs(x, 0, 0, 'suspended takes no arguments')
    suspended = getrevs(repo, 'suspended')
    return [r for r in subset if r in suspended]


@eh.revset('precursors')
def revsetprecursors(repo, subset, x):
    """``precursors(set)``
    Immediate precursors of changesets in set.
    """
    s = revset.getset(repo, range(len(repo)), x)
    cs = _precursors(repo, s)
    return [r for r in subset if r in cs]


@eh.revset('allprecursors')
def revsetallprecursors(repo, subset, x):
    """``allprecursors(set)``
    Transitive precursors of changesets in set.
    """
    s = revset.getset(repo, range(len(repo)), x)
    cs = _allprecursors(repo, s)
    return [r for r in subset if r in cs]


@eh.revset('successors')
def revsetsuccessors(repo, subset, x):
    """``successors(set)``
    Immediate successors of changesets in set.
    """
    s = revset.getset(repo, range(len(repo)), x)
    cs = _successors(repo, s)
    return [r for r in subset if r in cs]

@eh.revset('allsuccessors')
def revsetallsuccessors(repo, subset, x):
    """``allsuccessors(set)``
    Transitive successors of changesets in set.
    """
    s = revset.getset(repo, range(len(repo)), x)
    cs = _allsuccessors(repo, s)
    return [r for r in subset if r in cs]

### template keywords
# XXX it does not handle troubles well :-/

@eh.templatekw('obsolete')
def obsoletekw(repo, ctx, templ, **args):
    """:obsolete: String. The obsolescence level of the node, could be
    ``stable``, ``unstable``, ``suspended`` or ``extinct``.
    """
    rev = ctx.rev()
    if ctx.obsolete():
        if ctx.extinct():
            return 'extinct'
        else:
            return 'suspended'
    elif ctx.unstable():
        return 'unstable'
    return 'stable'

#####################################################################
### Various trouble warning                                       ###
#####################################################################

# This section take care of issue warning to the user when troubles appear

@eh.wrapcommand("update")
@eh.wrapcommand("pull")
def wrapmayobsoletewc(origfn, ui, repo, *args, **opts):
    """Warn that the working directory parent is an obsolete changeset"""
    res = origfn(ui, repo, *args, **opts)
    if repo['.'].obsolete():
        ui.warn(_('Working directory parent is obsolete\n'))
    return res

# XXX this could wrap transaction code
# XXX (but this is a bit a layer violation)
@eh.wrapcommand("commit")
@eh.wrapcommand("push")
@eh.wrapcommand("pull")
@eh.wrapcommand("graft")
@eh.wrapcommand("phase")
@eh.wrapcommand("unbundle")
def warnobserrors(orig, ui, repo, *args, **kwargs):
    """display warning is the command resulted in more instable changeset"""
    # part of the troubled stuff may be filtered (stash ?)
    # This needs a better implementation but will probably wait for core.
    filtered = repo.changelog.filteredrevs
    priorunstables = len(set(getrevs(repo, 'unstable')) - filtered)
    priorbumpeds = len(set(getrevs(repo, 'bumped')) - filtered)
    priordivergents = len(set(getrevs(repo, 'divergent')) - filtered)
    ret = orig(ui, repo, *args, **kwargs)
    # workaround phase stupidity
    #phases._filterunknown(ui, repo.changelog, repo._phasecache.phaseroots)
    filtered = repo.changelog.filteredrevs
    newunstables = len(set(getrevs(repo, 'unstable')) - filtered) - priorunstables
    newbumpeds = len(set(getrevs(repo, 'bumped')) - filtered) - priorbumpeds
    newdivergents = len(set(getrevs(repo, 'divergent')) - filtered) - priordivergents
    if newunstables > 0:
        ui.warn(_('%i new unstable changesets\n') % newunstables)
    if newbumpeds > 0:
        ui.warn(_('%i new bumped changesets\n') % newbumpeds)
    if newdivergents > 0:
        ui.warn(_('%i new divergent changesets\n') % newdivergents)
    return ret

@eh.reposetup
def _repostabilizesetup(ui, repo):
    """Add a hint for "hg evolve" when troubles make push fails
    """
    if not repo.local():
        return

    opush = repo.push

    class evolvingrepo(repo.__class__):
        def push(self, remote, *args, **opts):
            """wrapper around pull that pull obsolete relation"""
            try:
                result = opush(remote, *args, **opts)
            except util.Abort, ex:
                hint = _("use 'hg evolve' to get a stable history "
                         "or --force to ignore warnings")
                if (len(ex.args) >= 1
                    and ex.args[0].startswith('push includes ')
                    and ex.hint is None):
                    ex.hint = hint
                raise
            return result
    repo.__class__ = evolvingrepo

@eh.wrapcommand("summary")
def obssummary(orig, ui, repo, *args, **kwargs):
    def write(fmt, count):
        s = fmt % count
        if count:
            ui.write(s)
        else:
            ui.note(s)

    ret = orig(ui, repo, *args, **kwargs)
    nbunstable = len(getrevs(repo, 'unstable'))
    nbbumped = len(getrevs(repo, 'bumped'))
    nbdivergent = len(getrevs(repo, 'divergent'))
    write('unstable: %i changesets\n', nbunstable)
    write('bumped: %i changesets\n', nbbumped)
    write('divergent: %i changesets\n', nbdivergent)
    return ret


#####################################################################
### Core Other extension compat                                   ###
#####################################################################


@eh.extsetup
def _rebasewrapping(ui):
    # warning about more obsolete
    try:
        rebase = extensions.find('rebase')
        if rebase:
            extensions.wrapcommand(rebase.cmdtable, 'rebase', warnobserrors)
    except KeyError:
        pass  # rebase not found
    try:
        histedit = extensions.find('histedit')
        if histedit:
            extensions.wrapcommand(histedit.cmdtable, 'histedit', warnobserrors)
    except KeyError:
        pass  # rebase not found


#####################################################################
### Old Evolve extension content                                  ###
#####################################################################

# XXX need clean up and proper sorting in other section

### util function
#############################

### changeset rewriting logic
#############################

def rewrite(repo, old, updates, head, newbases, commitopts):
    """Return (nodeid, created) where nodeid is the identifier of the
    changeset generated by the rewrite process, and created is True if
    nodeid was actually created. If created is False, nodeid
    references a changeset existing before the rewrite call.
    """
    if len(old.parents()) > 1: #XXX remove this unecessary limitation.
        raise error.Abort(_('cannot amend merge changesets'))
    base = old.p1()
    updatebookmarks = _bookmarksupdater(repo, old.node())

    wlock = repo.wlock()
    try:

        # commit a new version of the old changeset, including the update
        # collect all files which might be affected
        files = set(old.files())
        for u in updates:
            files.update(u.files())

        # Recompute copies (avoid recording a -> b -> a)
        copied = copies.pathcopies(base, head)


        # prune files which were reverted by the updates
        def samefile(f):
            if f in head.manifest():
                a = head.filectx(f)
                if f in base.manifest():
                    b = base.filectx(f)
                    return (a.data() == b.data()
                            and a.flags() == b.flags())
                else:
                    return False
            else:
                return f not in base.manifest()
        files = [f for f in files if not samefile(f)]
        # commit version of these files as defined by head
        headmf = head.manifest()
        def filectxfn(repo, ctx, path):
            if path in headmf:
                fctx = head[path]
                flags = fctx.flags()
                mctx = context.memfilectx(fctx.path(), fctx.data(),
                                          islink='l' in flags,
                                          isexec='x' in flags,
                                          copied=copied.get(path))
                return mctx
            raise IOError()
        if commitopts.get('message') and commitopts.get('logfile'):
            raise util.Abort(_('options --message and --logfile are mutually'
                               ' exclusive'))
        if commitopts.get('logfile'):
            message= open(commitopts['logfile']).read()
        elif commitopts.get('message'):
            message = commitopts['message']
        else:
            message = old.description()

        user = commitopts.get('user') or old.user()
        date = commitopts.get('date') or None # old.date()
        extra = dict(commitopts.get('extra', {}))
        extra['branch'] = head.branch()

        new = context.memctx(repo,
                             parents=newbases,
                             text=message,
                             files=files,
                             filectxfn=filectxfn,
                             user=user,
                             date=date,
                             extra=extra)

        if commitopts.get('edit'):
            new._text = cmdutil.commitforceeditor(repo, new, [])
        revcount = len(repo)
        newid = repo.commitctx(new)
        new = repo[newid]
        created = len(repo) != revcount
        updatebookmarks(newid)
    finally:
        wlock.release()

    return newid, created

class MergeFailure(util.Abort):
    pass

def relocate(repo, orig, dest):
    """rewrite <rev> on dest"""
    try:
        rebase = extensions.find('rebase')
        # dummy state to trick rebase node
        assert orig.p2().rev() == node.nullrev, 'no support yet'
        destbookmarks = repo.nodebookmarks(dest.node())
        cmdutil.duplicatecopies(repo, orig.node(), dest.node())
        nodesrc = orig.node()
        destphase = repo[nodesrc].phase()
        try:
            r = rebase.rebasenode(repo, orig.node(), dest.node(),
                                  {node.nullrev: node.nullrev}, False)
            if r[-1]: #some conflict
                raise util.Abort(
                        'unresolved merge conflicts (see hg help resolve)')
            nodenew = rebase.concludenode(repo, orig.node(), dest.node(),
                                          node.nullid)
        except util.Abort, exc:
            class LocalMergeFailure(MergeFailure, exc.__class__):
                pass
            exc.__class__ = LocalMergeFailure
            raise
        oldbookmarks = repo.nodebookmarks(nodesrc)
        if nodenew is not None:
            phases.retractboundary(repo, destphase, [nodenew])
            createmarkers(repo, [(repo[nodesrc], (repo[nodenew],))])
            for book in oldbookmarks:
                repo._bookmarks[book] = nodenew
        else:
            createmarkers(repo, [(repo[nodesrc], ())])
            # Behave like rebase, move bookmarks to dest
            for book in oldbookmarks:
                repo._bookmarks[book] = dest.node()
        for book in destbookmarks: # restore bookmark that rebase move
            repo._bookmarks[book] = dest.node()
        if oldbookmarks or destbookmarks:
            repo._bookmarks.write()
        return nodenew
    except util.Abort:
        # Invalidate the previous setparents
        repo.dirstate.invalidate()
        raise

def _bookmarksupdater(repo, oldid):
    """Return a callable update(newid) updating the current bookmark
    and bookmarks bound to oldid to newid.
    """
    bm = bookmarks.readcurrent(repo)
    def updatebookmarks(newid):
        dirty = False
        if bm:
            repo._bookmarks[bm] = newid
            dirty = True
        oldbookmarks = repo.nodebookmarks(oldid)
        if oldbookmarks:
            for b in oldbookmarks:
                repo._bookmarks[b] = newid
            dirty = True
        if dirty:
            repo._bookmarks.write()
    return updatebookmarks

### new command
#############################
cmdtable = {}
command = cmdutil.command(cmdtable)

@command('^evolve|stabilize|solve',
    [('n', 'dry-run', False, 'do not perform actions, print what to be done'),
    ('A', 'any', False, 'evolve any troubled changeset'),
    ('a', 'all', False, 'evolve all troubled changesets'),
    ('c', 'continue', False, 'continue an interrupted evolution'), ],
    _('[OPTIONS]...'))
def evolve(ui, repo, **opts):
    """Solve trouble in your repository

    - rebase unstable changeset to make it stable again,
    - create proper diff from bumped changeset,
    - merge divergent changesets.

    By default, take the first trouble changeset that looks relevant.

    (The logic is still a bit fuzzy)

    - For unstable, this means taking the first which could be rebased as a
      child of the working directory parent revision or one of its descendants
      and rebasing it.

    - For divergent, this means taking "." if applicable.

    With --any, evolve picks any troubled changeset to solve.

    The working directory is updated to the newly created revision.
    """

    contopt = opts['continue']
    anyopt = opts['any']
    allopt = opts['all']
    dryrunopt = opts['dry_run']

    if contopt:
        if anyopt:
            raise util.Abort('can not specify both "--any" and "--continue"')
        if allopt:
            raise util.Abort('can not specify both "--all" and "--continue"')
        graftcmd = commands.table['graft'][0]
        return graftcmd(ui, repo, old_obsolete=True, **{'continue': True})

    tr = _picknexttroubled(ui, repo, anyopt or allopt)
    if tr is None:
        troubled = repo.revs('troubled()')
        if troubled:
            ui.write_err(_('nothing to evolve here\n'))
            ui.status(_('(%i troubled changesets, do you want --any ?)\n')
                      % len(troubled))
            return 2
        else:
            ui.write_err(_('no troubled changesets\n')) 
            return 1

    while tr is not None:
        result = _evolveany(ui, repo, tr, dryrunopt)
        if not allopt:
            return result
        tr = _picknexttroubled(ui, repo, anyopt or allopt)
        

def _evolveany(ui, repo, tr, dryrunopt):
    repo = repo.unfiltered()
    tr = repo[tr.rev()]
    cmdutil.bailifchanged(repo)
    troubles = tr.troubles()
    if 'unstable' in troubles:
        return _solveunstable(ui, repo, tr, dryrunopt)
    elif 'bumped' in troubles:
        return _solvebumped(ui, repo, tr, dryrunopt)
    elif 'divergent' in troubles:
        repo = repo.unfiltered()
        tr = repo[tr.rev()]
        return _solvedivergent(ui, repo, tr, dryrunopt)
    else:
        assert False  # WHAT? unknown troubles

def _picknexttroubled(ui, repo, pickany=False):
    """Pick a the next trouble changeset to solve"""
    tr = _stabilizableunstable(repo, repo['.'])
    if tr is None:
        wdp = repo['.']
        if 'divergent' in wdp.troubles():
            tr = wdp
    if tr is None and pickany:
        troubled = list(repo.set('unstable()'))
        if not troubled:
            troubled = list(repo.set('bumped()'))
        if not troubled:
            troubled = list(repo.set('divergent()'))
        if troubled:
            tr = troubled[0]

    return tr

def _stabilizableunstable(repo, pctx):
    """Return a changectx for an unstable changeset which can be
    stabilized on top of pctx or one of its descendants. None if none
    can be found.
    """
    def selfanddescendants(repo, pctx):
        yield pctx
        for prec in repo.set('allprecursors(%d)', pctx):
            yield prec
        for ctx in pctx.descendants():
            yield ctx
            for prec in repo.set('allprecursors(%d)', ctx):
                yield prec

    # Look for an unstable which can be stabilized as a child of
    # node. The unstable must be a child of one of node predecessors.
    for ctx in selfanddescendants(repo, pctx):
        for child in ctx.children():
            if child.unstable():
                return child
    return None

def _solveunstable(ui, repo, orig, dryrun=False):
    """Stabilize a unstable changeset"""
    obs = orig.parents()[0]
    if not obs.obsolete():
        print obs.rev(), orig.parents()
        print orig.rev()
        obs = orig.parents()[1]
    assert obs.obsolete()
    newer = obsolete.successorssets(repo, obs.node())
    # search of a parent which is not killed
    while not newer or newer == [()]:
        ui.debug("stabilize target %s is plain dead,"
                 " trying to stabilize on its parent")
        obs = obs.parents()[0]
        newer = obsolete.successorssets(repo, obs.node())
    if len(newer) > 1:
        raise util.Abort(_("conflict rewriting. can't choose destination\n"))
    targets = newer[0]
    assert targets
    if len(targets) > 1:
        raise util.Abort(_("does not handle split parents yet\n"))
        return 2
    target = targets[0]
    displayer = cmdutil.show_changeset(ui, repo, {'template': shorttemplate})
    target = repo[target]
    repo.ui.status(_('move:'))
    if not ui.quiet:
        displayer.show(orig)
    repo.ui.status(_('atop:'))
    if not ui.quiet:
        displayer.show(target)
    todo = 'hg rebase -r %s -d %s\n' % (orig, target)
    if dryrun:
        repo.ui.write(todo)
    else:
        repo.ui.note(todo)
        lock = repo.lock()
        try:
            relocate(repo, orig, target)
        except MergeFailure:
            repo.opener.write('graftstate', orig.hex() + '\n')
            repo.ui.write_err(_('evolve failed!\n'))
            repo.ui.write_err(_('fix conflict and run "hg evolve --continue"\n'))
            raise
        finally:
            lock.release()

def _solvebumped(ui, repo, bumped, dryrun=False):
    """Stabilize a bumped changeset"""
    # For now we deny bumped merge
    if len(bumped.parents()) > 1:
        raise util.Abort('late comer stabilization is confused by bumped'
                         ' %s being a merge' % bumped)
    prec = repo.set('last(allprecursors(%d) and public())', bumped).next()
    # For now we deny target merge
    if len(prec.parents()) > 1:
        raise util.Abort('late comer evolution is confused by precursors'
                         ' %s being a merge' % prec)

    displayer = cmdutil.show_changeset(ui, repo, {'template': shorttemplate})
    repo.ui.status(_('recreate:'))
    if not ui.quiet:
        displayer.show(bumped)
    repo.ui.status(_('atop:'))
    if not ui.quiet:
        displayer.show(prec)
    if dryrun:
        todo = 'hg rebase --rev %s --dest %s;\n' % (bumped, prec.p1())
        repo.ui.write(todo)
        repo.ui.write('hg update %s;\n' % prec)
        repo.ui.write('hg revert --all --rev %s;\n' % bumped)
        repo.ui.write('hg commit --msg "bumped update to %s"')
        return 0
    wlock = repo.wlock()
    try:
        newid = tmpctx = None
        tmpctx = bumped
        lock = repo.lock()
        try:
            bmupdate = _bookmarksupdater(repo, bumped.node())
            # Basic check for common parent. Far too complicated and fragile
            tr = repo.transaction('bumped-stabilize')
            try:
                if not list(repo.set('parents(%d) and parents(%d)', bumped, prec)):
                    # Need to rebase the changeset at the right place
                    repo.ui.status(_('rebasing to destination parent: %s\n') % prec.p1())
                    try:
                        tmpid = relocate(repo, bumped, prec.p1())
                        if tmpid is not None:
                            tmpctx = repo[tmpid]
                            createmarkers(repo, [(bumped, (tmpctx,))])
                    except MergeFailure:
                        repo.opener.write('graftstate', bumped.hex() + '\n')
                        repo.ui.write_err(_('evolution failed!\n'))
                        repo.ui.write_err(_('fix conflict and run "hg evolve --continue"\n'))
                        raise
                # Create the new commit context
                repo.ui.status(_('computing new diff\n'))
                files = set()
                copied = copies.pathcopies(prec, bumped)
                precmanifest = prec.manifest()
                for key, val in bumped.manifest().iteritems():
                    if precmanifest.pop(key, None) != val:
                        files.add(key)
                files.update(precmanifest)  # add missing files
                # commit it
                if files: # something to commit!
                    def filectxfn(repo, ctx, path):
                        if path in bumped:
                            fctx = bumped[path]
                            flags = fctx.flags()
                            mctx = context.memfilectx(fctx.path(), fctx.data(),
                                                      islink='l' in flags,
                                                      isexec='x' in flags,
                                                      copied=copied.get(path))
                            return mctx
                        raise IOError()
                    text = 'bumped update to %s:\n\n' % prec
                    text += bumped.description()

                    new = context.memctx(repo,
                                         parents=[prec.node(), node.nullid],
                                         text=text,
                                         files=files,
                                         filectxfn=filectxfn,
                                         user=bumped.user(),
                                         date=bumped.date(),
                                         extra=bumped.extra())

                    newid = repo.commitctx(new)
                if newid is None:
                    createmarkers(repo, [(tmpctx, ())])
                    newid = prec.node()
                else:
                    phases.retractboundary(repo, bumped.phase(), [newid])
                    createmarkers(repo, [(tmpctx, (repo[newid],))],
                                           flag=latediff)
                bmupdate(newid)
                tr.close()
                repo.ui.status(_('commited as %s\n') % node.short(newid))
            finally:
                tr.release()
        finally:
            lock.release()
        # reroute the working copy parent to the new changeset
        repo.dirstate.setparents(newid, node.nullid)
    finally:
        wlock.release()

def _solvedivergent(ui, repo, divergent, dryrun=False):
    base, others = divergentdata(divergent)
    if len(others) > 1:
        raise util.Abort("We do not handle split yet")
    other = others[0]
    if divergent.phase() <= phases.public:
        raise util.Abort("We can't resolve this conflict from the public side")
    if len(other.parents()) > 1:
        raise util.Abort("divergent changeset can't be a merge (yet)")
    if other.p1() not in divergent.parents():
        raise util.Abort("parents are not common (not handled yet)")

    displayer = cmdutil.show_changeset(ui, repo, {'template': shorttemplate})
    ui.status(_('merge:'))
    if not ui.quiet:
        displayer.show(divergent)
    ui.status(_('with: '))
    if not ui.quiet:
        displayer.show(other)
    ui.status(_('base: '))
    if not ui.quiet:
        displayer.show(base)
    if dryrun:
        ui.write('hg update -c %s &&\n' % divergent)
        ui.write('hg merge %s &&\n' % other)
        ui.write('hg commit -m "auto merge resolving conflict between '
                 '%s and %s"&&\n' % (divergent, other))
        ui.write('hg up -C %s &&\n' % base)
        ui.write('hg revert --all --rev tip &&\n')
        ui.write('hg commit -m "`hg log -r %s --template={desc}`";\n'
                 % divergent)
        return
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        if divergent not in repo[None].parents():
            repo.ui.status(_('updating to "local" conflict\n'))
            hg.update(repo, divergent.rev())
        repo.ui.note(_('merging divergent changeset\n'))
        stats = merge.update(repo,
                             other.node(),
                             branchmerge=True,
                             force=False,
                             partial=None,
                             ancestor=base.node(),
                             mergeancestor=True)
        hg._showstats(repo, stats)
        if stats[3]:
            repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
                             "or 'hg update -C .' to abandon\n"))
        if stats[3] > 0:
            raise util.Abort('Merge conflict between several amendments, and this is not yet automated',
                hint="""/!\ You can try:
/!\ * manual merge + resolve => new cset X
/!\ * hg up to the parent of the amended changeset (which are named W and Z)
/!\ * hg revert --all -r X
/!\ * hg ci -m "same message as the amended changeset" => new cset Y
/!\ * hg kill -n Y W Z
""")
        tr = repo.transaction('stabilize-divergent')
        try:
            repo.dirstate.setparents(divergent.node(), node.nullid)
            oldlen = len(repo)
            amend(ui, repo)
            if oldlen == len(repo):
                new = divergent
                # no changes
            else:
                new = repo['.']
            createmarkers(repo, [(other, (new,))])
            phases.retractboundary(repo, other.phase(), [new.node()])
            tr.close()
        finally:
            tr.release()
    finally:
        lockmod.release(lock, wlock)


def divergentdata(ctx):
    """return base, other part of a conflict

    This only return the first one.

    XXX this woobly function won't survive XXX
    """
    for base in ctx._repo.set('reverse(precursors(%d))', ctx):
        newer = obsolete.successorssets(ctx._repo, base.node())
        # drop filter and solution including the original ctx
        newer = [n for n in newer if n and ctx.node() not in n]
        if newer:
            return base, tuple(ctx._repo[o] for o in newer[0])
    raise KeyError('Base seem unknown. This case is not handled yet.')



shorttemplate = '[{rev}] {desc|firstline}\n'

@command('^gdown',
         [],
         '')
def cmdgdown(ui, repo):
    """update to parent an display summary lines"""
    wkctx = repo[None]
    wparents = wkctx.parents()
    if len(wparents) != 1:
        raise util.Abort('merge in progress')

    parents = wparents[0].parents()
    displayer = cmdutil.show_changeset(ui, repo, {'template': shorttemplate})
    if len(parents) == 1:
        p = parents[0]
        hg.update(repo, p.rev())
        displayer.show(p)
        return 0
    else:
        for p in parents:
            displayer.show(p)
        ui.warn(_('multiple parents, explicitly update to one\n'))
        return 1

@command('^gup',
         [],
         '')
def cmdup(ui, repo):
    """update to child an display summary lines"""
    wkctx = repo[None]
    wparents = wkctx.parents()
    if len(wparents) != 1:
        raise util.Abort('merge in progress')

    children = [ctx for ctx in wparents[0].children() if not ctx.obsolete()]
    displayer = cmdutil.show_changeset(ui, repo, {'template': shorttemplate})
    if not children:
        ui.warn(_('No non-obsolete children\n'))
        return 1
    if len(children) == 1:
        c = children[0]
        hg.update(repo, c.rev())
        displayer.show(c)
        return 0
    else:
        for c in children:
            displayer.show(c)
        ui.warn(_('Multiple non-obsolete children, explicitly update to one\n'))
        return 1

@command('^prune|obsolete|kill',
    [('n', 'new', [], _("successor changeset (DEPRECATED)")),
     ('s', 'succ', [], _("successor changeset")),
     ('r', 'rev', [], _("revisions to prune"))],
    _('[OPTION] [-r] REV...'))
    # -d --date
    # -u --user
    # -U  --noupdate option to prevent wc update and or bookmarks update ?
def cmdprune(ui, repo, *revs, **opts):
    """get rid of changesets by marking them obsolete

    Obsolete changesets becomes invisible to all commands.

    Non-pruned descendant of pruned changesets becomes "unstable". Use the
    :hg:`evolve` to handle such situation.

    When the working directory parent is pruned the repository is updated to a
    non obsolete parents.

    you can use the ``--succ`` option to informs mercurial that a newer version
    of the pruned changeset exists.

    XXX this commands needs bookmarks support.
    """
    revs = list(revs)
    revs.extend(opts['rev'])
    succs = opts['new'] + opts['succ']
    wlock = lock = None
    wlock = repo.wlock()
    sortedrevs = lambda specs: sorted(set(scmutil.revrange(repo, specs)))
    try:
        lock = repo.lock()
        # defines pruned changesets
        precs = []
        for p in sortedrevs(revs):
            cp = repo[p]
            if not cp.mutable():
                # note: create marker would had raise something anyway
                raise util.Abort('cannot prune immutable changeset: %s' % cp,
                                 hint='see "hg help phases" for details')
            precs.append(cp)
        if not precs:
            raise util.Abort('nothing to prune')

        # defines successors changesets
        sucs = tuple(repo[n] for n in sortedrevs(succs))
        if len(sucs) > 1 and len(precs) > 1:
            msg = "Can't use multiple successors for multiple precursors"
            raise util.Abort(msg)
        # create markers
        createmarkers(repo, [(p, sucs) for p in precs])
        # informs that changeset have been pruned
        ui.status(_('%i changesets pruned\n') % len(precs))
        # update to an unkilled parent
        wdp = repo['.']
        newnode = wdp
        while newnode.obsolete():
            newnode = newnode.parents()[0]
        if newnode.node() != wdp.node():
            commands.update(ui, repo, newnode.rev())
            ui.status(_('working directory now at %s\n') % newnode)
        # upVdate bookmarks
        for ctx in repo.unfiltered().set('bookmark() and %ld', precs):
            ldest = list(repo.set('max((::%d) - obsolete())', ctx))
            if ldest:
                dest = ldest[0]
                updatebookmarks = _bookmarksupdater(repo, ctx.node())
                updatebookmarks(dest.node())
            else:
                # delete bookmarks
                pass
    finally:
        lockmod.release(lock, wlock)

@command('amend|refresh',
    [('A', 'addremove', None,
     _('mark new/missing files as added/removed before committing')),
    ('n', 'note', '', _('use text as commit message for this update')),
    ('e', 'edit', False, _('invoke editor on commit messages')),
    ] + walkopts + commitopts + commitopts2,
    _('[OPTION]... [FILE]...'))
def amend(ui, repo, *pats, **opts):
    """combine a changeset with updates and replace it with a new one

    Commits a new changeset incorporating both the changes to the given files
    and all the changes from the current parent changeset into the repository.

    See :hg:`commit` for details about committing changes.

    If you don't specify -m, the parent's message will be reused.

    Behind the scenes, Mercurial first commits the update as a regular child
    of the current parent. Then it creates a new commit on the parent's parents
    with the updated contents. Then it changes the working copy parent to this
    new combined changeset. Finally, the old changeset and its update are hidden
    from :hg:`log` (unless you use --hidden with log).

    Returns 0 on success, 1 if nothing changed.
    """

    # determine updates to subsume
    old = scmutil.revsingle(repo, '.')

    lock = repo.lock()
    try:
        wlock = repo.wlock()
        try:
            if old.phase() == phases.public:
                raise util.Abort(_("can not rewrite immutable changeset %s")
                                 % old)
            tr = repo.transaction('amend')
            try:
                oldphase = old.phase()
                # commit current changes as update
                # code copied from commands.commit to avoid noisy messages
                ciopts = dict(opts)
                ciopts.pop('message', None)
                ciopts.pop('logfile', None)
                ciopts['message'] = opts.get('note') or ('amends %s' % old.hex())
                e = cmdutil.commiteditor
                def commitfunc(ui, repo, message, match, opts):
                    return repo.commit(message, opts.get('user'), opts.get('date'),
                                       match, editor=e)
                revcount = len(repo)
                tempid = cmdutil.commit(ui, repo, commitfunc, pats, ciopts)
                if len(repo) == revcount:
                    # No revision created
                    tempid = None

                # find all changesets to be considered updates
                head = repo['.']
                updatenodes = set(repo.changelog.nodesbetween(
                        roots=[old.node()], heads=[head.node()])[0])
                updatenodes.remove(old.node())
                okoptions = ['message', 'logfile', 'edit', 'user']
                if not updatenodes:
                    for o in okoptions:
                        if opts.get(o):
                            break
                    else:
                        raise error.Abort(_('no updates found'))
                updates = [repo[n] for n in updatenodes]

                # perform amend
                if opts.get('edit'):
                    opts['force_editor'] = True
                newid, created = rewrite(repo, old, updates, head,
                                         [old.p1().node(), old.p2().node()], opts)

                if newid != old.node():
                    createmarkers(repo, [(old, (repo[newid],))])
                if tempid is not None:
                    createmarkers(repo, [(repo[tempid], ())])
                if created:
                    # reroute the working copy parent to the new changeset
                    phases.retractboundary(repo, oldphase, [newid])
                    repo.dirstate.setparents(newid, node.nullid)
                else:
                    # rewrite() recreated an existing revision, discard
                    # the intermediate revision if any. No need to update
                    # phases or parents.
                    # XXX: need another message in collapse case.
                    tr.close()
                    raise error.Abort(_('no updates found'))
                tr.close()
            finally:
                tr.release()
        finally:
            wlock.release()
    finally:
        lock.release()

def _commitfiltered(repo, ctx, match):
    """Recommit ctx with changed files not in match. Return the new
    node identifier, or None if nothing changed.
    """
    base = ctx.p1()
    m, a, r = repo.status(base, ctx)[:3]
    allfiles = set(m + a + r)
    files = set(f for f in allfiles if not match(f))
    if files == allfiles:
        return None

    # Filter copies
    copied = copies.pathcopies(base, ctx)
    copied = dict((src, dst) for src, dst in copied.iteritems()
                  if dst in files)
    def filectxfn(repo, memctx, path):
        if path not in ctx:
            raise IOError()
        fctx = ctx[path]
        flags = fctx.flags()
        mctx = context.memfilectx(fctx.path(), fctx.data(),
                                  islink='l' in flags,
                                  isexec='x' in flags,
                                  copied=copied.get(path))
        return mctx

    new = context.memctx(repo,
                         parents=[base.node(), node.nullid],
                         text=ctx.description(),
                         files=files,
                         filectxfn=filectxfn,
                         user=ctx.user(),
                         date=ctx.date(),
                         extra=ctx.extra())
    # commitctx always create a new revision, no need to check
    newid = repo.commitctx(new)
    return newid

def _uncommitdirstate(repo, oldctx, match):
    """Fix the dirstate after switching the working directory from
    oldctx to a copy of oldctx not containing changed files matched by
    match.
    """
    ctx = repo['.']
    ds = repo.dirstate
    copies = dict(ds.copies())
    m, a, r = repo.status(oldctx.p1(), oldctx, match=match)[:3]
    for f in m:
        if ds[f] == 'r':
            # modified + removed -> removed
            continue
        ds.normallookup(f)

    for f in a:
        if ds[f] == 'r':
            # added + removed -> unknown
            ds.drop(f)
        elif ds[f] != 'a':
            ds.add(f)

    for f in r:
        if ds[f] == 'a':
            # removed + added -> normal
            ds.normallookup(f)
        elif ds[f] != 'r':
            ds.remove(f)

    # Merge old parent and old working dir copies
    oldcopies = {}
    for f in (m + a):
        src = oldctx[f].renamed()
        if src:
            oldcopies[f] = src[0]
    oldcopies.update(copies)
    copies = dict((dst, oldcopies.get(src, src))
                  for dst, src in oldcopies.iteritems())
    # Adjust the dirstate copies
    for dst, src in copies.iteritems():
        if (src not in ctx or dst in ctx or ds[dst] != 'a'):
            src = None
        ds.copy(src, dst)

@command('^uncommit',
    [('a', 'all', None, _('uncommit all changes when no arguments given')),
     ] + commands.walkopts,
    _('[OPTION]... [NAME]'))
def uncommit(ui, repo, *pats, **opts):
    """move changes from parent revision to working directory

    Changes to selected files in parent revision appear again as
    uncommitted changed in the working directory. A new revision
    without selected changes is created, becomes the new parent and
    obsoletes the previous one.

    The --include option specify pattern to uncommit
    The --exclude option specify pattern to keep in the commit

    Return 0 if changed files are uncommitted.
    """
    lock = repo.lock()
    try:
        wlock = repo.wlock()
        try:
            wctx = repo[None]
            if len(wctx.parents()) <= 0:
                raise util.Abort(_("cannot uncommit null changeset"))
            if len(wctx.parents()) > 1:
                raise util.Abort(_("cannot uncommit while merging"))
            old = repo['.']
            if old.phase() == phases.public:
                raise util.Abort(_("cannot rewrite immutable changeset"))
            if len(old.parents()) > 1:
                raise util.Abort(_("cannot uncommit merge changeset"))
            oldphase = old.phase()
            updatebookmarks = _bookmarksupdater(repo, old.node())
            # Recommit the filtered changeset
            newid = None
            if (pats or opts.get('include') or opts.get('exclude')
                or opts.get('all')):
                match = scmutil.match(old, pats, opts)
                newid = _commitfiltered(repo, old, match)
            if newid is None:
                raise util.Abort(_('nothing to uncommit'))
            # Move local changes on filtered changeset
            createmarkers(repo, [(old, (repo[newid],))])
            phases.retractboundary(repo, oldphase, [newid])
            repo.dirstate.setparents(newid, node.nullid)
            _uncommitdirstate(repo, old, match)
            updatebookmarks(newid)
            if not repo[newid].files():
                ui.warn(_("new changeset is empty\n"))
                ui.status(_('(use "hg kill ." to remove it)\n'))
        finally:
            wlock.release()
    finally:
        lock.release()

@eh.wrapcommand('commit')
def commitwrapper(orig, ui, repo, *arg, **kwargs):
    if kwargs.get('amend', False):
        lock = None
    else:
        lock = repo.lock()
    try:
        obsoleted = kwargs.get('obsolete', [])
        if obsoleted:
            obsoleted = repo.set('%lr', obsoleted)
        result = orig(ui, repo, *arg, **kwargs)
        if not result: # commit successed
            new = repo['-1']
            oldbookmarks = []
            markers = []
            for old in obsoleted:
                oldbookmarks.extend(repo.nodebookmarks(old.node()))
                markers.append((old, (new,)))
            if markers:
                createmarkers(repo, markers)
            for book in oldbookmarks:
                repo._bookmarks[book] = new.node()
            if oldbookmarks:
                repo._bookmarks.write()
        return result
    finally:
        if lock is not None:
            lock.release()

@command('^touch',
    [('r', 'rev', [], 'revision to update'),
     ('D', 'duplicate', False,
      'do not mark the new revision as successor of the old one')],
    # allow to choose the seed ?
    _('[-r] revs'))
def touch(ui, repo, *revs, **opts):
    """Create successors with exact same property but hash

    This is used to "resurrect" changesets
    """
    duplicate = opts['duplicate']
    revs = list(revs)
    revs.extend(opts['rev'])
    if not revs:
        revs = ['.']
    revs = scmutil.revrange(repo, revs)
    if not revs:
        ui.write_err('no revision to touch\n')
        return 1
    if not duplicate and repo.revs('public() and %ld', revs):
        raise util.Abort("can't touch public revision")
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        tr = repo.transaction('touch')
        revs.sort() # ensure parent are run first
        newmapping = {}
        try:
            for r in revs:
                ctx = repo[r]
                extra = ctx.extra().copy()
                extra['__touch-noise__'] = random.randint(0, 0xffffffff)
                # search for touched parent
                p1 = ctx.p1().node()
                p2 = ctx.p2().node()
                p1 = newmapping.get(p1, p1)
                p2 = newmapping.get(p2, p2)
                new, _ = rewrite(repo, ctx, [], ctx,
                                 [p1, p2],
                                 commitopts={'extra': extra})
                # store touched version to help potential children
                newmapping[ctx.node()] = new
                if not duplicate:
                    createmarkers(repo, [(ctx, (repo[new],))])
                phases.retractboundary(repo, ctx.phase(), [new])
                if ctx in repo[None].parents():
                    repo.dirstate.setparents(new, node.nullid)
            tr.close()
        finally:
            tr.release()
    finally:
        lockmod.release(lock, wlock)

@command('^fold',
    [('r', 'rev', [], _("explicitly specify the full set of revision to fold")),
    ],
    # allow to choose the seed ?
    _('rev'))
def fold(ui, repo, *revs, **opts):
    """Fold multiple revisions into a single one

    Revision from your current working directory to the specified one are fold
    as a new one replacing the other

    you can alternatively use --rev to explicitly specify revision to be fold
    ignoring the current working directory parent.
    """
    revs = list(revs)
    if revs:
        if opts.get('rev', ()):
            raise util.Abort("cannot specify both --rev and a target revision")
        targets = scmutil.revrange(repo, revs)
        revs = repo.revs('(%ld::.) or (.::%ld)', targets, targets)
    elif 'rev' in opts:
        revs = scmutil.revrange(repo, opts['rev'])
    else:
        revs = ()
    if not revs:
        ui.write_err('no revision to fold\n')
        return 1
    roots = repo.revs('roots(%ld)', revs)
    if len(roots) > 1:
        raise util.Abort("set has multiple roots")
    root = repo[roots[0]]
    if root.phase() <= phases.public:
        raise util.Abort("can't fold public revisions")
    heads = repo.revs('heads(%ld)', revs)
    if len(heads) > 1:
        raise util.Abort("set has multiple heads")
    head = repo[heads[0]]
    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        tr = repo.transaction('touch')
        try:
            allctx = [repo[r] for r in revs]
            targetphase = max(c.phase() for c in allctx)
            msgs = ["HG: This is a fold of %d changesets." % len(allctx)]
            msgs += ["HG: Commit message of changeset %s.\n\n%s\n" %
                     (c.rev(), c.description()) for c in allctx]
            commitopts = {'message': "\n".join(msgs)}
            commitopts['edit'] = True
            newid, _ = rewrite(repo, root, allctx, head,
                             [root.p1().node(), root.p2().node()],
                             commitopts=commitopts)
            phases.retractboundary(repo, targetphase, [newid])
            createmarkers(repo, [(ctx, (repo[newid],))
                                 for ctx in allctx])
            tr.close()
        finally:
            tr.release()
        ui.status('%i changesets folded\n' % len(revs))
        if repo['.'].rev() in revs:
            hg.update(repo, newid)
    finally:
        lockmod.release(lock, wlock)



@eh.wrapcommand('graft')
def graftwrapper(orig, ui, repo, *revs, **kwargs):
    kwargs = dict(kwargs)
    revs = list(revs) + kwargs.get('rev', [])
    kwargs['rev'] = []
    obsoleted = kwargs.setdefault('obsolete', [])

    lock = repo.lock()
    try:
        if kwargs.get('old_obsolete'):
            if kwargs.get('continue'):
                obsoleted.extend(repo.opener.read('graftstate').splitlines())
            else:
                obsoleted.extend(revs)
        # convert obsolete target into revs to avoid alias joke
        obsoleted[:] = [str(i) for i in repo.revs('%lr', obsoleted)]
        if obsoleted and len(revs) > 1:

            raise error.Abort(_('Can not graft multiple revision while '
                                'obsoleting (for now).'))

        return commitwrapper(orig, ui, repo,*revs, **kwargs)
    finally:
        lock.release()

@eh.extsetup
def oldevolveextsetup(ui):
    try:
        rebase = extensions.find('rebase')
    except KeyError:
        raise error.Abort(_('evolution extension requires rebase extension.'))

    for cmd in ['amend', 'kill', 'uncommit', 'touch', 'fold']:
        entry = extensions.wrapcommand(cmdtable, cmd,
                                       warnobserrors)

    entry = cmdutil.findcmd('commit', commands.table)[1]
    entry[1].append(('o', 'obsolete', [],
                     _("make commit obsolete this revision")))
    entry = cmdutil.findcmd('graft', commands.table)[1]
    entry[1].append(('o', 'obsolete', [],
                     _("make graft obsoletes this revision")))
    entry[1].append(('O', 'old-obsolete', False,
                     _("make graft obsoletes its source")))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.